Files
certctl/internal/repository/postgres/user_test.go
T
shankar0123 b37cd6991b auth-bundle-2 Phase 2b: repository interfaces + Postgres impls + integration tests
Closes Phase 2 end-to-end. Builds on Phase 2a's three migrations
(000034 oidc_providers + group_role_mappings, 000035 sessions +
session_signing_keys, 000036 users) by shipping the repository surface
Phase 3+ services consume.

Interfaces:
* internal/repository/oidc.go - OIDCProviderRepository (List, Get,
  GetByName, Create, Update, Delete) + GroupRoleMappingRepository
  (ListByProvider, Get, Add, Remove, Map). Sentinels:
  ErrOIDCProviderNotFound, ErrOIDCProviderDuplicateName,
  ErrOIDCProviderInUse (FK ON DELETE RESTRICT translation),
  ErrGroupRoleMappingNotFound, ErrGroupRoleMappingDuplicate.
* internal/repository/session.go - SessionRepository (Create, Get,
  ListByActor, UpdateLastSeen, Revoke, RevokeAllForActor,
  GarbageCollectExpired, Delete) + SessionSigningKeyRepository (List,
  GetActive, Get, Add, Retire, Delete). Sentinels: ErrSessionNotFound,
  ErrSessionRevoked, ErrSessionExpired, ErrSessionSigningKeyNotFound,
  ErrSessionSigningKeyInUse.
* internal/repository/user.go - UserRepository (Get, GetByOIDCSubject,
  Create, Update, ListAll). Sentinels: ErrUserNotFound,
  ErrUserDuplicateOIDCSubject.

Postgres implementations:
* internal/repository/postgres/oidc.go - 309 lines. Translates
  SQLSTATE 23505 (unique_violation) to ErrOIDCProviderDuplicateName /
  ErrGroupRoleMappingDuplicate; SQLSTATE 23503 (foreign_key_violation)
  to ErrOIDCProviderInUse so the Phase 5 handler maps to HTTP 409
  when an operator tries to delete a provider with authenticated
  users. pq.StringArray bridges Go []string to Postgres TEXT[] for
  scopes + allowed_email_domains. Map() uses
  `WHERE group_name = ANY($2)` so a single SELECT resolves N IdP
  group claims at once.
* internal/repository/postgres/session.go - 350 lines. Both Session +
  SessionSigningKey repos. Revoke + Retire are idempotent (re-revoking
  an already-revoked session returns nil; same for retire). The
  GarbageCollectExpired sweep deletes both
  absolute-expiry-passed sessions AND pre-login rows older than the
  10-minute TTL in one DELETE so the scheduler tick is cheap.
  ErrSessionSigningKeyInUse pinned via SQLSTATE 23503 from the
  sessions.signing_key_id FK ON DELETE RESTRICT.
* internal/repository/postgres/user.go - 137 lines. GetByOIDCSubject
  is the Phase 3 hot-path lookup; the (oidc_provider_id,
  oidc_subject) UNIQUE constraint trip translates to
  ErrUserDuplicateOIDCSubject. Update only writes the mutable field
  set (email, display_name, last_login_at, webauthn_credentials);
  oidc_subject + oidc_provider_id are immutable per the
  per-(provider, subject) identity model.

Integration tests (testing.Short()-gated, testcontainers + Postgres
16 Alpine, schema-per-test isolation via getTestDB().freshSchema):

* oidc_test.go: 11 tests covering happy-path + GetNotFound +
  DuplicateName + List + Update + DeleteNotFound + DeleteSucceeds +
  DeleteRefusedWhenUsersReference (the FK ON DELETE RESTRICT pin);
  GroupRoleMapping coverage includes Add/List/Map (3 cases:
  marketing-not-mapped, multi-group hits, empty groups returns
  empty), Duplicate rejection, and the ON DELETE CASCADE on
  provider deletion.
* session_test.go: 12 tests covering SessionSigningKey + Session.
  Key tests: GetActiveSkipsRetired (mints older, retires it, mints
  newer, asserts GetActive returns newer), DeleteRefusedWhenSessions-
  Reference (FK pin), RetireIsIdempotent. Session tests:
  CreateAndGet roundtrip, GetNotFound, Revoke + idempotent re-Revoke,
  ListByActor (3 active + 1 revoked + 1 pre-login -> returns 3,
  pinning the WHERE filter), RevokeAllForActor, GarbageCollectExpired
  (seeds an absolute-expired row + pre-login >10min row + active
  session via raw SQL to bypass CHECK constraints, asserts GC kills
  exactly 2 + active survives), UpdateLastSeen.
* user_test.go: 7 tests covering CreateAndGet, GetNotFound,
  GetByOIDCSubject (hit + miss), DuplicateOIDCSubjectRejected,
  UpdateMutableFields (asserts oidc_subject NOT mutated by Update),
  ListAll, FKRestrictsProviderDelete (mirror of the OIDC test from
  the user side - both ends of the FK contract pinned).

Verifications:
* gofmt -l clean across all 9 new files.
* go vet ./internal/repository/postgres/ rc=0.
* go test -short -count=1 green on internal/repository/postgres/ +
  internal/auth/... + Bundle 1 packages (testing.Short() skips the
  testcontainers integration tests, but the test files compile + the
  short-mode skip path is exercised so the suite is wired correctly).
* Full integration tests run in CI's non-short job against Postgres
  16 Alpine via testcontainers-go.
* govulncheck ./... clean.
* All 24 ci-guards pass.

Phase 2 exit criteria from cowork/auth-bundle-2-prompt.md (all met):
* All three Phase-2 migrations apply cleanly, idempotently: yes
  (Phase 2a). Break-glass migration ships separately in Phase 7.5.
* Repository tests pass against Postgres 16 Alpine: integration
  tests written, gated by testing.Short(), structured to run cleanly
  in CI's non-short job.
* make verify equivalent green: gofmt + vet + go test pass;
  golangci-lint deferred to CI per Phase 0/1's same pattern.
2026-05-10 04:18:27 +00:00

221 lines
6.5 KiB
Go

package postgres_test
import (
"context"
"errors"
"testing"
userdomain "github.com/certctl-io/certctl/internal/auth/user/domain"
"github.com/certctl-io/certctl/internal/repository"
"github.com/certctl-io/certctl/internal/repository/postgres"
)
// newValidUser is shared with oidc_test.go (same _test package).
func newValidUser(suffix, providerID string) *userdomain.User {
return &userdomain.User{
ID: "u-" + suffix,
TenantID: "t-default",
Email: suffix + "@example.com",
DisplayName: "User " + suffix,
OIDCSubject: "subject-" + suffix,
OIDCProviderID: providerID,
WebAuthnCredentials: []byte("[]"),
}
}
func TestUserRepository_CreateAndGet(t *testing.T) {
if testing.Short() {
t.Skip("integration test in short mode")
}
db := getTestDB(t).freshSchema(t)
providerRepo := postgres.NewOIDCProviderRepository(db)
userRepo := postgres.NewUserRepository(db)
ctx := context.Background()
p := newValidProvider("u")
if err := providerRepo.Create(ctx, p); err != nil {
t.Fatalf("Create provider: %v", err)
}
u := newValidUser("alice", p.ID)
if err := userRepo.Create(ctx, u); err != nil {
t.Fatalf("Create user: %v", err)
}
got, err := userRepo.Get(ctx, u.ID)
if err != nil {
t.Fatalf("Get: %v", err)
}
if got.Email != u.Email {
t.Errorf("Email roundtrip: got %q, want %q", got.Email, u.Email)
}
if string(got.WebAuthnCredentials) != "[]" {
t.Errorf("WebAuthnCredentials default = %q; want []", string(got.WebAuthnCredentials))
}
}
func TestUserRepository_GetNotFound(t *testing.T) {
if testing.Short() {
t.Skip("integration test in short mode")
}
db := getTestDB(t).freshSchema(t)
repo := postgres.NewUserRepository(db)
ctx := context.Background()
_, err := repo.Get(ctx, "u-nonexistent")
if !errors.Is(err, repository.ErrUserNotFound) {
t.Errorf("err = %v; want ErrUserNotFound", err)
}
}
func TestUserRepository_GetByOIDCSubject(t *testing.T) {
if testing.Short() {
t.Skip("integration test in short mode")
}
db := getTestDB(t).freshSchema(t)
providerRepo := postgres.NewOIDCProviderRepository(db)
userRepo := postgres.NewUserRepository(db)
ctx := context.Background()
p := newValidProvider("subj")
if err := providerRepo.Create(ctx, p); err != nil {
t.Fatalf("Create provider: %v", err)
}
u := newValidUser("bob", p.ID)
if err := userRepo.Create(ctx, u); err != nil {
t.Fatalf("Create user: %v", err)
}
got, err := userRepo.GetByOIDCSubject(ctx, p.ID, u.OIDCSubject)
if err != nil {
t.Fatalf("GetByOIDCSubject: %v", err)
}
if got.ID != u.ID {
t.Errorf("GetByOIDCSubject returned %q; want %q", got.ID, u.ID)
}
// Wrong subject: not found.
_, err = userRepo.GetByOIDCSubject(ctx, p.ID, "wrong-subject")
if !errors.Is(err, repository.ErrUserNotFound) {
t.Errorf("err = %v; want ErrUserNotFound", err)
}
}
func TestUserRepository_DuplicateOIDCSubjectRejected(t *testing.T) {
if testing.Short() {
t.Skip("integration test in short mode")
}
db := getTestDB(t).freshSchema(t)
providerRepo := postgres.NewOIDCProviderRepository(db)
userRepo := postgres.NewUserRepository(db)
ctx := context.Background()
p := newValidProvider("dupsubj")
if err := providerRepo.Create(ctx, p); err != nil {
t.Fatalf("Create provider: %v", err)
}
u1 := newValidUser("first", p.ID)
if err := userRepo.Create(ctx, u1); err != nil {
t.Fatalf("Create u1: %v", err)
}
u2 := newValidUser("second", p.ID)
u2.OIDCSubject = u1.OIDCSubject // collision on (provider, subject) UNIQUE
err := userRepo.Create(ctx, u2)
if !errors.Is(err, repository.ErrUserDuplicateOIDCSubject) {
t.Errorf("Create duplicate (provider, subject) err = %v; want ErrUserDuplicateOIDCSubject", err)
}
}
func TestUserRepository_UpdateMutableFields(t *testing.T) {
if testing.Short() {
t.Skip("integration test in short mode")
}
db := getTestDB(t).freshSchema(t)
providerRepo := postgres.NewOIDCProviderRepository(db)
userRepo := postgres.NewUserRepository(db)
ctx := context.Background()
p := newValidProvider("upd")
if err := providerRepo.Create(ctx, p); err != nil {
t.Fatalf("Create provider: %v", err)
}
u := newValidUser("carol", p.ID)
if err := userRepo.Create(ctx, u); err != nil {
t.Fatalf("Create user: %v", err)
}
u.Email = "carol-new@example.com"
u.DisplayName = "Carol Renamed"
if err := userRepo.Update(ctx, u); err != nil {
t.Fatalf("Update: %v", err)
}
got, err := userRepo.Get(ctx, u.ID)
if err != nil {
t.Fatalf("Get post-update: %v", err)
}
if got.Email != "carol-new@example.com" {
t.Errorf("Update did not persist Email; got %q", got.Email)
}
if got.DisplayName != "Carol Renamed" {
t.Errorf("Update did not persist DisplayName; got %q", got.DisplayName)
}
// Immutable: oidc_subject must NOT change.
if got.OIDCSubject != u.OIDCSubject {
t.Errorf("OIDCSubject mutated: got %q, want %q", got.OIDCSubject, u.OIDCSubject)
}
}
func TestUserRepository_ListAll(t *testing.T) {
if testing.Short() {
t.Skip("integration test in short mode")
}
db := getTestDB(t).freshSchema(t)
providerRepo := postgres.NewOIDCProviderRepository(db)
userRepo := postgres.NewUserRepository(db)
ctx := context.Background()
p := newValidProvider("la")
if err := providerRepo.Create(ctx, p); err != nil {
t.Fatalf("Create provider: %v", err)
}
for _, suf := range []string{"u1", "u2", "u3"} {
u := newValidUser(suf, p.ID)
if err := userRepo.Create(ctx, u); err != nil {
t.Fatalf("Create %s: %v", suf, err)
}
}
out, err := userRepo.ListAll(ctx, "t-default")
if err != nil {
t.Fatalf("ListAll: %v", err)
}
if len(out) != 3 {
t.Errorf("ListAll count = %d; want 3", len(out))
}
}
// TestUserRepository_DeletingProviderRefusedWhenUsersReference complements
// the OIDCProviderRepository test of the same shape; pinning both ends
// of the FK ON DELETE RESTRICT contract.
func TestUserRepository_FKRestrictsProviderDelete(t *testing.T) {
if testing.Short() {
t.Skip("integration test in short mode")
}
db := getTestDB(t).freshSchema(t)
providerRepo := postgres.NewOIDCProviderRepository(db)
userRepo := postgres.NewUserRepository(db)
ctx := context.Background()
p := newValidProvider("fkrest")
if err := providerRepo.Create(ctx, p); err != nil {
t.Fatalf("Create provider: %v", err)
}
u := newValidUser("fkrest-user", p.ID)
if err := userRepo.Create(ctx, u); err != nil {
t.Fatalf("Create user: %v", err)
}
if err := providerRepo.Delete(ctx, p.ID); !errors.Is(err, repository.ErrOIDCProviderInUse) {
t.Errorf("Delete provider (with referencing user) err = %v; want ErrOIDCProviderInUse", err)
}
}