diff --git a/cmd/api/bootstrap.go b/cmd/api/bootstrap.go new file mode 100644 index 0000000..b321ef3 --- /dev/null +++ b/cmd/api/bootstrap.go @@ -0,0 +1,35 @@ +package main + +import ( + "context" + "errors" + "fmt" + "log" + "time" + + postgresstore "knowledge-governance/internal/platform/postgres" +) + +// bootstrapInitialAdmin creates the fixed day-one administrator when the user +// table is still empty. The initial password is a known constant the operator +// hands to the owner in person; must_change_password forces a private change +// on first login before any other screen is reachable. Once any user exists +// this is a no-op, so accounts are managed through the UI afterwards. +func bootstrapInitialAdmin(ctx context.Context, store *postgresstore.Store, now func() time.Time) error { + count, err := store.CountAuthUsers(ctx) + if err != nil { + return err + } + if count > 0 { + return nil + } + _, err = store.CreateInitialAdmin(ctx, "admin", "dobotai", now().UTC()) + if errors.Is(err, postgresstore.ErrAuthDuplicateUsername) { + return nil + } + if err != nil { + return fmt.Errorf("bootstrap initial admin: %w", err) + } + log.Printf("bootstrap: created initial admin account (first login must change the password)") + return nil +} diff --git a/cmd/api/main.go b/cmd/api/main.go index 0b305ae..50b3381 100644 --- a/cmd/api/main.go +++ b/cmd/api/main.go @@ -44,6 +44,10 @@ func run(ctx context.Context, getenv func(string) string) error { if err := postgresstore.ApplyMigrations(ctx, pool); err != nil { return err } + authStore := postgresstore.NewStore(pool) + if err := bootstrapInitialAdmin(ctx, authStore, time.Now); err != nil { + return err + } releaseAuthorizationToken := "" if config.ProductionReleaseRequestsEnabled { releaseAuthorizationToken, err = weknora.ReadAPIKeyFile(config.ProductionReleaseAuthTokenFile) @@ -82,6 +86,7 @@ func run(ctx context.Context, getenv func(string) string) error { ProductionBackupRestoreVerified: config.ProductionBackupRestoreVerified, ProductionReleaseAuthorizerRef: config.ProductionReleaseAuthorizerRef, ProductionReleaseAuthorizationToken: releaseAuthorizationToken, + Auth: &httpapi.AuthConfig{Store: authStore, SessionTTL: 12 * time.Hour}, }) if err != nil { return err diff --git a/go.mod b/go.mod index 7d48916..ad827c1 100644 --- a/go.mod +++ b/go.mod @@ -8,6 +8,7 @@ require ( github.com/aws/aws-sdk-go-v2/credentials v1.20.4 github.com/aws/aws-sdk-go-v2/service/s3 v1.101.0 github.com/jackc/pgx/v5 v5.9.2 + golang.org/x/crypto v0.57.0 ) require ( @@ -28,6 +29,6 @@ require ( github.com/jackc/pgpassfile v1.0.0 // indirect github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect github.com/jackc/puddle/v2 v2.2.2 // indirect - golang.org/x/sync v0.17.0 // indirect - golang.org/x/text v0.29.0 // indirect + golang.org/x/sync v0.23.0 // indirect + golang.org/x/text v0.42.0 // indirect ) diff --git a/go.sum b/go.sum index 1a07b91..12474eb 100644 --- a/go.sum +++ b/go.sum @@ -1,37 +1,23 @@ -github.com/aws/aws-sdk-go-v2 v1.41.7 h1:DWpAJt66FmnnaRIOT/8ASTucrvuDPZASqhhLey6tLY8= -github.com/aws/aws-sdk-go-v2 v1.41.7/go.mod h1:4LAfZOPHNVNQEckOACQx60Y8pSRjIkNZQz1w92xpMJc= github.com/aws/aws-sdk-go-v2 v1.47.0 h1:0jsHallhJCeaU0Ko48c/3FK1ctOQ7NpzggxriJOQ8MQ= github.com/aws/aws-sdk-go-v2 v1.47.0/go.mod h1:bttEH6JqnUL8LepvDVfdrds/fZ5bCIxzpe3abyUrhDU= github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.10 h1:gx1AwW1Iyk9Z9dD9F4akX5gnN3QZwUB20GGKH/I+Rho= github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.10/go.mod h1:qqY157uZoqm5OXq/amuaBJyC9hgBCBQnsaWnPe905GY= github.com/aws/aws-sdk-go-v2/config v1.33.4 h1:FzvkXKSzwqHni4U7nDigHg4jjtqMpVUuHgmZfSoJVQ0= github.com/aws/aws-sdk-go-v2/config v1.33.4/go.mod h1:VZqGZnZsCWVfK/iGPptJIyNIX3XEX6iQU2Rel4sLrr8= -github.com/aws/aws-sdk-go-v2/credentials v1.19.16 h1:r3RJBuU7X9ibt8RHbMjWE6y60QbKBiII6wSrXnapxSU= -github.com/aws/aws-sdk-go-v2/credentials v1.19.16/go.mod h1:6cx7zqDENJDbBIIWX6P8s0h6hqHC8Avbjh9Dseo27ug= github.com/aws/aws-sdk-go-v2/credentials v1.20.4 h1:hTvrJJseKbvw32kmiE0G+u/9ZqpqscjDrTigHIXP2qs= github.com/aws/aws-sdk-go-v2/credentials v1.20.4/go.mod h1:gWp9O1ZBWwpcIrgV+mVHk4gZUurAEDkgypu/OXOlIaw= github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.20.0 h1:AM4hHjww+PSFtt6E+UrBrPlZkWsePCLEt9AjkfQX+yM= github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.20.0/go.mod h1:3x/yXezeQjpOvBb4jEMxrS8SXvpdvJ5abv6l5c1gWM8= -github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.23 h1:GpT/TrnBYuE5gan2cZbTtvP+JlHsutdmlV2YfEyNde0= -github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.23/go.mod h1:xYWD6BS9ywC5bS3sz9Xh04whO/hzK2plt2Zkyrp4JuA= github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.3 h1:Hp/VgjP0BysR3OgLlR057Vz2LcbbVnoWeJ+3qWiS/fY= github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.3/go.mod h1:nwGV5qw7F1IZPgxCvA/ph8N2TAuz+BkRG/bXn808qMA= -github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.23 h1:bpd8vxhlQi2r1hiueOw02f/duEPTMK59Q4QMAoTTtTo= -github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.23/go.mod h1:15DfR2nw+CRHIk0tqNyifu3G1YdAOy68RftkhMDDwYk= github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.3 h1:MUaM4f+kj1ZIBPZfUS8cxP1GKXXZtHJjAthy93AN7SM= github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.3/go.mod h1:6YmVmEVRI5ZZzRjCSsb9SryKH0hAlMRdgA7kG9aDvBU= -github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.24 h1:OQqn11BtaYv1WLUowvcA30MpzIu8Ti4pcLPIIyoKZrA= -github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.24/go.mod h1:X5ZJyfwVrWA96GzPmUCWFQaEARPR7gCrpq2E92PJwAE= github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.3 h1:fuSCw4Z2qfRCztMPO3GXJNSiEp6Wee+WOLwrHHUMy9c= github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.3/go.mod h1:6SxcHheD1pPR5+kWm1wGvjlL/YqUsh267sAfEmN4K7A= -github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.9 h1:FLudkZLt5ci0ozzgkVo8BJGwvqNaZbTWb3UcucAateA= -github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.9/go.mod h1:w7wZ/s9qK7c8g4al+UyoF1Sp/Z45UwMGcqIzLWVQHWk= github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.19 h1:bAdDl/HkGCcGPoe25ToSHEw23VIxt6CT5fLcg111BKg= github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.19/go.mod h1:KaUzbLxv4CeSxh6ZCl9B4m7CuFenS8kUEaDs+f/DQr4= github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.15 h1:ieLCO1JxUWuxTZ1cRd0GAaeX7O6cIxnwk7tc1LsQhC4= github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.15/go.mod h1:e3IzZvQ3kAWNykvE0Tr0RDZCMFInMvhku3qNpcIQXhM= -github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.23 h1:pbrxO/kuIwgEsOPLkaHu0O+m4fNgLU8B3vxQ+72jTPw= -github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.23/go.mod h1:/CMNUqoj46HpS3MNRDEDIwcgEnrtZlKRaHNaHxIFpNA= github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.3 h1:bON1rJf67TSTDCKg816AAIE4xSTtoo9tl0XRkO72R+I= github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.3/go.mod h1:c5BBpjJcQXpfeq9iASyVKA3T6vX6B6LEXY4mL/gklDY= github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.23 h1:03xatSQO4+AM1lTAbnRg5OK528EUg744nW7F73U8DKw= @@ -46,8 +32,6 @@ github.com/aws/aws-sdk-go-v2/service/ssooidc v1.43.0 h1:obhahQXDEdVEv8y5bTKXR30L github.com/aws/aws-sdk-go-v2/service/ssooidc v1.43.0/go.mod h1:6twZZ/aXHNy1vXUO8koUbp++MYzMASkOgEBdkbJYmO0= github.com/aws/aws-sdk-go-v2/service/sts v1.50.0 h1:khXV3+K5D3f4e8xtplaRdSFn1bEg3gj5EBHQvbCOZbQ= github.com/aws/aws-sdk-go-v2/service/sts v1.50.0/go.mod h1:/8JRcdTt//hG0Q4BTmGbuOplT7ABe+5rdtqUHqXvYIM= -github.com/aws/smithy-go v1.25.1 h1:J8ERsGSU7d+aCmdQur5Txg6bVoYelvQJgtZehD12GkI= -github.com/aws/smithy-go v1.25.1/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc= github.com/aws/smithy-go v1.28.1 h1:R/nXH00c8qcfCzQVELtRw+eLQWtzv+VAIEFJ1/xxXlQ= github.com/aws/smithy-go v1.28.1/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= @@ -68,10 +52,12 @@ github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UV github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= -golang.org/x/sync v0.17.0 h1:l60nONMj9l5drqw6jlhIELNv9I0A4OFgRsG9k2oT9Ug= -golang.org/x/sync v0.17.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI= -golang.org/x/text v0.29.0 h1:1neNs90w9YzJ9BocxfsQNHKuAT4pkghyXc4nhZ6sJvk= -golang.org/x/text v0.29.0/go.mod h1:7MhJOA9CD2qZyOKYazxdYMF85OwPdEr9jTtBpO7ydH4= +golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M= +golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA= +golang.org/x/sync v0.23.0 h1:KameEIfc1IkluZyXWLn39Wd4tURc6GbCiISGiZm2bQk= +golang.org/x/sync v0.23.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= +golang.org/x/text v0.42.0 h1:JbOZXgfeCPU9gacVtYliJqOhD+zhrEqK4LfdpmlUZqI= +golang.org/x/text v0.42.0/go.mod h1:ojzP1Z+2QtioaF8DTtO8K5q7JWVVYwZKenzujK0Zd0E= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= diff --git a/internal/httpapi/auth.go b/internal/httpapi/auth.go new file mode 100644 index 0000000..d601a7b --- /dev/null +++ b/internal/httpapi/auth.go @@ -0,0 +1,180 @@ +package httpapi + +import ( + "context" + "net/http" + "strings" + "time" + + postgresstore "knowledge-governance/internal/platform/postgres" +) + +// Session identity injected by the auth middleware. Business handlers read it +// to stamp actor fields server-side; the browser never types a name. +type sessionIdentity struct { + UserID string + Username string + DisplayName string + Role string + MustChangePassword bool + SessionID string +} + +type sessionKey struct{} + +func sessionFrom(ctx context.Context) (sessionIdentity, bool) { + value, ok := ctx.Value(sessionKey{}).(sessionIdentity) + return value, ok +} + +const sessionCookieName = "kg_session" + +const ( + roleViewer = postgresstore.RoleViewer + roleEngineer = postgresstore.RoleEngineer + roleAdmin = postgresstore.RoleAdmin +) + +func roleRank(role string) int { + switch role { + case roleAdmin: + return 2 + case roleEngineer: + return 1 + default: + return 0 + } +} + +// AuthStore is the account/session capability the HTTP layer needs; the +// concrete postgres *Store implements it, and fakes keep handler tests cheap. +type AuthStore interface { + Login(ctx context.Context, username, password, userAgent string, now time.Time, ttl time.Duration) (postgresstore.LoginOutcome, error) + LookupSession(ctx context.Context, token string, now time.Time) (postgresstore.AuthSession, error) + Logout(ctx context.Context, sessionID string, now time.Time) error + TouchSession(ctx context.Context, sessionID string, now, expiresAt time.Time) error + ChangePassword(ctx context.Context, userID, oldPassword, newPassword string, now time.Time) error + CreateUser(ctx context.Context, username, displayName, role, password, createdBy string, now time.Time) (postgresstore.AuthUser, error) + GetAuthUserByID(ctx context.Context, id string) (postgresstore.AuthUser, error) + ListAuthUsers(ctx context.Context) ([]postgresstore.AuthUser, error) + SetUserRole(ctx context.Context, actorID, userID, role string, now time.Time) error + SetUserState(ctx context.Context, actorID, userID, state string, now time.Time) error + AdminResetPassword(ctx context.Context, actorID, userID, temporaryPassword string, now time.Time) error +} + +// AuthConfig wires the account/session store into the HTTP layer. When the +// server's Auth field is nil, auth stays disabled (unit tests and the local +// job-debug socket); production main must always provide it. +type AuthConfig struct { + Store AuthStore + Now func() time.Time + SessionTTL time.Duration +} + +func (auth AuthConfig) sessionTTL() time.Duration { + if auth.SessionTTL > 0 { + return auth.SessionTTL + } + return defaultSessionTTL +} + +func (auth AuthConfig) now() time.Time { + if auth.Now != nil { + return auth.Now() + } + return time.Now() +} + +func isPublicEndpoint(method, path string) bool { + switch path { + case "/health", "/livez", "/readyz": + return true + } + return path == "/api/v1/auth/login" && method == http.MethodPost +} + +func isAuthEndpoint(method, path string) bool { + return strings.HasPrefix(path, "/api/v1/auth/") +} + +// classify maps a request to the minimum role required. +func classifyRole(method, path string) string { + // The member roster exposes account identities and roles: admin-only for + // every method, checked before the read shortcut below. + if strings.HasPrefix(path, "/api/v1/users") { + return roleAdmin + } + if method == http.MethodGet { + return roleViewer + } + // Production authority is a role, not a typed name: both double-gated + // authorizations require admin on top of the environment switches. + if strings.HasSuffix(path, "/authorize-production") || strings.HasSuffix(path, "/authorize-rollback") || + (strings.HasPrefix(path, "/api/v1/release-executions/") && strings.HasSuffix(path, "/retry")) { + return roleAdmin + } + // Connector settings revisions are admin-only. + if strings.Contains(path, "/settings/revisions") { + return roleAdmin + } + // Everything else that mutates (review, batch, seal, confirm, start, retry, + // route visibility, disable) is engineer work; viewers cannot POST at all. + return roleEngineer +} + +// authenticate wraps the mux: cookie session → context identity → lockdown → +// RBAC. Business handlers assume a valid identity exists in the context. +func (auth AuthConfig) authenticate(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if isPublicEndpoint(r.Method, r.URL.Path) { + next.ServeHTTP(w, r) + return + } + cookie, err := r.Cookie(sessionCookieName) + if err != nil || cookie.Value == "" { + writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "authentication required"}) + return + } + session, err := auth.Store.LookupSession(r.Context(), cookie.Value, auth.now()) + if err != nil { + writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "authentication required"}) + return + } + identity := sessionIdentity{ + UserID: session.User.ID, Username: session.User.Username, DisplayName: session.User.DisplayName, + Role: session.User.Role, MustChangePassword: session.User.MustChangePassword, SessionID: session.ID, + } + if session.User.MustChangePassword && !isAuthEndpoint(r.Method, r.URL.Path) { + writeJSON(w, http.StatusForbidden, map[string]string{"error": "password change required"}) + return + } + if !isAuthEndpoint(r.Method, r.URL.Path) { + if roleRank(identity.Role) < roleRank(classifyRole(r.Method, r.URL.Path)) { + writeJSON(w, http.StatusForbidden, map[string]string{"error": "insufficient role"}) + return + } + } + ctx := context.WithValue(r.Context(), sessionKey{}, identity) + expiresAt := auth.now().UTC().Add(auth.sessionTTL()) + if err := auth.Store.TouchSession(r.Context(), session.ID, auth.now().UTC(), expiresAt); err != nil { + writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "could not refresh session"}) + return + } + auth.setSessionCookie(w, cookie.Value, expiresAt) + next.ServeHTTP(w, r.WithContext(ctx)) + }) +} + +func (auth AuthConfig) setSessionCookie(w http.ResponseWriter, token string, expiresAt time.Time) { + http.SetCookie(w, &http.Cookie{ + Name: sessionCookieName, Value: token, Path: "/", + Expires: expiresAt, HttpOnly: true, SameSite: http.SameSiteLaxMode, + }) +} + +func (auth AuthConfig) clearSessionCookie(w http.ResponseWriter) { + http.SetCookie(w, &http.Cookie{ + Name: sessionCookieName, Value: "", Path: "/", MaxAge: -1, Expires: time.Unix(0, 0), + HttpOnly: true, SameSite: http.SameSiteLaxMode, + }) +} diff --git a/internal/httpapi/auth_handlers.go b/internal/httpapi/auth_handlers.go new file mode 100644 index 0000000..8175d87 --- /dev/null +++ b/internal/httpapi/auth_handlers.go @@ -0,0 +1,121 @@ +package httpapi + +import ( + "errors" + "net/http" + "strings" + "time" + + postgresstore "knowledge-governance/internal/platform/postgres" +) + +const defaultSessionTTL = 12 * time.Hour + +type loginRequest struct { + Username string `json:"username"` + Password string `json:"password"` +} + +func (config Config) handleLogin(w http.ResponseWriter, r *http.Request) { + var input loginRequest + if err := decodeStrictJSON(r, &input); err != nil || input.Username == "" || input.Password == "" { + writeJSON(w, http.StatusBadRequest, map[string]string{"error": "username and password are required"}) + return + } + outcome, err := config.Auth.Store.Login(r.Context(), strings.TrimSpace(input.Username), input.Password, r.UserAgent(), config.Now().UTC(), config.Auth.SessionTTL) + switch { + case errors.Is(err, postgresstore.ErrAuthInvalidCredential): + writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "invalid username or password"}) + case errors.Is(err, postgresstore.ErrAuthLocked): + writeJSON(w, http.StatusTooManyRequests, map[string]string{"error": "account temporarily locked, try again later"}) + case errors.Is(err, postgresstore.ErrAuthUserDisabled): + writeJSON(w, http.StatusForbidden, map[string]string{"error": "account is disabled"}) + case err != nil: + writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "login failed"}) + default: + ttl := config.Auth.SessionTTL + if ttl <= 0 { + ttl = defaultSessionTTL + } + config.Auth.setSessionCookie(w, outcome.SessionToken, config.Now().UTC().Add(ttl)) + writeJSON(w, http.StatusOK, map[string]any{"data": userPayload(outcome.User)}) + } +} + +func userPayload(user postgresstore.AuthUser) map[string]any { + payload := map[string]any{ + "id": user.ID, "username": user.Username, "display_name": user.DisplayName, + "role": user.Role, "state": user.State, "must_change_password": user.MustChangePassword, + } + if user.LastLoginAt != nil { + payload["last_login_at"] = user.LastLoginAt.UTC().Format(time.RFC3339) + } + return payload +} + +func (config Config) handleLogout(w http.ResponseWriter, r *http.Request) { + if identity, ok := sessionFrom(r.Context()); ok && identity.SessionID != "" { + _ = config.Auth.Store.Logout(r.Context(), identity.SessionID, config.Now().UTC()) + } + config.Auth.clearSessionCookie(w) + writeJSON(w, http.StatusOK, map[string]any{"data": map[string]string{"status": "logged_out"}}) +} + +func (config Config) handleMe(w http.ResponseWriter, r *http.Request) { + identity, ok := sessionFrom(r.Context()) + if !ok { + writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "authentication required"}) + return + } + writeJSON(w, http.StatusOK, map[string]any{"data": map[string]any{ + "id": identity.UserID, "username": identity.Username, "display_name": identity.DisplayName, + "role": identity.Role, "must_change_password": identity.MustChangePassword, + }}) +} + +type changePasswordRequest struct { + CurrentPassword string `json:"current_password"` + NewPassword string `json:"new_password"` +} + +func (config Config) handleChangePassword(w http.ResponseWriter, r *http.Request) { + identity, ok := sessionFrom(r.Context()) + if !ok { + writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "authentication required"}) + return + } + var input changePasswordRequest + if err := decodeStrictJSON(r, &input); err != nil || input.CurrentPassword == "" || len(input.NewPassword) < 8 { + writeJSON(w, http.StatusBadRequest, map[string]string{"error": "current_password and new_password (min 8 chars) are required"}) + return + } + err := config.Auth.Store.ChangePassword(r.Context(), identity.UserID, input.CurrentPassword, input.NewPassword, config.Now().UTC()) + switch { + case errors.Is(err, postgresstore.ErrAuthInvalidCredential): + writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "current password is incorrect"}) + case errors.Is(err, postgresstore.ErrAuthInvalidUser): + writeJSON(w, http.StatusBadRequest, map[string]string{"error": "new password must differ from the old one"}) + case err != nil: + writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "password change failed"}) + default: + // ChangePassword revoked every session including this one; re-login + // with the new password so a forced first-login change keeps the + // operator inside the app instead of bouncing to the login screen. + outcome, loginErr := config.Auth.Store.Login(r.Context(), identity.Username, input.NewPassword, r.UserAgent(), config.Now().UTC(), config.Auth.SessionTTL) + if loginErr == nil { + ttl := config.Auth.SessionTTL + if ttl <= 0 { + ttl = defaultSessionTTL + } + config.Auth.setSessionCookie(w, outcome.SessionToken, config.Now().UTC().Add(ttl)) + } + writeJSON(w, http.StatusOK, map[string]any{"data": map[string]bool{"changed": true}}) + } +} + +func (config Config) authRoutes(mux *http.ServeMux) { + mux.HandleFunc("POST /api/v1/auth/login", config.handleLogin) + mux.HandleFunc("POST /api/v1/auth/logout", config.handleLogout) + mux.HandleFunc("GET /api/v1/auth/me", config.handleMe) + mux.HandleFunc("POST /api/v1/auth/change-password", config.handleChangePassword) +} diff --git a/internal/httpapi/auth_test.go b/internal/httpapi/auth_test.go new file mode 100644 index 0000000..af1f66a --- /dev/null +++ b/internal/httpapi/auth_test.go @@ -0,0 +1,426 @@ +package httpapi + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "knowledge-governance/internal/governance" + postgresstore "knowledge-governance/internal/platform/postgres" +) + +type fakeAuthStore struct { + users map[string]postgresstore.AuthUser + sessions map[string]string // token -> user id + passwords map[string]string // user id -> password + touched int + loggedOut []string + createdBy string + roleChanges []string + stateErrors []string +} + +func newFakeAuthStore() *fakeAuthStore { + store := &fakeAuthStore{users: map[string]postgresstore.AuthUser{}, sessions: map[string]string{}, passwords: map[string]string{}} + for _, seed := range []struct{ name, role string }{{"boss", roleAdmin}, {"eng", roleEngineer}, {"eye", roleViewer}} { + id := "usr-" + seed.name + store.users[seed.name] = postgresstore.AuthUser{ID: id, Username: seed.name, Role: seed.role, State: "active"} + store.passwords[id] = "passw0rd!" + } + return store +} + +func (f *fakeAuthStore) Login(ctx context.Context, username, password, userAgent string, now time.Time, ttl time.Duration) (postgresstore.LoginOutcome, error) { + user, ok := f.users[username] + if !ok || f.passwords[user.ID] != password { + return postgresstore.LoginOutcome{}, postgresstore.ErrAuthInvalidCredential + } + if user.State != "active" { + return postgresstore.LoginOutcome{}, postgresstore.ErrAuthUserDisabled + } + token := "tok-" + username + f.sessions[token] = user.ID + return postgresstore.LoginOutcome{SessionToken: token, SessionID: "ses-" + username, User: user}, nil +} + +func (f *fakeAuthStore) LookupSession(ctx context.Context, token string, now time.Time) (postgresstore.AuthSession, error) { + userID, ok := f.sessions[token] + if !ok { + return postgresstore.AuthSession{}, postgresstore.ErrAuthSessionInvalid + } + for _, user := range f.users { + if user.ID == userID { + return postgresstore.AuthSession{ID: "ses-" + user.Username, User: user, ExpiresAt: now.Add(time.Hour)}, nil + } + } + return postgresstore.AuthSession{}, postgresstore.ErrAuthSessionInvalid +} + +func (f *fakeAuthStore) Logout(ctx context.Context, sessionID string, now time.Time) error { + for token, userID := range f.sessions { + if "ses-"+strings.TrimPrefix(userID, "usr-") == sessionID { + delete(f.sessions, token) + } + } + f.loggedOut = append(f.loggedOut, sessionID) + return nil +} + +func (f *fakeAuthStore) TouchSession(ctx context.Context, sessionID string, now, expiresAt time.Time) error { + f.touched++ + return nil +} + +func (f *fakeAuthStore) ChangePassword(ctx context.Context, userID, oldPassword, newPassword string, now time.Time) error { + if f.passwords[userID] != oldPassword { + return postgresstore.ErrAuthInvalidCredential + } + f.passwords[userID] = newPassword + for name, user := range f.users { + if user.ID == userID { + fresh := user + fresh.MustChangePassword = false + f.users[name] = fresh + } + } + return nil +} + +func (f *fakeAuthStore) CreateUser(ctx context.Context, username, displayName, role, password, createdBy string, now time.Time) (postgresstore.AuthUser, error) { + if _, exists := f.users[username]; exists { + return postgresstore.AuthUser{}, postgresstore.ErrAuthDuplicateUsername + } + if role != roleAdmin && role != roleEngineer && role != roleViewer { + return postgresstore.AuthUser{}, postgresstore.ErrAuthInvalidUser + } + user := postgresstore.AuthUser{ID: "usr-" + username, Username: username, DisplayName: displayName, Role: role, State: "active", MustChangePassword: true} + f.users[username] = user + f.passwords[user.ID] = password + f.createdBy = createdBy + return user, nil +} + +func (f *fakeAuthStore) GetAuthUserByID(ctx context.Context, id string) (postgresstore.AuthUser, error) { + for _, user := range f.users { + if user.ID == id { + return user, nil + } + } + return postgresstore.AuthUser{}, postgresstore.ErrAuthUserNotFound +} + +func (f *fakeAuthStore) ListAuthUsers(ctx context.Context) ([]postgresstore.AuthUser, error) { + out := []postgresstore.AuthUser{} + for _, user := range f.users { + out = append(out, user) + } + return out, nil +} + +func (f *fakeAuthStore) SetUserRole(ctx context.Context, actorID, userID, role string, now time.Time) error { + if role != roleAdmin && role != roleEngineer && role != roleViewer { + return postgresstore.ErrAuthInvalidUser + } + f.roleChanges = append(f.roleChanges, actorID+">"+userID+":"+role) + return nil +} + +func (f *fakeAuthStore) SetUserState(ctx context.Context, actorID, userID, state string, now time.Time) error { + f.stateErrors = append(f.stateErrors, actorID+">"+userID+":"+state) + return nil +} + +func (f *fakeAuthStore) AdminResetPassword(ctx context.Context, actorID, userID, temporaryPassword string, now time.Time) error { + f.passwords[userID] = temporaryPassword + return nil +} + +func authTestServer(t *testing.T, store Store, auth *fakeAuthStore) http.Handler { + t.Helper() + handler, err := NewHandler(Config{Store: store, Auth: &AuthConfig{Store: auth, Now: func() time.Time { return time.Date(2026, 9, 13, 6, 0, 0, 0, time.UTC) }, SessionTTL: time.Hour}}) + if err != nil { + t.Fatalf("new handler: %v", err) + } + return handler +} + +func loginAs(t *testing.T, handler http.Handler, username string) *http.Cookie { + t.Helper() + rec := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/login", strings.NewReader(`{"username":"`+username+`","password":"passw0rd!"}`)) + req.Header.Set("Content-Type", "application/json") + handler.ServeHTTP(rec, req) + if rec.Code != http.StatusOK { + t.Fatalf("login %s = %d body=%s", username, rec.Code, rec.Body.String()) + } + for _, cookie := range rec.Result().Cookies() { + if cookie.Name == sessionCookieName { + return cookie + } + } + t.Fatal("no session cookie issued") + return nil +} + +func TestAuthLoginMeLogoutFlow(t *testing.T) { + auth := newFakeAuthStore() + handler := authTestServer(t, &fakeJobStore{}, auth) + + rec := httptest.NewRecorder() + handler.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/api/v1/auth/me", nil)) + if rec.Code != http.StatusUnauthorized { + t.Fatalf("anonymous me = %d", rec.Code) + } + + cookie := loginAs(t, handler, "eng") + rec = httptest.NewRecorder() + req := httptest.NewRequest(http.MethodGet, "/api/v1/auth/me", nil) + req.AddCookie(cookie) + handler.ServeHTTP(rec, req) + if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), `"role":"engineer"`) { + t.Fatalf("me = %d %s", rec.Code, rec.Body.String()) + } + + rec = httptest.NewRecorder() + req = httptest.NewRequest(http.MethodPost, "/api/v1/auth/logout", nil) + req.AddCookie(cookie) + handler.ServeHTTP(rec, req) + if rec.Code != http.StatusOK || len(auth.loggedOut) != 1 { + t.Fatalf("logout = %d %#v", rec.Code, auth.loggedOut) + } + + rec = httptest.NewRecorder() + req = httptest.NewRequest(http.MethodGet, "/api/v1/auth/me", nil) + req.AddCookie(cookie) + handler.ServeHTTP(rec, req) + if rec.Code != http.StatusUnauthorized { + t.Fatalf("me after logout = %d", rec.Code) + } +} + +func TestAuthRBACMatrix(t *testing.T) { + cases := []struct { + user, method, path, idem string + want int + }{ + {"", http.MethodPost, "/api/v1/release-batches", "k1", http.StatusUnauthorized}, + {"eye", http.MethodGet, "/api/v1/test-publications", "", http.StatusOK}, + {"eye", http.MethodPost, "/api/v1/release-batches", "k2", http.StatusForbidden}, + {"eng", http.MethodPost, "/api/v1/release-batches", "k3", http.StatusForbidden}, // batches need created_by name? use store fake -> 201 actually; adjusted below + } + _ = cases + auth := newFakeAuthStore() + store := &fakeJobStore{} + handler := authTestServer(t, store, auth) + + viewer := loginAs(t, handler, "eye") + engineer := loginAs(t, handler, "eng") + admin := loginAs(t, handler, "boss") + + // viewer may read, may not write + rec := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodGet, "/api/v1/release-capabilities", nil) + req.AddCookie(viewer) + handler.ServeHTTP(rec, req) + if rec.Code != http.StatusOK { + t.Fatalf("viewer read = %d", rec.Code) + } + rec = httptest.NewRecorder() + req = httptest.NewRequest(http.MethodPost, "/api/v1/release-change-sets", strings.NewReader(`{"name":"x"}`)) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Idempotency-Key", "rbac-viewer") + req.AddCookie(viewer) + handler.ServeHTTP(rec, req) + if rec.Code != http.StatusForbidden { + t.Fatalf("viewer write = %d", rec.Code) + } + + // engineer may create batches but not authorize production + rec = httptest.NewRecorder() + req = httptest.NewRequest(http.MethodPost, "/api/v1/release-change-sets", strings.NewReader(`{"name":"x"}`)) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Idempotency-Key", "rbac-eng") + req.AddCookie(engineer) + handler.ServeHTTP(rec, req) + if rec.Code != http.StatusCreated { + t.Fatalf("engineer changeset = %d body=%s", rec.Code, rec.Body.String()) + } + rec = httptest.NewRecorder() + req = httptest.NewRequest(http.MethodPost, "/api/v1/release-batches/rb-1/authorize-production", strings.NewReader(`{"confirmation":"publish-to-production"}`)) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Idempotency-Key", "rbac-eng-auth") + req.AddCookie(engineer) + handler.ServeHTTP(rec, req) + if rec.Code != http.StatusForbidden { + t.Fatalf("engineer authorize-production = %d", rec.Code) + } + + // engineer may not manage members + rec = httptest.NewRecorder() + req = httptest.NewRequest(http.MethodGet, "/api/v1/users", nil) + req.AddCookie(engineer) + handler.ServeHTTP(rec, req) + if rec.Code != http.StatusForbidden { + t.Fatalf("engineer list users = %d", rec.Code) + } + + // admin can manage members + rec = httptest.NewRecorder() + req = httptest.NewRequest(http.MethodPost, "/api/v1/users", strings.NewReader(`{"username":"new-eng","display_name":"新工","role":"engineer","password":"temppass1"}`)) + req.Header.Set("Content-Type", "application/json") + req.AddCookie(admin) + handler.ServeHTTP(rec, req) + if rec.Code != http.StatusCreated { + t.Fatalf("admin create user = %d body=%s", rec.Code, rec.Body.String()) + } + if auth.createdBy != "usr-boss" { + t.Fatalf("created_by not session-stamped: %q", auth.createdBy) + } +} + +func TestAuthSealAndBatchStampSessionActor(t *testing.T) { + auth := newFakeAuthStore() + store := &fakeJobStore{ + createBatchResult: governance.ReleaseBatch{ID: "rb-1", State: "draft", ItemCount: 1}, + sealBatchResult: governance.ReleaseBatch{ID: "rb-1", State: "sealed", ItemCount: 1}, + } + handler := authTestServer(t, store, auth) + engineer := loginAs(t, handler, "eng") + + rec := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodPost, "/api/v1/release-batches", bytes.NewBufferString(`{"name":"rbac","publication_ids":["tp-1"],"delete_publication_ids":[]}`)) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Idempotency-Key", "actor-batch") + req.AddCookie(engineer) + handler.ServeHTTP(rec, req) + if rec.Code != http.StatusCreated { + t.Fatalf("batch = %d body=%s", rec.Code, rec.Body.String()) + } + if store.createBatchRequest.CreatedBy != "eng" { + t.Fatalf("created_by=%q want session username", store.createBatchRequest.CreatedBy) + } + + rec = httptest.NewRecorder() + req = httptest.NewRequest(http.MethodPost, "/api/v1/release-batches/rb-1/seal", strings.NewReader(`{}`)) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Idempotency-Key", "actor-seal") + req.AddCookie(engineer) + handler.ServeHTTP(rec, req) + if rec.Code != http.StatusOK { + t.Fatalf("seal = %d body=%s", rec.Code, rec.Body.String()) + } + if store.sealBatchRequest.SealedBy != "eng" { + t.Fatalf("sealed_by=%q want eng", store.sealBatchRequest.SealedBy) + } +} + +func TestAuthMustChangePasswordLockdown(t *testing.T) { + auth := newFakeAuthStore() + user := auth.users["eng"] + user.MustChangePassword = true + auth.users["eng"] = user + store := &fakeJobStore{} + handler := authTestServer(t, store, auth) + cookie := loginAs(t, handler, "eng") + + rec := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodPost, "/api/v1/release-change-sets", strings.NewReader(`{"name":"x"}`)) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Idempotency-Key", "lockdown") + req.AddCookie(cookie) + handler.ServeHTTP(rec, req) + if rec.Code != http.StatusForbidden || !strings.Contains(rec.Body.String(), "password change required") { + t.Fatalf("locked write = %d %s", rec.Code, rec.Body.String()) + } + + // change-password itself stays reachable and clears the flag + rec = httptest.NewRecorder() + req = httptest.NewRequest(http.MethodPost, "/api/v1/auth/change-password", strings.NewReader(`{"current_password":"passw0rd!","new_password":"brand-new-pw"}`)) + req.Header.Set("Content-Type", "application/json") + req.AddCookie(cookie) + handler.ServeHTTP(rec, req) + if rec.Code != http.StatusOK { + t.Fatalf("change password = %d %s", rec.Code, rec.Body.String()) + } + + rec = httptest.NewRecorder() + req = httptest.NewRequest(http.MethodPost, "/api/v1/release-change-sets", strings.NewReader(`{"name":"y"}`)) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Idempotency-Key", "after-change") + req.AddCookie(cookie) + handler.ServeHTTP(rec, req) + if rec.Code != http.StatusCreated { + t.Fatalf("post-change write = %d %s", rec.Code, rec.Body.String()) + } +} + +func TestAuthLoginErrorsDoNotEnumerate(t *testing.T) { + auth := newFakeAuthStore() + handler := authTestServer(t, &fakeJobStore{}, auth) + bodies := []string{} + for _, body := range []string{`{"username":"nobody","password":"whatever"}`, `{"username":"eng","password":"wrong"}`} { + rec := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/login", strings.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + handler.ServeHTTP(rec, req) + if rec.Code != http.StatusUnauthorized { + t.Fatalf("login %s = %d", body, rec.Code) + } + var payload map[string]string + if json.Unmarshal(rec.Body.Bytes(), &payload) != nil { + t.Fatal("bad json") + } + bodies = append(bodies, payload["error"]) + } + if bodies[0] != bodies[1] { + t.Fatalf("username enumeration: %q vs %q", bodies[0], bodies[1]) + } +} + +func TestAuthDisabledKeepsLegacyOpenSocket(t *testing.T) { + store := &fakeJobStore{createBatchResult: governance.ReleaseBatch{ID: "rb-1", State: "draft"}} + handler, err := NewHandler(Config{Store: store}) + if err != nil { + t.Fatal(err) + } + rec := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodPost, "/api/v1/release-batches", bytes.NewBufferString(`{"name":"rbac","publication_ids":["tp-1"],"delete_publication_ids":[]}`)) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Idempotency-Key", "legacy-batch") + handler.ServeHTTP(rec, req) + if rec.Code != http.StatusCreated { + t.Fatalf("legacy socket = %d %s", rec.Code, rec.Body.String()) + } + if store.createBatchRequest.CreatedBy != "system" { + t.Fatalf("legacy actor=%q want system", store.createBatchRequest.CreatedBy) + } +} + +func TestClassifyRoleMatrix(t *testing.T) { + // Pure matrix checks so route changes cannot silently widen authority. + cases := map[string]string{ + http.MethodPost + " /api/v1/release-batches/rb-1/authorize-production": roleAdmin, + http.MethodPost + " /api/v1/release-executions/rx-1/authorize-rollback": roleAdmin, + http.MethodPost + " /api/v1/release-executions/rx-1/retry": roleAdmin, + http.MethodPost + " /api/v1/users": roleAdmin, + http.MethodPost + " /api/v1/source-connections/c-1/settings/revisions": roleAdmin, + http.MethodPost + " /api/v1/review-candidates/tp-1/decision": roleEngineer, + http.MethodPost + " /api/v1/release-batches/rb-1/seal": roleEngineer, + http.MethodPost + " /api/v1/test-publications/start": roleEngineer, + http.MethodGet + " /api/v1/release-plan": roleViewer, + } + for key, want := range cases { + fields := strings.Fields(key) + if got := classifyRole(fields[0], fields[1]); got != want { + t.Fatalf("%s -> %s want %s", key, got, want) + } + } +} + +var _ = errors.Is diff --git a/internal/httpapi/server.go b/internal/httpapi/server.go index 13a6558..690a416 100644 --- a/internal/httpapi/server.go +++ b/internal/httpapi/server.go @@ -106,6 +106,7 @@ type Config struct { ProductionReleaseAuthorizerRef string ProductionReleaseAuthorizationToken string NewID func() (string, error) + Auth *AuthConfig } func NewHandler(config Config) (http.Handler, error) { @@ -344,6 +345,14 @@ func NewHandler(config Config) (http.Handler, error) { mux.HandleFunc("GET /api/v1/job-failures", func(w http.ResponseWriter, r *http.Request) { listJobFailures(w, r, config.Store) }) + if config.Auth != nil { + if config.Auth.Store == nil { + return nil, errors.New("auth configuration requires a store") + } + config.authRoutes(mux) + config.userRoutes(mux) + return config.Auth.authenticate(mux), nil + } return mux, nil } @@ -622,7 +631,6 @@ type catalogRouteInput struct { NodeIDs []string `json:"node_ids"` Policy string `json:"policy"` Visibility string `json:"visibility"` - OperatorRef string `json:"operator_ref"` Reason string `json:"reason"` } @@ -678,8 +686,7 @@ func routeCatalogFiles(w http.ResponseWriter, r *http.Request, config Config) { result, replayed, err := config.Store.RouteCatalogFilesWithOperation(r.Context(), governance.CatalogRouteRequest{ ConnectionID: input.ConnectionID, NodeIDs: input.NodeIDs, Visibility: visibility, TargetKnowledgeBaseID: targetKnowledgeBaseID, TargetKnowledgeBaseIDs: targetKnowledgeBaseIDs, - OperatorRef: strings.TrimSpace(input.OperatorRef), - Reason: strings.TrimSpace(input.Reason), Now: config.Now().UTC(), + OperatorRef: actorFor(r), Reason: strings.TrimSpace(input.Reason), Now: config.Now().UTC(), }, operationID) if errors.Is(err, postgresstore.ErrOperationRequestConflict) { writeJSON(w, http.StatusConflict, map[string]string{"error": "Idempotency-Key conflicts with a different request"}) @@ -791,7 +798,7 @@ type scopeRuleInput struct { DirectoryPath string `json:"directory_path"` SourceItemID string `json:"source_item_id"` Visibility governance.Visibility `json:"visibility"` - OperatorRef string `json:"operator_ref"` + Reason string `json:"reason"` } @@ -828,7 +835,7 @@ func mutateScopeRule(w http.ResponseWriter, r *http.Request, config Config, clea request := governance.ScopeRuleMutation{ TargetType: input.TargetType, ConnectionID: strings.TrimSpace(input.ConnectionID), DirectoryPath: input.DirectoryPath, SourceItemID: strings.TrimSpace(input.SourceItemID), - Visibility: input.Visibility, OperatorRef: strings.TrimSpace(input.OperatorRef), Reason: strings.TrimSpace(input.Reason), + Visibility: input.Visibility, OperatorRef: actorFor(r), Reason: strings.TrimSpace(input.Reason), Clear: clear, Now: config.Now().UTC(), } if clear { @@ -1091,7 +1098,6 @@ func listReviewCandidates(w http.ResponseWriter, r *http.Request, store Store) { type reviewPublicationRequest struct { Decision string `json:"decision"` DecidedVisibility string `json:"decided_visibility"` - ReviewerRef string `json:"reviewer_ref"` DecisionCode string `json:"decision_code"` } @@ -1107,7 +1113,7 @@ func reviewPublication(w http.ResponseWriter, r *http.Request, config Config) { } review, replayed, err := config.Store.ReviewPublicationWithOperation(r.Context(), governance.ReviewPublicationRequest{ PublicationID: r.PathValue("id"), Decision: governance.ReviewState(input.Decision), - DecidedVisibility: governance.Visibility(input.DecidedVisibility), ReviewerRef: input.ReviewerRef, + DecidedVisibility: governance.Visibility(input.DecidedVisibility), ReviewerRef: actorFor(r), DecisionCode: input.DecisionCode, Now: config.Now().UTC(), }, operationID) switch { @@ -1222,7 +1228,6 @@ func activateUISettings(w http.ResponseWriter, r *http.Request, config Config) { type createReleaseBatchRequest struct { Name string `json:"name"` - CreatedBy string `json:"created_by"` PublicationIDs []string `json:"publication_ids"` DeletePublicationIDs []string `json:"delete_publication_ids"` ReleaseChangeSetID string `json:"release_change_set_id"` @@ -1239,7 +1244,7 @@ func createReleaseBatch(w http.ResponseWriter, r *http.Request, config Config) { return } batch, replayed, err := config.Store.CreateReleaseBatchWithOperation(r.Context(), governance.CreateReleaseBatchRequest{ - Name: input.Name, CreatedBy: input.CreatedBy, PublicationIDs: input.PublicationIDs, DeletePublicationIDs: input.DeletePublicationIDs, ReleaseChangeSetID: input.ReleaseChangeSetID, Now: config.Now().UTC(), + Name: input.Name, CreatedBy: actorFor(r), PublicationIDs: input.PublicationIDs, DeletePublicationIDs: input.DeletePublicationIDs, ReleaseChangeSetID: input.ReleaseChangeSetID, Now: config.Now().UTC(), }, operationID) switch { case errors.Is(err, postgresstore.ErrOperationRequestConflict): @@ -1262,8 +1267,7 @@ func createReleaseBatch(w http.ResponseWriter, r *http.Request, config Config) { } type generateReleaseChangeSetRequest struct { - Name string `json:"name"` - CreatedBy string `json:"created_by"` + Name string `json:"name"` } func getReleaseAuditChain(w http.ResponseWriter, r *http.Request, store Store) { @@ -1294,7 +1298,7 @@ func generateReleaseChangeSet(w http.ResponseWriter, r *http.Request, config Con return } set, replayed, err := config.Store.GenerateReleaseChangeSetWithOperation(r.Context(), governance.GenerateReleaseChangeSetRequest{ - Name: input.Name, CreatedBy: input.CreatedBy, Now: config.Now().UTC(), + Name: input.Name, CreatedBy: actorFor(r), Now: config.Now().UTC(), }, operationID) switch { case errors.Is(err, postgresstore.ErrOperationRequestConflict): @@ -1358,16 +1362,14 @@ func confirmReleaseChangeSet(w http.ResponseWriter, r *http.Request, config Conf if !ok { return } - var input struct { - ConfirmedBy string `json:"confirmed_by"` - } + var input struct{} if err := decodeStrictJSON(r, &input); err != nil { writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid confirmation request"}) return } id := r.PathValue("id") set, replayed, err := config.Store.ConfirmReleaseChangeSetWithOperation(r.Context(), governance.ConfirmReleaseChangeSetRequest{ - ChangeSetID: id, ConfirmedBy: input.ConfirmedBy, Now: config.Now().UTC(), + ChangeSetID: id, ConfirmedBy: actorFor(r), Now: config.Now().UTC(), }, operationID) switch { case errors.Is(err, postgresstore.ErrOperationRequestConflict): @@ -1389,9 +1391,7 @@ func confirmReleaseChangeSet(w http.ResponseWriter, r *http.Request, config Conf } } -type sealReleaseBatchRequest struct { - SealedBy string `json:"sealed_by"` -} +type sealReleaseBatchRequest struct{} func sealReleaseBatch(w http.ResponseWriter, r *http.Request, config Config) { operationID, ok := requireOperationID(w, r) @@ -1404,7 +1404,7 @@ func sealReleaseBatch(w http.ResponseWriter, r *http.Request, config Config) { return } batch, replayed, err := config.Store.SealReleaseBatchWithOperation(r.Context(), governance.SealReleaseBatchRequest{ - BatchID: r.PathValue("id"), SealedBy: input.SealedBy, Now: config.Now().UTC(), + BatchID: r.PathValue("id"), SealedBy: actorFor(r), Now: config.Now().UTC(), }, operationID) switch { case errors.Is(err, postgresstore.ErrOperationRequestConflict): @@ -1451,7 +1451,7 @@ func authorizeProductionRelease(w http.ResponseWriter, r *http.Request, config C return } execution, replayed, err := config.Store.AuthorizeReleaseBatchWithOperation(r.Context(), governance.AuthorizeReleaseBatchRequest{ - BatchID: r.PathValue("id"), AuthorizedBy: config.ProductionReleaseAuthorizerRef, + BatchID: r.PathValue("id"), AuthorizedBy: productionAuthorizer(r, config), AuthorizationCode: "production_release_authorized", Now: config.Now().UTC(), }, operationID) switch { @@ -1496,7 +1496,7 @@ func authorizeProductionRollback(w http.ResponseWriter, r *http.Request, config return } execution, replayed, err := config.Store.AuthorizeReleaseRollbackWithOperation(r.Context(), governance.AuthorizeReleaseRollbackRequest{ - PriorExecutionID: r.PathValue("id"), AuthorizedBy: config.ProductionReleaseAuthorizerRef, + PriorExecutionID: r.PathValue("id"), AuthorizedBy: productionAuthorizer(r, config), AuthorizationCode: "production_rollback_authorized", Now: config.Now().UTC(), }, operationID) switch { @@ -1560,6 +1560,17 @@ func retryProductionRelease(w http.ResponseWriter, r *http.Request, config Confi writeJSON(w, http.StatusAccepted, map[string]any{"data": safeReleaseExecution(execution), "operation": operation}) } +// productionAuthorizer names the human behind a production double-gate call. +// With auth enabled the session identity (an admin, enforced by the RBAC +// matrix) is authoritative; the env-declared ref is only the fallback for the +// auth-disabled development socket. +func productionAuthorizer(r *http.Request, config Config) string { + if identity, ok := sessionFrom(r.Context()); ok { + return identity.Username + } + return config.ProductionReleaseAuthorizerRef +} + func productionReleaseAuthorized(r *http.Request, token string) bool { provided := r.Header.Get("Authorization") expected := "Bearer " + token @@ -1700,9 +1711,8 @@ func listTestPublications(w http.ResponseWriter, r *http.Request, store Store) { } type confirmChangeSetInput struct { - ItemSeqs []int64 `json:"item_seqs"` - OperatorRef string `json:"operator_ref"` - Reason string `json:"reason"` + ItemSeqs []int64 `json:"item_seqs"` + Reason string `json:"reason"` } func confirmCatalogChangeSet(w http.ResponseWriter, r *http.Request, config Config) { @@ -1719,7 +1729,7 @@ func confirmCatalogChangeSet(w http.ResponseWriter, r *http.Request, config Conf } result, replayed, err := config.Store.ConfirmCatalogChangeSetWithOperation(r.Context(), governance.ConfirmCatalogChangeSetRequest{ ChangeSetID: r.PathValue("id"), ItemSeqs: input.ItemSeqs, - OperatorRef: input.OperatorRef, Reason: input.Reason, + OperatorRef: actorFor(r), Reason: input.Reason, InternalTargetKBID: config.InternalRoutingKnowledgeBaseID, ExternalTargetKBID: config.ExternalRoutingKnowledgeBaseID, Now: config.Now().UTC(), }, operationID) @@ -1743,7 +1753,6 @@ func confirmCatalogChangeSet(w http.ResponseWriter, r *http.Request, config Conf type startTestPublicationsInput struct { PublicationIDs []string `json:"publication_ids"` - OperatorRef string `json:"operator_ref"` Reason string `json:"reason"` } @@ -1757,10 +1766,9 @@ func startTestPublications(w http.ResponseWriter, r *http.Request, config Config writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid processing confirmation"}) return } - operator := strings.TrimSpace(input.OperatorRef) reason := strings.TrimSpace(input.Reason) - if operator == "" || len(operator) > 128 || reason == "" || len(reason) > 500 { - writeJSON(w, http.StatusBadRequest, map[string]string{"error": "operator_ref and reason are required"}) + if reason == "" || len(reason) > 500 { + writeJSON(w, http.StatusBadRequest, map[string]string{"error": "reason is required"}) return } seen := make(map[string]bool, len(input.PublicationIDs)) @@ -1773,7 +1781,7 @@ func startTestPublications(w http.ResponseWriter, r *http.Request, config Config } result, replayed, err := config.Store.StartTestPublicationsWithOperation(r.Context(), governance.StartTestPublicationsRequest{ PublicationIDs: input.PublicationIDs, - OperatorRef: operator, + OperatorRef: actorFor(r), Reason: reason, Now: config.Now().UTC(), }, operationID) @@ -1826,10 +1834,9 @@ func retryPublicationsBatch(w http.ResponseWriter, r *http.Request, config Confi writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid retry batch"}) return } - operator := strings.TrimSpace(input.OperatorRef) reason := strings.TrimSpace(input.Reason) - if operator == "" || len(operator) > 128 || reason == "" || len(reason) > 500 { - writeJSON(w, http.StatusBadRequest, map[string]string{"error": "operator_ref and reason are required"}) + if reason == "" || len(reason) > 500 { + writeJSON(w, http.StatusBadRequest, map[string]string{"error": "reason is required"}) return } seen := make(map[string]bool, len(input.PublicationIDs)) @@ -1842,7 +1849,7 @@ func retryPublicationsBatch(w http.ResponseWriter, r *http.Request, config Confi } result, replayed, err := config.Store.RetryPublicationsBatchWithOperation(r.Context(), governance.RetryPublicationsBatchRequest{ PublicationIDs: input.PublicationIDs, - OperatorRef: operator, + OperatorRef: actorFor(r), Reason: reason, Now: config.Now().UTC(), }, operationID) diff --git a/internal/httpapi/server_test.go b/internal/httpapi/server_test.go index 11f9f2d..810ab58 100644 --- a/internal/httpapi/server_test.go +++ b/internal/httpapi/server_test.go @@ -118,7 +118,7 @@ func TestHandlerListsJobFailuresAndRunsServerSideBatchRetry(t *testing.T) { recorder = httptest.NewRecorder() request := httptest.NewRequest(http.MethodPost, "/api/v1/test-publications/retry-batch", - strings.NewReader(`{"publication_ids":["tp-1","tp-2"],"operator_ref":"姚工","reason":"解析服务恢复"}`)) + strings.NewReader(`{"publication_ids":["tp-1","tp-2"],"reason":"解析服务恢复"}`)) request.Header.Set("Content-Type", "application/json") request.Header.Set("Idempotency-Key", "op-batch-1") handler.ServeHTTP(recorder, request) @@ -145,14 +145,14 @@ func TestHandlerListsJobFailuresAndRunsServerSideBatchRetry(t *testing.T) { // Missing Idempotency-Key is rejected before touching the store. recorder = httptest.NewRecorder() handler.ServeHTTP(recorder, httptest.NewRequest(http.MethodPost, "/api/v1/test-publications/retry-batch", - strings.NewReader(`{"publication_ids":["tp-1"],"operator_ref":"姚工","reason":"r"}`))) + strings.NewReader(`{"publication_ids":["tp-1"],"reason":"r"}`))) if recorder.Code != http.StatusBadRequest { t.Fatalf("missing key status = %d", recorder.Code) } // Duplicate ids rejected. recorder = httptest.NewRecorder() dup := httptest.NewRequest(http.MethodPost, "/api/v1/test-publications/retry-batch", - strings.NewReader(`{"publication_ids":["tp-1","tp-1"],"operator_ref":"姚工","reason":"r"}`)) + strings.NewReader(`{"publication_ids":["tp-1","tp-1"],"reason":"r"}`)) dup.Header.Set("Idempotency-Key", "op-dup") handler.ServeHTTP(recorder, dup) if recorder.Code != http.StatusBadRequest { @@ -224,7 +224,7 @@ func TestHandlerSetsListsAndClearsAuditedScopeRules(t *testing.T) { t.Fatal(err) } set := httptest.NewRecorder() - request := httptest.NewRequest(http.MethodPut, "/api/v1/scope-rules", bytes.NewBufferString(`{"target_type":"directory","connection_id":"conn-safe","directory_path":"产品","visibility":"internal","operator_ref":"engineer-1","reason":"内部资料"}`)) + request := httptest.NewRequest(http.MethodPut, "/api/v1/scope-rules", bytes.NewBufferString(`{"target_type":"directory","connection_id":"conn-safe","directory_path":"产品","visibility":"internal","reason":"内部资料"}`)) request.Header.Set("Idempotency-Key", "op-scope-set") handler.ServeHTTP(set, request) if set.Code != http.StatusOK || store.scopeRuleRequest.ConnectionID != "conn-safe" || store.scopeRuleOperationID != "op-scope-set" || store.scopeRuleRequest.Clear || store.scopeRuleRequest.Now != now || !strings.Contains(set.Body.String(), `"operation":"created"`) { @@ -237,7 +237,7 @@ func TestHandlerSetsListsAndClearsAuditedScopeRules(t *testing.T) { t.Fatalf("list=%d id=%q body=%s", list.Code, store.scopeRuleConnectionID, list.Body.String()) } clear := httptest.NewRecorder() - request = httptest.NewRequest(http.MethodDelete, "/api/v1/scope-rules", bytes.NewBufferString(`{"target_type":"directory","connection_id":"conn-safe","directory_path":"产品","operator_ref":"engineer-1","reason":"恢复来源设置"}`)) + request = httptest.NewRequest(http.MethodDelete, "/api/v1/scope-rules", bytes.NewBufferString(`{"target_type":"directory","connection_id":"conn-safe","directory_path":"产品","reason":"恢复来源设置"}`)) request.Header.Set("Idempotency-Key", "op-scope-clear") handler.ServeHTTP(clear, request) if clear.Code != http.StatusOK || !store.scopeRuleRequest.Clear || store.scopeRuleRequest.Visibility != "" || !strings.Contains(clear.Body.String(), `"operation":"created"`) { @@ -249,7 +249,7 @@ func TestHandlerRejectsUnsafeScopeRuleBeforeStore(t *testing.T) { store := &fakeJobStore{} handler, _ := NewHandler(Config{Store: store, Now: time.Now}) response := httptest.NewRecorder() - request := httptest.NewRequest(http.MethodPut, "/api/v1/scope-rules", bytes.NewBufferString(`{"target_type":"directory","connection_id":"conn-safe","directory_path":"../private","visibility":"external","operator_ref":"engineer","reason":"bad"}`)) + request := httptest.NewRequest(http.MethodPut, "/api/v1/scope-rules", bytes.NewBufferString(`{"target_type":"directory","connection_id":"conn-safe","directory_path":"../private","visibility":"external","reason":"bad"}`)) handler.ServeHTTP(response, request) if response.Code != http.StatusBadRequest || store.scopeRuleRequest.TargetType != "" { t.Fatalf("status=%d request=%#v", response.Code, store.scopeRuleRequest) @@ -354,7 +354,7 @@ func TestHandlerRoutesSelectedCatalogFilesToServerBoundScopeKB(t *testing.T) { t.Fatal(err) } response := httptest.NewRecorder() - request := httptest.NewRequest(http.MethodPost, "/api/v1/source-catalog/route", bytes.NewBufferString(`{"connection_id":"conn-cat","node_ids":["file-a","file-b"],"visibility":"internal","operator_ref":"engineer-1","reason":"当前页批量标注"}`)) + request := httptest.NewRequest(http.MethodPost, "/api/v1/source-catalog/route", bytes.NewBufferString(`{"connection_id":"conn-cat","node_ids":["file-a","file-b"],"visibility":"internal","reason":"当前页批量标注"}`)) request.Header.Set("Idempotency-Key", "op-route-internal") handler.ServeHTTP(response, request) if response.Code != http.StatusAccepted || store.catalogRouteRequest.TargetKnowledgeBaseID != "kb-internal" || store.catalogRouteRequest.Now != now || store.catalogRouteRequest.Visibility != governance.VisibilityInternal { @@ -378,7 +378,7 @@ func TestHandlerRoutesBothScopesInOneAtomicRequest(t *testing.T) { t.Fatal(err) } response := httptest.NewRecorder() - request := httptest.NewRequest(http.MethodPost, "/api/v1/source-catalog/route", bytes.NewBufferString(`{"connection_id":"conn-cat","node_ids":["file-a"],"policy":"both","operator_ref":"engineer-1","reason":"同时供内外知识库使用"}`)) + request := httptest.NewRequest(http.MethodPost, "/api/v1/source-catalog/route", bytes.NewBufferString(`{"connection_id":"conn-cat","node_ids":["file-a"],"policy":"both","reason":"同时供内外知识库使用"}`)) request.Header.Set("Idempotency-Key", "op-route-both") handler.ServeHTTP(response, request) if response.Code != http.StatusAccepted || store.catalogRouteRequest.Visibility != governance.VisibilityBoth { @@ -399,7 +399,7 @@ func TestHandlerAcceptsBlockedPolicyWithoutAConfiguredTarget(t *testing.T) { t.Fatal(err) } response := httptest.NewRecorder() - request := httptest.NewRequest(http.MethodPost, "/api/v1/source-catalog/route", bytes.NewBufferString(`{"connection_id":"conn-cat","node_ids":["file-a"],"policy":"blocked","operator_ref":"engineer-1","reason":"资料已禁止导入"}`)) + request := httptest.NewRequest(http.MethodPost, "/api/v1/source-catalog/route", bytes.NewBufferString(`{"connection_id":"conn-cat","node_ids":["file-a"],"policy":"blocked","reason":"资料已禁止导入"}`)) request.Header.Set("Idempotency-Key", "op-route-blocked") handler.ServeHTTP(response, request) if response.Code != http.StatusAccepted || store.catalogRouteRequest.Visibility != governance.VisibilityBlocked || len(store.catalogRouteRequest.TargetKnowledgeBaseIDs) != 0 { @@ -566,7 +566,7 @@ func TestHandlerReleaseChangeSetEndpoints(t *testing.T) { if err != nil { t.Fatal(err) } - body := strings.NewReader(`{"name":"9月发布","created_by":"yaozhanghao"}`) + body := strings.NewReader(`{"name":"9月发布"}`) generated := httptest.NewRecorder() request := httptest.NewRequest(http.MethodPost, "/api/v1/release-change-sets", body) request.Header.Set("Idempotency-Key", "11111111-1111-4111-8111-111111111111") @@ -576,14 +576,14 @@ func TestHandlerReleaseChangeSetEndpoints(t *testing.T) { } // Missing header → 400 (C4 contract). noKey := httptest.NewRecorder() - handler.ServeHTTP(noKey, httptest.NewRequest(http.MethodPost, "/api/v1/release-change-sets", strings.NewReader(`{"name":"x","created_by":"y"}`))) + handler.ServeHTTP(noKey, httptest.NewRequest(http.MethodPost, "/api/v1/release-change-sets", strings.NewReader(`{"name":"x"}`))) if noKey.Code != http.StatusBadRequest { t.Fatalf("generate without key = %d", noKey.Code) } // Empty plan → 422 honest reason. store.generateChangeSetErr = postgresstore.ErrReleaseChangeSetEmpty empty := httptest.NewRecorder() - request = httptest.NewRequest(http.MethodPost, "/api/v1/release-change-sets", strings.NewReader(`{"name":"x","created_by":"y"}`)) + request = httptest.NewRequest(http.MethodPost, "/api/v1/release-change-sets", strings.NewReader(`{"name":"x"}`)) request.Header.Set("Idempotency-Key", "22222222-2222-4222-8222-222222222222") handler.ServeHTTP(empty, request) if empty.Code != http.StatusUnprocessableEntity { @@ -593,7 +593,7 @@ func TestHandlerReleaseChangeSetEndpoints(t *testing.T) { // Confirm path with envelope. store.confirmReleaseSetResult = governance.ReleaseChangeSet{ID: "rcs-1", State: "confirmed"} confirmed := httptest.NewRecorder() - request = httptest.NewRequest(http.MethodPost, "/api/v1/release-change-sets/rcs-1/confirm", strings.NewReader(`{"confirmed_by":"yaozhanghao"}`)) + request = httptest.NewRequest(http.MethodPost, "/api/v1/release-change-sets/rcs-1/confirm", strings.NewReader(`{}`)) request.Header.Set("Idempotency-Key", "33333333-3333-4333-8333-333333333333") handler.ServeHTTP(confirmed, request) if confirmed.Code != http.StatusOK || store.confirmReleaseSetRequest.ChangeSetID != "rcs-1" || !strings.Contains(confirmed.Body.String(), `"operation":"created"`) { @@ -602,7 +602,7 @@ func TestHandlerReleaseChangeSetEndpoints(t *testing.T) { // State conflict → 409. store.confirmReleaseSetErr = postgresstore.ErrReleaseChangeSetStateConflict conflict := httptest.NewRecorder() - request = httptest.NewRequest(http.MethodPost, "/api/v1/release-change-sets/rcs-1/confirm", strings.NewReader(`{"confirmed_by":"yaozhanghao"}`)) + request = httptest.NewRequest(http.MethodPost, "/api/v1/release-change-sets/rcs-1/confirm", strings.NewReader(`{}`)) request.Header.Set("Idempotency-Key", "44444444-4444-4444-8444-444444444444") handler.ServeHTTP(conflict, request) if conflict.Code != http.StatusConflict { @@ -629,7 +629,7 @@ func TestHandlerReleaseChangeSetEndpoints(t *testing.T) { // Batch citing a change set passes the binding through; unconfirmed → 422. store.createBatchResult = governance.ReleaseBatch{ID: "rb-1"} batch := httptest.NewRecorder() - request = httptest.NewRequest(http.MethodPost, "/api/v1/release-batches", strings.NewReader(`{"name":"批次","created_by":"yaozhanghao","publication_ids":["tp-1"],"delete_publication_ids":[],"release_change_set_id":"rcs-1"}`)) + request = httptest.NewRequest(http.MethodPost, "/api/v1/release-batches", strings.NewReader(`{"name":"批次","publication_ids":["tp-1"],"delete_publication_ids":[],"release_change_set_id":"rcs-1"}`)) request.Header.Set("Idempotency-Key", "55555555-5555-4555-8555-555555555555") handler.ServeHTTP(batch, request) if batch.Code != http.StatusCreated || store.createBatchRequest.ReleaseChangeSetID != "rcs-1" { @@ -637,7 +637,7 @@ func TestHandlerReleaseChangeSetEndpoints(t *testing.T) { } store.createBatchErr = postgresstore.ErrReleaseChangeSetUnconfirmed unconf := httptest.NewRecorder() - request = httptest.NewRequest(http.MethodPost, "/api/v1/release-batches", strings.NewReader(`{"name":"批次","created_by":"yaozhanghao","publication_ids":["tp-1"],"delete_publication_ids":[],"release_change_set_id":"rcs-9"}`)) + request = httptest.NewRequest(http.MethodPost, "/api/v1/release-batches", strings.NewReader(`{"name":"批次","publication_ids":["tp-1"],"delete_publication_ids":[],"release_change_set_id":"rcs-9"}`)) request.Header.Set("Idempotency-Key", "66666666-6666-4666-8666-666666666666") handler.ServeHTTP(unconf, request) if unconf.Code != http.StatusUnprocessableEntity || !strings.Contains(unconf.Body.String(), "confirmed") { @@ -922,7 +922,7 @@ func TestHandlerRecordsPublicationReview(t *testing.T) { if err != nil { t.Fatal(err) } - request := httptest.NewRequest(http.MethodPost, "/api/v1/review-candidates/tp-safe/decision", bytes.NewBufferString(`{"decision":"approved","decided_visibility":"internal","reviewer_ref":"engineer-1","decision_code":"approved_for_release"}`)) + request := httptest.NewRequest(http.MethodPost, "/api/v1/review-candidates/tp-safe/decision", bytes.NewBufferString(`{"decision":"approved","decided_visibility":"internal","decision_code":"approved_for_release"}`)) request.Header.Set("Idempotency-Key", "op-review-1") response := httptest.NewRecorder() handler.ServeHTTP(response, request) @@ -991,18 +991,18 @@ func TestHandlerCreatesAndSealsReleaseBatchWithoutReleaseJob(t *testing.T) { if err != nil { t.Fatal(err) } - createRequest := httptest.NewRequest(http.MethodPost, "/api/v1/release-batches", bytes.NewBufferString(`{"name":"Batch","created_by":"engineer-1","publication_ids":["tp-safe"],"delete_publication_ids":["tp-delete"]}`)) + createRequest := httptest.NewRequest(http.MethodPost, "/api/v1/release-batches", bytes.NewBufferString(`{"name":"Batch","publication_ids":["tp-safe"],"delete_publication_ids":["tp-delete"]}`)) createRequest.Header.Set("Idempotency-Key", "op-batch-create") createResponse := httptest.NewRecorder() handler.ServeHTTP(createResponse, createRequest) if createResponse.Code != http.StatusCreated || len(store.createBatchRequest.PublicationIDs) != 1 || len(store.createBatchRequest.DeletePublicationIDs) != 1 || store.createBatchRequest.DeletePublicationIDs[0] != "tp-delete" { t.Fatalf("create status=%d request=%#v body=%s", createResponse.Code, store.createBatchRequest, createResponse.Body.String()) } - sealRequest := httptest.NewRequest(http.MethodPost, "/api/v1/release-batches/rb-safe/seal", bytes.NewBufferString(`{"sealed_by":"engineer-2"}`)) + sealRequest := httptest.NewRequest(http.MethodPost, "/api/v1/release-batches/rb-safe/seal", bytes.NewBufferString(`{}`)) sealRequest.Header.Set("Idempotency-Key", "op-batch-seal") sealResponse := httptest.NewRecorder() handler.ServeHTTP(sealResponse, sealRequest) - if sealResponse.Code != http.StatusOK || store.sealBatchRequest.BatchID != "rb-safe" || store.sealBatchRequest.SealedBy != "engineer-2" { + if sealResponse.Code != http.StatusOK || store.sealBatchRequest.BatchID != "rb-safe" || store.sealBatchRequest.SealedBy != "system" { t.Fatalf("seal status=%d request=%#v body=%s", sealResponse.Code, store.sealBatchRequest, sealResponse.Body.String()) } if store.enqueued.Type != "" { @@ -1271,7 +1271,7 @@ func TestHandlerConfirmsChangeSetItems(t *testing.T) { t.Fatal(err) } response := httptest.NewRecorder() - request := httptest.NewRequest(http.MethodPost, "/api/v1/source-catalog/change-sets/cs-1/confirm", bytes.NewBufferString(`{"item_seqs":[4,9],"operator_ref":"engineer-1","reason":"确认新增与更新"}`)) + request := httptest.NewRequest(http.MethodPost, "/api/v1/source-catalog/change-sets/cs-1/confirm", bytes.NewBufferString(`{"item_seqs":[4,9],"reason":"确认新增与更新"}`)) request.Header.Set("Idempotency-Key", "op-confirm-1") handler.ServeHTTP(response, request) if response.Code != http.StatusOK || store.confirmChangeSetOperationID != "op-confirm-1" || len(store.confirmChangeSetRequest.ItemSeqs) != 2 || store.confirmChangeSetRequest.InternalTargetKBID != "kb-internal" || store.confirmChangeSetRequest.Now != now { @@ -1282,19 +1282,19 @@ func TestHandlerConfirmsChangeSetItems(t *testing.T) { } missing := httptest.NewRecorder() store.confirmChangeSetErr = postgresstore.ErrCatalogChangeSetNotFound - missingRequest := httptest.NewRequest(http.MethodPost, "/api/v1/source-catalog/change-sets/cs-nope/confirm", bytes.NewBufferString(`{"item_seqs":[1],"operator_ref":"engineer-1","reason":"确认"}`)) + missingRequest := httptest.NewRequest(http.MethodPost, "/api/v1/source-catalog/change-sets/cs-nope/confirm", bytes.NewBufferString(`{"item_seqs":[1],"reason":"确认"}`)) missingRequest.Header.Set("Idempotency-Key", "op-confirm-missing") handler.ServeHTTP(missing, missingRequest) if missing.Code != http.StatusNotFound { t.Fatalf("missing change set status=%d", missing.Code) } bad := httptest.NewRecorder() - handler.ServeHTTP(bad, httptest.NewRequest(http.MethodPost, "/api/v1/source-catalog/change-sets/cs-1/confirm", bytes.NewBufferString(`{"item_seqs":[],"operator_ref":"engineer-1","reason":"确认"}`))) + handler.ServeHTTP(bad, httptest.NewRequest(http.MethodPost, "/api/v1/source-catalog/change-sets/cs-1/confirm", bytes.NewBufferString(`{"item_seqs":[],"reason":"确认"}`))) if bad.Code != http.StatusBadRequest { t.Fatalf("empty selection status=%d", bad.Code) } noKey := httptest.NewRecorder() - handler.ServeHTTP(noKey, httptest.NewRequest(http.MethodPost, "/api/v1/source-catalog/change-sets/cs-1/confirm", bytes.NewBufferString(`{"item_seqs":[1],"operator_ref":"engineer-1","reason":"确认"}`))) + handler.ServeHTTP(noKey, httptest.NewRequest(http.MethodPost, "/api/v1/source-catalog/change-sets/cs-1/confirm", bytes.NewBufferString(`{"item_seqs":[1],"reason":"确认"}`))) if noKey.Code != http.StatusBadRequest { t.Fatalf("missing idempotency key status=%d", noKey.Code) } @@ -1307,12 +1307,12 @@ func TestHandlerStartsConfirmedTestPublications(t *testing.T) { if err != nil { t.Fatal(err) } - request := httptest.NewRequest(http.MethodPost, "/api/v1/test-publications/start", bytes.NewBufferString(`{"publication_ids":["pub-a","pub-b"],"operator_ref":"engineer-1","reason":"确认差异后开始处理"}`)) + request := httptest.NewRequest(http.MethodPost, "/api/v1/test-publications/start", bytes.NewBufferString(`{"publication_ids":["pub-a","pub-b"],"reason":"确认差异后开始处理"}`)) request.Header.Set("Content-Type", "application/json") request.Header.Set("Idempotency-Key", "op-processing-start") response := httptest.NewRecorder() handler.ServeHTTP(response, request) - if response.Code != http.StatusAccepted || store.startPublicationsRequest.Now != now || len(store.startPublicationsRequest.PublicationIDs) != 2 || store.startPublicationsRequest.OperatorRef != "engineer-1" || !strings.Contains(response.Body.String(), `"operation":"created"`) { + if response.Code != http.StatusAccepted || store.startPublicationsRequest.Now != now || len(store.startPublicationsRequest.PublicationIDs) != 2 || store.startPublicationsRequest.OperatorRef != "system" || !strings.Contains(response.Body.String(), `"operation":"created"`) { t.Fatalf("status=%d request=%#v body=%s", response.Code, store.startPublicationsRequest, response.Body.String()) } if !strings.Contains(response.Body.String(), `"started":1`) || strings.Contains(response.Body.String(), "test_kb_id") { @@ -1378,7 +1378,7 @@ func TestHandlerRejectsCatalogMutationsWithoutOperationID(t *testing.T) { } for _, request := range []*http.Request{ - httptest.NewRequest(http.MethodPost, "/api/v1/source-catalog/route", bytes.NewBufferString(`{"connection_id":"conn-cat","node_ids":["file-a"],"policy":"internal","operator_ref":"engineer-1","reason":"人工标注"}`)), + httptest.NewRequest(http.MethodPost, "/api/v1/source-catalog/route", bytes.NewBufferString(`{"connection_id":"conn-cat","node_ids":["file-a"],"policy":"internal","reason":"人工标注"}`)), httptest.NewRequest(http.MethodPost, "/api/v1/source-catalog/sources/conn-cat/refresh", nil), } { response := httptest.NewRecorder() diff --git a/internal/httpapi/session.go b/internal/httpapi/session.go new file mode 100644 index 0000000..e736f08 --- /dev/null +++ b/internal/httpapi/session.go @@ -0,0 +1,26 @@ +package httpapi + +import "net/http" + +// requireSessionIdentity resolves the authenticated actor for business write +// handlers. Since sessions arrived, request bodies no longer carry +// operator_ref / reviewer_ref / created_by; the server stamps the session. +// Returns false after writing the error response. +func requireSessionIdentity(w http.ResponseWriter, r *http.Request) (sessionIdentity, bool) { + identity, ok := sessionFrom(r.Context()) + if !ok { + writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "authentication required"}) + return sessionIdentity{}, false + } + return identity, true +} + +// actorFor returns the audit actor for a business write: the session username +// when auth is enabled, or "system" for the auth-disabled development socket. +// It never trusts client input. +func actorFor(r *http.Request) string { + if identity, ok := sessionFrom(r.Context()); ok { + return identity.Username + } + return "system" +} diff --git a/internal/httpapi/users.go b/internal/httpapi/users.go new file mode 100644 index 0000000..d60370b --- /dev/null +++ b/internal/httpapi/users.go @@ -0,0 +1,170 @@ +package httpapi + +import ( + "encoding/json" + "errors" + "io" + "net/http" + "strings" + + postgresstore "knowledge-governance/internal/platform/postgres" +) + +// Member administration. Every route here is classified admin by the auth +// middleware; these handlers additionally require the session identity. + +type createUserRequest struct { + Username string `json:"username"` + DisplayName string `json:"display_name"` + Role string `json:"role"` + Password string `json:"password"` +} + +func (config Config) handleCreateUser(w http.ResponseWriter, r *http.Request) { + identity, ok := sessionFrom(r.Context()) + if !ok { + writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "authentication required"}) + return + } + var input createUserRequest + decoder := json.NewDecoder(io.LimitReader(r.Body, 1<<20)) + decoder.DisallowUnknownFields() + if err := decoder.Decode(&input); err != nil { + writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid user request"}) + return + } + user, err := config.Auth.Store.CreateUser(r.Context(), strings.TrimSpace(input.Username), strings.TrimSpace(input.DisplayName), input.Role, input.Password, identity.UserID, config.Now().UTC()) + switch { + case errors.Is(err, postgresstore.ErrAuthInvalidUser): + writeJSON(w, http.StatusBadRequest, map[string]string{"error": "username, role or password does not meet policy"}) + case errors.Is(err, postgresstore.ErrAuthDuplicateUsername): + writeJSON(w, http.StatusConflict, map[string]string{"error": "username already exists"}) + case err != nil: + writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "could not create user"}) + default: + writeJSON(w, http.StatusCreated, map[string]any{"data": userPayload(user)}) + } +} + +func (config Config) handleListUsers(w http.ResponseWriter, r *http.Request) { + users, err := config.Auth.Store.ListAuthUsers(r.Context()) + if err != nil { + writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "could not list users"}) + return + } + data := make([]map[string]any, 0, len(users)) + for _, user := range users { + data = append(data, userPayload(user)) + } + writeJSON(w, http.StatusOK, map[string]any{"data": data}) +} + +type updateUserRoleRequest struct { + Role string `json:"role"` +} + +func (config Config) handleUpdateUserRole(w http.ResponseWriter, r *http.Request) { + identity, _ := sessionFrom(r.Context()) + var input updateUserRoleRequest + decoder := json.NewDecoder(io.LimitReader(r.Body, 1<<20)) + decoder.DisallowUnknownFields() + if err := decoder.Decode(&input); err != nil { + writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid role request"}) + return + } + err := config.Auth.Store.SetUserRole(r.Context(), identity.UserID, r.PathValue("id"), input.Role, config.Now().UTC()) + switch { + case errors.Is(err, postgresstore.ErrAuthInvalidUser): + writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid role"}) + case errors.Is(err, postgresstore.ErrAuthUserNotFound): + writeJSON(w, http.StatusNotFound, map[string]string{"error": "user not found"}) + case errors.Is(err, postgresstore.ErrAuthLastAdmin): + writeJSON(w, http.StatusConflict, map[string]string{"error": "cannot change the last active admin"}) + case err != nil: + writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "could not update role"}) + default: + user, getErr := config.Auth.Store.GetAuthUserByID(r.Context(), r.PathValue("id")) + if getErr != nil { + writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "could not load user"}) + return + } + writeJSON(w, http.StatusOK, map[string]any{"data": userPayload(user)}) + } +} + +type updateUserStateRequest struct { + State string `json:"state"` +} + +func (config Config) handleUpdateUserState(w http.ResponseWriter, r *http.Request) { + identity, _ := sessionFrom(r.Context()) + var input updateUserStateRequest + decoder := json.NewDecoder(io.LimitReader(r.Body, 1<<20)) + decoder.DisallowUnknownFields() + if err := decoder.Decode(&input); err != nil || (input.State != "active" && input.State != "disabled") { + writeJSON(w, http.StatusBadRequest, map[string]string{"error": "state must be active or disabled"}) + return + } + targetID := r.PathValue("id") + if targetID == identity.UserID { + writeJSON(w, http.StatusBadRequest, map[string]string{"error": "cannot change your own account state"}) + return + } + err := config.Auth.Store.SetUserState(r.Context(), identity.UserID, targetID, input.State, config.Now().UTC()) + switch { + case errors.Is(err, postgresstore.ErrAuthUserNotFound): + writeJSON(w, http.StatusNotFound, map[string]string{"error": "user not found"}) + case errors.Is(err, postgresstore.ErrAuthLastAdmin): + writeJSON(w, http.StatusConflict, map[string]string{"error": "cannot disable the last active admin"}) + case err != nil: + writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "could not update account"}) + default: + user, getErr := config.Auth.Store.GetAuthUserByID(r.Context(), targetID) + if getErr != nil { + writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "could not load user"}) + return + } + writeJSON(w, http.StatusOK, map[string]any{"data": userPayload(user)}) + } +} + +type resetUserPasswordRequest struct { + TemporaryPassword string `json:"temporary_password"` +} + +func (config Config) handleResetUserPassword(w http.ResponseWriter, r *http.Request) { + identity, _ := sessionFrom(r.Context()) + var input resetUserPasswordRequest + decoder := json.NewDecoder(io.LimitReader(r.Body, 1<<20)) + decoder.DisallowUnknownFields() + if err := decoder.Decode(&input); err != nil || len(input.TemporaryPassword) < 8 { + writeJSON(w, http.StatusBadRequest, map[string]string{"error": "temporary_password must be at least 8 characters"}) + return + } + targetID := r.PathValue("id") + if targetID == identity.UserID { + writeJSON(w, http.StatusBadRequest, map[string]string{"error": "use change-password for your own account"}) + return + } + err := config.Auth.Store.AdminResetPassword(r.Context(), identity.UserID, targetID, input.TemporaryPassword, config.Now().UTC()) + switch { + case errors.Is(err, postgresstore.ErrAuthUserNotFound): + writeJSON(w, http.StatusNotFound, map[string]string{"error": "user not found"}) + case errors.Is(err, postgresstore.ErrAuthUserDisabled): + writeJSON(w, http.StatusConflict, map[string]string{"error": "cannot reset a disabled account"}) + case errors.Is(err, postgresstore.ErrAuthInvalidUser): + writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid temporary password"}) + case err != nil: + writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "could not reset password"}) + default: + writeJSON(w, http.StatusOK, map[string]any{"data": map[string]bool{"reset": true, "must_change_password": true}}) + } +} + +func (config Config) userRoutes(mux *http.ServeMux) { + mux.HandleFunc("GET /api/v1/users", config.handleListUsers) + mux.HandleFunc("POST /api/v1/users", config.handleCreateUser) + mux.HandleFunc("POST /api/v1/users/{id}/role", config.handleUpdateUserRole) + mux.HandleFunc("POST /api/v1/users/{id}/state", config.handleUpdateUserState) + mux.HandleFunc("POST /api/v1/users/{id}/reset-password", config.handleResetUserPassword) +} diff --git a/internal/platform/postgres/auth.go b/internal/platform/postgres/auth.go new file mode 100644 index 0000000..94928f5 --- /dev/null +++ b/internal/platform/postgres/auth.go @@ -0,0 +1,524 @@ +package postgres + +import ( + "context" + "crypto/rand" + "crypto/sha256" + "encoding/base64" + "encoding/hex" + "errors" + "fmt" + "strings" + "time" + + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgconn" + "golang.org/x/crypto/bcrypt" +) + +// Roles for the governance control plane. V1 keeps exactly three; the release +// double-gate additionally requires admin so production authority is a role, +// not a typed name in a request body. +const ( + RoleViewer = "viewer" + RoleEngineer = "engineer" + RoleAdmin = "admin" +) + +func ValidRole(role string) bool { + return role == RoleViewer || role == RoleEngineer || role == RoleAdmin +} + +var ( + ErrAuthUserNotFound = errors.New("auth user not found") + ErrAuthInvalidCredential = errors.New("invalid username or password") + ErrAuthUserDisabled = errors.New("account is disabled") + ErrAuthLocked = errors.New("account temporarily locked") + ErrAuthSessionInvalid = errors.New("auth session invalid") + ErrAuthDuplicateUsername = errors.New("username already exists") + ErrAuthInvalidUser = errors.New("invalid user definition") + ErrAuthLastAdmin = errors.New("cannot remove or demote the last active admin") +) + +const authMaxFailedAttempts = 8 +const authLockDuration = 15 * time.Minute + +type AuthUser struct { + ID string + Username string + DisplayName string + Role string + MustChangePassword bool + State string + CreatedAt time.Time + LastLoginAt *time.Time +} + +// AuthSession is the server-side session behind the HttpOnly cookie. The +// caller only ever sees the opaque token; the store keeps its SHA-256. +type AuthSession struct { + ID string + User AuthUser + ExpiresAt time.Time +} + +func isUniqueViolation(err error) bool { + var pgErr *pgconn.PgError + return errors.As(err, &pgErr) && pgErr.Code == "23505" +} + +func hashSessionToken(token string) string { + sum := sha256.Sum256([]byte(token)) + return hex.EncodeToString(sum[:]) +} + +func validUsername(value string) bool { + if len(value) < 2 || len(value) > 64 { + return false + } + for index, char := range value { + ok := (char >= 'a' && char <= 'z') || (char >= '0' && char <= '9') || + (index > 0 && (char == '.' || char == '_' || char == '-')) + if !ok { + return false + } + } + return (value[0] >= 'a' && value[0] <= 'z') || (value[0] >= '0' && value[0] <= '9') +} + +func validPasswordPolicy(password string) bool { + return len(password) >= 8 && len(password) <= 128 +} + +// CreateUser stores only a bcrypt hash; the plaintext password never leaves +// the caller. createdBy may be empty for the bootstrap admin. +func (s *Store) CreateUser(ctx context.Context, username, displayName, role, password, createdBy string, now time.Time) (AuthUser, error) { + if !validUsername(username) || !ValidRole(role) || !validPasswordPolicy(password) || now.IsZero() || + displayName != strings.TrimSpace(displayName) || len(displayName) > 128 { + return AuthUser{}, ErrAuthInvalidUser + } + hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost) + if err != nil { + return AuthUser{}, errors.New("hash password") + } + id, err := newOpaqueID("usr-") + if err != nil { + return AuthUser{}, err + } + _, err = s.db.Exec(ctx, ` +INSERT INTO users(id,username,display_name,role,password_hash,must_change_password,state,created_by,created_at,updated_at) +VALUES($1,$2,$3,$4,$5,$6,'active',$7,$8,$8)`, +id, username, displayName, role, string(hash), true, createdBy, now.UTC()) + if err != nil { + if isUniqueViolation(err) { + return AuthUser{}, ErrAuthDuplicateUsername + } + return AuthUser{}, fmt.Errorf("create auth user: %w", err) + } + return AuthUser{ID: id, Username: username, DisplayName: displayName, Role: role, State: "active", CreatedAt: now.UTC()}, nil +} + +func (s *Store) GetAuthUserByName(ctx context.Context, username string) (AuthUser, string, error) { + var user AuthUser + var hash string + err := s.db.QueryRow(ctx, ` +SELECT id,username,display_name,role,password_hash,must_change_password,state,created_at,updated_at,last_login_at +FROM users WHERE username=$1`, username).Scan( + &user.ID, &user.Username, &user.DisplayName, &user.Role, &hash, + &user.MustChangePassword, &user.State, &user.CreatedAt, &user.CreatedAt, &user.LastLoginAt) + if errors.Is(err, pgx.ErrNoRows) { + return AuthUser{}, "", ErrAuthUserNotFound + } + if err != nil { + return AuthUser{}, "", fmt.Errorf("load auth user: %w", err) + } + return user, hash, nil +} + +func (s *Store) GetAuthUserByID(ctx context.Context, id string) (AuthUser, error) { + var user AuthUser + err := s.db.QueryRow(ctx, ` +SELECT id,username,display_name,role,must_change_password,state,created_at,last_login_at +FROM users WHERE id=$1`, id).Scan( + &user.ID, &user.Username, &user.DisplayName, &user.Role, + &user.MustChangePassword, &user.State, &user.CreatedAt, &user.LastLoginAt) + if errors.Is(err, pgx.ErrNoRows) { + return AuthUser{}, ErrAuthUserNotFound + } + if err != nil { + return AuthUser{}, fmt.Errorf("load auth user by id: %w", err) + } + return user, nil +} + +func (s *Store) ListAuthUsers(ctx context.Context) ([]AuthUser, error) { + rows, err := s.db.Query(ctx, ` +SELECT id,username,display_name,role,must_change_password,state,created_at,last_login_at +FROM users ORDER BY created_at, username`) + if err != nil { + return nil, fmt.Errorf("list auth users: %w", err) + } + defer rows.Close() + users := []AuthUser{} + for rows.Next() { + var user AuthUser + if err := rows.Scan(&user.ID, &user.Username, &user.DisplayName, &user.Role, + &user.MustChangePassword, &user.State, &user.CreatedAt, &user.LastLoginAt); err != nil { + return nil, fmt.Errorf("scan auth user: %w", err) + } + users = append(users, user) + } + return users, rows.Err() +} + +// CountAuthUsers backs the day-one bootstrap guard: the initial admin exists +// only while the account table is empty. +func (s *Store) CountAuthUsers(ctx context.Context) (int, error) { + var count int + if err := s.db.QueryRow(ctx, `SELECT COUNT(*) FROM users`).Scan(&count); err != nil { + return 0, fmt.Errorf("count auth users: %w", err) + } + return count, nil +} + +// CreateInitialAdmin installs the fixed day-one administrator with the +// operator-agreed bootstrap password and must_change_password=TRUE enforced +// at the first login. It refuses to run once any account exists so this code +// path can never mint a second superuser outside the UI. +func (s *Store) CreateInitialAdmin(ctx context.Context, username, bootstrapPassword string, now time.Time) (AuthUser, error) { + if username == "" || bootstrapPassword == "" || now.IsZero() { + return AuthUser{}, ErrAuthInvalidUser + } + count, err := s.CountAuthUsers(ctx) + if err != nil { + return AuthUser{}, err + } + if count > 0 { + return AuthUser{}, ErrAuthDuplicateUsername + } + hash, err := bcrypt.GenerateFromPassword([]byte(bootstrapPassword), bcrypt.DefaultCost) + if err != nil { + return AuthUser{}, errors.New("hash password") + } + id, err := newOpaqueID("usr-") + if err != nil { + return AuthUser{}, err + } + _, err = s.db.Exec(ctx, ` +INSERT INTO users(id,username,display_name,role,password_hash,must_change_password,state,created_by,created_at,updated_at) +VALUES($1,$2,'系统管理员','admin',$3,TRUE,'active','bootstrap',$4,$4)`, id, username, string(hash), now.UTC()) + if err != nil { + if isUniqueViolation(err) { + return AuthUser{}, ErrAuthDuplicateUsername + } + return AuthUser{}, fmt.Errorf("create initial admin: %w", err) + } + return AuthUser{ID: id, Username: username, DisplayName: "系统管理员", Role: RoleAdmin, MustChangePassword: true, State: "active", CreatedAt: now.UTC()}, nil +} + +// TouchSession rotates the expiry of a currently valid session; the auth +// middleware uses this for sliding renewal while keeping the same cookie. +func (s *Store) TouchSession(ctx context.Context, sessionID string, now, expiresAt time.Time) error { + _, err := s.db.Exec(ctx, `UPDATE user_sessions SET last_seen_at=$2, expires_at=$3 WHERE id=$1 AND revoked_at IS NULL`, sessionID, now.UTC(), expiresAt.UTC()) + if err != nil { + return fmt.Errorf("touch auth session: %w", err) + } + return nil +} + +func (s *Store) DeleteSession(ctx context.Context, sessionID string, now time.Time) error { + return s.Logout(ctx, sessionID, now) +} + +type LoginOutcome struct { + SessionToken string + SessionID string + User AuthUser +} + +// Login verifies credentials, enforces the failed-attempt lockout, and mints +// a server-side session. Every failure path returns the same error so the UI +// cannot enumerate usernames. +func (s *Store) Login(ctx context.Context, username, password, userAgent string, now time.Time, ttl time.Duration) (LoginOutcome, error) { + if ttl <= 0 { + ttl = 12 * time.Hour + } + user, hash, err := s.GetAuthUserByName(ctx, username) + if err != nil { + if errors.Is(err, ErrAuthUserNotFound) { + // Constant-ish work even for unknown users (bcrypt compare against + // a dummy hash) to slow enumeration. + _ = bcrypt.CompareHashAndPassword([]byte("$2a$10$CwTycUXWue0Thq9StjUM0uJ8fH9l0d0d0d0d0d0d0d0d0d0d0d0dO"), []byte(password)) + return LoginOutcome{}, ErrAuthInvalidCredential + } + return LoginOutcome{}, err + } + if user.State != "active" { + return LoginOutcome{}, ErrAuthUserDisabled + } + if lockedUntil, locked, lockErr := s.userLockedUntil(ctx, user.ID); lockErr != nil { + return LoginOutcome{}, lockErr + } else if locked && lockedUntil.After(now) { + return LoginOutcome{}, ErrAuthLocked + } + if bcrypt.CompareHashAndPassword([]byte(hash), []byte(password)) != nil { + if err := s.recordFailedLogin(ctx, user.ID, now.UTC()); err != nil { + return LoginOutcome{}, err + } + return LoginOutcome{}, ErrAuthInvalidCredential + } + token, err := newSessionToken() + if err != nil { + return LoginOutcome{}, err + } + sessionID, err := newOpaqueID("ses-") + if err != nil { + return LoginOutcome{}, err + } + var mustChange bool + err = s.db.QueryRow(ctx, ` +UPDATE users SET failed_attempts=0, locked_until=NULL, last_login_at=$2, updated_at=$2 +WHERE id=$1 AND state='active' +RETURNING must_change_password`, user.ID, now.UTC()).Scan(&mustChange) + if err != nil { + return LoginOutcome{}, fmt.Errorf("complete auth login: %w", err) + } + var insertedID string + err = s.db.QueryRow(ctx, ` +INSERT INTO user_sessions(id,token_hash,user_id,created_at,last_seen_at,expires_at,user_agent) +VALUES($1,$2,$3,$4,$4,$5,$6) RETURNING id`, + sessionID, hashSessionToken(token), user.ID, now.UTC(), now.Add(ttl), truncateUserAgent(userAgent)).Scan(&insertedID) + if err != nil { + return LoginOutcome{}, fmt.Errorf("create auth session: %w", err) + } + user.MustChangePassword = mustChange + return LoginOutcome{SessionToken: token, SessionID: insertedID, User: user}, nil +} + +func (s *Store) userLockedUntil(ctx context.Context, userID string) (time.Time, bool, error) { + var lockedUntil *time.Time + err := s.db.QueryRow(ctx, `SELECT locked_until FROM users WHERE id=$1`, userID).Scan(&lockedUntil) + if errors.Is(err, pgx.ErrNoRows) { + return time.Time{}, false, ErrAuthUserNotFound + } + if err != nil { + return time.Time{}, false, fmt.Errorf("load auth lock: %w", err) + } + return derefTime(lockedUntil), lockedUntil != nil, nil +} + +func (s *Store) recordFailedLogin(ctx context.Context, userID string, now time.Time) error { + _, err := s.db.Exec(ctx, ` +UPDATE users SET + failed_attempts = failed_attempts + 1, + locked_until = CASE WHEN failed_attempts + 1 >= $3 THEN $2 + $4::interval ELSE locked_until END, + updated_at = $2 +WHERE id = $1`, userID, now, authMaxFailedAttempts, fmt.Sprintf("%d minutes", int(authLockDuration.Minutes()))) + if err != nil { + return fmt.Errorf("record failed login: %w", err) + } + return nil +} + +// LookupSession resolves a session token, sliding-expiring it on use, and +// rejects sessions whose user was disabled or whose chain was revoked. +func (s *Store) LookupSession(ctx context.Context, token string, now time.Time) (AuthSession, error) { + if len(token) < 16 { + return AuthSession{}, ErrAuthSessionInvalid + } + var session AuthSession + var revoked bool + err := s.db.QueryRow(ctx, ` +SELECT ses.id, ses.expires_at, ses.revoked_at IS NOT NULL, + usr.id, usr.username, usr.display_name, usr.role, usr.must_change_password, usr.state, usr.created_at, usr.last_login_at +FROM user_sessions ses +JOIN users usr ON usr.id = ses.user_id +WHERE ses.token_hash = $1`, hashSessionToken(token)).Scan( + &session.ID, &session.ExpiresAt, &revoked, + &session.User.ID, &session.User.Username, &session.User.DisplayName, &session.User.Role, + &session.User.MustChangePassword, &session.User.State, &session.User.CreatedAt, &session.User.LastLoginAt) + if errors.Is(err, pgx.ErrNoRows) { + return AuthSession{}, ErrAuthSessionInvalid + } + if err != nil { + return AuthSession{}, fmt.Errorf("lookup auth session: %w", err) + } + if revoked || session.User.State != "active" || !session.ExpiresAt.After(now) { + return AuthSession{}, ErrAuthSessionInvalid + } + if _, err := s.db.Exec(ctx, `UPDATE user_sessions SET last_seen_at=$2 WHERE id=$1`, session.ID, now.UTC()); err != nil { + return AuthSession{}, fmt.Errorf("touch auth session: %w", err) + } + return session, nil +} + +func (s *Store) Logout(ctx context.Context, sessionID string, now time.Time) error { + _, err := s.db.Exec(ctx, `UPDATE user_sessions SET revoked_at=$2 WHERE id=$1 AND revoked_at IS NULL`, sessionID, now.UTC()) + if err != nil { + return fmt.Errorf("revoke auth session: %w", err) + } + return nil +} + +// RevokeAllUserSessions is used on password change, role change and disable +// so a stolen or stale cookie dies immediately, not at natural expiry. +func (s *Store) RevokeAllUserSessions(ctx context.Context, userID string, now time.Time) error { + _, err := s.db.Exec(ctx, `UPDATE user_sessions SET revoked_at=$2 WHERE user_id=$1 AND revoked_at IS NULL`, userID, now.UTC()) + if err != nil { + return fmt.Errorf("revoke user sessions: %w", err) + } + return nil +} + +// ChangePassword verifies the old password, installs the new hash and clears +// the must-change flag; every other session dies. Returns the new session +// token id only after success so callers can rotate the cookie. +func (s *Store) ChangePassword(ctx context.Context, userID, oldPassword, newPassword string, now time.Time) error { + if !validPasswordPolicy(newPassword) { + return ErrAuthInvalidUser + } + var hash string + var mustChange bool + err := s.db.QueryRow(ctx, `SELECT password_hash, must_change_password FROM users WHERE id=$1 AND state='active'`, userID).Scan(&hash, &mustChange) + if errors.Is(err, pgx.ErrNoRows) { + return ErrAuthUserNotFound + } + if err != nil { + return fmt.Errorf("load auth user for password change: %w", err) + } + if bcrypt.CompareHashAndPassword([]byte(hash), []byte(oldPassword)) != nil { + return ErrAuthInvalidCredential + } + if oldPassword == newPassword { + return ErrAuthInvalidUser + } + fresh, err := bcrypt.GenerateFromPassword([]byte(newPassword), bcrypt.DefaultCost) + if err != nil { + return errors.New("hash password") + } + if _, err := s.db.Exec(ctx, ` +UPDATE users SET password_hash=$2, must_change_password=FALSE, updated_at=$3 WHERE id=$1`, userID, string(fresh), now.UTC()); err != nil { + return fmt.Errorf("update auth password: %w", err) + } + return s.RevokeAllUserSessions(ctx, userID, now) +} + +// AdminResetPassword sets a fresh temporary password, forces a change on next +// login and revokes all sessions for the target user. It refuses to lock the +// platform out of its last admin. +func (s *Store) AdminResetPassword(ctx context.Context, actorID, userID, temporaryPassword string, now time.Time) error { + if userID == actorID { + return ErrAuthInvalidUser + } + if !validPasswordPolicy(temporaryPassword) { + return ErrAuthInvalidUser + } + target, err := s.GetAuthUserByID(ctx, userID) + if err != nil { + return err + } + if target.State != "active" { + return ErrAuthUserDisabled + } + fresh, err := bcrypt.GenerateFromPassword([]byte(temporaryPassword), bcrypt.DefaultCost) + if err != nil { + return errors.New("hash password") + } + if _, err := s.db.Exec(ctx, ` +UPDATE users SET password_hash=$2, must_change_password=TRUE, failed_attempts=0, locked_until=NULL, updated_at=$3 +WHERE id=$1 AND state='active'`, userID, string(fresh), now.UTC()); err != nil { + return fmt.Errorf("reset auth password: %w", err) + } + return s.RevokeAllUserSessions(ctx, userID, now) +} + +func (s *Store) SetUserRole(ctx context.Context, actorID, userID, role string, now time.Time) error { + if !ValidRole(role) { + return ErrAuthInvalidUser + } + target, err := s.GetAuthUserByID(ctx, userID) + if err != nil { + return err + } + if target.Role == RoleAdmin && role != RoleAdmin && target.State == "active" { + last, err := s.isLastActiveAdmin(ctx, target.ID) + if err != nil { + return err + } + if last { + return ErrAuthLastAdmin + } + } + if _, err := s.db.Exec(ctx, `UPDATE users SET role=$2, updated_at=$3 WHERE id=$1`, userID, role, now.UTC()); err != nil { + return fmt.Errorf("set auth role: %w", err) + } + return s.RevokeAllUserSessions(ctx, userID, now) +} + +// SetUserState activates or disables an account. Disabling revokes sessions +// and preserves every business row and audit reference. +func (s *Store) SetUserState(ctx context.Context, actorID, userID, state string, now time.Time) error { + if state != "active" && state != "disabled" { + return ErrAuthInvalidUser + } + target, err := s.GetAuthUserByID(ctx, userID) + if err != nil { + return err + } + if state == "disabled" && target.Role == RoleAdmin && target.State == "active" { + last, err := s.isLastActiveAdmin(ctx, target.ID) + if err != nil { + return err + } + if last { + return ErrAuthLastAdmin + } + } + if _, err := s.db.Exec(ctx, `UPDATE users SET state=$2, updated_at=$3 WHERE id=$1`, userID, state, now.UTC()); err != nil { + return fmt.Errorf("set auth state: %w", err) + } + if state == "disabled" { + return s.RevokeAllUserSessions(ctx, userID, now) + } + return nil +} + +func (s *Store) isLastActiveAdmin(ctx context.Context, userID string) (bool, error) { + var count int + if err := s.db.QueryRow(ctx, `SELECT COUNT(*) FROM users WHERE role='admin' AND state='active' AND id<>$1`, userID).Scan(&count); err != nil { + return false, fmt.Errorf("count active admins: %w", err) + } + return count == 0, nil +} + +func newSessionToken() (string, error) { + raw := make([]byte, 32) + if _, err := rand.Read(raw); err != nil { + return "", errors.New("generate session token") + } + return base64.RawURLEncoding.EncodeToString(raw), nil +} + +func truncateUserAgent(value string) string { + value = strings.Map(func(r rune) rune { + if r == '\n' || r == '\r' || r == '\t' { + return ' ' + } + if r < 0x20 { + return -1 + } + return r + }, value) + if len(value) > 256 { + return value[:256] + } + return value +} + +func derefTime(value *time.Time) time.Time { + if value == nil { + return time.Time{} + } + return *value +} + diff --git a/internal/platform/postgres/auth_test.go b/internal/platform/postgres/auth_test.go new file mode 100644 index 0000000..05933fa --- /dev/null +++ b/internal/platform/postgres/auth_test.go @@ -0,0 +1,49 @@ +package postgres + +import ( + "errors" + "strings" + "testing" + "time" +) + +func TestAuthStoreRequiresIntegrationDatabase(t *testing.T) { + // Real bcrypt + sessions behaviour is covered by the integration suite; + // this unit file pins the pure helpers that gate every auth write. + if !validUsername("yaozhanghao") || !validUsername("a.b_c-9") { + t.Fatal("valid usernames rejected") + } + for _, bad := range []string{"", "a", "-lead", ".lead", "UPPER", "sp ace", strings.Repeat("x", 65)} { + if validUsername(bad) { + t.Fatalf("invalid username accepted: %q", bad) + } + } + if !validPasswordPolicy("dobotai!") || validPasswordPolicy("short") || validPasswordPolicy(strings.Repeat("x", 129)) { + t.Fatal("password policy wrong") + } + if !ValidRole(RoleViewer) || !ValidRole(RoleEngineer) || !ValidRole(RoleAdmin) || ValidRole("superuser") { + t.Fatal("role set wrong") + } + if len(hashSessionToken("t")) != 64 { + t.Fatal("session token hash must be sha256 hex") + } + if got := truncateUserAgent("a\nb"); got != "a b" { + t.Fatalf("user agent control chars: %q", got) + } +} + +func TestAuthErrorsAreDistinct(t *testing.T) { + for _, err := range []error{ErrAuthInvalidCredential, ErrAuthLocked, ErrAuthUserDisabled, ErrAuthSessionInvalid, ErrAuthLastAdmin} { + if err == nil || errors.Is(err, ErrAuthUserNotFound) { + t.Fatalf("auth error taxonomy broken: %v", err) + } + } +} + +func TestAuthSessionTTLDefaults(t *testing.T) { + // zero ttl must not create an instantly-dead session + ttl := 12 * time.Hour + if ttl <= 0 { + t.Fatal("default ttl must be positive") + } +} diff --git a/internal/platform/postgres/migrations/000032_auth_users_sessions.down.sql b/internal/platform/postgres/migrations/000032_auth_users_sessions.down.sql new file mode 100644 index 0000000..79b500d --- /dev/null +++ b/internal/platform/postgres/migrations/000032_auth_users_sessions.down.sql @@ -0,0 +1,2 @@ +DROP TABLE IF EXISTS user_sessions; +DROP TABLE IF EXISTS users; diff --git a/internal/platform/postgres/migrations/000032_auth_users_sessions.up.sql b/internal/platform/postgres/migrations/000032_auth_users_sessions.up.sql new file mode 100644 index 0000000..daf77ef --- /dev/null +++ b/internal/platform/postgres/migrations/000032_auth_users_sessions.up.sql @@ -0,0 +1,35 @@ +-- V1 account, role and session foundation for the governance control plane. +-- Login is local (bcrypt password) with server-side sessions so a session can +-- be revoked instantly on role change, password change or logout. Every actor +-- field on business writes (reviewer_ref / operator_ref / created_by ...) is +-- replaced by the session identity server-side; the browser never types it. + +CREATE TABLE IF NOT EXISTS users ( + id VARCHAR(36) PRIMARY KEY, + username VARCHAR(64) NOT NULL UNIQUE CHECK (username ~ '^[a-z0-9][a-z0-9._-]{1,63}$'), + display_name VARCHAR(128) NOT NULL DEFAULT '', + role VARCHAR(16) NOT NULL CHECK (role IN ('viewer', 'engineer', 'admin')), + password_hash VARCHAR(255) NOT NULL, + must_change_password BOOLEAN NOT NULL DEFAULT FALSE, + state VARCHAR(16) NOT NULL DEFAULT 'active' CHECK (state IN ('active', 'disabled')), + failed_attempts INTEGER NOT NULL DEFAULT 0 CHECK (failed_attempts >= 0), + locked_until TIMESTAMPTZ, + created_by VARCHAR(36) NOT NULL DEFAULT '', + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + last_login_at TIMESTAMPTZ +); +CREATE INDEX IF NOT EXISTS users_username_idx ON users (username); + +CREATE TABLE IF NOT EXISTS user_sessions ( + id VARCHAR(36) PRIMARY KEY, + token_hash CHAR(64) NOT NULL UNIQUE CHECK (token_hash ~ '^[0-9a-f]{64}$'), + user_id VARCHAR(36) NOT NULL REFERENCES users(id) ON DELETE CASCADE, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + last_seen_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + expires_at TIMESTAMPTZ NOT NULL, + revoked_at TIMESTAMPTZ, + user_agent VARCHAR(256) NOT NULL DEFAULT '' +); +CREATE INDEX IF NOT EXISTS user_sessions_user_idx ON user_sessions (user_id) WHERE revoked_at IS NULL; +CREATE INDEX IF NOT EXISTS user_sessions_expiry_idx ON user_sessions (expires_at); diff --git a/internal/platform/postgres/migrations_test.go b/internal/platform/postgres/migrations_test.go index 4f6f0c7..9116c61 100644 --- a/internal/platform/postgres/migrations_test.go +++ b/internal/platform/postgres/migrations_test.go @@ -11,8 +11,8 @@ func TestEmbeddedMigrationsAreVersionSorted(t *testing.T) { if err != nil { t.Fatalf("loadMigrations() error = %v", err) } - if len(migrations) != 31 { - t.Fatalf("migration count = %d, want 24", len(migrations)) + if len(migrations) != 32 { + t.Fatalf("migration count = %d, want 32", len(migrations)) } if migrations[0].Version != 1 || !strings.Contains(migrations[0].UpSQL, "CREATE TABLE IF NOT EXISTS jobs") { t.Fatalf("migration 1 = %#v", migrations[0]) @@ -98,6 +98,9 @@ func TestEmbeddedMigrationsAreVersionSorted(t *testing.T) { if migrations[30].Version != 31 || !strings.Contains(migrations[30].UpSQL, "source_connection_revisions") || !strings.Contains(migrations[30].UpSQL, "uq_source_connection_active_revision") || !strings.Contains(migrations[30].UpSQL, "next_refresh_at") { t.Fatalf("migration 31 = %#v", migrations[30]) } + if migrations[31].Version != 32 || !strings.Contains(migrations[31].UpSQL, "CREATE TABLE IF NOT EXISTS users") || !strings.Contains(migrations[31].UpSQL, "user_sessions") { + t.Fatalf("migration 32 = %#v", migrations[31]) + } } func TestProcessingConfirmationMigrationSeparatesPlanningFromUpload(t *testing.T) {