feat(auth): add refresh tokens, admin role and user management

- feat(auth): short-lived access tokens plus rotating refresh tokens stored as
  SHA-256 hashes; replaying a spent token revokes every session of that user
- feat(auth): is_admin flag; the first registered user is the admin and the
  last admin can be neither demoted nor deleted
- feat(api): POST /auth/refresh, /auth/logout, /auth/password and GET /auth/me
- feat(api): admin-only GET/POST /users, PATCH /users/{id}, PUT
  /users/{id}/password and DELETE /users/{id}; the admin check reads the role
  from the database on every call
- feat(api): starting a library scan is now admin-only
- feat(storage): users and refresh token repositories for SQLite and
  PostgreSQL (migration 0004; the oldest existing account becomes admin)
- feat(config): auth.access_ttl_minutes and auth.refresh_ttl_hours replace
  auth.token_ttl_hours
- test: rotation, reuse detection, concurrent rotation with a single winner,
  admin rules, role changes taking effect immediately
This commit is contained in:
tgiachi 2026-11-11 12:38:42 +01:00
commit dbe9338af3
20 changed files with 1883 additions and 187 deletions

View file

@ -79,7 +79,7 @@ func run() error {
}
// Composition root: build services and hand them to the HTTP layer.
tokens := auth.NewTokenIssuer(cfg.Auth.JWTSecret, cfg.Auth.TokenTTL())
tokens := auth.NewTokenIssuer(cfg.Auth.JWTSecret, cfg.Auth.AccessTTL())
if cfg.Log.Env == "production" {
gin.SetMode(gin.ReleaseMode)
}
@ -93,7 +93,7 @@ func run() error {
router := httpapi.NewRouter(httpapi.Deps{
Logger: logger,
Auth: auth.NewService(storage.NewUserRepo(db), tokens),
Auth: auth.NewService(storage.NewUserRepo(db), storage.NewRefreshRepo(db), tokens, cfg.Auth.RefreshTTL()),
Tokens: tokens,
Listening: listening.NewService(storage.NewListeningRepo(db)),
Scan: scanControl{ctx: ctx, m: scans},

View file

@ -51,7 +51,7 @@ func newTestAPIWithScan(t *testing.T, scan scanService) http.Handler {
tokens := auth.NewTokenIssuer(secret, time.Hour)
return NewRouter(Deps{
Logger: zap.NewNop(),
Auth: auth.NewService(storage.NewUserRepo(db), tokens),
Auth: auth.NewService(storage.NewUserRepo(db), storage.NewRefreshRepo(db), tokens, 24*time.Hour),
Tokens: tokens,
Listening: listening.NewService(storage.NewListeningRepo(db)),
Scan: scan,
@ -103,9 +103,9 @@ func registerAndLogin(t *testing.T, h http.Handler) string {
if r.Code != http.StatusOK {
t.Fatalf("login: %d %v", r.Code, r.Body)
}
tok, _ := r.Body["token"].(string)
tok, _ := r.Body["access_token"].(string)
if tok == "" {
t.Fatal("no token in login response")
t.Fatal("no access_token in login response")
}
return tok
}

View file

@ -0,0 +1,320 @@
package httpapi
import (
"net/http"
"strconv"
"testing"
)
func str(m map[string]any, key string) string {
v, _ := m[key].(string)
return v
}
func sub(m map[string]any, key string) map[string]any {
v, _ := m[key].(map[string]any)
return v
}
// loginSession logs in and returns the whole session body.
func loginSession(t *testing.T, h http.Handler, user, pass string) map[string]any {
t.Helper()
r := do(t, h, "POST", "/api/v1/auth/login", "", map[string]string{"username": user, "password": pass})
if r.Code != http.StatusOK {
t.Fatalf("login %s: %d %v", user, r.Code, r.Body)
}
return r.Body
}
// addUser has the admin create an account and returns that account's access token.
func addUser(t *testing.T, h http.Handler, adminTok, name string, admin bool) (id float64, token string) {
t.Helper()
r := do(t, h, "POST", "/api/v1/users", adminTok,
map[string]any{"username": name, "password": "longenough", "is_admin": admin})
if r.Code != http.StatusCreated {
t.Fatalf("create %s: %d %v", name, r.Code, r.Body)
}
id, _ = r.Body["id"].(float64)
return id, str(loginSession(t, h, name, "longenough"), "access_token")
}
func userPath(id float64) string {
return "/api/v1/users/" + strconv.FormatInt(int64(id), 10)
}
// ---- login, me ----
func TestLoginReturnsSessionWithRoles(t *testing.T) {
h := newTestAPI(t)
registerAndLogin(t, h)
s := loginSession(t, h, "alice", "longenough")
for _, k := range []string{"access_token", "refresh_token", "access_expires_at", "refresh_expires_at"} {
if str(s, k) == "" {
t.Errorf("%s missing from %v", k, s)
}
}
u := sub(s, "user")
if u["username"] != "alice" || u["is_admin"] != true {
t.Errorf("user = %v, want alice as admin", u)
}
}
func TestMe(t *testing.T) {
h := newTestAPI(t)
tok := registerAndLogin(t, h)
if r := do(t, h, "GET", "/api/v1/auth/me", "", nil); r.Code != http.StatusUnauthorized {
t.Errorf("no token: %d", r.Code)
}
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 {
t.Fatalf("me: %d %v", r.Code, r.Body)
}
if _, leaked := r.Body["password_hash"]; leaked {
t.Error("password hash leaked")
}
}
// ---- refresh, logout ----
func TestRefreshRotatesAndOldTokenIsDead(t *testing.T) {
h := newTestAPI(t)
registerAndLogin(t, h)
first := loginSession(t, h, "alice", "longenough")
r := do(t, h, "POST", "/api/v1/auth/refresh", "", map[string]string{"refresh_token": str(first, "refresh_token")})
if r.Code != http.StatusOK || str(r.Body, "access_token") == "" {
t.Fatalf("refresh: %d %v", r.Code, r.Body)
}
second := str(r.Body, "refresh_token")
if second == "" || second == str(first, "refresh_token") {
t.Fatal("refresh token was not rotated")
}
// The new access token works.
if r := do(t, h, "GET", "/api/v1/auth/me", str(r.Body, "access_token"), nil); r.Code != http.StatusOK {
t.Errorf("new access token: %d", r.Code)
}
// Replaying the spent token fails and kills the newer one too.
r = do(t, h, "POST", "/api/v1/auth/refresh", "", map[string]string{"refresh_token": str(first, "refresh_token")})
if r.Code != http.StatusUnauthorized || errCode(r) != "invalid_refresh_token" {
t.Fatalf("reuse: %d %v", r.Code, r.Body)
}
r = do(t, h, "POST", "/api/v1/auth/refresh", "", map[string]string{"refresh_token": second})
if r.Code != http.StatusUnauthorized {
t.Fatalf("after reuse the newer token must be dead: %d", r.Code)
}
}
func TestRefreshRejectsBadRequests(t *testing.T) {
h := newTestAPI(t)
for name, body := range map[string]any{
"empty": map[string]string{},
"unknown": map[string]string{"refresh_token": "nope"},
"malformed": "{oops",
} {
r := do(t, h, "POST", "/api/v1/auth/refresh", "", body)
want := http.StatusUnauthorized
if name == "malformed" {
want = http.StatusBadRequest
}
if r.Code != want {
t.Errorf("%s: %d %v, want %d", name, r.Code, r.Body, want)
}
}
}
func TestAccessTokenCannotBeUsedAsRefreshToken(t *testing.T) {
h := newTestAPI(t)
registerAndLogin(t, h)
s := loginSession(t, h, "alice", "longenough")
r := do(t, h, "POST", "/api/v1/auth/refresh", "", map[string]string{"refresh_token": str(s, "access_token")})
if r.Code != http.StatusUnauthorized {
t.Fatalf("access token accepted as refresh token: %d", r.Code)
}
}
func TestLogout(t *testing.T) {
h := newTestAPI(t)
registerAndLogin(t, h)
s := loginSession(t, h, "alice", "longenough")
body := map[string]string{"refresh_token": str(s, "refresh_token")}
if r := do(t, h, "POST", "/api/v1/auth/logout", "", body); r.Code != http.StatusNoContent {
t.Fatalf("logout: %d", r.Code)
}
if r := do(t, h, "POST", "/api/v1/auth/refresh", "", body); r.Code != http.StatusUnauthorized {
t.Errorf("refresh after logout: %d", r.Code)
}
// Idempotent, and it never reveals whether the token existed.
if r := do(t, h, "POST", "/api/v1/auth/logout", "", body); r.Code != http.StatusNoContent {
t.Errorf("second logout: %d", r.Code)
}
if r := do(t, h, "POST", "/api/v1/auth/logout", "", map[string]string{"refresh_token": "junk"}); r.Code != http.StatusNoContent {
t.Errorf("junk logout: %d", r.Code)
}
}
// ---- password ----
func TestChangePassword(t *testing.T) {
h := newTestAPI(t)
tok := registerAndLogin(t, h)
s := loginSession(t, h, "alice", "longenough")
if r := do(t, h, "POST", "/api/v1/auth/password", "", map[string]string{"current_password": "x", "new_password": "y"}); r.Code != http.StatusUnauthorized {
t.Errorf("no token: %d", r.Code)
}
r := do(t, h, "POST", "/api/v1/auth/password", tok, map[string]string{"current_password": "wrongwrong", "new_password": "brandnewpass"})
if r.Code != http.StatusForbidden || errCode(r) != "invalid_credentials" {
t.Fatalf("wrong current: %d %v", r.Code, r.Body)
}
r = do(t, h, "POST", "/api/v1/auth/password", tok, map[string]string{"current_password": "longenough", "new_password": "short"})
if r.Code != http.StatusBadRequest {
t.Fatalf("weak new password: %d %v", r.Code, r.Body)
}
r = do(t, h, "POST", "/api/v1/auth/password", tok, map[string]string{"current_password": "longenough", "new_password": "brandnewpass"})
if r.Code != http.StatusNoContent {
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 {
t.Errorf("old password still works: %d", r.Code)
}
loginSession(t, h, "alice", "brandnewpass")
if r := do(t, h, "POST", "/api/v1/auth/refresh", "", map[string]string{"refresh_token": str(s, "refresh_token")}); r.Code != http.StatusUnauthorized {
t.Errorf("old session survived a password change: %d", r.Code)
}
}
// ---- admin ----
func TestAdminEndpointsRejectNonAdmins(t *testing.T) {
h := newTestAPIWithScan(t, &fakeScan{})
admin := registerAndLogin(t, h)
bobID, bob := addUser(t, h, admin, "bob", false)
calls := []struct{ method, path string }{
{"GET", "/api/v1/users"},
{"POST", "/api/v1/users"},
{"PATCH", userPath(bobID)},
{"PUT", userPath(bobID) + "/password"},
{"DELETE", userPath(bobID)},
{"POST", "/api/v1/library/scan"},
}
for _, c := range calls {
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)
}
r := do(t, h, c.method, c.path, bob, map[string]any{"username": "x", "password": "longenough", "is_admin": true})
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)
}
}
// Reading the scan status stays open to every signed-in user.
if r := do(t, h, "GET", "/api/v1/library/scan", bob, nil); r.Code != http.StatusOK {
t.Errorf("scan status as user: %d", r.Code)
}
}
func TestAdminUserLifecycle(t *testing.T) {
h := newTestAPI(t)
admin := registerAndLogin(t, h)
bobID, bob := addUser(t, h, admin, "bob", false)
r := do(t, h, "GET", "/api/v1/users", admin, nil)
users, _ := r.Body["users"].([]any)
if r.Code != http.StatusOK || len(users) != 2 {
t.Fatalf("list: %d %v", r.Code, r.Body)
}
for _, u := range users {
if _, leaked := u.(map[string]any)["password_hash"]; leaked {
t.Error("password hash leaked in the user list")
}
}
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" {
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 {
t.Errorf("invalid: %d", r.Code)
}
// Promote bob: his existing token now passes the admin check.
r = do(t, h, "PATCH", userPath(bobID), admin, map[string]any{"is_admin": true})
if r.Code != http.StatusOK || r.Body["is_admin"] != true {
t.Fatalf("promote: %d %v", r.Code, r.Body)
}
if r := do(t, h, "GET", "/api/v1/users", bob, nil); r.Code != http.StatusOK {
t.Errorf("promoted user cannot list users: %d", r.Code)
}
// Reset bob's password: the new one works, his sessions are gone.
bobSession := loginSession(t, h, "bob", "longenough")
if r := do(t, h, "PUT", userPath(bobID)+"/password", admin, map[string]string{"password": "resetpassword"}); r.Code != http.StatusNoContent {
t.Fatalf("reset: %d %v", r.Code, r.Body)
}
loginSession(t, h, "bob", "resetpassword")
if r := do(t, h, "POST", "/api/v1/auth/refresh", "", map[string]string{"refresh_token": str(bobSession, "refresh_token")}); r.Code != http.StatusUnauthorized {
t.Errorf("session survived a password reset: %d", r.Code)
}
// Delete bob: his still-valid access token stops working on admin routes.
if r := do(t, h, "DELETE", userPath(bobID), admin, nil); r.Code != http.StatusNoContent {
t.Fatalf("delete: %d %v", r.Code, r.Body)
}
if r := do(t, h, "GET", "/api/v1/users", bob, nil); r.Code != http.StatusUnauthorized {
t.Errorf("deleted admin's token: %d, want 401", r.Code)
}
if r := do(t, h, "DELETE", userPath(bobID), admin, nil); r.Code != http.StatusNotFound || errCode(r) != "user_not_found" {
t.Errorf("delete twice: %d %v", r.Code, r.Body)
}
}
func TestLastAdminCannotBeRemoved(t *testing.T) {
h := newTestAPI(t)
admin := registerAndLogin(t, h)
me := do(t, h, "GET", "/api/v1/auth/me", admin, nil)
id, _ := me.Body["id"].(float64)
r := do(t, h, "PATCH", userPath(id), admin, map[string]any{"is_admin": false})
if r.Code != http.StatusConflict || errCode(r) != "last_admin" {
t.Errorf("demote last admin: %d %v", r.Code, r.Body)
}
r = do(t, h, "DELETE", userPath(id), admin, nil)
if r.Code != http.StatusConflict || errCode(r) != "last_admin" {
t.Errorf("delete last admin: %d %v", r.Code, r.Body)
}
}
func TestAdminRoutesValidateInput(t *testing.T) {
h := newTestAPI(t)
admin := registerAndLogin(t, h)
if r := do(t, h, "PATCH", "/api/v1/users/abc", admin, map[string]any{"is_admin": true}); r.Code != http.StatusBadRequest {
t.Errorf("non-numeric id: %d", r.Code)
}
if r := do(t, h, "PATCH", "/api/v1/users/1", admin, map[string]any{}); r.Code != http.StatusBadRequest {
t.Errorf("missing is_admin: %d", r.Code)
}
if r := do(t, h, "PATCH", "/api/v1/users/999", admin, map[string]any{"is_admin": true}); r.Code != http.StatusNotFound {
t.Errorf("unknown user: %d", r.Code)
}
if r := do(t, h, "PUT", "/api/v1/users/999/password", admin, map[string]string{"password": "longenough"}); r.Code != http.StatusNotFound {
t.Errorf("reset unknown: %d", r.Code)
}
}
func TestAdminCanStartScan(t *testing.T) {
scan := &fakeScan{}
h := newTestAPIWithScan(t, scan)
admin := registerAndLogin(t, h)
if r := do(t, h, "POST", "/api/v1/library/scan", admin, nil); r.Code != http.StatusAccepted {
t.Fatalf("admin scan: %d %v", r.Code, r.Body)
}
if scan.starts != 1 {
t.Errorf("starts = %d", scan.starts)
}
}

View file

@ -20,16 +20,34 @@ type credentials struct {
type userJSON struct {
ID int64 `json:"id"`
Username string `json:"username"`
IsAdmin bool `json:"is_admin"`
}
// register creates the first user. It is closed once any user exists.
func (h *authHandlers) register(c *gin.Context) {
var req credentials
if err := c.ShouldBindJSON(&req); err != nil {
writeError(c, http.StatusBadRequest, "invalid_input", "malformed JSON body")
return
func toUserJSON(u auth.User) userJSON {
return userJSON{ID: u.ID, Username: u.Username, IsAdmin: u.IsAdmin}
}
func sessionJSON(s auth.Session) gin.H {
return gin.H{
"access_token": s.AccessToken,
"access_expires_at": s.AccessExpiresAt.UTC().Format(time.RFC3339),
"refresh_token": s.RefreshToken,
"refresh_expires_at": s.RefreshExpiresAt.UTC().Format(time.RFC3339),
"user": toUserJSON(s.User),
}
user, err := h.svc.Register(c.Request.Context(), req.Username, req.Password)
}
// bindJSON reads the request body, answering 400 itself on failure.
func bindJSON(c *gin.Context, dst any) bool {
if err := c.ShouldBindJSON(dst); err != nil {
writeError(c, http.StatusBadRequest, "invalid_input", "malformed JSON body")
return false
}
return true
}
// writeAuthError maps service errors to the standard envelope.
func writeAuthError(c *gin.Context, err error) {
switch {
case errors.Is(err, auth.ErrInvalidInput):
writeError(c, http.StatusBadRequest, "invalid_input", err.Error())
@ -37,32 +55,116 @@ func (h *authHandlers) register(c *gin.Context) {
writeError(c, http.StatusForbidden, "registration_closed", err.Error())
case errors.Is(err, auth.ErrUsernameTaken):
writeError(c, http.StatusConflict, "username_taken", err.Error())
case err != nil:
case errors.Is(err, auth.ErrUserNotFound):
writeError(c, http.StatusNotFound, "user_not_found", err.Error())
case errors.Is(err, auth.ErrLastAdmin):
writeError(c, http.StatusConflict, "last_admin", err.Error())
case errors.Is(err, auth.ErrInvalidCredentials):
writeError(c, http.StatusUnauthorized, "invalid_credentials", err.Error())
case errors.Is(err, auth.ErrInvalidRefreshToken):
writeError(c, http.StatusUnauthorized, "invalid_refresh_token", err.Error())
default:
_ = c.Error(err)
writeError(c, http.StatusInternalServerError, "internal", "internal error")
default:
c.JSON(http.StatusCreated, userJSON{ID: user.ID, Username: user.Username})
}
}
// register creates the first user, who becomes the admin. It is closed once any user exists.
func (h *authHandlers) register(c *gin.Context) {
var req credentials
if !bindJSON(c, &req) {
return
}
user, err := h.svc.Register(c.Request.Context(), req.Username, req.Password)
if err != nil {
writeAuthError(c, err)
return
}
c.JSON(http.StatusCreated, toUserJSON(user))
}
func (h *authHandlers) login(c *gin.Context) {
var req credentials
if err := c.ShouldBindJSON(&req); err != nil {
writeError(c, http.StatusBadRequest, "invalid_input", "malformed JSON body")
if !bindJSON(c, &req) {
return
}
res, err := h.svc.Login(c.Request.Context(), req.Username, req.Password)
switch {
case errors.Is(err, auth.ErrInvalidCredentials):
writeError(c, http.StatusUnauthorized, "invalid_credentials", err.Error())
case err != nil:
_ = c.Error(err)
writeError(c, http.StatusInternalServerError, "internal", "internal error")
default:
c.JSON(http.StatusOK, gin.H{
"token": res.Token,
"expires_at": res.ExpiresAt.UTC().Format(time.RFC3339),
"user": userJSON{ID: res.User.ID, Username: res.User.Username},
})
sess, err := h.svc.Login(c.Request.Context(), req.Username, req.Password)
if err != nil {
writeAuthError(c, err)
return
}
c.JSON(http.StatusOK, sessionJSON(sess))
}
type refreshRequest struct {
RefreshToken string `json:"refresh_token"`
}
// refresh swaps a refresh token for a new session; the old token is spent.
func (h *authHandlers) refresh(c *gin.Context) {
var req refreshRequest
if !bindJSON(c, &req) {
return
}
sess, err := h.svc.Refresh(c.Request.Context(), req.RefreshToken)
if err != nil {
writeAuthError(c, err)
return
}
c.JSON(http.StatusOK, sessionJSON(sess))
}
// logout revokes a refresh token. It always answers 204, so it never reveals
// whether the token was valid.
func (h *authHandlers) logout(c *gin.Context) {
var req refreshRequest
if !bindJSON(c, &req) {
return
}
if err := h.svc.Logout(c.Request.Context(), req.RefreshToken); err != nil {
writeAuthError(c, err)
return
}
c.Status(http.StatusNoContent)
}
func (h *authHandlers) me(c *gin.Context) {
user, err := h.svc.User(c.Request.Context(), currentUserID(c))
if errors.Is(err, auth.ErrUserNotFound) {
writeError(c, http.StatusUnauthorized, "unauthorized", "account no longer exists")
return
}
if err != nil {
writeAuthError(c, err)
return
}
c.JSON(http.StatusOK, toUserJSON(user))
}
type passwordChangeRequest struct {
CurrentPassword string `json:"current_password"`
NewPassword string `json:"new_password"`
}
// changePassword needs the current password and signs the user out everywhere.
func (h *authHandlers) changePassword(c *gin.Context) {
var req passwordChangeRequest
if !bindJSON(c, &req) {
return
}
err := h.svc.ChangePassword(c.Request.Context(), currentUserID(c), req.CurrentPassword, req.NewPassword)
if errors.Is(err, auth.ErrInvalidCredentials) {
// 403, not 401: the token is fine, and 401 would tell clients to refresh it.
writeError(c, http.StatusForbidden, "invalid_credentials", "current password is wrong")
return
}
if errors.Is(err, auth.ErrUserNotFound) {
writeError(c, http.StatusUnauthorized, "unauthorized", "account no longer exists")
return
}
if err != nil {
writeAuthError(c, err)
return
}
c.Status(http.StatusNoContent)
}

View file

@ -0,0 +1,109 @@
package httpapi
import (
"net/http"
"strconv"
"github.com/gin-gonic/gin"
)
// usersHandlers are the admin-only user management routes.
type usersHandlers struct{ svc authService }
func (h *usersHandlers) list(c *gin.Context) {
users, err := h.svc.ListUsers(c.Request.Context())
if err != nil {
writeAuthError(c, err)
return
}
out := make([]userJSON, len(users))
for i, u := range users {
out[i] = toUserJSON(u)
}
c.JSON(http.StatusOK, gin.H{"users": out})
}
type createUserRequest struct {
Username string `json:"username"`
Password string `json:"password"`
IsAdmin bool `json:"is_admin"`
}
func (h *usersHandlers) create(c *gin.Context) {
var req createUserRequest
if !bindJSON(c, &req) {
return
}
user, err := h.svc.CreateUser(c.Request.Context(), req.Username, req.Password, req.IsAdmin)
if err != nil {
writeAuthError(c, err)
return
}
c.JSON(http.StatusCreated, toUserJSON(user))
}
type updateUserRequest struct {
IsAdmin *bool `json:"is_admin"` // pointer: absent must not mean false
}
func (h *usersHandlers) update(c *gin.Context) {
id, ok := pathID(c)
if !ok {
return
}
var req updateUserRequest
if !bindJSON(c, &req) {
return
}
if req.IsAdmin == nil {
writeError(c, http.StatusBadRequest, "invalid_input", "is_admin is required")
return
}
user, err := h.svc.SetAdmin(c.Request.Context(), id, *req.IsAdmin)
if err != nil {
writeAuthError(c, err)
return
}
c.JSON(http.StatusOK, toUserJSON(user))
}
type resetPasswordRequest struct {
Password string `json:"password"`
}
func (h *usersHandlers) resetPassword(c *gin.Context) {
id, ok := pathID(c)
if !ok {
return
}
var req resetPasswordRequest
if !bindJSON(c, &req) {
return
}
if err := h.svc.ResetPassword(c.Request.Context(), id, req.Password); err != nil {
writeAuthError(c, err)
return
}
c.Status(http.StatusNoContent)
}
func (h *usersHandlers) remove(c *gin.Context) {
id, ok := pathID(c)
if !ok {
return
}
if err := h.svc.DeleteUser(c.Request.Context(), id); err != nil {
writeAuthError(c, err)
return
}
c.Status(http.StatusNoContent)
}
func pathID(c *gin.Context) (int64, bool) {
id, err := strconv.ParseInt(c.Param("id"), 10, 64)
if err != nil || id <= 0 {
writeError(c, http.StatusBadRequest, "invalid_input", "id must be a positive number")
return 0, false
}
return id, true
}

View file

@ -1,12 +1,16 @@
package httpapi
import (
"context"
"errors"
"net/http"
"strings"
"time"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
"codeberg.org/squidd/sonda/internal/auth"
)
const (
@ -37,6 +41,38 @@ func requestLog(logger *zap.Logger) gin.HandlerFunc {
}
}
// currentUserID returns the authenticated user's id (set by requireAuth).
func currentUserID(c *gin.Context) int64 {
v, _ := c.Get(ctxUserID)
id, _ := v.(int64)
return id
}
// userLookup finds an account by id.
type userLookup interface {
User(ctx context.Context, id int64) (auth.User, error)
}
// requireAdmin runs after requireAuth. It reads the role from the database on
// every call, so a demoted or deleted admin loses access immediately instead
// of when the access token expires.
func requireAdmin(users userLookup) gin.HandlerFunc {
return func(c *gin.Context) {
user, err := users.User(c.Request.Context(), currentUserID(c))
switch {
case errors.Is(err, auth.ErrUserNotFound):
writeError(c, http.StatusUnauthorized, "unauthorized", "account no longer exists")
case err != nil:
_ = c.Error(err)
writeError(c, http.StatusInternalServerError, "internal", "internal error")
case !user.IsAdmin:
writeError(c, http.StatusForbidden, "admin_required", "this action needs an admin account")
default:
c.Next()
}
}
}
// requireAuth accepts only "Authorization: Bearer <jwt>".
func requireAuth(tokens tokenParser) gin.HandlerFunc {
return func(c *gin.Context) {

View file

@ -20,7 +20,16 @@ const maxBodyBytes = 64 << 10
type authService interface {
Register(ctx context.Context, username, password string) (auth.User, error)
Login(ctx context.Context, username, password string) (auth.LoginResult, error)
Login(ctx context.Context, username, password string) (auth.Session, error)
Refresh(ctx context.Context, refreshToken string) (auth.Session, error)
Logout(ctx context.Context, refreshToken string) error
User(ctx context.Context, id int64) (auth.User, error)
ChangePassword(ctx context.Context, userID int64, current, next string) error
ListUsers(ctx context.Context) ([]auth.User, error)
CreateUser(ctx context.Context, username, password string, 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
DeleteUser(ctx context.Context, id int64) error
}
type tokenParser interface {
@ -58,15 +67,29 @@ func NewRouter(d Deps) *gin.Engine {
a := &authHandlers{svc: d.Auth}
v1.POST("/auth/register", a.register)
v1.POST("/auth/login", a.login)
v1.POST("/auth/refresh", a.refresh)
v1.POST("/auth/logout", a.logout)
// Any signed-in user.
protected := v1.Group("", requireAuth(d.Tokens))
protected.GET("/auth/me", a.me)
protected.POST("/auth/password", a.changePassword)
l := &listenHandlers{svc: d.Listening}
protected.POST("/listens", l.record)
lib := &libraryHandlers{scan: d.Scan}
protected.POST("/library/scan", lib.startScan)
protected.GET("/library/scan", lib.scanStatus)
// Admins only.
admin := protected.Group("", requireAdmin(d.Auth))
admin.POST("/library/scan", lib.startScan)
u := &usersHandlers{svc: d.Auth}
admin.GET("/users", u.list)
admin.POST("/users", u.create)
admin.PATCH("/users/:id", u.update)
admin.PUT("/users/:id/password", u.resetPassword)
admin.DELETE("/users/:id", u.remove)
return r
}

View file

@ -1,8 +1,6 @@
package auth
import (
"context"
"errors"
"strings"
"testing"
"time"
@ -107,96 +105,3 @@ func TestTokenGarbage(t *testing.T) {
t.Fatal("garbage token accepted")
}
}
// ---- service ----
type fakeStore struct {
users map[string]fakeUser
next int64
}
type fakeUser struct {
u User
hash string
}
func newFakeStore() *fakeStore { return &fakeStore{users: map[string]fakeUser{}} }
func (f *fakeStore) CountUsers(context.Context) (int, error) { return len(f.users), nil }
func (f *fakeStore) CreateUser(_ context.Context, username, hash string) (User, error) {
key := strings.ToLower(username)
if _, ok := f.users[key]; ok {
return User{}, ErrUsernameTaken
}
f.next++
u := User{ID: f.next, Username: username, CreatedAt: time.Now()}
f.users[key] = fakeUser{u: u, hash: hash}
return u, nil
}
func (f *fakeStore) UserByUsername(_ context.Context, username string) (User, string, error) {
fu, ok := f.users[strings.ToLower(username)]
if !ok {
return User{}, "", ErrUserNotFound
}
return fu.u, fu.hash, nil
}
func newTestService() *Service {
return NewService(newFakeStore(), NewTokenIssuer(testSecret, time.Hour))
}
func TestRegisterFirstUserThenClosed(t *testing.T) {
s := newTestService()
ctx := context.Background()
if _, err := s.Register(ctx, "alice", "longenough"); err != nil {
t.Fatal(err)
}
if _, err := s.Register(ctx, "bob", "longenough"); !errors.Is(err, ErrRegistrationClosed) {
t.Fatalf("err = %v, want ErrRegistrationClosed", err)
}
}
func TestRegisterValidation(t *testing.T) {
tests := []struct {
name, user, pass string
}{
{"short username", "ab", "longenough"},
{"long username", strings.Repeat("a", 65), "longenough"},
{"bad chars", "bad name!", "longenough"},
{"short password", "alice", "short"},
{"huge password", "alice", strings.Repeat("x", 300)},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
_, err := newTestService().Register(context.Background(), tt.user, tt.pass)
if !errors.Is(err, ErrInvalidInput) {
t.Fatalf("err = %v, want ErrInvalidInput", err)
}
})
}
}
func TestLogin(t *testing.T) {
s := newTestService()
ctx := context.Background()
if _, err := s.Register(ctx, "alice", "longenough"); err != nil {
t.Fatal(err)
}
res, err := s.Login(ctx, "ALICE", "longenough") // usernames are case-insensitive
if err != nil {
t.Fatal(err)
}
if res.Token == "" || res.User.Username != "alice" {
t.Errorf("result = %+v", res)
}
if _, err := s.Login(ctx, "alice", "wrongpass1"); !errors.Is(err, ErrInvalidCredentials) {
t.Errorf("wrong password: err = %v", err)
}
if _, err := s.Login(ctx, "nobody", "longenough"); !errors.Is(err, ErrInvalidCredentials) {
t.Errorf("unknown user: err = %v", err)
}
}

View file

@ -1,8 +1,13 @@
// Package auth implements local users, password hashing and JWT access tokens.
// Package auth implements local users, roles, password hashing, JWT access
// tokens and rotating refresh tokens.
package auth
import (
"context"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"errors"
"fmt"
"regexp"
@ -12,11 +17,13 @@ import (
// Errors returned by the service. Handlers map them to HTTP statuses.
var (
ErrInvalidInput = errors.New("invalid input")
ErrUsernameTaken = errors.New("username already taken")
ErrUserNotFound = errors.New("user not found")
ErrInvalidCredentials = errors.New("invalid username or password")
ErrRegistrationClosed = errors.New("registration is closed")
ErrInvalidInput = errors.New("invalid input")
ErrUsernameTaken = errors.New("username already taken")
ErrUserNotFound = errors.New("user not found")
ErrInvalidCredentials = errors.New("invalid username or password")
ErrRegistrationClosed = errors.New("registration is closed")
ErrInvalidRefreshToken = errors.New("invalid refresh token")
ErrLastAdmin = errors.New("cannot remove the last admin")
)
var usernameRe = regexp.MustCompile(`^[A-Za-z0-9._-]{3,64}$`)
@ -30,92 +37,329 @@ const (
type User struct {
ID int64
Username string
IsAdmin bool
CreatedAt time.Time
}
// UserStore is what the service needs from persistence.
// RefreshToken is the stored form of a refresh token: only a hash, never the token.
type RefreshToken struct {
UserID int64
TokenHash string
ExpiresAt time.Time
}
// UserStore is what the service needs to persist users.
type UserStore interface {
CountUsers(ctx context.Context) (int, error)
CountAdmins(ctx context.Context) (int, error)
// CreateUser returns ErrUsernameTaken when the name exists (case-insensitive).
CreateUser(ctx context.Context, username, passwordHash string) (User, error)
// UserByUsername returns ErrUserNotFound when there is no such user.
CreateUser(ctx context.Context, username, passwordHash string, isAdmin bool) (User, error)
// UserByUsername and UserByID return the password hash too, and ErrUserNotFound.
UserByUsername(ctx context.Context, username string) (User, string, error)
UserByID(ctx context.Context, id int64) (User, string, error)
ListUsers(ctx context.Context) ([]User, error)
// The three below return ErrUserNotFound for an unknown id.
SetAdmin(ctx context.Context, id int64, isAdmin bool) error
SetPasswordHash(ctx context.Context, id int64, passwordHash string) error
DeleteUser(ctx context.Context, id int64) error
}
// LoginResult is returned by a successful login.
type LoginResult struct {
Token string
ExpiresAt time.Time
User User
// RefreshStore is what the service needs to persist refresh tokens.
type RefreshStore interface {
SaveRefreshToken(ctx context.Context, t RefreshToken) error
// RotateRefreshToken atomically revokes the active, unexpired token with
// hash oldHash and stores next for the same user, returning that user.
// An unknown or expired token gives ErrInvalidRefreshToken. A token that
// was already revoked is a reuse: every token of its user is revoked and
// ErrInvalidRefreshToken is returned.
RotateRefreshToken(ctx context.Context, oldHash string, next RefreshToken, now time.Time) (userID int64, err error)
// RevokeRefreshToken is idempotent and ignores unknown tokens.
RevokeRefreshToken(ctx context.Context, hash string, now time.Time) error
RevokeUserRefreshTokens(ctx context.Context, userID int64, now time.Time) error
}
// Service registers users and logs them in.
// Session is what a client receives after logging in or refreshing.
type Session struct {
AccessToken string
AccessExpiresAt time.Time
RefreshToken string
RefreshExpiresAt time.Time
User User
}
// Service handles accounts and sessions.
type Service struct {
store UserStore
tokens *TokenIssuer
users UserStore
refresh RefreshStore
tokens *TokenIssuer
refreshTTL time.Duration
now func() time.Time
mu sync.Mutex // serialises Register so only one first user can win
mu sync.Mutex // serialises registration and admin changes (last-admin rule)
dummyOnce sync.Once
dummyHash string
}
// NewService builds a Service.
func NewService(store UserStore, tokens *TokenIssuer) *Service {
return &Service{store: store, tokens: tokens}
func NewService(users UserStore, refresh RefreshStore, tokens *TokenIssuer, refreshTTL time.Duration) *Service {
return &Service{users: users, refresh: refresh, tokens: tokens, refreshTTL: refreshTTL, now: time.Now}
}
// Register creates the first user. Once any user exists, registration is
// closed: there is no admin flow yet.
func (s *Service) Register(ctx context.Context, username, password string) (User, error) {
// ---- validation ----
func validateUsername(username string) error {
if !usernameRe.MatchString(username) {
return User{}, fmt.Errorf("%w: username must be 3-64 characters: letters, digits, '.', '_' or '-'", ErrInvalidInput)
return fmt.Errorf("%w: username must be 3-64 characters: letters, digits, '.', '_' or '-'", ErrInvalidInput)
}
return nil
}
func validatePassword(password string) error {
if len(password) < minPasswordLen || len(password) > maxPasswordLen {
return User{}, fmt.Errorf("%w: password must be %d-%d bytes", ErrInvalidInput, minPasswordLen, maxPasswordLen)
return fmt.Errorf("%w: password must be %d-%d bytes", ErrInvalidInput, minPasswordLen, maxPasswordLen)
}
return nil
}
// ---- registration and login ----
// Register creates the first user, who becomes the admin. Once any user
// exists, registration is closed: admins create further accounts.
func (s *Service) Register(ctx context.Context, username, password string) (User, error) {
if err := validateUsername(username); err != nil {
return User{}, err
}
if err := validatePassword(password); err != nil {
return User{}, err
}
s.mu.Lock()
defer s.mu.Unlock()
n, err := s.store.CountUsers(ctx)
n, err := s.users.CountUsers(ctx)
if err != nil {
return User{}, fmt.Errorf("count users: %w", err)
}
if n > 0 {
return User{}, ErrRegistrationClosed
}
hash, err := HashPassword(password)
if err != nil {
return User{}, err
}
return s.store.CreateUser(ctx, username, hash)
return s.users.CreateUser(ctx, username, hash, true)
}
// Login checks the credentials and returns a signed token.
// Login checks the credentials and opens a session.
// Unknown user and wrong password are indistinguishable to the caller.
func (s *Service) Login(ctx context.Context, username, password string) (LoginResult, error) {
user, hash, err := s.store.UserByUsername(ctx, username)
func (s *Service) Login(ctx context.Context, username, password string) (Session, error) {
user, hash, err := s.users.UserByUsername(ctx, username)
if errors.Is(err, ErrUserNotFound) {
// Spend the same time as a real check to avoid revealing which names exist.
VerifyPassword(s.fakeHash(), password)
return LoginResult{}, ErrInvalidCredentials
return Session{}, ErrInvalidCredentials
}
if err != nil {
return LoginResult{}, fmt.Errorf("find user: %w", err)
return Session{}, fmt.Errorf("find user: %w", err)
}
if !VerifyPassword(hash, password) {
return LoginResult{}, ErrInvalidCredentials
return Session{}, ErrInvalidCredentials
}
token, exp, err := s.tokens.Issue(user)
if err != nil {
return LoginResult{}, err
}
return LoginResult{Token: token, ExpiresAt: exp, User: user}, nil
return s.openSession(ctx, user)
}
func (s *Service) fakeHash() string {
s.dummyOnce.Do(func() { s.dummyHash, _ = HashPassword("sonda-dummy-password") })
return s.dummyHash
}
func (s *Service) openSession(ctx context.Context, user User) (Session, error) {
raw, hash, err := newRefreshToken()
if err != nil {
return Session{}, err
}
exp := s.now().Add(s.refreshTTL)
if err := s.refresh.SaveRefreshToken(ctx, RefreshToken{UserID: user.ID, TokenHash: hash, ExpiresAt: exp}); err != nil {
return Session{}, fmt.Errorf("save refresh token: %w", err)
}
return s.sign(user, raw, exp)
}
func (s *Service) sign(user User, refreshRaw string, refreshExp time.Time) (Session, error) {
access, accessExp, err := s.tokens.Issue(user)
if err != nil {
return Session{}, err
}
return Session{
AccessToken: access, AccessExpiresAt: accessExp,
RefreshToken: refreshRaw, RefreshExpiresAt: refreshExp,
User: user,
}, nil
}
// ---- refresh and logout ----
// Refresh exchanges a refresh token for a new session. The old token stops
// working; presenting it again revokes every session of that user.
func (s *Service) Refresh(ctx context.Context, refreshToken string) (Session, error) {
if refreshToken == "" {
return Session{}, ErrInvalidRefreshToken
}
raw, hash, err := newRefreshToken()
if err != nil {
return Session{}, err
}
now := s.now()
exp := now.Add(s.refreshTTL)
userID, err := s.refresh.RotateRefreshToken(ctx, hashRefreshToken(refreshToken),
RefreshToken{TokenHash: hash, ExpiresAt: exp}, now)
if err != nil {
return Session{}, err
}
user, _, err := s.users.UserByID(ctx, userID)
if errors.Is(err, ErrUserNotFound) {
return Session{}, ErrInvalidRefreshToken
}
if err != nil {
return Session{}, fmt.Errorf("find user: %w", err)
}
return s.sign(user, raw, exp)
}
// Logout revokes one refresh token. It is idempotent and never reveals
// whether the token existed.
func (s *Service) Logout(ctx context.Context, refreshToken string) error {
if refreshToken == "" {
return nil
}
return s.refresh.RevokeRefreshToken(ctx, hashRefreshToken(refreshToken), s.now())
}
func newRefreshToken() (raw, hash string, err error) {
b := make([]byte, 32)
if _, err := rand.Read(b); err != nil {
return "", "", fmt.Errorf("generate refresh token: %w", err)
}
raw = base64.RawURLEncoding.EncodeToString(b)
return raw, hashRefreshToken(raw), nil
}
func hashRefreshToken(raw string) string {
sum := sha256.Sum256([]byte(raw))
return hex.EncodeToString(sum[:])
}
// ---- own account ----
// User returns the account with the given id.
func (s *Service) User(ctx context.Context, id int64) (User, error) {
u, _, err := s.users.UserByID(ctx, id)
return u, err
}
// ChangePassword sets a new password after checking the current one, and
// signs the user out everywhere.
func (s *Service) ChangePassword(ctx context.Context, userID int64, current, next string) error {
_, hash, err := s.users.UserByID(ctx, userID)
if err != nil {
return err
}
if !VerifyPassword(hash, current) {
return ErrInvalidCredentials
}
return s.setPassword(ctx, userID, next)
}
func (s *Service) setPassword(ctx context.Context, userID int64, password string) error {
if err := validatePassword(password); err != nil {
return err
}
hash, err := HashPassword(password)
if err != nil {
return err
}
if err := s.users.SetPasswordHash(ctx, userID, hash); err != nil {
return err
}
return s.refresh.RevokeUserRefreshTokens(ctx, userID, s.now())
}
// ---- admin ----
// ListUsers returns every account.
func (s *Service) ListUsers(ctx context.Context) ([]User, error) {
return s.users.ListUsers(ctx)
}
// 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) {
if err := validateUsername(username); err != nil {
return User{}, err
}
if err := validatePassword(password); err != nil {
return User{}, err
}
hash, err := HashPassword(password)
if err != nil {
return User{}, err
}
return s.users.CreateUser(ctx, username, hash, isAdmin)
}
// SetAdmin grants or removes the admin role. The last admin cannot be demoted.
func (s *Service) SetAdmin(ctx context.Context, id int64, isAdmin bool) (User, error) {
s.mu.Lock()
defer s.mu.Unlock()
user, _, err := s.users.UserByID(ctx, id)
if err != nil {
return User{}, err
}
if user.IsAdmin && !isAdmin {
if err := s.ensureAnotherAdmin(ctx); err != nil {
return User{}, err
}
}
if err := s.users.SetAdmin(ctx, id, isAdmin); err != nil {
return User{}, err
}
user.IsAdmin = isAdmin
return user, nil
}
// ResetPassword sets a new password without knowing the old one and signs the
// user out everywhere. Callers must have checked that the actor is an admin.
func (s *Service) ResetPassword(ctx context.Context, id int64, password string) error {
return s.setPassword(ctx, id, password)
}
// DeleteUser removes an account and its sessions. The last admin cannot be deleted.
func (s *Service) DeleteUser(ctx context.Context, id int64) error {
s.mu.Lock()
defer s.mu.Unlock()
user, _, err := s.users.UserByID(ctx, id)
if err != nil {
return err
}
if user.IsAdmin {
if err := s.ensureAnotherAdmin(ctx); err != nil {
return err
}
}
return s.users.DeleteUser(ctx, id)
}
// ensureAnotherAdmin fails with ErrLastAdmin when only one admin exists.
// The caller must hold s.mu and have checked that the target is an admin.
func (s *Service) ensureAnotherAdmin(ctx context.Context) error {
n, err := s.users.CountAdmins(ctx)
if err != nil {
return fmt.Errorf("count admins: %w", err)
}
if n <= 1 {
return ErrLastAdmin
}
return nil
}

View file

@ -0,0 +1,465 @@
package auth
import (
"context"
"errors"
"strings"
"testing"
"time"
)
// ---- fake stores ----
type fakeUserRow struct {
u User
hash string
}
type fakeRefreshRow struct {
userID int64
expires time.Time
revoked bool
}
// fakeStore implements UserStore and RefreshStore in memory, following the
// same rules as the real repositories.
type fakeStore struct {
users map[int64]*fakeUserRow
tokens map[string]*fakeRefreshRow // by hash
nextID int64
revokes int
}
func newFakeStore() *fakeStore {
return &fakeStore{users: map[int64]*fakeUserRow{}, tokens: map[string]*fakeRefreshRow{}}
}
func (f *fakeStore) find(username string) *fakeUserRow {
for _, r := range f.users {
if strings.EqualFold(r.u.Username, username) {
return r
}
}
return nil
}
func (f *fakeStore) CountUsers(context.Context) (int, error) { return len(f.users), nil }
func (f *fakeStore) CountAdmins(context.Context) (int, error) {
n := 0
for _, r := range f.users {
if r.u.IsAdmin {
n++
}
}
return n, nil
}
func (f *fakeStore) CreateUser(_ context.Context, username, hash string, isAdmin bool) (User, error) {
if f.find(username) != nil {
return User{}, ErrUsernameTaken
}
f.nextID++
u := User{ID: f.nextID, Username: username, IsAdmin: isAdmin, CreatedAt: time.Now()}
f.users[u.ID] = &fakeUserRow{u: u, hash: hash}
return u, nil
}
func (f *fakeStore) UserByUsername(_ context.Context, username string) (User, string, error) {
r := f.find(username)
if r == nil {
return User{}, "", ErrUserNotFound
}
return r.u, r.hash, nil
}
func (f *fakeStore) UserByID(_ context.Context, id int64) (User, string, error) {
r, ok := f.users[id]
if !ok {
return User{}, "", ErrUserNotFound
}
return r.u, r.hash, nil
}
func (f *fakeStore) ListUsers(context.Context) ([]User, error) {
var out []User
for id := int64(1); id <= f.nextID; id++ {
if r, ok := f.users[id]; ok {
out = append(out, r.u)
}
}
return out, nil
}
func (f *fakeStore) SetAdmin(_ context.Context, id int64, isAdmin bool) error {
r, ok := f.users[id]
if !ok {
return ErrUserNotFound
}
r.u.IsAdmin = isAdmin
return nil
}
func (f *fakeStore) SetPasswordHash(_ context.Context, id int64, hash string) error {
r, ok := f.users[id]
if !ok {
return ErrUserNotFound
}
r.hash = hash
return nil
}
func (f *fakeStore) DeleteUser(_ context.Context, id int64) error {
if _, ok := f.users[id]; !ok {
return ErrUserNotFound
}
delete(f.users, id)
for h, t := range f.tokens { // cascade
if t.userID == id {
delete(f.tokens, h)
}
}
return nil
}
func (f *fakeStore) SaveRefreshToken(_ context.Context, t RefreshToken) error {
f.tokens[t.TokenHash] = &fakeRefreshRow{userID: t.UserID, expires: t.ExpiresAt}
return nil
}
func (f *fakeStore) RotateRefreshToken(ctx context.Context, oldHash string, next RefreshToken, now time.Time) (int64, error) {
t, ok := f.tokens[oldHash]
if !ok {
return 0, ErrInvalidRefreshToken
}
if t.revoked {
_ = f.RevokeUserRefreshTokens(ctx, t.userID, now) // reuse: kill every session
return 0, ErrInvalidRefreshToken
}
if !now.Before(t.expires) {
return 0, ErrInvalidRefreshToken
}
t.revoked = true
f.tokens[next.TokenHash] = &fakeRefreshRow{userID: t.userID, expires: next.ExpiresAt}
return t.userID, nil
}
func (f *fakeStore) RevokeRefreshToken(_ context.Context, hash string, _ time.Time) error {
if t, ok := f.tokens[hash]; ok {
t.revoked = true
}
return nil
}
func (f *fakeStore) RevokeUserRefreshTokens(_ context.Context, userID int64, _ time.Time) error {
f.revokes++
for _, t := range f.tokens {
if t.userID == userID {
t.revoked = true
}
}
return nil
}
func newTestService() (*Service, *fakeStore) {
st := newFakeStore()
return NewService(st, st, NewTokenIssuer(testSecret, 15*time.Minute), 24*time.Hour), st
}
// bootstrap registers the first (admin) user and returns the service.
func bootstrap(t *testing.T) (*Service, *fakeStore, User) {
t.Helper()
s, st := newTestService()
u, err := s.Register(context.Background(), "alice", "longenough")
if err != nil {
t.Fatal(err)
}
return s, st, u
}
// ---- register / login ----
func TestRegisterFirstUserIsAdminThenClosed(t *testing.T) {
s, _, u := bootstrap(t)
if !u.IsAdmin {
t.Error("the first user must be an admin")
}
if _, err := s.Register(context.Background(), "bob", "longenough"); !errors.Is(err, ErrRegistrationClosed) {
t.Fatalf("err = %v, want ErrRegistrationClosed", err)
}
}
func TestRegisterValidation(t *testing.T) {
tests := []struct {
name, user, pass string
}{
{"short username", "ab", "longenough"},
{"long username", strings.Repeat("a", 65), "longenough"},
{"bad chars", "bad name!", "longenough"},
{"short password", "alice", "short"},
{"huge password", "alice", strings.Repeat("x", 300)},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
s, _ := newTestService()
if _, err := s.Register(context.Background(), tt.user, tt.pass); !errors.Is(err, ErrInvalidInput) {
t.Fatalf("err = %v, want ErrInvalidInput", err)
}
})
}
}
func TestLoginIssuesBothTokens(t *testing.T) {
s, _, _ := bootstrap(t)
ctx := context.Background()
sess, err := s.Login(ctx, "ALICE", "longenough") // usernames are case-insensitive
if err != nil {
t.Fatal(err)
}
if sess.AccessToken == "" || sess.RefreshToken == "" || sess.User.Username != "alice" || !sess.User.IsAdmin {
t.Fatalf("session = %+v", sess)
}
if !sess.RefreshExpiresAt.After(sess.AccessExpiresAt) {
t.Error("refresh token must outlive the access token")
}
if _, err := NewTokenIssuer(testSecret, time.Hour).Parse(sess.AccessToken); err != nil {
t.Errorf("access token does not verify: %v", err)
}
if _, err := s.Login(ctx, "alice", "wrongpass1"); !errors.Is(err, ErrInvalidCredentials) {
t.Errorf("wrong password: err = %v", err)
}
if _, err := s.Login(ctx, "nobody", "longenough"); !errors.Is(err, ErrInvalidCredentials) {
t.Errorf("unknown user: err = %v", err)
}
}
func TestRefreshTokenIsStoredHashed(t *testing.T) {
s, st, _ := bootstrap(t)
sess, _ := s.Login(context.Background(), "alice", "longenough")
if _, ok := st.tokens[sess.RefreshToken]; ok {
t.Fatal("the raw refresh token is stored; only its hash may be")
}
if _, ok := st.tokens[hashRefreshToken(sess.RefreshToken)]; !ok {
t.Fatal("hash of the refresh token not stored")
}
}
// ---- refresh ----
func TestRefreshRotates(t *testing.T) {
s, _, _ := bootstrap(t)
ctx := context.Background()
first, _ := s.Login(ctx, "alice", "longenough")
second, err := s.Refresh(ctx, first.RefreshToken)
if err != nil {
t.Fatal(err)
}
if second.RefreshToken == first.RefreshToken || second.AccessToken == "" || second.User.Username != "alice" {
t.Fatalf("second = %+v", second)
}
// The new token works.
if _, err := s.Refresh(ctx, second.RefreshToken); err != nil {
t.Fatalf("refreshing with the new token: %v", err)
}
}
func TestReusedRefreshTokenRevokesEverySession(t *testing.T) {
s, _, _ := bootstrap(t)
ctx := context.Background()
first, _ := s.Login(ctx, "alice", "longenough")
second, _ := s.Refresh(ctx, first.RefreshToken)
// Presenting the already-rotated token looks like theft.
if _, err := s.Refresh(ctx, first.RefreshToken); !errors.Is(err, ErrInvalidRefreshToken) {
t.Fatalf("reuse: err = %v, want ErrInvalidRefreshToken", err)
}
// ...so the legitimate newer token is dead too.
if _, err := s.Refresh(ctx, second.RefreshToken); !errors.Is(err, ErrInvalidRefreshToken) {
t.Fatalf("after reuse the newer token must be revoked: err = %v", err)
}
}
func TestRefreshRejectsExpiredUnknownAndEmpty(t *testing.T) {
s, _, _ := bootstrap(t)
ctx := context.Background()
sess, _ := s.Login(ctx, "alice", "longenough")
for _, tok := range []string{"", "not-a-token", strings.Repeat("a", 43)} {
if _, err := s.Refresh(ctx, tok); !errors.Is(err, ErrInvalidRefreshToken) {
t.Errorf("token %q: err = %v", tok, err)
}
}
s.now = func() time.Time { return time.Now().Add(48 * time.Hour) }
if _, err := s.Refresh(ctx, sess.RefreshToken); !errors.Is(err, ErrInvalidRefreshToken) {
t.Errorf("expired token: err = %v", err)
}
}
func TestRefreshFailsForDeletedUser(t *testing.T) {
s, _, admin := bootstrap(t)
ctx := context.Background()
bob, err := s.CreateUser(ctx, "bob", "longenough", false)
if err != nil {
t.Fatal(err)
}
bobSess, _ := s.Login(ctx, "bob", "longenough")
if err := s.DeleteUser(ctx, bob.ID); err != nil {
t.Fatal(err)
}
if _, err := s.Refresh(ctx, bobSess.RefreshToken); !errors.Is(err, ErrInvalidRefreshToken) {
t.Fatalf("err = %v", err)
}
_ = admin
}
// ---- logout / password ----
func TestLogoutRevokesTheToken(t *testing.T) {
s, _, _ := bootstrap(t)
ctx := context.Background()
sess, _ := s.Login(ctx, "alice", "longenough")
if err := s.Logout(ctx, sess.RefreshToken); err != nil {
t.Fatal(err)
}
if _, err := s.Refresh(ctx, sess.RefreshToken); !errors.Is(err, ErrInvalidRefreshToken) {
t.Fatalf("after logout: err = %v", err)
}
// Logging out twice, or with garbage, is not an error.
if err := s.Logout(ctx, sess.RefreshToken); err != nil {
t.Errorf("second logout: %v", err)
}
if err := s.Logout(ctx, "garbage"); err != nil {
t.Errorf("garbage logout: %v", err)
}
}
func TestChangePassword(t *testing.T) {
s, _, u := bootstrap(t)
ctx := context.Background()
sess, _ := s.Login(ctx, "alice", "longenough")
if err := s.ChangePassword(ctx, u.ID, "wrong-current", "brandnewpass"); !errors.Is(err, ErrInvalidCredentials) {
t.Fatalf("wrong current: err = %v", err)
}
if err := s.ChangePassword(ctx, u.ID, "longenough", "short"); !errors.Is(err, ErrInvalidInput) {
t.Fatalf("weak new password: err = %v", err)
}
if err := s.ChangePassword(ctx, u.ID, "longenough", "brandnewpass"); err != nil {
t.Fatal(err)
}
if _, err := s.Login(ctx, "alice", "longenough"); !errors.Is(err, ErrInvalidCredentials) {
t.Error("old password still works")
}
if _, err := s.Login(ctx, "alice", "brandnewpass"); err != nil {
t.Errorf("new password: %v", err)
}
if _, err := s.Refresh(ctx, sess.RefreshToken); !errors.Is(err, ErrInvalidRefreshToken) {
t.Error("a password change must revoke existing sessions")
}
}
// ---- admin ----
func TestAdminCreateAndListUsers(t *testing.T) {
s, _, _ := bootstrap(t)
ctx := context.Background()
bob, err := s.CreateUser(ctx, "bob", "longenough", false)
if err != nil || bob.IsAdmin {
t.Fatalf("bob = %+v err=%v", bob, err)
}
if _, err := s.CreateUser(ctx, "BOB", "longenough", false); !errors.Is(err, ErrUsernameTaken) {
t.Errorf("duplicate: err = %v", err)
}
if _, err := s.CreateUser(ctx, "x", "longenough", false); !errors.Is(err, ErrInvalidInput) {
t.Errorf("bad username: err = %v", err)
}
users, err := s.ListUsers(ctx)
if err != nil || len(users) != 2 || users[0].Username != "alice" || users[1].Username != "bob" {
t.Fatalf("users = %+v err=%v", users, err)
}
}
func TestSetAdminAndLastAdminGuard(t *testing.T) {
s, _, alice := bootstrap(t)
ctx := context.Background()
bob, _ := s.CreateUser(ctx, "bob", "longenough", false)
// The only admin cannot be demoted.
if _, err := s.SetAdmin(ctx, alice.ID, false); !errors.Is(err, ErrLastAdmin) {
t.Fatalf("demoting the last admin: err = %v", err)
}
got, err := s.SetAdmin(ctx, bob.ID, true)
if err != nil || !got.IsAdmin {
t.Fatalf("promote: %+v err=%v", got, err)
}
// With two admins, one can step down.
if got, err = s.SetAdmin(ctx, alice.ID, false); err != nil || got.IsAdmin {
t.Fatalf("demote with two admins: %+v err=%v", got, err)
}
// Now bob is the last one.
if _, err := s.SetAdmin(ctx, bob.ID, false); !errors.Is(err, ErrLastAdmin) {
t.Fatalf("demoting the new last admin: err = %v", err)
}
if _, err := s.SetAdmin(ctx, 999, true); !errors.Is(err, ErrUserNotFound) {
t.Errorf("unknown user: err = %v", err)
}
}
func TestDeleteUserGuards(t *testing.T) {
s, _, alice := bootstrap(t)
ctx := context.Background()
bob, _ := s.CreateUser(ctx, "bob", "longenough", false)
if err := s.DeleteUser(ctx, alice.ID); !errors.Is(err, ErrLastAdmin) {
t.Fatalf("deleting the last admin: err = %v", err)
}
if err := s.DeleteUser(ctx, bob.ID); err != nil {
t.Fatal(err)
}
if err := s.DeleteUser(ctx, bob.ID); !errors.Is(err, ErrUserNotFound) {
t.Errorf("deleting twice: err = %v", err)
}
}
func TestResetPasswordRevokesSessions(t *testing.T) {
s, _, _ := bootstrap(t)
ctx := context.Background()
bob, _ := s.CreateUser(ctx, "bob", "longenough", false)
sess, _ := s.Login(ctx, "bob", "longenough")
if err := s.ResetPassword(ctx, bob.ID, "short"); !errors.Is(err, ErrInvalidInput) {
t.Fatalf("weak password: err = %v", err)
}
if err := s.ResetPassword(ctx, bob.ID, "resetpassword"); err != nil {
t.Fatal(err)
}
if _, err := s.Login(ctx, "bob", "resetpassword"); err != nil {
t.Errorf("login with the reset password: %v", err)
}
if _, err := s.Refresh(ctx, sess.RefreshToken); !errors.Is(err, ErrInvalidRefreshToken) {
t.Error("a reset must revoke the user's sessions")
}
if err := s.ResetPassword(ctx, 999, "resetpassword"); !errors.Is(err, ErrUserNotFound) {
t.Errorf("unknown user: err = %v", err)
}
}
func TestUserLookup(t *testing.T) {
s, _, alice := bootstrap(t)
u, err := s.User(context.Background(), alice.ID)
if err != nil || u.Username != "alice" || !u.IsAdmin {
t.Fatalf("u = %+v err=%v", u, err)
}
if _, err := s.User(context.Background(), 999); !errors.Is(err, ErrUserNotFound) {
t.Errorf("err = %v", err)
}
}

View file

@ -53,13 +53,19 @@ type Log struct {
// Auth holds token settings. JWTSecret must be long and random,
// for example: openssl rand -hex 32.
type Auth struct {
JWTSecret string `toml:"jwt_secret"`
TokenTTLHours int `toml:"token_ttl_hours"`
JWTSecret string `toml:"jwt_secret"`
AccessTTLMinutes int `toml:"access_ttl_minutes"` // lifetime of an access token
RefreshTTLHours int `toml:"refresh_ttl_hours"` // lifetime of a refresh token
}
// TokenTTL returns the access token lifetime.
func (a Auth) TokenTTL() time.Duration {
return time.Duration(a.TokenTTLHours) * time.Hour
// AccessTTL returns the access token lifetime.
func (a Auth) AccessTTL() time.Duration {
return time.Duration(a.AccessTTLMinutes) * time.Minute
}
// RefreshTTL returns the refresh token lifetime.
func (a Auth) RefreshTTL() time.Duration {
return time.Duration(a.RefreshTTLHours) * time.Hour
}
// Providers holds external provider settings.
@ -79,7 +85,7 @@ func Default() Config {
Library: Library{ScanWorkers: 4},
Database: Database{Driver: "sqlite", Path: "sonda.db"},
Log: Log{Env: "production"},
Auth: Auth{TokenTTLHours: 168}, // one week
Auth: Auth{AccessTTLMinutes: 15, RefreshTTLHours: 720}, // 15 minutes, 30 days
}
}
@ -153,8 +159,11 @@ func (c Config) Validate() error {
if len(c.Auth.JWTSecret) < minJWTSecretLen {
errs = append(errs, fmt.Errorf("auth.jwt_secret must be at least %d characters (try: openssl rand -hex 32)", minJWTSecretLen))
}
if c.Auth.TokenTTLHours <= 0 {
errs = append(errs, errors.New("auth.token_ttl_hours must be greater than 0"))
if c.Auth.AccessTTLMinutes <= 0 {
errs = append(errs, errors.New("auth.access_ttl_minutes must be greater than 0"))
}
if c.Auth.RefreshTTLHours <= 0 {
errs = append(errs, errors.New("auth.refresh_ttl_hours must be greater than 0"))
}
if c.Library.ScanWorkers < 1 {
errs = append(errs, errors.New("library.scan_workers must be at least 1"))

View file

@ -37,8 +37,11 @@ func TestLoadEmptyPathReturnsDefaults(t *testing.T) {
if cfg.Library.ScanWorkers != 4 {
t.Errorf("scan workers = %d", cfg.Library.ScanWorkers)
}
if cfg.Auth.TokenTTL() != 168*time.Hour {
t.Errorf("token ttl = %v", cfg.Auth.TokenTTL())
if cfg.Auth.AccessTTL() != 15*time.Minute {
t.Errorf("access ttl = %v", cfg.Auth.AccessTTL())
}
if cfg.Auth.RefreshTTL() != 720*time.Hour {
t.Errorf("refresh ttl = %v", cfg.Auth.RefreshTTL())
}
}
@ -138,7 +141,8 @@ func TestValidate(t *testing.T) {
{"no secret", func(c *Config) { c.Auth.JWTSecret = "" }, "auth.jwt_secret"},
{"short secret", func(c *Config) { c.Auth.JWTSecret = "short" }, "auth.jwt_secret"},
{"bad workers", func(c *Config) { c.Library.ScanWorkers = 0 }, "library.scan_workers"},
{"bad ttl", func(c *Config) { c.Auth.TokenTTLHours = 0 }, "auth.token_ttl_hours"},
{"bad access ttl", func(c *Config) { c.Auth.AccessTTLMinutes = 0 }, "auth.access_ttl_minutes"},
{"bad refresh ttl", func(c *Config) { c.Auth.RefreshTTLHours = 0 }, "auth.refresh_ttl_hours"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {

View file

@ -0,0 +1,246 @@
package storage
import (
"context"
"errors"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/uptrace/bun"
"codeberg.org/squidd/sonda/internal/auth"
)
func TestUserRepoRolesAndLookup(t *testing.T) {
forEachBackend(t, func(t *testing.T, db *bun.DB, _ string) {
ctx := context.Background()
repo := NewUserRepo(db)
alice, err := repo.CreateUser(ctx, "alice", "h1", true)
if err != nil || !alice.IsAdmin {
t.Fatalf("alice = %+v err=%v", alice, err)
}
bob, err := repo.CreateUser(ctx, "bob", "h2", false)
if err != nil || bob.IsAdmin {
t.Fatalf("bob = %+v err=%v", bob, err)
}
if n, _ := repo.CountAdmins(ctx); n != 1 {
t.Errorf("CountAdmins = %d, want 1", n)
}
got, hash, err := repo.UserByID(ctx, bob.ID)
if err != nil || got.Username != "bob" || hash != "h2" || got.IsAdmin {
t.Errorf("UserByID = %+v %q err=%v", got, hash, err)
}
byName, _, _ := repo.UserByUsername(ctx, "ALICE")
if !byName.IsAdmin {
t.Error("UserByUsername lost the admin flag")
}
list, err := repo.ListUsers(ctx)
if err != nil || len(list) != 2 || list[0].ID != alice.ID || list[1].ID != bob.ID {
t.Fatalf("ListUsers = %+v err=%v", list, err)
}
if err := repo.SetAdmin(ctx, bob.ID, true); err != nil {
t.Fatal(err)
}
if n, _ := repo.CountAdmins(ctx); n != 2 {
t.Errorf("CountAdmins after promote = %d, want 2", n)
}
if err := repo.SetAdmin(ctx, bob.ID, false); err != nil {
t.Fatal(err)
}
if u, _, _ := repo.UserByID(ctx, bob.ID); u.IsAdmin {
t.Error("demotion not stored")
}
if err := repo.SetPasswordHash(ctx, bob.ID, "h3"); err != nil {
t.Fatal(err)
}
if _, hash, _ := repo.UserByID(ctx, bob.ID); hash != "h3" {
t.Errorf("password hash = %q", hash)
}
if err := repo.DeleteUser(ctx, bob.ID); err != nil {
t.Fatal(err)
}
if _, _, err := repo.UserByID(ctx, bob.ID); !errors.Is(err, auth.ErrUserNotFound) {
t.Errorf("after delete: err = %v", err)
}
})
}
func TestUserRepoUnknownIDs(t *testing.T) {
forEachBackend(t, func(t *testing.T, db *bun.DB, _ string) {
ctx := context.Background()
repo := NewUserRepo(db)
if _, _, err := repo.UserByID(ctx, 999); !errors.Is(err, auth.ErrUserNotFound) {
t.Errorf("UserByID: %v", err)
}
if err := repo.SetAdmin(ctx, 999, true); !errors.Is(err, auth.ErrUserNotFound) {
t.Errorf("SetAdmin: %v", err)
}
if err := repo.SetPasswordHash(ctx, 999, "x"); !errors.Is(err, auth.ErrUserNotFound) {
t.Errorf("SetPasswordHash: %v", err)
}
if err := repo.DeleteUser(ctx, 999); !errors.Is(err, auth.ErrUserNotFound) {
t.Errorf("DeleteUser: %v", err)
}
})
}
func newUserWithToken(t *testing.T, db *bun.DB, name, hash string, expires time.Time) int64 {
t.Helper()
ctx := context.Background()
u, err := NewUserRepo(db).CreateUser(ctx, name, "h", false)
if err != nil {
t.Fatal(err)
}
if err := NewRefreshRepo(db).SaveRefreshToken(ctx, auth.RefreshToken{UserID: u.ID, TokenHash: hash, ExpiresAt: expires}); err != nil {
t.Fatal(err)
}
return u.ID
}
func TestRefreshRepoRotate(t *testing.T) {
forEachBackend(t, func(t *testing.T, db *bun.DB, _ string) {
ctx := context.Background()
repo := NewRefreshRepo(db)
now := time.Now()
uid := newUserWithToken(t, db, "alice", "hash-a", now.Add(time.Hour))
got, err := repo.RotateRefreshToken(ctx, "hash-a", auth.RefreshToken{TokenHash: "hash-b", ExpiresAt: now.Add(time.Hour)}, now)
if err != nil || got != uid {
t.Fatalf("rotate: uid=%d err=%v, want %d", got, err, uid)
}
// The new token is usable, the old one is spent.
if _, err := repo.RotateRefreshToken(ctx, "hash-b", auth.RefreshToken{TokenHash: "hash-c", ExpiresAt: now.Add(time.Hour)}, now); err != nil {
t.Fatalf("rotating the new token: %v", err)
}
})
}
func TestRefreshRepoRejectsUnknownAndExpired(t *testing.T) {
forEachBackend(t, func(t *testing.T, db *bun.DB, _ string) {
ctx := context.Background()
repo := NewRefreshRepo(db)
now := time.Now()
newUserWithToken(t, db, "alice", "old", now.Add(-time.Minute))
next := auth.RefreshToken{TokenHash: "next", ExpiresAt: now.Add(time.Hour)}
if _, err := repo.RotateRefreshToken(ctx, "nope", next, now); !errors.Is(err, auth.ErrInvalidRefreshToken) {
t.Errorf("unknown: %v", err)
}
if _, err := repo.RotateRefreshToken(ctx, "old", next, now); !errors.Is(err, auth.ErrInvalidRefreshToken) {
t.Errorf("expired: %v", err)
}
if n := count(t, db, "SELECT COUNT(*) FROM refresh_tokens WHERE token_hash = 'next'"); n != 0 {
t.Error("a failed rotation must not store the next token")
}
})
}
func TestRefreshRepoReuseRevokesEveryTokenOfTheUser(t *testing.T) {
forEachBackend(t, func(t *testing.T, db *bun.DB, _ string) {
ctx := context.Background()
repo := NewRefreshRepo(db)
now := time.Now()
uid := newUserWithToken(t, db, "alice", "a1", now.Add(time.Hour))
if err := repo.SaveRefreshToken(ctx, auth.RefreshToken{UserID: uid, TokenHash: "other-device", ExpiresAt: now.Add(time.Hour)}); err != nil {
t.Fatal(err)
}
bobID := newUserWithToken(t, db, "bob", "bob-token", now.Add(time.Hour))
if _, err := repo.RotateRefreshToken(ctx, "a1", auth.RefreshToken{TokenHash: "a2", ExpiresAt: now.Add(time.Hour)}, now); err != nil {
t.Fatal(err)
}
// Replaying a1 is a reuse.
if _, err := repo.RotateRefreshToken(ctx, "a1", auth.RefreshToken{TokenHash: "a3", ExpiresAt: now.Add(time.Hour)}, now); !errors.Is(err, auth.ErrInvalidRefreshToken) {
t.Fatalf("reuse: %v", err)
}
if n := count(t, db, "SELECT COUNT(*) FROM refresh_tokens WHERE user_id = ? AND revoked_at IS NULL", uid); n != 0 {
t.Errorf("%d active tokens left for the user after a reuse, want 0", n)
}
// The revocation must survive the failed call.
if _, err := repo.RotateRefreshToken(ctx, "a2", auth.RefreshToken{TokenHash: "a4", ExpiresAt: now.Add(time.Hour)}, now); !errors.Is(err, auth.ErrInvalidRefreshToken) {
t.Errorf("a2 should be revoked: %v", err)
}
if n := count(t, db, "SELECT COUNT(*) FROM refresh_tokens WHERE user_id = ? AND revoked_at IS NULL", bobID); n != 1 {
t.Errorf("another user's token was revoked (active = %d)", n)
}
})
}
func TestRefreshRepoConcurrentRotationHasOneWinner(t *testing.T) {
forEachBackend(t, func(t *testing.T, db *bun.DB, _ string) {
ctx := context.Background()
repo := NewRefreshRepo(db)
now := time.Now()
newUserWithToken(t, db, "alice", "shared", now.Add(time.Hour))
var wins atomic.Int64
var wg sync.WaitGroup
for i := 0; i < 8; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
next := auth.RefreshToken{TokenHash: "next-" + string(rune('a'+i)), ExpiresAt: now.Add(time.Hour)}
if _, err := repo.RotateRefreshToken(ctx, "shared", next, now); err == nil {
wins.Add(1)
}
}(i)
}
wg.Wait()
if wins.Load() != 1 {
t.Fatalf("%d concurrent rotations of the same token succeeded, want exactly 1", wins.Load())
}
})
}
func TestRefreshRepoRevoke(t *testing.T) {
forEachBackend(t, func(t *testing.T, db *bun.DB, _ string) {
ctx := context.Background()
repo := NewRefreshRepo(db)
now := time.Now()
uid := newUserWithToken(t, db, "alice", "t1", now.Add(time.Hour))
_ = repo.SaveRefreshToken(ctx, auth.RefreshToken{UserID: uid, TokenHash: "t2", ExpiresAt: now.Add(time.Hour)})
if err := repo.RevokeRefreshToken(ctx, "t1", now); err != nil {
t.Fatal(err)
}
if err := repo.RevokeRefreshToken(ctx, "t1", now); err != nil { // idempotent
t.Fatal(err)
}
if err := repo.RevokeRefreshToken(ctx, "unknown", now); err != nil {
t.Fatal(err)
}
if _, err := repo.RotateRefreshToken(ctx, "t1", auth.RefreshToken{TokenHash: "x", ExpiresAt: now.Add(time.Hour)}, now); !errors.Is(err, auth.ErrInvalidRefreshToken) {
t.Errorf("revoked token still rotates: %v", err)
}
// t1 above was a reuse and revoked t2 as well; start again to test RevokeUser alone.
uid2 := newUserWithToken(t, db, "bob", "b1", now.Add(time.Hour))
if err := repo.RevokeUserRefreshTokens(ctx, uid2, now); err != nil {
t.Fatal(err)
}
if n := count(t, db, "SELECT COUNT(*) FROM refresh_tokens WHERE user_id = ? AND revoked_at IS NULL", uid2); n != 0 {
t.Errorf("active tokens = %d, want 0", n)
}
})
}
func TestDeletingAUserDeletesTheirRefreshTokens(t *testing.T) {
forEachBackend(t, func(t *testing.T, db *bun.DB, _ string) {
uid := newUserWithToken(t, db, "alice", "t1", time.Now().Add(time.Hour))
if err := NewUserRepo(db).DeleteUser(context.Background(), uid); err != nil {
t.Fatal(err)
}
if n := count(t, db, "SELECT COUNT(*) FROM refresh_tokens"); n != 0 {
t.Errorf("refresh tokens left = %d, want 0", n)
}
})
}

129
internal/storage/refresh.go Normal file
View file

@ -0,0 +1,129 @@
package storage
import (
"context"
"database/sql"
"errors"
"fmt"
"time"
"github.com/uptrace/bun"
"codeberg.org/squidd/sonda/internal/auth"
)
type refreshRow struct {
bun.BaseModel `bun:"table:refresh_tokens"`
ID int64 `bun:"id,pk,autoincrement"`
UserID int64 `bun:"user_id,notnull"`
TokenHash string `bun:"token_hash,notnull"`
CreatedAt int64 `bun:"created_at,notnull"`
ExpiresAt int64 `bun:"expires_at,notnull"`
RevokedAt sql.NullInt64 `bun:"revoked_at"`
}
// RefreshRepo stores refresh token hashes. It implements auth.RefreshStore.
type RefreshRepo struct{ db *bun.DB }
// NewRefreshRepo builds a RefreshRepo.
func NewRefreshRepo(db *bun.DB) *RefreshRepo { return &RefreshRepo{db: db} }
// SaveRefreshToken stores a new active token.
func (r *RefreshRepo) SaveRefreshToken(ctx context.Context, t auth.RefreshToken) error {
row := &refreshRow{
UserID: t.UserID, TokenHash: t.TokenHash,
CreatedAt: time.Now().Unix(), ExpiresAt: t.ExpiresAt.Unix(),
}
if _, err := r.db.NewInsert().Model(row).Exec(ctx); err != nil {
return fmt.Errorf("insert refresh token: %w", err)
}
return nil
}
// RotateRefreshToken revokes an active token and stores its successor in one
// transaction. The revoke is a single conditional UPDATE, so of any number of
// concurrent calls with the same token exactly one succeeds.
func (r *RefreshRepo) RotateRefreshToken(ctx context.Context, oldHash string, next auth.RefreshToken, now time.Time) (int64, error) {
var userID int64
var reused bool
err := r.db.RunInTx(ctx, nil, func(ctx context.Context, tx bun.Tx) error {
res, err := tx.NewUpdate().Model((*refreshRow)(nil)).
Set("revoked_at = ?", now.Unix()).
Where("token_hash = ?", oldHash).
Where("revoked_at IS NULL").
Where("expires_at > ?", now.Unix()).
Exec(ctx)
if err != nil {
return fmt.Errorf("revoke refresh token: %w", err)
}
n, err := res.RowsAffected()
if err != nil {
return err
}
var old refreshRow
err = tx.NewSelect().Model(&old).Where("token_hash = ?", oldHash).Limit(1).Scan(ctx)
if errors.Is(err, sql.ErrNoRows) {
return nil // unknown token: nothing to do, reported below
}
if err != nil {
return fmt.Errorf("select refresh token: %w", err)
}
if n == 0 {
// Known token that is revoked or expired. Revoked means somebody
// presented a spent token: assume theft and end every session.
if old.RevokedAt.Valid {
reused = true
_, err := tx.NewUpdate().Model((*refreshRow)(nil)).
Set("revoked_at = ?", now.Unix()).
Where("user_id = ?", old.UserID).Where("revoked_at IS NULL").Exec(ctx)
if err != nil {
return fmt.Errorf("revoke user tokens: %w", err)
}
}
return nil
}
userID = old.UserID
row := &refreshRow{
UserID: userID, TokenHash: next.TokenHash,
CreatedAt: now.Unix(), ExpiresAt: next.ExpiresAt.Unix(),
}
if _, err := tx.NewInsert().Model(row).Exec(ctx); err != nil {
return fmt.Errorf("insert next refresh token: %w", err)
}
return nil
})
if err != nil {
return 0, err
}
if userID == 0 || reused {
return 0, auth.ErrInvalidRefreshToken
}
return userID, nil
}
// RevokeRefreshToken revokes one token. Unknown or already revoked tokens are ignored.
func (r *RefreshRepo) RevokeRefreshToken(ctx context.Context, hash string, now time.Time) error {
_, err := r.db.NewUpdate().Model((*refreshRow)(nil)).
Set("revoked_at = ?", now.Unix()).
Where("token_hash = ?", hash).Where("revoked_at IS NULL").Exec(ctx)
if err != nil {
return fmt.Errorf("revoke refresh token: %w", err)
}
return nil
}
// RevokeUserRefreshTokens revokes every active token of a user.
func (r *RefreshRepo) RevokeUserRefreshTokens(ctx context.Context, userID int64, now time.Time) error {
_, err := r.db.NewUpdate().Model((*refreshRow)(nil)).
Set("revoked_at = ?", now.Unix()).
Where("user_id = ?", userID).Where("revoked_at IS NULL").Exec(ctx)
if err != nil {
return fmt.Errorf("revoke user refresh tokens: %w", err)
}
return nil
}

View file

@ -22,7 +22,7 @@ func TestUserRepo(t *testing.T) {
t.Fatalf("CountUsers = %d, %v", n, err)
}
u, err := repo.CreateUser(ctx, "Alice", "hash1")
u, err := repo.CreateUser(ctx, "Alice", "hash1", false)
if err != nil {
t.Fatal(err)
}
@ -40,7 +40,7 @@ func TestUserRepo(t *testing.T) {
}
// Same name in another case is a duplicate.
if _, err := repo.CreateUser(ctx, "ALICE", "hash2"); !errors.Is(err, auth.ErrUsernameTaken) {
if _, err := repo.CreateUser(ctx, "ALICE", "hash2", false); !errors.Is(err, auth.ErrUsernameTaken) {
t.Errorf("duplicate: err = %v, want ErrUsernameTaken", err)
}
@ -60,11 +60,11 @@ func TestListeningRepo(t *testing.T) {
users := NewUserRepo(db)
repo := NewListeningRepo(db)
u1, err := users.CreateUser(ctx, "alice", "h")
u1, err := users.CreateUser(ctx, "alice", "h", false)
if err != nil {
t.Fatal(err)
}
u2, err := users.CreateUser(ctx, "bob", "h")
u2, err := users.CreateUser(ctx, "bob", "h", false)
if err != nil {
t.Fatal(err)
}

View file

@ -156,8 +156,8 @@ func TestMigrateCreatesSchemaAndIsIdempotent(t *testing.T) {
if err := db.QueryRow("SELECT COUNT(*) FROM schema_migrations").Scan(&applied); err != nil {
t.Fatal(err)
}
if applied != 3 {
t.Errorf("applied migrations = %d, want 3", applied)
if applied != 4 {
t.Errorf("applied migrations = %d, want 4", applied)
}
})
}

View file

@ -23,11 +23,12 @@ type userRow struct {
ID int64 `bun:"id,pk,autoincrement"`
Username string `bun:"username,notnull"`
PasswordHash string `bun:"password_hash,notnull"`
IsAdmin bool `bun:"is_admin,notnull"`
CreatedAt int64 `bun:"created_at,notnull"`
}
func (r userRow) toUser() auth.User {
return auth.User{ID: r.ID, Username: r.Username, CreatedAt: time.Unix(r.CreatedAt, 0)}
return auth.User{ID: r.ID, Username: r.Username, IsAdmin: r.IsAdmin, CreatedAt: time.Unix(r.CreatedAt, 0)}
}
// UserRepo stores users. It implements auth.UserStore.
@ -42,9 +43,15 @@ func (r *UserRepo) CountUsers(ctx context.Context) (int, error) {
return int(n), err
}
// CountAdmins returns how many users are admins.
func (r *UserRepo) CountAdmins(ctx context.Context) (int, error) {
n, err := r.db.NewSelect().Model((*userRow)(nil)).Where("is_admin = ?", true).Count(ctx)
return int(n), err
}
// CreateUser inserts a user. Usernames are unique case-insensitively.
func (r *UserRepo) CreateUser(ctx context.Context, username, passwordHash string) (auth.User, error) {
row := &userRow{Username: username, PasswordHash: passwordHash, CreatedAt: time.Now().Unix()}
func (r *UserRepo) CreateUser(ctx context.Context, username, passwordHash string, isAdmin bool) (auth.User, error) {
row := &userRow{Username: username, PasswordHash: passwordHash, IsAdmin: isAdmin, CreatedAt: time.Now().Unix()}
if _, err := r.db.NewInsert().Model(row).Exec(ctx); err != nil {
if isUniqueViolation(err) {
return auth.User{}, auth.ErrUsernameTaken
@ -70,6 +77,66 @@ func (r *UserRepo) UserByUsername(ctx context.Context, username string) (auth.Us
// postgresUniqueViolation is the SQLSTATE for unique_violation.
const postgresUniqueViolation = "23505"
// UserByID finds a user by id and returns their password hash.
func (r *UserRepo) UserByID(ctx context.Context, id int64) (auth.User, string, error) {
var row userRow
err := r.db.NewSelect().Model(&row).Where("id = ?", id).Limit(1).Scan(ctx)
if errors.Is(err, sql.ErrNoRows) {
return auth.User{}, "", auth.ErrUserNotFound
}
if err != nil {
return auth.User{}, "", fmt.Errorf("select user: %w", err)
}
return row.toUser(), row.PasswordHash, nil
}
// ListUsers returns every user, oldest first.
func (r *UserRepo) ListUsers(ctx context.Context) ([]auth.User, error) {
var rows []userRow
if err := r.db.NewSelect().Model(&rows).OrderExpr("id").Scan(ctx); err != nil {
return nil, fmt.Errorf("list users: %w", err)
}
out := make([]auth.User, len(rows))
for i, row := range rows {
out[i] = row.toUser()
}
return out, nil
}
// SetAdmin sets the admin flag.
func (r *UserRepo) SetAdmin(ctx context.Context, id int64, isAdmin bool) error {
res, err := r.db.NewUpdate().Model((*userRow)(nil)).
Set("is_admin = ?", isAdmin).Where("id = ?", id).Exec(ctx)
return affectedOrNotFound(res, err, "set admin")
}
// SetPasswordHash replaces the stored password hash.
func (r *UserRepo) SetPasswordHash(ctx context.Context, id int64, passwordHash string) error {
res, err := r.db.NewUpdate().Model((*userRow)(nil)).
Set("password_hash = ?", passwordHash).Where("id = ?", id).Exec(ctx)
return affectedOrNotFound(res, err, "set password")
}
// DeleteUser removes a user; their refresh tokens and listening events go with them.
func (r *UserRepo) DeleteUser(ctx context.Context, id int64) error {
res, err := r.db.NewDelete().Model((*userRow)(nil)).Where("id = ?", id).Exec(ctx)
return affectedOrNotFound(res, err, "delete user")
}
func affectedOrNotFound(res sql.Result, err error, what string) error {
if err != nil {
return fmt.Errorf("%s: %w", what, err)
}
n, err := res.RowsAffected()
if err != nil {
return fmt.Errorf("%s: %w", what, err)
}
if n == 0 {
return auth.ErrUserNotFound
}
return nil
}
func isUniqueViolation(err error) bool {
var se *msqlite.Error
if errors.As(err, &se) {

View file

@ -0,0 +1,18 @@
-- Admin flag and rotating refresh tokens.
ALTER TABLE users ADD COLUMN is_admin BOOLEAN NOT NULL DEFAULT FALSE;
-- Accounts that already exist: the oldest one becomes the admin.
UPDATE users SET is_admin = TRUE WHERE id = (SELECT MIN(id) FROM users);
-- Only a hash of the token is stored, never the token itself.
CREATE TABLE refresh_tokens (
id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
user_id BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
token_hash TEXT NOT NULL UNIQUE, -- SHA-256 of the token, hex
created_at BIGINT NOT NULL, -- unix seconds
expires_at BIGINT NOT NULL, -- unix seconds
revoked_at BIGINT -- unix seconds, NULL while active
);
CREATE INDEX idx_refresh_tokens_user ON refresh_tokens(user_id);

View file

@ -0,0 +1,18 @@
-- Admin flag and rotating refresh tokens.
ALTER TABLE users ADD COLUMN is_admin INTEGER NOT NULL DEFAULT 0;
-- Accounts that already exist: the oldest one becomes the admin.
UPDATE users SET is_admin = 1 WHERE id = (SELECT MIN(id) FROM users);
-- Only a hash of the token is stored, never the token itself.
CREATE TABLE refresh_tokens (
id INTEGER PRIMARY KEY,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
token_hash TEXT NOT NULL UNIQUE, -- SHA-256 of the token, hex
created_at INTEGER NOT NULL, -- unix seconds
expires_at INTEGER NOT NULL, -- unix seconds
revoked_at INTEGER -- unix seconds, NULL while active
);
CREATE INDEX idx_refresh_tokens_user ON refresh_tokens(user_id);

View file

@ -20,7 +20,8 @@ env = "production" # "dev" or "production"
[auth]
jwt_secret = "" # required, 32+ chars: openssl rand -hex 32
token_ttl_hours = 168 # one week
access_ttl_minutes = 15 # lifetime of an access token
refresh_ttl_hours = 720 # lifetime of a refresh token (30 days)
[providers.lastfm]
api_key = ""