feat(auth): accounts are identified by an email address
Registration, login and the admin's create-user call take `email` instead of `username`, and the user object returns `email`. The address is checked for its shape (a plain address, no display name, at most 254 bytes), trimmed, lowercased and unique. Sonda sends no mail and does not verify it. - Migration 0018 renames the users column (and the PostgreSQL index); values are kept, so an account made before keeps its plain name and still logs in with it (login does not check the shape). - Error code username_taken becomes email_taken; the JWT claim is now `email`, so access tokens issued before the upgrade are refused once and clients refresh. - OpenAPI spec, README, the web login form (type email), strings (en, it) and the generated API types follow. Closes #65
This commit is contained in:
parent
850ae11f3d
commit
96ad8b1f62
42 changed files with 606 additions and 244 deletions
10
README.md
10
README.md
|
|
@ -8,7 +8,7 @@ It is a single executable, one database (SQLite by default, PostgreSQL if you pr
|
||||||
|
|
||||||
## What works today
|
## What works today
|
||||||
|
|
||||||
- **Accounts.** The first user to register becomes the admin and registration then closes; admins create the other users. Short-lived access tokens (JWT) plus rotating refresh tokens, so a stolen refresh token is detected.
|
- **Accounts.** An account is an email address and a password. The first user to register becomes the admin and registration then closes; admins create the other users. The address only identifies the account: Sonda sends no mail, does not check that the address exists, and keeps it on your server. It is trimmed and lowercased, and unique. Accounts made before addresses were asked for keep the plain name they had as their login. Short-lived access tokens (JWT) plus rotating refresh tokens, so a stolen refresh token is detected.
|
||||||
- **Libraries.** A library is a name and a folder, managed through the API. Sonda only ever reads your music folders: it never writes, renames or deletes a file.
|
- **Libraries.** A library is a name and a folder, managed through the API. Sonda only ever reads your music folders: it never writes, renames or deletes a file.
|
||||||
- **Scanner.** Reads MP3 and FLAC tags and audio properties with several workers in parallel. Rescans are incremental, renamed files keep their identity, vanished files are flagged (never deleted), and a library whose folder looks empty or unreadable (an unmounted NAS) is left alone instead of being wiped. Audio in other formats (m4a, ogg, opus, wav, wma and similar) is not read yet, but it is counted as `unsupported` in the scan result instead of disappearing silently. NAS housekeeping folders (`@Recycle`, `#recycle`, `@eaDir`, `.@__thumb`, `$RECYCLE.BIN`) are skipped.
|
- **Scanner.** Reads MP3 and FLAC tags and audio properties with several workers in parallel. Rescans are incremental, renamed files keep their identity, vanished files are flagged (never deleted), and a library whose folder looks empty or unreadable (an unmounted NAS) is left alone instead of being wiped. Audio in other formats (m4a, ogg, opus, wav, wma and similar) is not read yet, but it is counted as `unsupported` in the scan result instead of disappearing silently. NAS housekeeping folders (`@Recycle`, `#recycle`, `@eaDir`, `.@__thumb`, `$RECYCLE.BIN`) are skipped.
|
||||||
- **Catalog.** Browse and search artists, albums and tracks, with paging, by library, artist or album. Only tracks you can actually play are listed.
|
- **Catalog.** Browse and search artists, albums and tracks, with paging, by library, artist or album. Only tracks you can actually play are listed.
|
||||||
|
|
@ -134,9 +134,9 @@ BASE=http://127.0.0.1:8080/api/v1
|
||||||
curl -s $BASE/health
|
curl -s $BASE/health
|
||||||
|
|
||||||
# The first user becomes the admin; registration is then closed.
|
# The first user becomes the admin; registration is then closed.
|
||||||
curl -s -X POST $BASE/auth/register -d '{"username":"alice","password":"correct horse battery"}'
|
curl -s -X POST $BASE/auth/register -d '{"email":"alice@example.org","password":"correct horse battery"}'
|
||||||
|
|
||||||
LOGIN=$(curl -s -X POST $BASE/auth/login -d '{"username":"alice","password":"correct horse battery"}')
|
LOGIN=$(curl -s -X POST $BASE/auth/login -d '{"email":"alice@example.org","password":"correct horse battery"}')
|
||||||
TOKEN=$(echo "$LOGIN" | jq -r .access_token)
|
TOKEN=$(echo "$LOGIN" | jq -r .access_token)
|
||||||
REFRESH=$(echo "$LOGIN" | jq -r .refresh_token)
|
REFRESH=$(echo "$LOGIN" | jq -r .refresh_token)
|
||||||
AUTH="Authorization: Bearer $TOKEN"
|
AUTH="Authorization: Bearer $TOKEN"
|
||||||
|
|
@ -204,9 +204,9 @@ Each refresh token works once. Presenting a spent one again, more than ten secon
|
||||||
**9. Add another user** (admins only):
|
**9. Add another user** (admins only):
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
TOKEN=$(curl -s -X POST $BASE/auth/login -d '{"username":"alice","password":"correct horse battery"}' | jq -r .access_token)
|
TOKEN=$(curl -s -X POST $BASE/auth/login -d '{"email":"alice@example.org","password":"correct horse battery"}' | jq -r .access_token)
|
||||||
AUTH="Authorization: Bearer $TOKEN"
|
AUTH="Authorization: Bearer $TOKEN"
|
||||||
curl -s -X POST $BASE/users -H "$AUTH" -d '{"username":"bob","password":"another long password"}' | jq
|
curl -s -X POST $BASE/users -H "$AUTH" -d '{"email":"bob@example.org","password":"another long password"}' | jq
|
||||||
```
|
```
|
||||||
|
|
||||||
## External providers
|
## External providers
|
||||||
|
|
|
||||||
|
|
@ -189,7 +189,7 @@ func errCode(r resp) string {
|
||||||
// registerAndLogin creates the first user and returns a valid token.
|
// registerAndLogin creates the first user and returns a valid token.
|
||||||
func registerAndLogin(t *testing.T, h http.Handler) string {
|
func registerAndLogin(t *testing.T, h http.Handler) string {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
creds := map[string]string{"username": "alice", "password": "longenough"}
|
creds := map[string]string{"email": "alice@example.org", "password": "longenough"}
|
||||||
if r := do(t, h, "POST", "/api/v1/auth/register", "", creds); r.Code != http.StatusCreated {
|
if r := do(t, h, "POST", "/api/v1/auth/register", "", creds); r.Code != http.StatusCreated {
|
||||||
t.Fatalf("register: %d %v", r.Code, r.Body)
|
t.Fatalf("register: %d %v", r.Code, r.Body)
|
||||||
}
|
}
|
||||||
|
|
@ -215,7 +215,7 @@ func TestRegisterThenClosed(t *testing.T) {
|
||||||
h := newTestAPI(t)
|
h := newTestAPI(t)
|
||||||
registerAndLogin(t, h)
|
registerAndLogin(t, h)
|
||||||
|
|
||||||
r := do(t, h, "POST", "/api/v1/auth/register", "", map[string]string{"username": "bob", "password": "longenough"})
|
r := do(t, h, "POST", "/api/v1/auth/register", "", map[string]string{"email": "bob@example.org", "password": "longenough"})
|
||||||
if r.Code != http.StatusForbidden || errCode(r) != "registration_closed" {
|
if r.Code != http.StatusForbidden || errCode(r) != "registration_closed" {
|
||||||
t.Fatalf("second register: %d %v", r.Code, r.Body)
|
t.Fatalf("second register: %d %v", r.Code, r.Body)
|
||||||
}
|
}
|
||||||
|
|
@ -224,8 +224,8 @@ func TestRegisterThenClosed(t *testing.T) {
|
||||||
func TestRegisterInvalid(t *testing.T) {
|
func TestRegisterInvalid(t *testing.T) {
|
||||||
h := newTestAPI(t)
|
h := newTestAPI(t)
|
||||||
for name, body := range map[string]any{
|
for name, body := range map[string]any{
|
||||||
"short password": map[string]string{"username": "alice", "password": "x"},
|
"short password": map[string]string{"email": "alice@example.org", "password": "x"},
|
||||||
"bad username": map[string]string{"username": "a", "password": "longenough"},
|
"bad email": map[string]string{"email": "a", "password": "longenough"},
|
||||||
"malformed json": "{not json",
|
"malformed json": "{not json",
|
||||||
} {
|
} {
|
||||||
r := do(t, h, "POST", "/api/v1/auth/register", "", body)
|
r := do(t, h, "POST", "/api/v1/auth/register", "", body)
|
||||||
|
|
@ -238,7 +238,7 @@ func TestRegisterInvalid(t *testing.T) {
|
||||||
func TestLoginWrongPassword(t *testing.T) {
|
func TestLoginWrongPassword(t *testing.T) {
|
||||||
h := newTestAPI(t)
|
h := newTestAPI(t)
|
||||||
registerAndLogin(t, h)
|
registerAndLogin(t, h)
|
||||||
r := do(t, h, "POST", "/api/v1/auth/login", "", map[string]string{"username": "alice", "password": "nopenopenope"})
|
r := do(t, h, "POST", "/api/v1/auth/login", "", map[string]string{"email": "alice@example.org", "password": "nopenopenope"})
|
||||||
if r.Code != http.StatusUnauthorized || errCode(r) != "invalid_credentials" {
|
if r.Code != http.StatusUnauthorized || errCode(r) != "invalid_credentials" {
|
||||||
t.Fatalf("login: %d %v", r.Code, r.Body)
|
t.Fatalf("login: %d %v", r.Code, r.Body)
|
||||||
}
|
}
|
||||||
|
|
@ -256,7 +256,7 @@ func TestListenRequiresAuth(t *testing.T) {
|
||||||
}
|
}
|
||||||
|
|
||||||
// A token signed with another secret is rejected.
|
// A token signed with another secret is rejected.
|
||||||
other, _, _ := auth.NewTokenIssuer("ffffffffffffffffffffffffffffffff", time.Hour).Issue(auth.User{ID: 1, Username: "alice"})
|
other, _, _ := auth.NewTokenIssuer("ffffffffffffffffffffffffffffffff", time.Hour).Issue(auth.User{ID: 1, Email: "alice"})
|
||||||
if r := do(t, h, "POST", "/api/v1/listens", other, body); r.Code != http.StatusUnauthorized {
|
if r := do(t, h, "POST", "/api/v1/listens", other, body); r.Code != http.StatusUnauthorized {
|
||||||
t.Errorf("foreign token: %d", r.Code)
|
t.Errorf("foreign token: %d", r.Code)
|
||||||
}
|
}
|
||||||
|
|
@ -305,7 +305,7 @@ func TestListenFlow(t *testing.T) {
|
||||||
|
|
||||||
func TestBodyTooLarge(t *testing.T) {
|
func TestBodyTooLarge(t *testing.T) {
|
||||||
h := newTestAPI(t)
|
h := newTestAPI(t)
|
||||||
huge := `{"username":"` + strings.Repeat("a", 200_000) + `","password":"longenough"}`
|
huge := `{"email":"` + strings.Repeat("a", 200_000) + `","password":"longenough"}`
|
||||||
r := do(t, h, "POST", "/api/v1/auth/register", "", huge)
|
r := do(t, h, "POST", "/api/v1/auth/register", "", huge)
|
||||||
if r.Code != http.StatusBadRequest && r.Code != http.StatusRequestEntityTooLarge {
|
if r.Code != http.StatusBadRequest && r.Code != http.StatusRequestEntityTooLarge {
|
||||||
t.Fatalf("huge body: %d", r.Code)
|
t.Fatalf("huge body: %d", r.Code)
|
||||||
|
|
|
||||||
|
|
@ -4,6 +4,7 @@ import (
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/http/httptest"
|
"net/http/httptest"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
@ -20,7 +21,7 @@ func sub(m map[string]any, key string) map[string]any {
|
||||||
// loginSession logs in and returns the whole session body.
|
// loginSession logs in and returns the whole session body.
|
||||||
func loginSession(t *testing.T, h http.Handler, user, pass string) map[string]any {
|
func loginSession(t *testing.T, h http.Handler, user, pass string) map[string]any {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
r := do(t, h, "POST", "/api/v1/auth/login", "", map[string]string{"username": user, "password": pass})
|
r := do(t, h, "POST", "/api/v1/auth/login", "", map[string]string{"email": address(user), "password": pass})
|
||||||
if r.Code != http.StatusOK {
|
if r.Code != http.StatusOK {
|
||||||
t.Fatalf("login %s: %d %v", user, r.Code, r.Body)
|
t.Fatalf("login %s: %d %v", user, r.Code, r.Body)
|
||||||
}
|
}
|
||||||
|
|
@ -31,7 +32,7 @@ func loginSession(t *testing.T, h http.Handler, user, pass string) map[string]an
|
||||||
func addUser(t *testing.T, h http.Handler, adminTok, name string, admin bool) (id float64, token string) {
|
func addUser(t *testing.T, h http.Handler, adminTok, name string, admin bool) (id float64, token string) {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
r := do(t, h, "POST", "/api/v1/users", adminTok,
|
r := do(t, h, "POST", "/api/v1/users", adminTok,
|
||||||
map[string]any{"username": name, "password": "longenough", "is_admin": admin})
|
map[string]any{"email": address(name), "password": "longenough", "is_admin": admin})
|
||||||
if r.Code != http.StatusCreated {
|
if r.Code != http.StatusCreated {
|
||||||
t.Fatalf("create %s: %d %v", name, r.Code, r.Body)
|
t.Fatalf("create %s: %d %v", name, r.Code, r.Body)
|
||||||
}
|
}
|
||||||
|
|
@ -56,7 +57,7 @@ func TestLoginReturnsSessionWithRoles(t *testing.T) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
u := sub(s, "user")
|
u := sub(s, "user")
|
||||||
if u["username"] != "alice" || u["is_admin"] != true {
|
if u["email"] != "alice@example.org" || u["is_admin"] != true {
|
||||||
t.Errorf("user = %v, want alice as admin", u)
|
t.Errorf("user = %v, want alice as admin", u)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -69,7 +70,7 @@ func TestMe(t *testing.T) {
|
||||||
t.Errorf("no token: %d", r.Code)
|
t.Errorf("no token: %d", r.Code)
|
||||||
}
|
}
|
||||||
r := do(t, h, "GET", "/api/v1/auth/me", tok, nil)
|
r := do(t, h, "GET", "/api/v1/auth/me", tok, nil)
|
||||||
if r.Code != http.StatusOK || r.Body["username"] != "alice" || r.Body["is_admin"] != true {
|
if r.Code != http.StatusOK || r.Body["email"] != "alice@example.org" || r.Body["is_admin"] != true {
|
||||||
t.Fatalf("me: %d %v", r.Code, r.Body)
|
t.Fatalf("me: %d %v", r.Code, r.Body)
|
||||||
}
|
}
|
||||||
if _, leaked := r.Body["password_hash"]; leaked {
|
if _, leaked := r.Body["password_hash"]; leaked {
|
||||||
|
|
@ -182,7 +183,7 @@ func TestChangePassword(t *testing.T) {
|
||||||
t.Fatalf("change: %d %v", r.Code, r.Body)
|
t.Fatalf("change: %d %v", r.Code, r.Body)
|
||||||
}
|
}
|
||||||
|
|
||||||
if r := do(t, h, "POST", "/api/v1/auth/login", "", map[string]string{"username": "alice", "password": "longenough"}); r.Code != http.StatusUnauthorized {
|
if r := do(t, h, "POST", "/api/v1/auth/login", "", map[string]string{"email": "alice@example.org", "password": "longenough"}); r.Code != http.StatusUnauthorized {
|
||||||
t.Errorf("old password still works: %d", r.Code)
|
t.Errorf("old password still works: %d", r.Code)
|
||||||
}
|
}
|
||||||
loginSession(t, h, "alice", "brandnewpass")
|
loginSession(t, h, "alice", "brandnewpass")
|
||||||
|
|
@ -210,7 +211,7 @@ func TestAdminEndpointsRejectNonAdmins(t *testing.T) {
|
||||||
if r := do(t, h, c.method, c.path, "", nil); r.Code != http.StatusUnauthorized {
|
if r := do(t, h, c.method, c.path, "", nil); r.Code != http.StatusUnauthorized {
|
||||||
t.Errorf("%s %s without token: %d", c.method, c.path, r.Code)
|
t.Errorf("%s %s without token: %d", c.method, c.path, r.Code)
|
||||||
}
|
}
|
||||||
r := do(t, h, c.method, c.path, bob, map[string]any{"username": "x", "password": "longenough", "is_admin": true})
|
r := do(t, h, c.method, c.path, bob, map[string]any{"email": "x", "password": "longenough", "is_admin": true})
|
||||||
if r.Code != http.StatusForbidden || errCode(r) != "admin_required" {
|
if r.Code != http.StatusForbidden || errCode(r) != "admin_required" {
|
||||||
t.Errorf("%s %s as non-admin: %d %v", c.method, c.path, r.Code, r.Body)
|
t.Errorf("%s %s as non-admin: %d %v", c.method, c.path, r.Code, r.Body)
|
||||||
}
|
}
|
||||||
|
|
@ -238,10 +239,10 @@ func TestAdminUserLifecycle(t *testing.T) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if r := do(t, h, "POST", "/api/v1/users", admin, map[string]any{"username": "BOB", "password": "longenough"}); r.Code != http.StatusConflict || errCode(r) != "username_taken" {
|
if r := do(t, h, "POST", "/api/v1/users", admin, map[string]any{"email": "BOB@example.org", "password": "longenough"}); r.Code != http.StatusConflict || errCode(r) != "email_taken" {
|
||||||
t.Errorf("duplicate: %d %v", r.Code, r.Body)
|
t.Errorf("duplicate: %d %v", r.Code, r.Body)
|
||||||
}
|
}
|
||||||
if r := do(t, h, "POST", "/api/v1/users", admin, map[string]any{"username": "x", "password": "longenough"}); r.Code != http.StatusBadRequest {
|
if r := do(t, h, "POST", "/api/v1/users", admin, map[string]any{"email": "x", "password": "longenough"}); r.Code != http.StatusBadRequest {
|
||||||
t.Errorf("invalid: %d", r.Code)
|
t.Errorf("invalid: %d", r.Code)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -389,3 +390,11 @@ func TestListenWithADeletedAccountsTokenIsUnauthorized(t *testing.T) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// address makes an email of a short test name: "bob" is "bob@example.org".
|
||||||
|
func address(name string) string {
|
||||||
|
if strings.Contains(name, "@") {
|
||||||
|
return name
|
||||||
|
}
|
||||||
|
return name + "@example.org"
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -299,12 +299,12 @@ func TestResponsesMatchTheSpec(t *testing.T) {
|
||||||
c.expect(c.call("GET", "/openapi.yaml", "", nil), 200, "openapi.yaml")
|
c.expect(c.call("GET", "/openapi.yaml", "", nil), 200, "openapi.yaml")
|
||||||
|
|
||||||
// ---- auth ----
|
// ---- auth ----
|
||||||
creds := map[string]string{"username": "alice", "password": "correct horse"}
|
creds := map[string]string{"email": "alice@example.org", "password": "correct horse"}
|
||||||
c.expect(c.call("POST", "/auth/register", "", map[string]string{"username": "x", "password": "short"}), 400, "register invalid", "invalid_input")
|
c.expect(c.call("POST", "/auth/register", "", map[string]string{"email": "x", "password": "short"}), 400, "register invalid", "invalid_input")
|
||||||
c.expect(c.call("POST", "/auth/register", "", creds), 201, "register")
|
c.expect(c.call("POST", "/auth/register", "", creds), 201, "register")
|
||||||
c.expect(c.call("POST", "/auth/register", "", map[string]string{"username": "eve", "password": "correct horse"}), 403, "register closed", "registration_closed")
|
c.expect(c.call("POST", "/auth/register", "", map[string]string{"email": "eve@example.org", "password": "correct horse"}), 403, "register closed", "registration_closed")
|
||||||
|
|
||||||
c.expect(c.call("POST", "/auth/login", "", map[string]string{"username": "alice", "password": "wrong password"}), 401, "login wrong", "invalid_credentials")
|
c.expect(c.call("POST", "/auth/login", "", map[string]string{"email": "alice@example.org", "password": "wrong password"}), 401, "login wrong", "invalid_credentials")
|
||||||
c.expect(c.call("POST", "/auth/login", "", "not an object"), 400, "login with a bad body", "invalid_input")
|
c.expect(c.call("POST", "/auth/login", "", "not an object"), 400, "login with a bad body", "invalid_input")
|
||||||
session := c.expect(c.call("POST", "/auth/login", "", creds), 200, "login")
|
session := c.expect(c.call("POST", "/auth/login", "", creds), 200, "login")
|
||||||
token := session["access_token"].(string)
|
token := session["access_token"].(string)
|
||||||
|
|
@ -327,10 +327,10 @@ func TestResponsesMatchTheSpec(t *testing.T) {
|
||||||
token = c.expect(c.call("POST", "/auth/login", "", creds), 200, "login again")["access_token"].(string)
|
token = c.expect(c.call("POST", "/auth/login", "", creds), 200, "login again")["access_token"].(string)
|
||||||
|
|
||||||
// ---- users ----
|
// ---- users ----
|
||||||
bob := c.expect(c.call("POST", "/users", token, map[string]any{"username": "bob", "password": "bobs long pass"}), 201, "create user")
|
bob := c.expect(c.call("POST", "/users", token, map[string]any{"email": "bob@example.org", "password": "bobs long pass"}), 201, "create user")
|
||||||
c.expect(c.call("POST", "/users", token, map[string]any{"username": "BOB", "password": "bobs long pass"}), 409, "create duplicate", "username_taken")
|
c.expect(c.call("POST", "/users", token, map[string]any{"email": "BOB@example.org", "password": "bobs long pass"}), 409, "create duplicate", "email_taken")
|
||||||
c.expect(c.call("POST", "/users", token, map[string]any{"username": "x", "password": "bobs long pass"}), 400, "create invalid", "invalid_input")
|
c.expect(c.call("POST", "/users", token, map[string]any{"email": "x", "password": "bobs long pass"}), 400, "create invalid", "invalid_input")
|
||||||
bobToken := c.expect(c.call("POST", "/auth/login", "", map[string]string{"username": "bob", "password": "bobs long pass"}), 200, "bob logs in")["access_token"].(string)
|
bobToken := c.expect(c.call("POST", "/auth/login", "", map[string]string{"email": "bob@example.org", "password": "bobs long pass"}), 200, "bob logs in")["access_token"].(string)
|
||||||
c.expect(c.call("GET", "/users", bobToken, nil), 403, "users as non-admin", "admin_required")
|
c.expect(c.call("GET", "/users", bobToken, nil), 403, "users as non-admin", "admin_required")
|
||||||
c.expect(c.call("GET", "/providers", bobToken, nil), 403, "providers as non-admin", "admin_required")
|
c.expect(c.call("GET", "/providers", bobToken, nil), 403, "providers as non-admin", "admin_required")
|
||||||
c.expect(c.call("GET", "/users", token, nil), 200, "list users")
|
c.expect(c.call("GET", "/users", token, nil), 200, "list users")
|
||||||
|
|
|
||||||
|
|
@ -188,7 +188,7 @@ func TestTheSettingBelongsToEachUser(t *testing.T) {
|
||||||
e.listen(t, e.admin, e.trackOf(t, "Alpha"), "complete", 1000, "a1")
|
e.listen(t, e.admin, e.trackOf(t, "Alpha"), "complete", 1000, "a1")
|
||||||
e.allowListening(t) // alice allows it
|
e.allowListening(t) // alice allows it
|
||||||
|
|
||||||
body := map[string]any{"username": "bob", "password": "longenough"}
|
body := map[string]any{"email": "bob@example.org", "password": "longenough"}
|
||||||
if r := do(t, e.h, "POST", "/api/v1/users", e.admin, body); r.Code != http.StatusCreated {
|
if r := do(t, e.h, "POST", "/api/v1/users", e.admin, body); r.Code != http.StatusCreated {
|
||||||
t.Fatalf("create bob: %d %v", r.Code, r.Body)
|
t.Fatalf("create bob: %d %v", r.Code, r.Body)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -21,7 +21,7 @@ func (e *discoverEnv) gamma(t *testing.T) int64 {
|
||||||
|
|
||||||
func (e *discoverEnv) bob(t *testing.T) string {
|
func (e *discoverEnv) bob(t *testing.T) string {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
body := map[string]any{"username": "bob", "password": "longenough"}
|
body := map[string]any{"email": "bob@example.org", "password": "longenough"}
|
||||||
if r := do(t, e.h, "POST", "/api/v1/users", e.admin, body); r.Code != http.StatusCreated {
|
if r := do(t, e.h, "POST", "/api/v1/users", e.admin, body); r.Code != http.StatusCreated {
|
||||||
t.Fatalf("create bob: %d %v", r.Code, r.Body)
|
t.Fatalf("create bob: %d %v", r.Code, r.Body)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -13,18 +13,18 @@ import (
|
||||||
type authHandlers struct{ svc authService }
|
type authHandlers struct{ svc authService }
|
||||||
|
|
||||||
type credentials struct {
|
type credentials struct {
|
||||||
Username string `json:"username"`
|
Email string `json:"email"`
|
||||||
Password string `json:"password"`
|
Password string `json:"password"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type userJSON struct {
|
type userJSON struct {
|
||||||
ID int64 `json:"id"`
|
ID int64 `json:"id"`
|
||||||
Username string `json:"username"`
|
Email string `json:"email"`
|
||||||
IsAdmin bool `json:"is_admin"`
|
IsAdmin bool `json:"is_admin"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func toUserJSON(u auth.User) userJSON {
|
func toUserJSON(u auth.User) userJSON {
|
||||||
return userJSON{ID: u.ID, Username: u.Username, IsAdmin: u.IsAdmin}
|
return userJSON{ID: u.ID, Email: u.Email, IsAdmin: u.IsAdmin}
|
||||||
}
|
}
|
||||||
|
|
||||||
func sessionJSON(s auth.Session) gin.H {
|
func sessionJSON(s auth.Session) gin.H {
|
||||||
|
|
@ -53,8 +53,8 @@ func writeAuthError(c *gin.Context, err error) {
|
||||||
writeError(c, http.StatusBadRequest, "invalid_input", err.Error())
|
writeError(c, http.StatusBadRequest, "invalid_input", err.Error())
|
||||||
case errors.Is(err, auth.ErrRegistrationClosed):
|
case errors.Is(err, auth.ErrRegistrationClosed):
|
||||||
writeError(c, http.StatusForbidden, "registration_closed", err.Error())
|
writeError(c, http.StatusForbidden, "registration_closed", err.Error())
|
||||||
case errors.Is(err, auth.ErrUsernameTaken):
|
case errors.Is(err, auth.ErrEmailTaken):
|
||||||
writeError(c, http.StatusConflict, "username_taken", err.Error())
|
writeError(c, http.StatusConflict, "email_taken", err.Error())
|
||||||
case errors.Is(err, auth.ErrUserNotFound):
|
case errors.Is(err, auth.ErrUserNotFound):
|
||||||
writeError(c, http.StatusNotFound, "user_not_found", err.Error())
|
writeError(c, http.StatusNotFound, "user_not_found", err.Error())
|
||||||
case errors.Is(err, auth.ErrLastAdmin):
|
case errors.Is(err, auth.ErrLastAdmin):
|
||||||
|
|
@ -75,7 +75,7 @@ func (h *authHandlers) register(c *gin.Context) {
|
||||||
if !bindJSON(c, &req) {
|
if !bindJSON(c, &req) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
user, err := h.svc.Register(c.Request.Context(), req.Username, req.Password)
|
user, err := h.svc.Register(c.Request.Context(), req.Email, req.Password)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeAuthError(c, err)
|
writeAuthError(c, err)
|
||||||
return
|
return
|
||||||
|
|
@ -88,7 +88,7 @@ func (h *authHandlers) login(c *gin.Context) {
|
||||||
if !bindJSON(c, &req) {
|
if !bindJSON(c, &req) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
sess, err := h.svc.Login(c.Request.Context(), req.Username, req.Password)
|
sess, err := h.svc.Login(c.Request.Context(), req.Email, req.Password)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeAuthError(c, err)
|
writeAuthError(c, err)
|
||||||
return
|
return
|
||||||
|
|
|
||||||
|
|
@ -24,7 +24,7 @@ func (h *usersHandlers) list(c *gin.Context) {
|
||||||
}
|
}
|
||||||
|
|
||||||
type createUserRequest struct {
|
type createUserRequest struct {
|
||||||
Username string `json:"username"`
|
Email string `json:"email"`
|
||||||
Password string `json:"password"`
|
Password string `json:"password"`
|
||||||
IsAdmin bool `json:"is_admin"`
|
IsAdmin bool `json:"is_admin"`
|
||||||
}
|
}
|
||||||
|
|
@ -34,7 +34,7 @@ func (h *usersHandlers) create(c *gin.Context) {
|
||||||
if !bindJSON(c, &req) {
|
if !bindJSON(c, &req) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
user, err := h.svc.CreateUser(c.Request.Context(), req.Username, req.Password, req.IsAdmin)
|
user, err := h.svc.CreateUser(c.Request.Context(), req.Email, req.Password, req.IsAdmin)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeAuthError(c, err)
|
writeAuthError(c, err)
|
||||||
return
|
return
|
||||||
|
|
|
||||||
|
|
@ -60,7 +60,7 @@ func newJobAPI(t *testing.T, jc jobCase) (http.Handler, *fakeJob, string, string
|
||||||
h, _ := newTestEnvDB(t, func(d *Deps, _ *bun.DB) { jc.set(d, fake) })
|
h, _ := newTestEnvDB(t, func(d *Deps, _ *bun.DB) { jc.set(d, fake) })
|
||||||
admin := registerAndLogin(t, h)
|
admin := registerAndLogin(t, h)
|
||||||
// A second user who is not an admin.
|
// A second user who is not an admin.
|
||||||
cred := map[string]any{"username": "bob", "password": "longenough"}
|
cred := map[string]any{"email": "bob@example.org", "password": "longenough"}
|
||||||
if r := do(t, h, "POST", "/api/v1/users", admin, cred); r.Code != http.StatusCreated {
|
if r := do(t, h, "POST", "/api/v1/users", admin, cred); r.Code != http.StatusCreated {
|
||||||
t.Fatalf("create bob: %d %v", r.Code, r.Body)
|
t.Fatalf("create bob: %d %v", r.Code, r.Body)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -14,9 +14,9 @@ import (
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
ctxUserID = "user_id"
|
ctxUserID = "user_id"
|
||||||
ctxUsername = "username"
|
ctxEmail = "email"
|
||||||
ctxAccount = "account" // the auth.User that requireAuth already looked up
|
ctxAccount = "account" // the auth.User that requireAuth already looked up
|
||||||
)
|
)
|
||||||
|
|
||||||
// limitBody caps the request body size.
|
// limitBody caps the request body size.
|
||||||
|
|
@ -150,13 +150,13 @@ func requireAuth(tokens tokenParser, users userLookup, allowQuery bool) gin.Hand
|
||||||
_ = c.Error(err)
|
_ = c.Error(err)
|
||||||
writeError(c, http.StatusInternalServerError, "internal", "internal error")
|
writeError(c, http.StatusInternalServerError, "internal", "internal error")
|
||||||
return
|
return
|
||||||
case user.Username != claims.Username || user.CreatedAt.Unix() > claims.IssuedAt.Unix():
|
case user.Email != claims.Email || user.CreatedAt.Unix() > claims.IssuedAt.Unix():
|
||||||
writeError(c, http.StatusUnauthorized, "unauthorized", "invalid or expired token")
|
writeError(c, http.StatusUnauthorized, "unauthorized", "invalid or expired token")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
c.Set(ctxUserID, claims.UserID)
|
c.Set(ctxUserID, claims.UserID)
|
||||||
c.Set(ctxAccount, user)
|
c.Set(ctxAccount, user)
|
||||||
c.Set(ctxUsername, claims.Username)
|
c.Set(ctxEmail, claims.Email)
|
||||||
c.Next()
|
c.Next()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -30,17 +30,17 @@ func (f fakeUsers) User(context.Context, int64) (auth.User, error) { return f.us
|
||||||
|
|
||||||
func TestRequireAuthChecksWhoTheTokenWasIssuedFor(t *testing.T) {
|
func TestRequireAuthChecksWhoTheTokenWasIssuedFor(t *testing.T) {
|
||||||
issued := time.Unix(1_700_000_000, 0)
|
issued := time.Unix(1_700_000_000, 0)
|
||||||
token := auth.Claims{UserID: 5, Username: "bob", IssuedAt: issued}
|
token := auth.Claims{UserID: 5, Email: "bob", IssuedAt: issued}
|
||||||
for _, tt := range []struct {
|
for _, tt := range []struct {
|
||||||
name string
|
name string
|
||||||
users fakeUsers
|
users fakeUsers
|
||||||
want int
|
want int
|
||||||
}{
|
}{
|
||||||
{"the same account", fakeUsers{user: auth.User{ID: 5, Username: "bob", CreatedAt: issued.Add(-time.Hour)}}, http.StatusOK},
|
{"the same account", fakeUsers{user: auth.User{ID: 5, Email: "bob", CreatedAt: issued.Add(-time.Hour)}}, http.StatusOK},
|
||||||
{"created in the same second as the token", fakeUsers{user: auth.User{ID: 5, Username: "bob", CreatedAt: issued}}, http.StatusOK},
|
{"created in the same second as the token", fakeUsers{user: auth.User{ID: 5, Email: "bob", CreatedAt: issued}}, http.StatusOK},
|
||||||
{"the account is gone", fakeUsers{err: auth.ErrUserNotFound}, http.StatusUnauthorized},
|
{"the account is gone", fakeUsers{err: auth.ErrUserNotFound}, http.StatusUnauthorized},
|
||||||
{"the id now belongs to somebody else", fakeUsers{user: auth.User{ID: 5, Username: "carol", CreatedAt: issued.Add(-time.Hour)}}, http.StatusUnauthorized},
|
{"the id now belongs to somebody else", fakeUsers{user: auth.User{ID: 5, Email: "carol", CreatedAt: issued.Add(-time.Hour)}}, http.StatusUnauthorized},
|
||||||
{"the id was reused for the same name, later", fakeUsers{user: auth.User{ID: 5, Username: "bob", CreatedAt: issued.Add(time.Minute)}}, http.StatusUnauthorized},
|
{"the id was reused for the same name, later", fakeUsers{user: auth.User{ID: 5, Email: "bob", CreatedAt: issued.Add(time.Minute)}}, http.StatusUnauthorized},
|
||||||
{"the database fails", fakeUsers{err: errors.New("boom")}, http.StatusInternalServerError},
|
{"the database fails", fakeUsers{err: errors.New("boom")}, http.StatusInternalServerError},
|
||||||
} {
|
} {
|
||||||
r := gin.New()
|
r := gin.New()
|
||||||
|
|
@ -66,7 +66,7 @@ func TestRequireAuthDoesNotCallAClientThatLeftAnInternalError(t *testing.T) {
|
||||||
r := gin.New()
|
r := gin.New()
|
||||||
var logged int
|
var logged int
|
||||||
r.Use(func(c *gin.Context) { c.Next(); logged = len(c.Errors) })
|
r.Use(func(c *gin.Context) { c.Next(); logged = len(c.Errors) })
|
||||||
r.GET("/x", requireAuth(fakeParser{claims: auth.Claims{UserID: 5, Username: "bob"}}, fakeUsers{err: context.Canceled}, false), func(c *gin.Context) {
|
r.GET("/x", requireAuth(fakeParser{claims: auth.Claims{UserID: 5, Email: "bob"}}, fakeUsers{err: context.Canceled}, false), func(c *gin.Context) {
|
||||||
t.Error("the handler ran for a client that left")
|
t.Error("the handler ran for a client that left")
|
||||||
})
|
})
|
||||||
req := httptest.NewRequest("GET", "/x", nil).WithContext(ctx)
|
req := httptest.NewRequest("GET", "/x", nil).WithContext(ctx)
|
||||||
|
|
@ -80,9 +80,9 @@ func TestRequireAuthDoesNotCallAClientThatLeftAnInternalError(t *testing.T) {
|
||||||
|
|
||||||
func TestAdminCheckReusesTheAccountAlreadyLookedUp(t *testing.T) {
|
func TestAdminCheckReusesTheAccountAlreadyLookedUp(t *testing.T) {
|
||||||
calls := 0
|
calls := 0
|
||||||
users := countingUsers{user: auth.User{ID: 5, Username: "root", IsAdmin: true}, calls: &calls}
|
users := countingUsers{user: auth.User{ID: 5, Email: "root", IsAdmin: true}, calls: &calls}
|
||||||
r := gin.New()
|
r := gin.New()
|
||||||
r.GET("/x", requireAuth(fakeParser{claims: auth.Claims{UserID: 5, Username: "root", IssuedAt: time.Now()}}, users, false),
|
r.GET("/x", requireAuth(fakeParser{claims: auth.Claims{UserID: 5, Email: "root", IssuedAt: time.Now()}}, users, false),
|
||||||
requireAdmin(users), func(c *gin.Context) { c.Status(http.StatusOK) })
|
requireAdmin(users), func(c *gin.Context) { c.Status(http.StatusOK) })
|
||||||
req := httptest.NewRequest("GET", "/x", nil)
|
req := httptest.NewRequest("GET", "/x", nil)
|
||||||
req.Header.Set("Authorization", "Bearer anything")
|
req.Header.Set("Authorization", "Bearer anything")
|
||||||
|
|
@ -123,7 +123,7 @@ func TestATokenOfADeletedUserDoesNotWorkAsWhoeverGetsTheSameId(t *testing.T) {
|
||||||
h := newTestAPI(t)
|
h := newTestAPI(t)
|
||||||
admin := registerAndLogin(t, h)
|
admin := registerAndLogin(t, h)
|
||||||
create := func(name string) (id int64, token string) {
|
create := func(name string) (id int64, token string) {
|
||||||
cred := map[string]any{"username": name, "password": "longenough"}
|
cred := map[string]any{"email": address(name), "password": "longenough"}
|
||||||
r := do(t, h, "POST", "/api/v1/users", admin, cred)
|
r := do(t, h, "POST", "/api/v1/users", admin, cred)
|
||||||
if r.Code != http.StatusCreated {
|
if r.Code != http.StatusCreated {
|
||||||
t.Fatalf("create %s: %d %v", name, r.Code, r.Body)
|
t.Fatalf("create %s: %d %v", name, r.Code, r.Body)
|
||||||
|
|
|
||||||
|
|
@ -32,14 +32,14 @@ import (
|
||||||
const maxBodyBytes = 64 << 10
|
const maxBodyBytes = 64 << 10
|
||||||
|
|
||||||
type authService interface {
|
type authService interface {
|
||||||
Register(ctx context.Context, username, password string) (auth.User, error)
|
Register(ctx context.Context, email, password string) (auth.User, error)
|
||||||
Login(ctx context.Context, username, password string) (auth.Session, error)
|
Login(ctx context.Context, email, password string) (auth.Session, error)
|
||||||
Refresh(ctx context.Context, refreshToken string) (auth.Session, error)
|
Refresh(ctx context.Context, refreshToken string) (auth.Session, error)
|
||||||
Logout(ctx context.Context, refreshToken string) error
|
Logout(ctx context.Context, refreshToken string) error
|
||||||
User(ctx context.Context, id int64) (auth.User, error)
|
User(ctx context.Context, id int64) (auth.User, error)
|
||||||
ChangePassword(ctx context.Context, userID int64, current, next string) error
|
ChangePassword(ctx context.Context, userID int64, current, next string) error
|
||||||
ListUsers(ctx context.Context) ([]auth.User, error)
|
ListUsers(ctx context.Context) ([]auth.User, error)
|
||||||
CreateUser(ctx context.Context, username, password string, isAdmin bool) (auth.User, error)
|
CreateUser(ctx context.Context, email, password string, isAdmin bool) (auth.User, error)
|
||||||
SetAdmin(ctx context.Context, id int64, isAdmin bool) (auth.User, error)
|
SetAdmin(ctx context.Context, id int64, isAdmin bool) (auth.User, error)
|
||||||
ResetPassword(ctx context.Context, id int64, password string) error
|
ResetPassword(ctx context.Context, id int64, password string) error
|
||||||
DeleteUser(ctx context.Context, id int64) error
|
DeleteUser(ctx context.Context, id int64) error
|
||||||
|
|
|
||||||
|
|
@ -105,7 +105,7 @@ func TestTasteIsPrivate(t *testing.T) {
|
||||||
e := newTasteEnv(t)
|
e := newTasteEnv(t)
|
||||||
e.listen(t, e.admin, e.trackOf(t, "Alpha"), "complete", 1000, "a1")
|
e.listen(t, e.admin, e.trackOf(t, "Alpha"), "complete", 1000, "a1")
|
||||||
|
|
||||||
body := map[string]any{"username": "bob", "password": "longenough"}
|
body := map[string]any{"email": "bob@example.org", "password": "longenough"}
|
||||||
if r := do(t, e.h, "POST", "/api/v1/users", e.admin, body); r.Code != http.StatusCreated {
|
if r := do(t, e.h, "POST", "/api/v1/users", e.admin, body); r.Code != http.StatusCreated {
|
||||||
t.Fatalf("create bob: %d %v", r.Code, r.Body)
|
t.Fatalf("create bob: %d %v", r.Code, r.Body)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -43,7 +43,7 @@ func TestSettingsStartOffAndStayMine(t *testing.T) {
|
||||||
}
|
}
|
||||||
|
|
||||||
// Another user has their own.
|
// Another user has their own.
|
||||||
cred := map[string]any{"username": "bob", "password": "longenough"}
|
cred := map[string]any{"email": "bob@example.org", "password": "longenough"}
|
||||||
if c := do(t, h, "POST", "/api/v1/users", alice, cred); c.Code != http.StatusCreated {
|
if c := do(t, h, "POST", "/api/v1/users", alice, cred); c.Code != http.StatusCreated {
|
||||||
t.Fatalf("create bob: %d %v", c.Code, c.Body)
|
t.Fatalf("create bob: %d %v", c.Code, c.Body)
|
||||||
}
|
}
|
||||||
|
|
@ -119,7 +119,7 @@ func TestSettingsAcceptOnlyOneExactObject(t *testing.T) {
|
||||||
func TestSettingsOfADeletedAccountAreRefused(t *testing.T) {
|
func TestSettingsOfADeletedAccountAreRefused(t *testing.T) {
|
||||||
h := newTestAPI(t)
|
h := newTestAPI(t)
|
||||||
admin := registerAndLogin(t, h)
|
admin := registerAndLogin(t, h)
|
||||||
cred := map[string]any{"username": "bob", "password": "longenough"}
|
cred := map[string]any{"email": "bob@example.org", "password": "longenough"}
|
||||||
created := do(t, h, "POST", "/api/v1/users", admin, cred)
|
created := do(t, h, "POST", "/api/v1/users", admin, cred)
|
||||||
if created.Code != http.StatusCreated {
|
if created.Code != http.StatusCreated {
|
||||||
t.Fatalf("create bob: %d %v", created.Code, created.Body)
|
t.Fatalf("create bob: %d %v", created.Code, created.Body)
|
||||||
|
|
|
||||||
|
|
@ -96,7 +96,7 @@ paths:
|
||||||
application/json:
|
application/json:
|
||||||
schema: {$ref: '#/components/schemas/Error'}
|
schema: {$ref: '#/components/schemas/Error'}
|
||||||
'409':
|
'409':
|
||||||
description: The username is taken (`username_taken`).
|
description: The email is already registered (`email_taken`).
|
||||||
content:
|
content:
|
||||||
application/json:
|
application/json:
|
||||||
schema: {$ref: '#/components/schemas/Error'}
|
schema: {$ref: '#/components/schemas/Error'}
|
||||||
|
|
@ -119,7 +119,7 @@ paths:
|
||||||
schema: {$ref: '#/components/schemas/Session'}
|
schema: {$ref: '#/components/schemas/Session'}
|
||||||
'400': {$ref: '#/components/responses/InvalidInput'}
|
'400': {$ref: '#/components/responses/InvalidInput'}
|
||||||
'401':
|
'401':
|
||||||
description: Wrong username or password (`invalid_credentials`).
|
description: Wrong email or password (`invalid_credentials`).
|
||||||
content:
|
content:
|
||||||
application/json:
|
application/json:
|
||||||
schema: {$ref: '#/components/schemas/Error'}
|
schema: {$ref: '#/components/schemas/Error'}
|
||||||
|
|
@ -249,7 +249,7 @@ paths:
|
||||||
'401': {$ref: '#/components/responses/Unauthorized'}
|
'401': {$ref: '#/components/responses/Unauthorized'}
|
||||||
'403': {$ref: '#/components/responses/AdminRequired'}
|
'403': {$ref: '#/components/responses/AdminRequired'}
|
||||||
'409':
|
'409':
|
||||||
description: The username is taken (`username_taken`).
|
description: The email is already registered (`email_taken`).
|
||||||
content:
|
content:
|
||||||
application/json:
|
application/json:
|
||||||
schema: {$ref: '#/components/schemas/Error'}
|
schema: {$ref: '#/components/schemas/Error'}
|
||||||
|
|
@ -2124,13 +2124,14 @@ components:
|
||||||
|
|
||||||
Credentials:
|
Credentials:
|
||||||
type: object
|
type: object
|
||||||
required: [username, password]
|
required: [email, password]
|
||||||
properties:
|
properties:
|
||||||
username:
|
email:
|
||||||
type: string
|
type: string
|
||||||
minLength: 3
|
maxLength: 254
|
||||||
maxLength: 64
|
description: |
|
||||||
pattern: '^[A-Za-z0-9._-]+$'
|
An address like `name@example.org`, with no display name. It is trimmed and lowercased,
|
||||||
|
and it is unique. Sonda sends no mail and does not check that the address exists.
|
||||||
password:
|
password:
|
||||||
type: string
|
type: string
|
||||||
format: password
|
format: password
|
||||||
|
|
@ -2138,9 +2139,13 @@ components:
|
||||||
|
|
||||||
LoginRequest:
|
LoginRequest:
|
||||||
type: object
|
type: object
|
||||||
required: [username, password]
|
required: [email, password]
|
||||||
properties:
|
properties:
|
||||||
username: {type: string}
|
email:
|
||||||
|
type: string
|
||||||
|
description: |
|
||||||
|
The address of the account, in any case. An account made before addresses were asked
|
||||||
|
for logs in with the plain name it has.
|
||||||
password: {type: string, format: password}
|
password: {type: string, format: password}
|
||||||
|
|
||||||
CreateUser:
|
CreateUser:
|
||||||
|
|
@ -2153,10 +2158,10 @@ components:
|
||||||
User:
|
User:
|
||||||
type: object
|
type: object
|
||||||
additionalProperties: false
|
additionalProperties: false
|
||||||
required: [id, username, is_admin]
|
required: [id, email, is_admin]
|
||||||
properties:
|
properties:
|
||||||
id: {type: integer, format: int64}
|
id: {type: integer, format: int64}
|
||||||
username: {type: string}
|
email: {type: string}
|
||||||
is_admin: {type: boolean}
|
is_admin: {type: boolean}
|
||||||
|
|
||||||
Session:
|
Session:
|
||||||
|
|
|
||||||
|
|
@ -48,7 +48,7 @@ const testSecret = "0123456789abcdef0123456789abcdef"
|
||||||
|
|
||||||
func TestTokenRoundTrip(t *testing.T) {
|
func TestTokenRoundTrip(t *testing.T) {
|
||||||
iss := NewTokenIssuer(testSecret, time.Hour)
|
iss := NewTokenIssuer(testSecret, time.Hour)
|
||||||
tok, exp, err := iss.Issue(User{ID: 7, Username: "bob"})
|
tok, exp, err := iss.Issue(User{ID: 7, Email: "bob"})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
|
|
@ -59,7 +59,7 @@ func TestTokenRoundTrip(t *testing.T) {
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
if claims.UserID != 7 || claims.Username != "bob" {
|
if claims.UserID != 7 || claims.Email != "bob" {
|
||||||
t.Errorf("claims = %+v", claims)
|
t.Errorf("claims = %+v", claims)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -68,7 +68,7 @@ func TestTokenCarriesTheMomentItWasIssued(t *testing.T) {
|
||||||
iss := NewTokenIssuer(testSecret, time.Hour)
|
iss := NewTokenIssuer(testSecret, time.Hour)
|
||||||
at := time.Date(2026, 5, 6, 7, 8, 9, 500_000_000, time.UTC)
|
at := time.Date(2026, 5, 6, 7, 8, 9, 500_000_000, time.UTC)
|
||||||
iss.now = func() time.Time { return at }
|
iss.now = func() time.Time { return at }
|
||||||
tok, _, err := iss.Issue(User{ID: 7, Username: "bob"})
|
tok, _, err := iss.Issue(User{ID: 7, Email: "bob"})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
|
|
@ -84,7 +84,7 @@ func TestTokenCarriesTheMomentItWasIssued(t *testing.T) {
|
||||||
func TestTokenExpired(t *testing.T) {
|
func TestTokenExpired(t *testing.T) {
|
||||||
iss := NewTokenIssuer(testSecret, time.Hour)
|
iss := NewTokenIssuer(testSecret, time.Hour)
|
||||||
iss.now = func() time.Time { return time.Now().Add(-2 * time.Hour) }
|
iss.now = func() time.Time { return time.Now().Add(-2 * time.Hour) }
|
||||||
tok, _, err := iss.Issue(User{ID: 1, Username: "a"})
|
tok, _, err := iss.Issue(User{ID: 1, Email: "a"})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
|
|
@ -95,7 +95,7 @@ func TestTokenExpired(t *testing.T) {
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestTokenWrongSecret(t *testing.T) {
|
func TestTokenWrongSecret(t *testing.T) {
|
||||||
tok, _, _ := NewTokenIssuer(testSecret, time.Hour).Issue(User{ID: 1, Username: "a"})
|
tok, _, _ := NewTokenIssuer(testSecret, time.Hour).Issue(User{ID: 1, Email: "a"})
|
||||||
other := NewTokenIssuer("ffffffffffffffffffffffffffffffff", time.Hour)
|
other := NewTokenIssuer("ffffffffffffffffffffffffffffffff", time.Hour)
|
||||||
if _, err := other.Parse(tok); err == nil {
|
if _, err := other.Parse(tok); err == nil {
|
||||||
t.Fatal("token signed with another secret accepted")
|
t.Fatal("token signed with another secret accepted")
|
||||||
|
|
|
||||||
|
|
@ -10,7 +10,8 @@ import (
|
||||||
"encoding/hex"
|
"encoding/hex"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"regexp"
|
"net/mail"
|
||||||
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
@ -18,15 +19,16 @@ import (
|
||||||
// Errors returned by the service. Handlers map them to HTTP statuses.
|
// Errors returned by the service. Handlers map them to HTTP statuses.
|
||||||
var (
|
var (
|
||||||
ErrInvalidInput = errors.New("invalid input")
|
ErrInvalidInput = errors.New("invalid input")
|
||||||
ErrUsernameTaken = errors.New("username already taken")
|
ErrEmailTaken = errors.New("email already registered")
|
||||||
ErrUserNotFound = errors.New("user not found")
|
ErrUserNotFound = errors.New("user not found")
|
||||||
ErrInvalidCredentials = errors.New("invalid username or password")
|
ErrInvalidCredentials = errors.New("invalid email or password")
|
||||||
ErrRegistrationClosed = errors.New("registration is closed")
|
ErrRegistrationClosed = errors.New("registration is closed")
|
||||||
ErrInvalidRefreshToken = errors.New("invalid refresh token")
|
ErrInvalidRefreshToken = errors.New("invalid refresh token")
|
||||||
ErrLastAdmin = errors.New("cannot remove the last admin")
|
ErrLastAdmin = errors.New("cannot remove the last admin")
|
||||||
)
|
)
|
||||||
|
|
||||||
var usernameRe = regexp.MustCompile(`^[A-Za-z0-9._-]{3,64}$`)
|
// maxEmailLen is the longest address there can be (RFC 5321).
|
||||||
|
const maxEmailLen = 254
|
||||||
|
|
||||||
const (
|
const (
|
||||||
minPasswordLen = 8
|
minPasswordLen = 8
|
||||||
|
|
@ -41,7 +43,7 @@ const RefreshReuseGrace = 10 * time.Second
|
||||||
// User is a local account. The password hash never leaves the store layer.
|
// User is a local account. The password hash never leaves the store layer.
|
||||||
type User struct {
|
type User struct {
|
||||||
ID int64
|
ID int64
|
||||||
Username string
|
Email string
|
||||||
IsAdmin bool
|
IsAdmin bool
|
||||||
CreatedAt time.Time
|
CreatedAt time.Time
|
||||||
}
|
}
|
||||||
|
|
@ -57,10 +59,10 @@ type RefreshToken struct {
|
||||||
type UserStore interface {
|
type UserStore interface {
|
||||||
CountUsers(ctx context.Context) (int, error)
|
CountUsers(ctx context.Context) (int, error)
|
||||||
CountAdmins(ctx context.Context) (int, error)
|
CountAdmins(ctx context.Context) (int, error)
|
||||||
// CreateUser returns ErrUsernameTaken when the name exists (case-insensitive).
|
// CreateUser returns ErrEmailTaken when the address exists (case-insensitive).
|
||||||
CreateUser(ctx context.Context, username, passwordHash string, isAdmin bool) (User, error)
|
CreateUser(ctx context.Context, email, passwordHash string, isAdmin bool) (User, error)
|
||||||
// UserByUsername and UserByID return the password hash too, and ErrUserNotFound.
|
// UserByEmail (case-insensitive) and UserByID return the password hash too, and ErrUserNotFound.
|
||||||
UserByUsername(ctx context.Context, username string) (User, string, error)
|
UserByEmail(ctx context.Context, email string) (User, string, error)
|
||||||
UserByID(ctx context.Context, id int64) (User, string, error)
|
UserByID(ctx context.Context, id int64) (User, string, error)
|
||||||
ListUsers(ctx context.Context) ([]User, error)
|
ListUsers(ctx context.Context) ([]User, error)
|
||||||
// The three below return ErrUserNotFound for an unknown id.
|
// The three below return ErrUserNotFound for an unknown id.
|
||||||
|
|
@ -119,11 +121,16 @@ func NewService(users UserStore, refresh RefreshStore, tokens *TokenIssuer, refr
|
||||||
|
|
||||||
// ---- validation ----
|
// ---- validation ----
|
||||||
|
|
||||||
func validateUsername(username string) error {
|
// normalizeEmail checks the shape of an address and returns it trimmed and lowercased, which is
|
||||||
if !usernameRe.MatchString(username) {
|
// how it is stored and compared. It is only a shape: Sonda sends no mail and does not check that
|
||||||
return fmt.Errorf("%w: username must be 3-64 characters: letters, digits, '.', '_' or '-'", ErrInvalidInput)
|
// the address exists. A display name ("Alice <a@b.c>") is not an address.
|
||||||
|
func normalizeEmail(email string) (string, error) {
|
||||||
|
email = strings.ToLower(strings.TrimSpace(email))
|
||||||
|
a, err := mail.ParseAddress(email)
|
||||||
|
if err != nil || a.Address != email || len(email) > maxEmailLen {
|
||||||
|
return "", fmt.Errorf("%w: email must be an address like name@example.org", ErrInvalidInput)
|
||||||
}
|
}
|
||||||
return nil
|
return email, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func validatePassword(password string) error {
|
func validatePassword(password string) error {
|
||||||
|
|
@ -137,8 +144,9 @@ func validatePassword(password string) error {
|
||||||
|
|
||||||
// Register creates the first user, who becomes the admin. Once any user
|
// Register creates the first user, who becomes the admin. Once any user
|
||||||
// exists, registration is closed: admins create further accounts.
|
// exists, registration is closed: admins create further accounts.
|
||||||
func (s *Service) Register(ctx context.Context, username, password string) (User, error) {
|
func (s *Service) Register(ctx context.Context, email, password string) (User, error) {
|
||||||
if err := validateUsername(username); err != nil {
|
email, err := normalizeEmail(email)
|
||||||
|
if err != nil {
|
||||||
return User{}, err
|
return User{}, err
|
||||||
}
|
}
|
||||||
if err := validatePassword(password); err != nil {
|
if err := validatePassword(password); err != nil {
|
||||||
|
|
@ -159,13 +167,16 @@ func (s *Service) Register(ctx context.Context, username, password string) (User
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return User{}, err
|
return User{}, err
|
||||||
}
|
}
|
||||||
return s.users.CreateUser(ctx, username, hash, true)
|
return s.users.CreateUser(ctx, email, hash, true)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Login checks the credentials and opens a session.
|
// Login checks the credentials and opens a session.
|
||||||
// Unknown user and wrong password are indistinguishable to the caller.
|
// Unknown user and wrong password are indistinguishable to the caller.
|
||||||
func (s *Service) Login(ctx context.Context, username, password string) (Session, error) {
|
//
|
||||||
user, hash, err := s.users.UserByUsername(ctx, username)
|
// The address is not checked for its shape: an account made before addresses were asked for
|
||||||
|
// logs in with the plain name it has.
|
||||||
|
func (s *Service) Login(ctx context.Context, email, password string) (Session, error) {
|
||||||
|
user, hash, err := s.users.UserByEmail(ctx, strings.ToLower(strings.TrimSpace(email)))
|
||||||
if errors.Is(err, ErrUserNotFound) {
|
if errors.Is(err, ErrUserNotFound) {
|
||||||
// Spend the same time as a real check to avoid revealing which names exist.
|
// Spend the same time as a real check to avoid revealing which names exist.
|
||||||
VerifyPassword(s.fakeHash(), password)
|
VerifyPassword(s.fakeHash(), password)
|
||||||
|
|
@ -302,8 +313,9 @@ func (s *Service) ListUsers(ctx context.Context) ([]User, error) {
|
||||||
}
|
}
|
||||||
|
|
||||||
// CreateUser creates an account. Callers must have checked that the actor is an admin.
|
// CreateUser creates an account. Callers must have checked that the actor is an admin.
|
||||||
func (s *Service) CreateUser(ctx context.Context, username, password string, isAdmin bool) (User, error) {
|
func (s *Service) CreateUser(ctx context.Context, email, password string, isAdmin bool) (User, error) {
|
||||||
if err := validateUsername(username); err != nil {
|
email, err := normalizeEmail(email)
|
||||||
|
if err != nil {
|
||||||
return User{}, err
|
return User{}, err
|
||||||
}
|
}
|
||||||
if err := validatePassword(password); err != nil {
|
if err := validatePassword(password); err != nil {
|
||||||
|
|
@ -313,7 +325,7 @@ func (s *Service) CreateUser(ctx context.Context, username, password string, isA
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return User{}, err
|
return User{}, err
|
||||||
}
|
}
|
||||||
return s.users.CreateUser(ctx, username, hash, isAdmin)
|
return s.users.CreateUser(ctx, email, hash, isAdmin)
|
||||||
}
|
}
|
||||||
|
|
||||||
// SetAdmin grants or removes the admin role. The last admin cannot be demoted.
|
// SetAdmin grants or removes the admin role. The last admin cannot be demoted.
|
||||||
|
|
|
||||||
|
|
@ -34,9 +34,9 @@ func newFakeStore() *fakeStore {
|
||||||
return &fakeStore{users: map[int64]*fakeUserRow{}, tokens: map[string]*fakeRefreshRow{}}
|
return &fakeStore{users: map[int64]*fakeUserRow{}, tokens: map[string]*fakeRefreshRow{}}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *fakeStore) find(username string) *fakeUserRow {
|
func (f *fakeStore) find(email string) *fakeUserRow {
|
||||||
for _, r := range f.users {
|
for _, r := range f.users {
|
||||||
if strings.EqualFold(r.u.Username, username) {
|
if strings.EqualFold(r.u.Email, email) {
|
||||||
return r
|
return r
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -55,18 +55,18 @@ func (f *fakeStore) CountAdmins(context.Context) (int, error) {
|
||||||
return n, nil
|
return n, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *fakeStore) CreateUser(_ context.Context, username, hash string, isAdmin bool) (User, error) {
|
func (f *fakeStore) CreateUser(_ context.Context, email, hash string, isAdmin bool) (User, error) {
|
||||||
if f.find(username) != nil {
|
if f.find(email) != nil {
|
||||||
return User{}, ErrUsernameTaken
|
return User{}, ErrEmailTaken
|
||||||
}
|
}
|
||||||
f.nextID++
|
f.nextID++
|
||||||
u := User{ID: f.nextID, Username: username, IsAdmin: isAdmin, CreatedAt: time.Now()}
|
u := User{ID: f.nextID, Email: email, IsAdmin: isAdmin, CreatedAt: time.Now()}
|
||||||
f.users[u.ID] = &fakeUserRow{u: u, hash: hash}
|
f.users[u.ID] = &fakeUserRow{u: u, hash: hash}
|
||||||
return u, nil
|
return u, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *fakeStore) UserByUsername(_ context.Context, username string) (User, string, error) {
|
func (f *fakeStore) UserByEmail(_ context.Context, email string) (User, string, error) {
|
||||||
r := f.find(username)
|
r := f.find(email)
|
||||||
if r == nil {
|
if r == nil {
|
||||||
return User{}, "", ErrUserNotFound
|
return User{}, "", ErrUserNotFound
|
||||||
}
|
}
|
||||||
|
|
@ -171,7 +171,7 @@ func newTestService() (*Service, *fakeStore) {
|
||||||
func bootstrap(t *testing.T) (*Service, *fakeStore, User) {
|
func bootstrap(t *testing.T) (*Service, *fakeStore, User) {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
s, st := newTestService()
|
s, st := newTestService()
|
||||||
u, err := s.Register(context.Background(), "alice", "longenough")
|
u, err := s.Register(context.Background(), "alice@example.org", "longenough")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
|
|
@ -185,7 +185,7 @@ func TestRegisterFirstUserIsAdminThenClosed(t *testing.T) {
|
||||||
if !u.IsAdmin {
|
if !u.IsAdmin {
|
||||||
t.Error("the first user must be an admin")
|
t.Error("the first user must be an admin")
|
||||||
}
|
}
|
||||||
if _, err := s.Register(context.Background(), "bob", "longenough"); !errors.Is(err, ErrRegistrationClosed) {
|
if _, err := s.Register(context.Background(), "bob@example.org", "longenough"); !errors.Is(err, ErrRegistrationClosed) {
|
||||||
t.Fatalf("err = %v, want ErrRegistrationClosed", err)
|
t.Fatalf("err = %v, want ErrRegistrationClosed", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -194,11 +194,16 @@ func TestRegisterValidation(t *testing.T) {
|
||||||
tests := []struct {
|
tests := []struct {
|
||||||
name, user, pass string
|
name, user, pass string
|
||||||
}{
|
}{
|
||||||
{"short username", "ab", "longenough"},
|
{"no address", "", "longenough"},
|
||||||
{"long username", strings.Repeat("a", 65), "longenough"},
|
{"a name, not an address", "alice", "longenough"},
|
||||||
{"bad chars", "bad name!", "longenough"},
|
{"no domain", "alice@", "longenough"},
|
||||||
{"short password", "alice", "short"},
|
{"no name", "@example.org", "longenough"},
|
||||||
{"huge password", "alice", strings.Repeat("x", 300)},
|
{"two at signs", "a@b@example.org", "longenough"},
|
||||||
|
{"a space", "al ice@example.org", "longenough"},
|
||||||
|
{"a display name", "Alice <alice@example.org>", "longenough"},
|
||||||
|
{"too long", strings.Repeat("a", 250) + "@example.org", "longenough"},
|
||||||
|
{"short password", "alice@example.org", "short"},
|
||||||
|
{"huge password", "alice@example.org", strings.Repeat("x", 300)},
|
||||||
}
|
}
|
||||||
for _, tt := range tests {
|
for _, tt := range tests {
|
||||||
t.Run(tt.name, func(t *testing.T) {
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
|
@ -214,11 +219,11 @@ func TestLoginIssuesBothTokens(t *testing.T) {
|
||||||
s, _, _ := bootstrap(t)
|
s, _, _ := bootstrap(t)
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
|
|
||||||
sess, err := s.Login(ctx, "ALICE", "longenough") // usernames are case-insensitive
|
sess, err := s.Login(ctx, "ALICE@Example.org", "longenough") // addresses are case-insensitive
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
if sess.AccessToken == "" || sess.RefreshToken == "" || sess.User.Username != "alice" || !sess.User.IsAdmin {
|
if sess.AccessToken == "" || sess.RefreshToken == "" || sess.User.Email != "alice@example.org" || !sess.User.IsAdmin {
|
||||||
t.Fatalf("session = %+v", sess)
|
t.Fatalf("session = %+v", sess)
|
||||||
}
|
}
|
||||||
if !sess.RefreshExpiresAt.After(sess.AccessExpiresAt) {
|
if !sess.RefreshExpiresAt.After(sess.AccessExpiresAt) {
|
||||||
|
|
@ -228,7 +233,7 @@ func TestLoginIssuesBothTokens(t *testing.T) {
|
||||||
t.Errorf("access token does not verify: %v", err)
|
t.Errorf("access token does not verify: %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
if _, err := s.Login(ctx, "alice", "wrongpass1"); !errors.Is(err, ErrInvalidCredentials) {
|
if _, err := s.Login(ctx, "alice@example.org", "wrongpass1"); !errors.Is(err, ErrInvalidCredentials) {
|
||||||
t.Errorf("wrong password: err = %v", err)
|
t.Errorf("wrong password: err = %v", err)
|
||||||
}
|
}
|
||||||
if _, err := s.Login(ctx, "nobody", "longenough"); !errors.Is(err, ErrInvalidCredentials) {
|
if _, err := s.Login(ctx, "nobody", "longenough"); !errors.Is(err, ErrInvalidCredentials) {
|
||||||
|
|
@ -238,7 +243,7 @@ func TestLoginIssuesBothTokens(t *testing.T) {
|
||||||
|
|
||||||
func TestRefreshTokenIsStoredHashed(t *testing.T) {
|
func TestRefreshTokenIsStoredHashed(t *testing.T) {
|
||||||
s, st, _ := bootstrap(t)
|
s, st, _ := bootstrap(t)
|
||||||
sess, _ := s.Login(context.Background(), "alice", "longenough")
|
sess, _ := s.Login(context.Background(), "alice@example.org", "longenough")
|
||||||
if _, ok := st.tokens[sess.RefreshToken]; ok {
|
if _, ok := st.tokens[sess.RefreshToken]; ok {
|
||||||
t.Fatal("the raw refresh token is stored; only its hash may be")
|
t.Fatal("the raw refresh token is stored; only its hash may be")
|
||||||
}
|
}
|
||||||
|
|
@ -252,13 +257,13 @@ func TestRefreshTokenIsStoredHashed(t *testing.T) {
|
||||||
func TestRefreshRotates(t *testing.T) {
|
func TestRefreshRotates(t *testing.T) {
|
||||||
s, _, _ := bootstrap(t)
|
s, _, _ := bootstrap(t)
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
first, _ := s.Login(ctx, "alice", "longenough")
|
first, _ := s.Login(ctx, "alice@example.org", "longenough")
|
||||||
|
|
||||||
second, err := s.Refresh(ctx, first.RefreshToken)
|
second, err := s.Refresh(ctx, first.RefreshToken)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
if second.RefreshToken == first.RefreshToken || second.AccessToken == "" || second.User.Username != "alice" {
|
if second.RefreshToken == first.RefreshToken || second.AccessToken == "" || second.User.Email != "alice@example.org" {
|
||||||
t.Fatalf("second = %+v", second)
|
t.Fatalf("second = %+v", second)
|
||||||
}
|
}
|
||||||
// The new token works.
|
// The new token works.
|
||||||
|
|
@ -270,7 +275,7 @@ func TestRefreshRotates(t *testing.T) {
|
||||||
func TestReusedRefreshTokenRevokesEverySession(t *testing.T) {
|
func TestReusedRefreshTokenRevokesEverySession(t *testing.T) {
|
||||||
s, _, _ := bootstrap(t)
|
s, _, _ := bootstrap(t)
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
first, _ := s.Login(ctx, "alice", "longenough")
|
first, _ := s.Login(ctx, "alice@example.org", "longenough")
|
||||||
second, _ := s.Refresh(ctx, first.RefreshToken)
|
second, _ := s.Refresh(ctx, first.RefreshToken)
|
||||||
|
|
||||||
// Well after the grace window, presenting the rotated token looks like theft.
|
// Well after the grace window, presenting the rotated token looks like theft.
|
||||||
|
|
@ -289,7 +294,7 @@ func TestReusedRefreshTokenRevokesEverySession(t *testing.T) {
|
||||||
func TestReplayInsideTheGraceWindowKeepsTheNewToken(t *testing.T) {
|
func TestReplayInsideTheGraceWindowKeepsTheNewToken(t *testing.T) {
|
||||||
s, _, _ := bootstrap(t)
|
s, _, _ := bootstrap(t)
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
first, _ := s.Login(ctx, "alice", "longenough")
|
first, _ := s.Login(ctx, "alice@example.org", "longenough")
|
||||||
second, err := s.Refresh(ctx, first.RefreshToken)
|
second, err := s.Refresh(ctx, first.RefreshToken)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
|
|
@ -306,7 +311,7 @@ func TestReplayInsideTheGraceWindowKeepsTheNewToken(t *testing.T) {
|
||||||
func TestRefreshRejectsExpiredUnknownAndEmpty(t *testing.T) {
|
func TestRefreshRejectsExpiredUnknownAndEmpty(t *testing.T) {
|
||||||
s, _, _ := bootstrap(t)
|
s, _, _ := bootstrap(t)
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
sess, _ := s.Login(ctx, "alice", "longenough")
|
sess, _ := s.Login(ctx, "alice@example.org", "longenough")
|
||||||
|
|
||||||
for _, tok := range []string{"", "not-a-token", strings.Repeat("a", 43)} {
|
for _, tok := range []string{"", "not-a-token", strings.Repeat("a", 43)} {
|
||||||
if _, err := s.Refresh(ctx, tok); !errors.Is(err, ErrInvalidRefreshToken) {
|
if _, err := s.Refresh(ctx, tok); !errors.Is(err, ErrInvalidRefreshToken) {
|
||||||
|
|
@ -323,11 +328,11 @@ func TestRefreshRejectsExpiredUnknownAndEmpty(t *testing.T) {
|
||||||
func TestRefreshFailsForDeletedUser(t *testing.T) {
|
func TestRefreshFailsForDeletedUser(t *testing.T) {
|
||||||
s, _, admin := bootstrap(t)
|
s, _, admin := bootstrap(t)
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
bob, err := s.CreateUser(ctx, "bob", "longenough", false)
|
bob, err := s.CreateUser(ctx, "bob@example.org", "longenough", false)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
bobSess, _ := s.Login(ctx, "bob", "longenough")
|
bobSess, _ := s.Login(ctx, "bob@example.org", "longenough")
|
||||||
|
|
||||||
if err := s.DeleteUser(ctx, bob.ID); err != nil {
|
if err := s.DeleteUser(ctx, bob.ID); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
|
|
@ -343,7 +348,7 @@ func TestRefreshFailsForDeletedUser(t *testing.T) {
|
||||||
func TestLogoutRevokesTheToken(t *testing.T) {
|
func TestLogoutRevokesTheToken(t *testing.T) {
|
||||||
s, _, _ := bootstrap(t)
|
s, _, _ := bootstrap(t)
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
sess, _ := s.Login(ctx, "alice", "longenough")
|
sess, _ := s.Login(ctx, "alice@example.org", "longenough")
|
||||||
|
|
||||||
if err := s.Logout(ctx, sess.RefreshToken); err != nil {
|
if err := s.Logout(ctx, sess.RefreshToken); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
|
|
@ -363,7 +368,7 @@ func TestLogoutRevokesTheToken(t *testing.T) {
|
||||||
func TestChangePassword(t *testing.T) {
|
func TestChangePassword(t *testing.T) {
|
||||||
s, _, u := bootstrap(t)
|
s, _, u := bootstrap(t)
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
sess, _ := s.Login(ctx, "alice", "longenough")
|
sess, _ := s.Login(ctx, "alice@example.org", "longenough")
|
||||||
|
|
||||||
if err := s.ChangePassword(ctx, u.ID, "wrong-current", "brandnewpass"); !errors.Is(err, ErrInvalidCredentials) {
|
if err := s.ChangePassword(ctx, u.ID, "wrong-current", "brandnewpass"); !errors.Is(err, ErrInvalidCredentials) {
|
||||||
t.Fatalf("wrong current: err = %v", err)
|
t.Fatalf("wrong current: err = %v", err)
|
||||||
|
|
@ -375,10 +380,10 @@ func TestChangePassword(t *testing.T) {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
if _, err := s.Login(ctx, "alice", "longenough"); !errors.Is(err, ErrInvalidCredentials) {
|
if _, err := s.Login(ctx, "alice@example.org", "longenough"); !errors.Is(err, ErrInvalidCredentials) {
|
||||||
t.Error("old password still works")
|
t.Error("old password still works")
|
||||||
}
|
}
|
||||||
if _, err := s.Login(ctx, "alice", "brandnewpass"); err != nil {
|
if _, err := s.Login(ctx, "alice@example.org", "brandnewpass"); err != nil {
|
||||||
t.Errorf("new password: %v", err)
|
t.Errorf("new password: %v", err)
|
||||||
}
|
}
|
||||||
if _, err := s.Refresh(ctx, sess.RefreshToken); !errors.Is(err, ErrInvalidRefreshToken) {
|
if _, err := s.Refresh(ctx, sess.RefreshToken); !errors.Is(err, ErrInvalidRefreshToken) {
|
||||||
|
|
@ -392,18 +397,18 @@ func TestAdminCreateAndListUsers(t *testing.T) {
|
||||||
s, _, _ := bootstrap(t)
|
s, _, _ := bootstrap(t)
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
|
|
||||||
bob, err := s.CreateUser(ctx, "bob", "longenough", false)
|
bob, err := s.CreateUser(ctx, "bob@example.org", "longenough", false)
|
||||||
if err != nil || bob.IsAdmin {
|
if err != nil || bob.IsAdmin {
|
||||||
t.Fatalf("bob = %+v err=%v", bob, err)
|
t.Fatalf("bob = %+v err=%v", bob, err)
|
||||||
}
|
}
|
||||||
if _, err := s.CreateUser(ctx, "BOB", "longenough", false); !errors.Is(err, ErrUsernameTaken) {
|
if _, err := s.CreateUser(ctx, "BOB@example.org", "longenough", false); !errors.Is(err, ErrEmailTaken) {
|
||||||
t.Errorf("duplicate: err = %v", err)
|
t.Errorf("duplicate: err = %v", err)
|
||||||
}
|
}
|
||||||
if _, err := s.CreateUser(ctx, "x", "longenough", false); !errors.Is(err, ErrInvalidInput) {
|
if _, err := s.CreateUser(ctx, "x", "longenough", false); !errors.Is(err, ErrInvalidInput) {
|
||||||
t.Errorf("bad username: err = %v", err)
|
t.Errorf("bad email: err = %v", err)
|
||||||
}
|
}
|
||||||
users, err := s.ListUsers(ctx)
|
users, err := s.ListUsers(ctx)
|
||||||
if err != nil || len(users) != 2 || users[0].Username != "alice" || users[1].Username != "bob" {
|
if err != nil || len(users) != 2 || users[0].Email != "alice@example.org" || users[1].Email != "bob@example.org" {
|
||||||
t.Fatalf("users = %+v err=%v", users, err)
|
t.Fatalf("users = %+v err=%v", users, err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -411,7 +416,7 @@ func TestAdminCreateAndListUsers(t *testing.T) {
|
||||||
func TestSetAdminAndLastAdminGuard(t *testing.T) {
|
func TestSetAdminAndLastAdminGuard(t *testing.T) {
|
||||||
s, _, alice := bootstrap(t)
|
s, _, alice := bootstrap(t)
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
bob, _ := s.CreateUser(ctx, "bob", "longenough", false)
|
bob, _ := s.CreateUser(ctx, "bob@example.org", "longenough", false)
|
||||||
|
|
||||||
// The only admin cannot be demoted.
|
// The only admin cannot be demoted.
|
||||||
if _, err := s.SetAdmin(ctx, alice.ID, false); !errors.Is(err, ErrLastAdmin) {
|
if _, err := s.SetAdmin(ctx, alice.ID, false); !errors.Is(err, ErrLastAdmin) {
|
||||||
|
|
@ -438,7 +443,7 @@ func TestSetAdminAndLastAdminGuard(t *testing.T) {
|
||||||
func TestDeleteUserGuards(t *testing.T) {
|
func TestDeleteUserGuards(t *testing.T) {
|
||||||
s, _, alice := bootstrap(t)
|
s, _, alice := bootstrap(t)
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
bob, _ := s.CreateUser(ctx, "bob", "longenough", false)
|
bob, _ := s.CreateUser(ctx, "bob@example.org", "longenough", false)
|
||||||
|
|
||||||
if err := s.DeleteUser(ctx, alice.ID); !errors.Is(err, ErrLastAdmin) {
|
if err := s.DeleteUser(ctx, alice.ID); !errors.Is(err, ErrLastAdmin) {
|
||||||
t.Fatalf("deleting the last admin: err = %v", err)
|
t.Fatalf("deleting the last admin: err = %v", err)
|
||||||
|
|
@ -454,8 +459,8 @@ func TestDeleteUserGuards(t *testing.T) {
|
||||||
func TestResetPasswordRevokesSessions(t *testing.T) {
|
func TestResetPasswordRevokesSessions(t *testing.T) {
|
||||||
s, _, _ := bootstrap(t)
|
s, _, _ := bootstrap(t)
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
bob, _ := s.CreateUser(ctx, "bob", "longenough", false)
|
bob, _ := s.CreateUser(ctx, "bob@example.org", "longenough", false)
|
||||||
sess, _ := s.Login(ctx, "bob", "longenough")
|
sess, _ := s.Login(ctx, "bob@example.org", "longenough")
|
||||||
|
|
||||||
if err := s.ResetPassword(ctx, bob.ID, "short"); !errors.Is(err, ErrInvalidInput) {
|
if err := s.ResetPassword(ctx, bob.ID, "short"); !errors.Is(err, ErrInvalidInput) {
|
||||||
t.Fatalf("weak password: err = %v", err)
|
t.Fatalf("weak password: err = %v", err)
|
||||||
|
|
@ -463,7 +468,7 @@ func TestResetPasswordRevokesSessions(t *testing.T) {
|
||||||
if err := s.ResetPassword(ctx, bob.ID, "resetpassword"); err != nil {
|
if err := s.ResetPassword(ctx, bob.ID, "resetpassword"); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
if _, err := s.Login(ctx, "bob", "resetpassword"); err != nil {
|
if _, err := s.Login(ctx, "bob@example.org", "resetpassword"); err != nil {
|
||||||
t.Errorf("login with the reset password: %v", err)
|
t.Errorf("login with the reset password: %v", err)
|
||||||
}
|
}
|
||||||
if _, err := s.Refresh(ctx, sess.RefreshToken); !errors.Is(err, ErrInvalidRefreshToken) {
|
if _, err := s.Refresh(ctx, sess.RefreshToken); !errors.Is(err, ErrInvalidRefreshToken) {
|
||||||
|
|
@ -477,10 +482,40 @@ func TestResetPasswordRevokesSessions(t *testing.T) {
|
||||||
func TestUserLookup(t *testing.T) {
|
func TestUserLookup(t *testing.T) {
|
||||||
s, _, alice := bootstrap(t)
|
s, _, alice := bootstrap(t)
|
||||||
u, err := s.User(context.Background(), alice.ID)
|
u, err := s.User(context.Background(), alice.ID)
|
||||||
if err != nil || u.Username != "alice" || !u.IsAdmin {
|
if err != nil || u.Email != "alice@example.org" || !u.IsAdmin {
|
||||||
t.Fatalf("u = %+v err=%v", u, err)
|
t.Fatalf("u = %+v err=%v", u, err)
|
||||||
}
|
}
|
||||||
if _, err := s.User(context.Background(), 999); !errors.Is(err, ErrUserNotFound) {
|
if _, err := s.User(context.Background(), 999); !errors.Is(err, ErrUserNotFound) {
|
||||||
t.Errorf("err = %v", err)
|
t.Errorf("err = %v", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestAnAddressIsTrimmedAndLowercased(t *testing.T) {
|
||||||
|
s, _ := newTestService()
|
||||||
|
ctx := context.Background()
|
||||||
|
u, err := s.Register(ctx, " Alice@Example.ORG ", "longenough")
|
||||||
|
if err != nil || u.Email != "alice@example.org" {
|
||||||
|
t.Fatalf("user = %+v err = %v", u, err)
|
||||||
|
}
|
||||||
|
if _, err := s.Login(ctx, " ALICE@example.org", "longenough"); err != nil {
|
||||||
|
t.Errorf("login with another spelling: %v", err)
|
||||||
|
}
|
||||||
|
if _, err := s.CreateUser(ctx, "alice@EXAMPLE.org", "longenough", false); !errors.Is(err, ErrEmailTaken) {
|
||||||
|
t.Errorf("same address, other case: err = %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Accounts made before addresses were asked for have a plain name: it stays their login.
|
||||||
|
func TestAnOldAccountNameStillLogsIn(t *testing.T) {
|
||||||
|
s, st := newTestService()
|
||||||
|
hash, err := HashPassword("longenough")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := st.CreateUser(context.Background(), "olduser", hash, true); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := s.Login(context.Background(), "OldUser", "longenough"); err != nil {
|
||||||
|
t.Errorf("an old name no longer logs in: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -12,15 +12,15 @@ const tokenIssuerName = "sonda"
|
||||||
|
|
||||||
// Claims is what a valid access token tells us about the caller.
|
// Claims is what a valid access token tells us about the caller.
|
||||||
type Claims struct {
|
type Claims struct {
|
||||||
UserID int64
|
UserID int64
|
||||||
Username string
|
Email string
|
||||||
// IssuedAt is when the token was signed. An account created after that moment
|
// IssuedAt is when the token was signed. An account created after that moment
|
||||||
// cannot be the one the token was issued for.
|
// cannot be the one the token was issued for.
|
||||||
IssuedAt time.Time
|
IssuedAt time.Time
|
||||||
}
|
}
|
||||||
|
|
||||||
type tokenClaims struct {
|
type tokenClaims struct {
|
||||||
Username string `json:"username"`
|
Email string `json:"email"`
|
||||||
jwt.RegisteredClaims
|
jwt.RegisteredClaims
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -40,7 +40,7 @@ func NewTokenIssuer(secret string, ttl time.Duration) *TokenIssuer {
|
||||||
func (i *TokenIssuer) Issue(user User) (string, time.Time, error) {
|
func (i *TokenIssuer) Issue(user User) (string, time.Time, error) {
|
||||||
now := i.now()
|
now := i.now()
|
||||||
exp := now.Add(i.ttl)
|
exp := now.Add(i.ttl)
|
||||||
claims := tokenClaims{Username: user.Username,
|
claims := tokenClaims{Email: user.Email,
|
||||||
Issuer: tokenIssuerName,
|
Issuer: tokenIssuerName,
|
||||||
Subject: strconv.FormatInt(user.ID, 10),
|
Subject: strconv.FormatInt(user.ID, 10),
|
||||||
IssuedAt: jwt.NewNumericDate(now),
|
IssuedAt: jwt.NewNumericDate(now),
|
||||||
|
|
@ -74,5 +74,5 @@ func (i *TokenIssuer) Parse(token string) (Claims, error) {
|
||||||
if tc.IssuedAt != nil {
|
if tc.IssuedAt != nil {
|
||||||
issued = tc.IssuedAt.Time
|
issued = tc.IssuedAt.Time
|
||||||
}
|
}
|
||||||
return Claims{UserID: id, Username: tc.Username, IssuedAt: issued}, nil
|
return Claims{UserID: id, Email: tc.Email, IssuedAt: issued}, nil
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -31,12 +31,12 @@ func TestUserRepoRolesAndLookup(t *testing.T) {
|
||||||
t.Errorf("CountAdmins = %d, want 1", n)
|
t.Errorf("CountAdmins = %d, want 1", n)
|
||||||
}
|
}
|
||||||
got, hash, err := repo.UserByID(ctx, bob.ID)
|
got, hash, err := repo.UserByID(ctx, bob.ID)
|
||||||
if err != nil || got.Username != "bob" || hash != "h2" || got.IsAdmin {
|
if err != nil || got.Email != "bob" || hash != "h2" || got.IsAdmin {
|
||||||
t.Errorf("UserByID = %+v %q err=%v", got, hash, err)
|
t.Errorf("UserByID = %+v %q err=%v", got, hash, err)
|
||||||
}
|
}
|
||||||
byName, _, _ := repo.UserByUsername(ctx, "ALICE")
|
byName, _, _ := repo.UserByEmail(ctx, "ALICE")
|
||||||
if !byName.IsAdmin {
|
if !byName.IsAdmin {
|
||||||
t.Error("UserByUsername lost the admin flag")
|
t.Error("UserByEmail lost the admin flag")
|
||||||
}
|
}
|
||||||
|
|
||||||
list, err := repo.ListUsers(ctx)
|
list, err := repo.ListUsers(ctx)
|
||||||
|
|
|
||||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue