package webui import ( "context" "encoding/json" "errors" "net/http" "net/http/httptest" "strings" "testing" "time" "github.com/samcharles93/archie-core/internal/domain/access" "github.com/samcharles93/archie-core/internal/domain/identity" "github.com/samcharles93/archie-core/internal/domain/org" infraaccess "github.com/samcharles93/archie-core/internal/infrastructure/access" ) type accountBoundaryStore struct { identity.Accounts identity.AccountSecurity fresh bool } func (accountBoundaryStore) AccountSetupRequired(context.Context) (bool, error) { return false, nil } func (accountBoundaryStore) ResolveAccountSession(_ context.Context, token string) (identity.Identity, error) { if token != "valid" { return identity.Identity{}, identity.ErrCredentialRejected } return identity.Identity{ID: "alice", Kind: identity.KindUser, DisplayName: "Alice", Lifecycle: identity.LifecycleActive}, nil } func (accountBoundaryStore) SignInAccount(_ context.Context, email, password string) (identity.AccountSession, error) { if email != "alice@example.com" || password != "a sufficiently long password" { return identity.AccountSession{}, identity.ErrCredentialRejected } return identity.AccountSession{Identity: identity.Identity{ID: "alice", Kind: identity.KindUser, Lifecycle: identity.LifecycleActive}, Token: "new-session", Expires: time.Now().Add(time.Hour)}, nil } func (s accountBoundaryStore) RequireFreshAccountSession(context.Context, string) error { if !s.fresh { return identity.ErrCredentialRejected } return nil } func (accountBoundaryStore) CreateAccountRecovery(context.Context) (string, error) { return "one-use-recovery-code", nil } func TestAccountBoundary(t *testing.T) { principal := access.Principal{IdentityID: "alice", Org: "acme", Memberships: []org.Membership{{IdentityID: "alice", OrgID: "acme", Role: org.RoleViewer}}} for _, tc := range []struct { name, method, path, body, cookie, csrf string fresh bool want int }{ {name: "shared token cannot authenticate", method: "GET", path: "/api/summary", cookie: "legacy", want: 401}, {name: "API reads reach authentication", method: "GET", path: "/api/chat/sessions", want: 401}, {name: "valid cookie reaches protected API", method: "GET", path: "/api/chat/sessions", cookie: "valid", want: 501}, {name: "login requires CSRF", method: "POST", path: "/api/auth/login", body: `{"email":"alice@example.com","password":"a sufficiently long password"}`, want: 403}, {name: "incorrect credentials use generic refusal", method: "POST", path: "/api/auth/login", csrf: "1", body: `{"email":"unknown@example.com","password":"wrong"}`, want: 401}, {name: "successful login", method: "POST", path: "/api/auth/login", csrf: "1", body: `{"email":"alice@example.com","password":"a sufficiently long password"}`, want: 200}, {name: "anonymous cannot manage personal security", method: "POST", path: "/api/account/recovery", csrf: "1", body: `{}`, want: 401}, {name: "viewer manages own security after recent sign in", method: "POST", path: "/api/account/recovery", csrf: "1", body: `{}`, cookie: "valid", fresh: true, want: 200}, {name: "stale session cannot replace recovery", method: "POST", path: "/api/account/recovery", csrf: "1", body: `{}`, cookie: "valid", want: 403}, {name: "viewer cannot create accounts", method: "POST", path: "/api/accounts", csrf: "1", body: `{}`, cookie: "valid", fresh: true, want: 403}, {name: "viewer cannot edit instance authentication", method: "PUT", path: "/api/authentication", csrf: "1", body: `{}`, cookie: "valid", fresh: true, want: 403}, } { t.Run(tc.name, func(t *testing.T) { srv := &Server{Accounts: accountBoundaryStore{fresh: tc.fresh}, Access: infraaccess.New(access.ShippedOrgPolicies("acme")), Principals: principalOf(principal)} req := httptest.NewRequestWithContext(t.Context(), tc.method, "https://archie.example"+tc.path, strings.NewReader(tc.body)) req.Header.Set("Content-Type", "application/json") req.Header.Set("X-Archie-CSRF", tc.csrf) if tc.cookie != "" { sendCookie(req, "archie_session", tc.cookie) } recorder := httptest.NewRecorder() srv.Handler().ServeHTTP(recorder, req) if recorder.Code != tc.want { t.Fatalf("status=%d want=%d body=%s", recorder.Code, tc.want, recorder.Body.String()) } if tc.name == "successful login" { var found bool for _, cookie := range recorder.Result().Cookies() { if cookie.Name == "archie_session" { found = true if !cookie.HttpOnly || !cookie.Secure || cookie.SameSite != http.SameSiteStrictMode || cookie.Value != "new-session" { t.Fatalf("unsafe session cookie: %+v", cookie) } } } if !found { t.Fatal("login did not set a session") } } }) } } func TestAuthenticationTransport(t *testing.T) { for _, tc := range []struct { name, url, origin, csrf string want bool }{ {"TLS", "https://archie.example/api/auth/login", "https://archie.example", "1", true}, {"localhost development", "http://localhost:8484/api/auth/login", "http://localhost:8484", "1", true}, {"network cleartext", "http://archie.example/api/auth/login", "http://archie.example", "1", false}, {"cross origin", "https://archie.example/api/auth/login", "https://attacker.example", "1", false}, {"missing CSRF", "https://archie.example/api/auth/login", "https://archie.example", "", false}, } { t.Run(tc.name, func(t *testing.T) { req := httptest.NewRequestWithContext(t.Context(), "POST", tc.url, strings.NewReader(`{}`)) req.Header.Set("Content-Type", "application/json") req.Header.Set("X-Archie-CSRF", tc.csrf) req.Header.Set("Origin", tc.origin) if got := (&Server{}).authorizeAuthenticationMutation(httptest.NewRecorder(), req); got != tc.want { t.Fatalf("allowed=%v want=%v", got, tc.want) } }) } } func TestAccountSessionFailureIsClosed(t *testing.T) { srv := &Server{Accounts: unavailableAccounts{}} req := httptest.NewRequestWithContext(t.Context(), "GET", "https://archie.example/api/auth/status", nil) rec := httptest.NewRecorder() srv.handleAccountStatus(rec, req) if rec.Code != 503 { t.Fatalf("account outage status=%d, want 503", rec.Code) } } // TestRequireAccountAdmitsAnyActiveIdentity pins the bearer-token gate: any // active identity -- a person or a service account -- is admitted and rides // the context as the acting identity, while an inactive one is refused, so a // scoped service-account token can use the API without being a user. func TestRequireAccountAdmitsAnyActiveIdentity(t *testing.T) { tests := []struct { name string value identity.Identity want int }{ {"active user", identity.Identity{ID: "u1", Kind: identity.KindUser, DisplayName: "User", Lifecycle: identity.LifecycleActive}, http.StatusOK}, {"active service account", identity.Identity{ID: "sa1", Kind: identity.KindServiceAccount, DisplayName: "Canary", Lifecycle: identity.LifecycleActive}, http.StatusOK}, {"active bot", identity.Identity{ID: "b1", Kind: identity.KindBot, DisplayName: "Bot", Lifecycle: identity.LifecycleActive}, http.StatusOK}, {"suspended user", identity.Identity{ID: "u2", Kind: identity.KindUser, DisplayName: "User", Lifecycle: identity.LifecycleSuspended}, http.StatusUnauthorized}, {"retired service account", identity.Identity{ID: "sa2", Kind: identity.KindServiceAccount, DisplayName: "Canary", Lifecycle: identity.LifecycleRetired}, http.StatusUnauthorized}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { srv := &Server{ Authenticate: func(context.Context, string) (identity.Identity, error) { return tt.value, nil }, } var acting identity.IdentityID handler := srv.requireAccount(http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) { if value, ok := ActingIdentity(r.Context()); ok { acting = value.ID } })) req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "https://archie.example/api/summary", nil) req.Header.Set("Authorization", "Bearer archie_pat_test") rec := httptest.NewRecorder() handler.ServeHTTP(rec, req) if rec.Code != tt.want { t.Fatalf("status=%d want=%d body=%s", rec.Code, tt.want, rec.Body.String()) } if tt.want == http.StatusOK && acting != tt.value.ID { t.Fatalf("acting identity = %q, want %q", acting, tt.value.ID) } }) } } // identityRepo answers Get for the identities a test names. type identityRepo struct { identity.Repository values map[identity.IdentityID]identity.Identity } func (s identityRepo) Get(_ context.Context, id identity.IdentityID) (identity.Identity, error) { value, ok := s.values[id] if !ok { return identity.Identity{}, identity.ErrNotFound } return value, nil } // identityTokenStore carries both token contracts: the remote caller's view // (embedded) and the store side, whose BindPersonalToken names an identity. type identityTokenStore struct { identity.PersonalTokens bound bool id identity.IdentityID subject identity.Subject name string } func (s *identityTokenStore) BindPersonalToken(_ context.Context, id identity.IdentityID, subject identity.Subject, name string, _ *time.Time, _ identity.Audit) error { s.bound, s.id, s.subject, s.name = true, id, subject, name return nil } func (s *identityTokenStore) SubjectsOf(context.Context, identity.IdentityID, string) ([]identity.PersonalToken, error) { return nil, nil } func (s *identityTokenStore) UnbindSubject(context.Context, identity.IdentityID, identity.Subject, identity.Audit) error { return nil } func (s *identityTokenStore) PersonalTokenOf(context.Context, identity.Subject) (identity.PersonalToken, error) { return identity.PersonalToken{}, identity.ErrNotFound } func (s *identityTokenStore) TouchPersonalToken(context.Context, identity.Subject, time.Time) error { return nil } // TestIdentityTokenCreate pins the per-identity token route: an active // service account gets its raw token exactly once and the store binds only // its hash, while an unknown or inactive identity is refused. func TestIdentityTokenCreate(t *testing.T) { active := identity.Identity{ID: "sa1", Kind: identity.KindServiceAccount, DisplayName: "Canary", Lifecycle: identity.LifecycleActive} suspended := identity.Identity{ID: "sa2", Kind: identity.KindServiceAccount, DisplayName: "Old", Lifecycle: identity.LifecycleSuspended} tests := []struct { name, id, body string want int }{ {"active service account", "sa1", `{"name":"ci","days":30}`, http.StatusCreated}, {"unknown identity", "nope", `{"name":"ci","days":30}`, http.StatusBadRequest}, {"inactive identity", "sa2", `{"name":"ci","days":30}`, http.StatusConflict}, {"bad name", "sa1", `{"name":" ","days":30}`, http.StatusBadRequest}, {"bad lifetime", "sa1", `{"name":"ci","days":10}`, http.StatusBadRequest}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { store := &identityTokenStore{} srv := &Server{ Identities: identityRepo{values: map[identity.IdentityID]identity.Identity{active.ID: active, suspended.ID: suspended}}, PersonalTokens: store, } req := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "https://archie.example/api/identities/"+tt.id+"/tokens", strings.NewReader(tt.body)) req.Header.Set("Content-Type", "application/json") req.SetPathValue("id", tt.id) rec := httptest.NewRecorder() newIdentitiesAPI(srv).handleIdentityTokenCreate(rec, req) if rec.Code != tt.want { t.Fatalf("status=%d want=%d body=%s", rec.Code, tt.want, rec.Body.String()) } if tt.want != http.StatusCreated { if store.bound { t.Fatal("a refused request still bound a token") } return } var body struct { ID string `json:"id"` Token string `json:"token"` } if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil { t.Fatalf("response: %v (%s)", err, rec.Body.String()) } if !strings.HasPrefix(body.Token, "archie_pat_") || body.ID == "" { t.Fatalf("response must show the raw token once: %+v", body) } if !store.bound || store.id != active.ID || store.name != "ci" { t.Fatalf("bound = %+v, want id %q name %q", store, active.ID, "ci") } if store.subject.Issuer != identity.PersonalTokenIssuer || store.subject.Subject != body.ID { t.Fatalf("store kept subject %+v, want the token's hash %q under %q", store.subject, body.ID, identity.PersonalTokenIssuer) } }) } } type unavailableAccounts struct{ identity.Accounts } func (unavailableAccounts) AccountSetupRequired(context.Context) (bool, error) { return false, errors.New("store unavailable") }