package governance import ( "context" "errors" "net/http" "net/http/httptest" "testing" "time" "github.com/samcharles93/archie-core/internal/platform/httpapi" "github.com/samcharles93/archie-core/internal/platform/httpjson" ) // fakeCredentials holds sessions and personal tokens by their raw value. type fakeCredentials struct { sessions map[string]Identity tokens map[Subject]PersonalToken subjects map[Subject]Identity principals map[IdentityID]Principal } func (f fakeCredentials) ResolveAccountSession(_ context.Context, token string) (Identity, error) { if token == "broken" { return Identity{}, errors.New("database down") } if v, ok := f.sessions[token]; ok { return v, nil } return Identity{}, ErrIdentityNotFound } func (f fakeCredentials) ResolveSubject(_ context.Context, s Subject) (Identity, error) { if v, ok := f.subjects[s]; ok { return v, nil } return Identity{}, ErrIdentityNotFound } func (f fakeCredentials) PersonalTokenOf(_ context.Context, s Subject) (PersonalToken, error) { if v, ok := f.tokens[s]; ok { return v, nil } return PersonalToken{}, ErrIdentityNotFound } func (fakeCredentials) TouchPersonalToken(context.Context, Subject, time.Time) error { return nil } func (f fakeCredentials) PrincipalFor(_ context.Context, id IdentityID) (Principal, error) { return f.principals[id], nil } // TestAuthenticateRequest guards the API's credential check: a session // cookie or personal token acts as its own identity with that identity's // role, the bootstrap admin token acts as the instance owner, and a // tampered, expired or inactive credential is refused rather than acting as // anyone. func TestAuthenticateRequest(t *testing.T) { const admin = "a-plainly-fake-admin-token" //nolint:gosec // test fixture, not a credential now := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC) past := now.Add(-time.Hour) owner := Identity{ID: "owner", Kind: KindUser, Lifecycle: LifecycleActive} viewer := Identity{ID: "viewer", Kind: KindUser, Lifecycle: LifecycleActive} suspended := Identity{ID: "suspended", Kind: KindUser, Lifecycle: LifecycleSuspended} ownerToken, ownerSubject := personalToken(t) viewerToken, viewerSubject := personalToken(t) expiredToken, expiredSubject := personalToken(t) creds := fakeCredentials{ sessions: map[string]Identity{"owner-session": owner, "viewer-session": viewer, "suspended-session": suspended}, tokens: map[Subject]PersonalToken{ ownerSubject: {}, viewerSubject: {}, expiredSubject: {ExpiresAt: &past}, }, subjects: map[Subject]Identity{ownerSubject: owner, viewerSubject: viewer, expiredSubject: owner}, principals: map[IdentityID]Principal{ "owner": {IdentityID: "owner", Org: DefaultOrgID, Memberships: []Membership{{IdentityID: "owner", OrgID: DefaultOrgID, Role: RoleOwner}}}, "viewer": {IdentityID: "viewer", Org: DefaultOrgID, Memberships: []Membership{{IdentityID: "viewer", OrgID: DefaultOrgID, Role: RoleViewer}}}, }, } tests := []struct { name, cookie, bearer, adminHash string wantErr error wantID IdentityID wantRole Role wantAdmin bool }{ {name: "no credential", wantErr: httpapi.ErrUnauthenticated}, {name: "owner session", cookie: "owner-session", wantID: "owner", wantRole: RoleOwner, wantAdmin: true}, {name: "viewer session", cookie: "viewer-session", wantID: "viewer", wantRole: RoleViewer}, {name: "tampered session", cookie: "owner-sessiom", wantErr: httpapi.ErrUnauthenticated}, {name: "suspended identity's session", cookie: "suspended-session", wantErr: httpapi.ErrUnauthenticated}, {name: "a failed session lookup is not a refusal", cookie: "broken", wantErr: errors.New("any")}, {name: "owner's personal token", bearer: ownerToken, wantID: "owner", wantRole: RoleOwner, wantAdmin: true}, {name: "viewer's personal token keeps the viewer role", bearer: viewerToken, wantID: "viewer", wantRole: RoleViewer}, {name: "expired personal token", bearer: expiredToken, wantErr: httpapi.ErrUnauthenticated}, {name: "unknown personal token", bearer: "archie_pat_00", wantErr: httpapi.ErrUnauthenticated}, //nolint:gosec // G101: a token no store holds, which must be refused. {name: "admin token", bearer: admin, adminHash: httpjson.TokenHash(admin), wantID: SystemID, wantRole: RoleOwner, wantAdmin: true}, {name: "wrong admin token", bearer: "other", adminHash: httpjson.TokenHash(admin), wantErr: httpapi.ErrUnauthenticated}, {name: "no admin hash locks the admin token out", bearer: admin, wantErr: httpapi.ErrUnauthenticated}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { auth := authenticator{creds: creds, adminHash: tt.adminHash, now: func() time.Time { return now }} req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/thing", nil) if tt.cookie != "" { req.AddCookie(&http.Cookie{Name: httpapi.SessionCookie, Value: tt.cookie}) //nolint:gosec // G124: a request cookie; attributes are the server's to set. } if tt.bearer != "" { req.Header.Set("Authorization", "Bearer "+tt.bearer) } acting, admin, err := auth.Authenticate(req.Context(), req) if tt.wantErr != nil { if err == nil { t.Fatal("authenticated, want refused") } if errors.Is(tt.wantErr, httpapi.ErrUnauthenticated) != errors.Is(err, httpapi.ErrUnauthenticated) { t.Fatalf("err = %v, want %v", err, tt.wantErr) } return } if err != nil { t.Fatalf("Authenticate: %v", err) } p, ok := PrincipalFromContext(acting) if !ok || p.IdentityID != tt.wantID || p.Role("") != tt.wantRole || admin != tt.wantAdmin { t.Fatalf("acts as %s role %q admin %v, want %s role %q admin %v", p.IdentityID, p.Role(""), admin, tt.wantID, tt.wantRole, tt.wantAdmin) } }) } } func personalToken(t *testing.T) (string, Subject) { t.Helper() raw, subject, err := NewPersonalToken() if err != nil { t.Fatal(err) } return raw, subject }