Unify API auth + RFC-compliant CRL/OCSP (M-002 + M-003 + M-006, auto-closes M-001)

Closes the remaining P1 gaps from coverage-gap-audit.md (M-001/M-002/M-003/M-006)
on top of the C-001/C-002 ownership + agent-FK contract fixes landed in
a53a4b8. The work lands as a single commit spanning server, docs, tests,
and the React client.

M-002 — Named API keys with per-key actor propagation
  * Migration 000014 adds the 'api_keys' table (id, name, hash,
    principal, role, created_at, last_used_at, disabled_at) so every
    credential carries an identifiable principal instead of the
    opaque 'anonymous'/'api-key' sentinel.
  * Auth middleware now rotates through configured keys, performs
    constant-time hash comparison, stamps 'last_used_at', and emits
    an actor struct via contextWithActor(). The audit middleware,
    bulk-revocation handler, approval handlers, and MCP tool layer
    now read the principal off the context and persist it on every
    audit_events row.
  * Regression coverage:
      - internal/api/middleware/audit_test.go — actor propagation,
        principal redaction for disabled keys, anonymous fallback for
        unauthenticated endpoints.
      - internal/api/handler/bulk_revocation_handler_test.go,
        job_handler_test.go — principal-on-audit assertions.

M-003 — Authorization gates (Phase B)
  * Approval handler rejects self-approval / self-rejection with 403
    when the actor principal equals the job's requested_by field.
  * Bulk revocation is gated behind the 'admin' role; operators and
    viewers receive 403.
  * Regression coverage:
      - internal/service/job_test.go — TestApproveJob_NotSelf,
        TestRejectJob_NotSelf.
      - internal/api/handler/bulk_revocation_handler_test.go —
        TestBulkRevoke_RequiresAdmin, TestBulkRevoke_AdminSucceeds.

M-006 — RFC-compliant CRL/OCSP on the unauthenticated .well-known mux
  * Per RFC 8615, relying parties cannot reasonably be asked to
    authenticate against the issuing certctl instance to retrieve
    revocation material. CRL and OCSP move off the authenticated
    '/api/v1/crl*' and '/api/v1/ocsp/*' paths onto:
        GET /.well-known/pki/crl/{issuer_id}
            Content-Type: application/pkix-crl   (RFC 5280 §5)
        GET /.well-known/pki/ocsp/{issuer_id}/{serial}
            Content-Type: application/ocsp-response  (RFC 6960)
  * Non-standard JSON CRL shape is removed; only DER is served.
  * Short-lived certificate exemption (profile TTL < 1h → skip
    CRL/OCSP) is preserved; the response simply omits the serial.
  * Routes are registered on the unauthenticated 'finalHandler' mux
    in cmd/server/main.go alongside EST ('/.well-known/est/*') and
    SCEP ('/scep'). Legacy authenticated paths return 404.
  * Regression coverage:
      - internal/api/handler/certificate_handler_test.go — content
        type, DER parseability, 404 for unknown issuer.
      - internal/api/handler/adversarial_path_test.go — unauthenticated
        access asserted for CRL, OCSP, EST, SCEP.
      - internal/api/router/router_test.go — route-table assertion
        that '.well-known/pki/*', '.well-known/est/*', and '/scep' are
        mounted on the unauthenticated branch.

M-001 — Auto-closed by M-002
  EST and SCEP were already registered on the unauthenticated
  'finalHandler' mux; the router comment at
  internal/api/router/router.go:247 now matches reality. The
  adversarial-path tests above lock the behavior in.

Verification (all gates green):
  * go vet ./...                                           — clean
  * go build ./...                                         — ok
  * go test -short ./... (55+ packages)                    — all pass
  * web/ : npm test (225 Vitest tests)                     — all pass
  * web/ : npx tsc --noEmit                                — clean
  * grep sweep for '/api/v1/(crl|ocsp)' — 13 surviving hits,
    all intentional M-006 tombstone/relocation comments.

Documentation:
  * coverage-gap-audit.md — status flips M-001/M-002/M-003/M-006 →
    Fixed, with per-finding resolution paragraphs citing regression
    test IDs. (Audit file lives outside this repo; see cowork root.)
  * CLAUDE.md Project Status line updated with the auth-unification
    closure note.
  * docs/features.md, docs/architecture.md, docs/quickstart.md,
    docs/concepts.md, docs/connectors.md, docs/test-env.md,
    docs/testing-guide.md, docs/compliance-*.md, docs/demo-advanced.md
    — refreshed for the new '.well-known/pki/*' namespace and named
    API keys.
  * api/openapi.yaml — documents the new unauthenticated endpoints
    and removes the legacy '/api/v1/crl*' + '/api/v1/ocsp/*' paths.

.gitignore: adds '/.gocache/' and '/.gomodcache/' for the session-
scoped Go caches so they never enter the tree.
This commit is contained in:
shankar0123
2026-04-18 18:17:41 +00:00
parent a53a4b845b
commit 3287e174dc
45 changed files with 1468 additions and 526 deletions
+18 -10
View File
@@ -517,12 +517,18 @@ func TestNotificationEndpoints(t *testing.T) {
})
}
// TestCRLEndpoint exercises the CRL listing endpoint (M15a).
// TestCRLEndpoint exercises the RFC 5280 DER-encoded CRL endpoint served
// unauthenticated at /.well-known/pki/crl/{issuer_id} (M-006 relocation from
// the pre-M-006 JSON CRL at /api/v1/crl, which was removed entirely because
// RFC 5280 §5 defines only the DER wire format).
func TestCRLEndpoint(t *testing.T) {
server, _, _, _ := setupTestServer(t)
t.Run("GetCRL_JSON", func(t *testing.T) {
resp, err := http.Get(server.URL + "/api/v1/crl")
t.Run("GetDERCRL_Unauthenticated", func(t *testing.T) {
// Intentionally no Authorization header — relying parties can't present
// a certctl API key, so the PKI endpoints are exposed under the
// RFC 8615 `.well-known` namespace with auth bypassed.
resp, err := http.Get(server.URL + "/.well-known/pki/crl/iss-local")
if err != nil {
t.Fatalf("request failed: %v", err)
}
@@ -531,15 +537,17 @@ func TestCRLEndpoint(t *testing.T) {
bodyBytes, _ := io.ReadAll(resp.Body)
t.Fatalf("expected 200, got %d: %s", resp.StatusCode, string(bodyBytes))
}
var crl map[string]interface{}
json.NewDecoder(resp.Body).Decode(&crl)
if crl["version"] == nil {
t.Error("expected version field in CRL response")
if ct := resp.Header.Get("Content-Type"); ct != "application/pkix-crl" {
t.Errorf("expected Content-Type application/pkix-crl, got %s", ct)
}
if crl["entries"] == nil {
t.Error("expected entries field in CRL response")
body, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatalf("read body failed: %v", err)
}
t.Logf("CRL response: version=%v, entries_count=%v", crl["version"], crl["total"])
if len(body) == 0 {
t.Error("expected non-empty DER CRL body")
}
t.Logf("DER CRL response: %d bytes", len(body))
})
}
+44 -1
View File
@@ -64,7 +64,8 @@ func TestCertificateLifecycle(t *testing.T) {
certificateService.SetTargetRepo(targetRepo)
renewalService := service.NewRenewalService(certRepo, jobRepo, renewalPolicyRepo, nil, auditService, notificationService, issuerRegistry, "server")
deploymentService := service.NewDeploymentService(jobRepo, targetRepo, agentRepo, certRepo, auditService, notificationService)
jobService := service.NewJobService(jobRepo, renewalService, deploymentService, logger)
ownerRepo := newMockOwnerRepository()
jobService := service.NewJobService(jobRepo, certRepo, ownerRepo, renewalService, deploymentService, logger)
agentService := service.NewAgentService(agentRepo, certRepo, jobRepo, targetRepo, auditService, issuerRegistry, renewalService)
// 32-byte AES-256 test key — C-2 remediation makes IssuerService fail closed
// without a configured CERTCTL_CONFIG_ENCRYPTION_KEY. Happy-path CRUD tests
@@ -862,6 +863,48 @@ func (m *mockTargetRepository) ListByCertificate(ctx context.Context, certID str
return m.List(ctx)
}
// mockOwnerRepository satisfies repository.OwnerRepository for the M-003
// not-self approval wiring. Tests that don't care about owner lookup get an
// empty map (Get returns errNotFound, which checkNotSelf permits).
type mockOwnerRepository struct {
owners map[string]*domain.Owner
}
func newMockOwnerRepository() *mockOwnerRepository {
return &mockOwnerRepository{owners: make(map[string]*domain.Owner)}
}
func (m *mockOwnerRepository) List(ctx context.Context) ([]*domain.Owner, error) {
var out []*domain.Owner
for _, o := range m.owners {
out = append(out, o)
}
return out, nil
}
func (m *mockOwnerRepository) Get(ctx context.Context, id string) (*domain.Owner, error) {
o, ok := m.owners[id]
if !ok {
return nil, fmt.Errorf("owner not found")
}
return o, nil
}
func (m *mockOwnerRepository) Create(ctx context.Context, o *domain.Owner) error {
m.owners[o.ID] = o
return nil
}
func (m *mockOwnerRepository) Update(ctx context.Context, o *domain.Owner) error {
m.owners[o.ID] = o
return nil
}
func (m *mockOwnerRepository) Delete(ctx context.Context, id string) error {
delete(m.owners, id)
return nil
}
type mockNotificationRepository struct {
notifications []*domain.NotificationEvent
}
+23 -12
View File
@@ -56,7 +56,8 @@ func setupTestServer(t *testing.T) (*httptest.Server, *mockCertificateRepository
certificateService.SetCAOperationsSvc(caOperationsSvc)
renewalService := service.NewRenewalService(certRepo, jobRepo, renewalPolicyRepo, nil, auditService, notificationService, issuerRegistry, "server")
deploymentService := service.NewDeploymentService(jobRepo, targetRepo, agentRepo, certRepo, auditService, notificationService)
jobService := service.NewJobService(jobRepo, renewalService, deploymentService, logger)
ownerRepo := newMockOwnerRepository()
jobService := service.NewJobService(jobRepo, certRepo, ownerRepo, renewalService, deploymentService, logger)
agentService := service.NewAgentService(agentRepo, certRepo, jobRepo, targetRepo, auditService, issuerRegistry, renewalService)
// 32-byte AES-256 test key — C-2 remediation makes IssuerService fail closed
// without a configured CERTCTL_CONFIG_ENCRYPTION_KEY. Happy-path CRUD tests
@@ -112,6 +113,10 @@ func setupTestServer(t *testing.T) (*httptest.Server, *mockCertificateRepository
BulkRevocation: handler.BulkRevocationHandler{},
})
r.RegisterESTHandlers(estHandler)
// M-006: CRL + OCSP live under /.well-known/pki/ (RFC 5280 + RFC 6960 + RFC 8615).
// The negative_test integration suite exercises the DER CRL at this path with
// no Authorization header to verify the relying-party contract.
r.RegisterPKIHandlers(certificateHandler)
server := httptest.NewServer(r)
t.Cleanup(func() { server.Close() })
@@ -789,8 +794,14 @@ func TestRevocationEndpoints(t *testing.T) {
}
})
t.Run("GetCRL_Success", func(t *testing.T) {
resp, err := http.Get(server.URL + "/api/v1/crl")
// M-006: the non-standard JSON CRL at GET /api/v1/crl was removed entirely.
// RFC 5280 §5 defines only the DER wire format, which is now served
// unauthenticated under /.well-known/pki/crl/{issuer_id} (RFC 8615) so
// relying parties can fetch revocation data without a certctl API key.
// We verify the contract by requesting with no Authorization header and
// asserting DER content-type + a non-empty body.
t.Run("GetDERCRL_Unauthenticated", func(t *testing.T) {
resp, err := http.Get(server.URL + "/.well-known/pki/crl/iss-local")
if err != nil {
t.Fatalf("request failed: %v", err)
}
@@ -801,17 +812,17 @@ func TestRevocationEndpoints(t *testing.T) {
t.Fatalf("expected 200, got %d: %s", resp.StatusCode, string(bodyBytes))
}
var crl map[string]interface{}
json.NewDecoder(resp.Body).Decode(&crl)
if crl["version"] != float64(1) {
t.Errorf("expected CRL version 1, got %v", crl["version"])
ct := resp.Header.Get("Content-Type")
if ct != "application/pkix-crl" {
t.Errorf("expected Content-Type application/pkix-crl, got %s", ct)
}
// Should have at least 1 entry from the revocation above
total, _ := crl["total"].(float64)
if total < 1 {
t.Errorf("expected at least 1 CRL entry, got %v", total)
body, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatalf("read body failed: %v", err)
}
if len(body) == 0 {
t.Error("expected non-empty DER CRL body")
}
})
}