feat(auth): accounts, sessions, RBAC and server-stamped actors
上线账号权限管理(后端): - 迁移 000032:users + user_sessions(token 只存 sha256,服务端可即时撤销) - bcrypt 密码、8 次失败锁 15 分钟、统一 401 错误防用户名枚举 - 三角色 viewer/engineer/admin;HttpOnly+SameSite=Lax 会话 cookie,滑动续期 - 强制改密锁定:must_change_password 会话只能走 auth 端点;首登 dobotai - bootstrap:users 表为空时创建 admin(初始密码 dobotai,强制改密) - 生产双闸授权/回滚/失败重试收敛为 admin 角色;AuthorizedBy 用会话身份 - 全部业务写端点删除手填 actor 字段(operator_ref/reviewer_ref/created_by/ sealed_by/confirmed_by),服务端从会话注入;auth 关闭的开发 socket 回退 system - 成员管理 API:列表/创建/改角色/启停/重置密码,最后一名 active admin 保护 - RBAC 矩阵纯函数契约测试 + 中间件行为测试(登录/锁定/角色/审计戳) - 附带修复:GET /api/v1/users 曾被 GET=viewer 规则误放行(测试抓到)
This commit is contained in:
@@ -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,
|
||||
})
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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
|
||||
+42
-35
@@ -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)
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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"
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
Reference in New Issue
Block a user