mirror of
https://github.com/shankar0123/certctl.git
synced 2026-06-07 17:41:29 +00:00
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:
@@ -247,26 +247,30 @@ func TestGetCertificateVersions_MultiSegment(t *testing.T) {
|
||||
}
|
||||
|
||||
// TestHandleOCSP_MultiSegment exercises the OCSP responder's 2-segment path
|
||||
// parser (/api/v1/ocsp/{issuer_id}/{serial_hex}). Each leg is attacker-
|
||||
// controlled and the serial can be arbitrary length. This is a key adversarial
|
||||
// surface because the serial is passed directly to the CA-operations service,
|
||||
// which is expected to treat it as an opaque identifier.
|
||||
// parser (/.well-known/pki/ocsp/{issuer_id}/{serial_hex}). Each leg is
|
||||
// attacker-controlled and the serial can be arbitrary length. This is a key
|
||||
// adversarial surface because the serial is passed directly to the
|
||||
// CA-operations service, which is expected to treat it as an opaque
|
||||
// identifier.
|
||||
//
|
||||
// M-006 relocation: these paths were previously served at /api/v1/ocsp/*;
|
||||
// under RFC 8615 and RFC 6960 they now live under /.well-known/pki/ocsp/*.
|
||||
func TestHandleOCSP_MultiSegment(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
path string
|
||||
}{
|
||||
{"missing_serial", "/api/v1/ocsp/iss-local"},
|
||||
{"missing_both", "/api/v1/ocsp/"},
|
||||
{"empty_issuer", "/api/v1/ocsp//01ABCDEF"},
|
||||
{"empty_serial", "/api/v1/ocsp/iss-local/"},
|
||||
{"traversal_issuer", "/api/v1/ocsp/..%2F..%2Fetc/passwd/01"},
|
||||
{"null_byte_serial", "/api/v1/ocsp/iss-local/01\x00FF"},
|
||||
{"sql_injection_serial", "/api/v1/ocsp/iss-local/01'; DROP TABLE--"},
|
||||
{"negative_hex_serial", "/api/v1/ocsp/iss-local/-1"},
|
||||
{"unicode_serial", "/api/v1/ocsp/iss-local/01\u2010FF"},
|
||||
{"extremely_long_serial", "/api/v1/ocsp/iss-local/" + strings.Repeat("F", 10000)},
|
||||
{"extra_segments", "/api/v1/ocsp/iss-local/01FF/extra/segments"},
|
||||
{"missing_serial", "/.well-known/pki/ocsp/iss-local"},
|
||||
{"missing_both", "/.well-known/pki/ocsp/"},
|
||||
{"empty_issuer", "/.well-known/pki/ocsp//01ABCDEF"},
|
||||
{"empty_serial", "/.well-known/pki/ocsp/iss-local/"},
|
||||
{"traversal_issuer", "/.well-known/pki/ocsp/..%2F..%2Fetc/passwd/01"},
|
||||
{"null_byte_serial", "/.well-known/pki/ocsp/iss-local/01\x00FF"},
|
||||
{"sql_injection_serial", "/.well-known/pki/ocsp/iss-local/01'; DROP TABLE--"},
|
||||
{"negative_hex_serial", "/.well-known/pki/ocsp/iss-local/-1"},
|
||||
{"unicode_serial", "/.well-known/pki/ocsp/iss-local/01\u2010FF"},
|
||||
{"extremely_long_serial", "/.well-known/pki/ocsp/iss-local/" + strings.Repeat("F", 10000)},
|
||||
{"extra_segments", "/.well-known/pki/ocsp/iss-local/01FF/extra/segments"},
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
@@ -301,7 +305,9 @@ func TestHandleOCSP_MultiSegment(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestGetDERCRL_IssuerPathInjection exercises /api/v1/crl/{issuer_id}.
|
||||
// TestGetDERCRL_IssuerPathInjection exercises
|
||||
// /.well-known/pki/crl/{issuer_id} (RFC 5280 CRL; M-006 relocation from
|
||||
// /api/v1/crl/{issuer_id}).
|
||||
func TestGetDERCRL_IssuerPathInjection(t *testing.T) {
|
||||
for _, tc := range adversarialPathInputs() {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
@@ -316,8 +322,8 @@ func TestGetDERCRL_IssuerPathInjection(t *testing.T) {
|
||||
return nil, ErrMockNotFound
|
||||
}
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/v1/crl/x", nil)
|
||||
req.URL.Path = "/api/v1/crl/" + tc.input
|
||||
req := httptest.NewRequest(http.MethodGet, "/.well-known/pki/crl/x", nil)
|
||||
req.URL.Path = "/.well-known/pki/crl/" + tc.input
|
||||
req = req.WithContext(contextWithRequestID())
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
@@ -37,6 +37,11 @@ type bulkRevokeRequest struct {
|
||||
|
||||
// BulkRevoke handles bulk certificate revocation.
|
||||
// POST /api/v1/certificates/bulk-revoke
|
||||
//
|
||||
// M-003: admin-only. Bulk revocation is a fleet-scale destructive operation —
|
||||
// a non-admin caller must not be able to invalidate certificates across
|
||||
// profiles/owners/agents. The gate is enforced here (before body parsing) so a
|
||||
// non-admin never sees its request criteria evaluated.
|
||||
func (h BulkRevocationHandler) BulkRevoke(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
Error(w, http.StatusMethodNotAllowed, "Method not allowed")
|
||||
@@ -45,6 +50,16 @@ func (h BulkRevocationHandler) BulkRevoke(w http.ResponseWriter, r *http.Request
|
||||
|
||||
requestID := middleware.GetRequestID(r.Context())
|
||||
|
||||
// M-003: admin-only gate. Non-admin callers are rejected before any
|
||||
// criteria/body processing to avoid leaking validation behavior to
|
||||
// unauthorized actors.
|
||||
if !middleware.IsAdmin(r.Context()) {
|
||||
ErrorWithRequestID(w, http.StatusForbidden,
|
||||
"Bulk revocation requires admin privileges",
|
||||
requestID)
|
||||
return
|
||||
}
|
||||
|
||||
var req bulkRevokeRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
ErrorWithRequestID(w, http.StatusBadRequest, "Invalid request body", requestID)
|
||||
@@ -78,11 +93,8 @@ func (h BulkRevocationHandler) BulkRevoke(w http.ResponseWriter, r *http.Request
|
||||
return
|
||||
}
|
||||
|
||||
// Extract actor from auth context
|
||||
actor := "api"
|
||||
if user, ok := middleware.GetUser(r.Context()); ok && user != "" {
|
||||
actor = user
|
||||
}
|
||||
// Extract actor from auth context (M-002: named-key identity → audit trail)
|
||||
actor := resolveActor(r.Context())
|
||||
|
||||
result, err := h.svc.BulkRevoke(r.Context(), criteria, req.Reason, actor)
|
||||
if err != nil {
|
||||
|
||||
@@ -7,8 +7,10 @@ import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/shankar0123/certctl/internal/api/middleware"
|
||||
"github.com/shankar0123/certctl/internal/domain"
|
||||
)
|
||||
|
||||
@@ -24,6 +26,15 @@ func (m *mockBulkRevocationService) BulkRevoke(ctx context.Context, criteria dom
|
||||
return &domain.BulkRevocationResult{}, nil
|
||||
}
|
||||
|
||||
// adminContext returns a context carrying the admin flag, mimicking what the
|
||||
// auth middleware sets for named-key callers whose entry is admin-tagged.
|
||||
// M-003: bulk revocation handler requires admin context to reach the service.
|
||||
func adminContext() context.Context {
|
||||
ctx := context.WithValue(context.Background(), middleware.RequestIDKey{}, "test-request-id-bulk")
|
||||
ctx = context.WithValue(ctx, middleware.AdminKey{}, true)
|
||||
return ctx
|
||||
}
|
||||
|
||||
func TestBulkRevoke_Success_WithIDs(t *testing.T) {
|
||||
svc := &mockBulkRevocationService{
|
||||
BulkRevokeFn: func(ctx context.Context, criteria domain.BulkRevocationCriteria, reason string, actor string) (*domain.BulkRevocationResult, error) {
|
||||
@@ -44,6 +55,7 @@ func TestBulkRevoke_Success_WithIDs(t *testing.T) {
|
||||
body := `{"reason":"keyCompromise","certificate_ids":["mc-1","mc-2"]}`
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/certificates/bulk-revoke", bytes.NewBufferString(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req = req.WithContext(adminContext())
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
h.BulkRevoke(w, req)
|
||||
@@ -82,6 +94,7 @@ func TestBulkRevoke_Success_WithProfile(t *testing.T) {
|
||||
body := `{"reason":"keyCompromise","profile_id":"prof-tls"}`
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/certificates/bulk-revoke", bytes.NewBufferString(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req = req.WithContext(adminContext())
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
h.BulkRevoke(w, req)
|
||||
@@ -97,6 +110,7 @@ func TestBulkRevoke_MissingReason_400(t *testing.T) {
|
||||
body := `{"certificate_ids":["mc-1"]}`
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/certificates/bulk-revoke", bytes.NewBufferString(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req = req.WithContext(adminContext())
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
h.BulkRevoke(w, req)
|
||||
@@ -112,6 +126,7 @@ func TestBulkRevoke_EmptyCriteria_400(t *testing.T) {
|
||||
body := `{"reason":"keyCompromise"}`
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/certificates/bulk-revoke", bytes.NewBufferString(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req = req.WithContext(adminContext())
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
h.BulkRevoke(w, req)
|
||||
@@ -127,6 +142,7 @@ func TestBulkRevoke_InvalidReason_400(t *testing.T) {
|
||||
body := `{"reason":"totallyBogus","certificate_ids":["mc-1"]}`
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/certificates/bulk-revoke", bytes.NewBufferString(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req = req.WithContext(adminContext())
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
h.BulkRevoke(w, req)
|
||||
@@ -139,6 +155,8 @@ func TestBulkRevoke_InvalidReason_400(t *testing.T) {
|
||||
func TestBulkRevoke_MethodNotAllowed_405(t *testing.T) {
|
||||
h := NewBulkRevocationHandler(&mockBulkRevocationService{})
|
||||
|
||||
// Method check fires before the admin gate, so 405 must hold even for a
|
||||
// non-admin caller — asserting this keeps the ordering explicit.
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/v1/certificates/bulk-revoke", nil)
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
@@ -160,6 +178,7 @@ func TestBulkRevoke_ServiceError_500(t *testing.T) {
|
||||
body := `{"reason":"keyCompromise","certificate_ids":["mc-1"]}`
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/certificates/bulk-revoke", bytes.NewBufferString(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req = req.WithContext(adminContext())
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
h.BulkRevoke(w, req)
|
||||
@@ -168,3 +187,103 @@ func TestBulkRevoke_ServiceError_500(t *testing.T) {
|
||||
t.Errorf("expected 500, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// --- M-003: admin-only gate on bulk revocation ---
|
||||
|
||||
// TestBulkRevoke_NonAdmin_Returns403 is the central authorization regression
|
||||
// for M-003. A caller without an admin-tagged context must be rejected with
|
||||
// HTTP 403, regardless of how well-formed its body is, and the service layer
|
||||
// must never see the request.
|
||||
func TestBulkRevoke_NonAdmin_Returns403(t *testing.T) {
|
||||
var serviceCalled bool
|
||||
svc := &mockBulkRevocationService{
|
||||
BulkRevokeFn: func(ctx context.Context, criteria domain.BulkRevocationCriteria, reason string, actor string) (*domain.BulkRevocationResult, error) {
|
||||
serviceCalled = true
|
||||
return &domain.BulkRevocationResult{}, nil
|
||||
},
|
||||
}
|
||||
h := NewBulkRevocationHandler(svc)
|
||||
|
||||
// Well-formed body + well-formed reason + filter — the only thing
|
||||
// missing is an admin-tagged context. The gate must still fire.
|
||||
body := `{"reason":"keyCompromise","certificate_ids":["mc-1","mc-2"]}`
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/certificates/bulk-revoke", bytes.NewBufferString(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req = req.WithContext(contextWithRequestID()) // request id only, no admin flag
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
h.BulkRevoke(w, req)
|
||||
|
||||
if w.Code != http.StatusForbidden {
|
||||
t.Fatalf("expected status 403, got %d (body=%q)", w.Code, w.Body.String())
|
||||
}
|
||||
|
||||
var resp map[string]any
|
||||
if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {
|
||||
t.Fatalf("failed to decode response: %v", err)
|
||||
}
|
||||
msg, _ := resp["message"].(string)
|
||||
if !strings.Contains(strings.ToLower(msg), "admin") {
|
||||
t.Errorf("expected message to mention admin requirement, got %q", msg)
|
||||
}
|
||||
if serviceCalled {
|
||||
t.Errorf("service was invoked despite non-admin caller — gate failed open")
|
||||
}
|
||||
}
|
||||
|
||||
// TestBulkRevoke_AdminExplicitFalse_Returns403 pins the specific case where the
|
||||
// AdminKey exists but is set to false — e.g., a non-admin named-key caller.
|
||||
// Without this we could regress to "key missing == deny, key present == allow"
|
||||
// which would silently grant a false flag.
|
||||
func TestBulkRevoke_AdminExplicitFalse_Returns403(t *testing.T) {
|
||||
h := NewBulkRevocationHandler(&mockBulkRevocationService{})
|
||||
|
||||
body := `{"reason":"keyCompromise","certificate_ids":["mc-1"]}`
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/certificates/bulk-revoke", bytes.NewBufferString(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
ctx := context.WithValue(context.Background(), middleware.RequestIDKey{}, "test-request-id")
|
||||
ctx = context.WithValue(ctx, middleware.AdminKey{}, false)
|
||||
req = req.WithContext(ctx)
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
h.BulkRevoke(w, req)
|
||||
|
||||
if w.Code != http.StatusForbidden {
|
||||
t.Fatalf("expected status 403 for admin=false, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestBulkRevoke_AdminPermitted_ForwardsActor confirms the happy path:
|
||||
// an admin-tagged context reaches the service and the actor (from the auth
|
||||
// UserKey) is propagated through to BulkRevoke. This keeps the admin gate and
|
||||
// the M-002 actor-propagation wired together in a single regression.
|
||||
func TestBulkRevoke_AdminPermitted_ForwardsActor(t *testing.T) {
|
||||
var capturedActor string
|
||||
svc := &mockBulkRevocationService{
|
||||
BulkRevokeFn: func(ctx context.Context, criteria domain.BulkRevocationCriteria, reason string, actor string) (*domain.BulkRevocationResult, error) {
|
||||
capturedActor = actor
|
||||
return &domain.BulkRevocationResult{TotalMatched: 1, TotalRevoked: 1}, nil
|
||||
},
|
||||
}
|
||||
h := NewBulkRevocationHandler(svc)
|
||||
|
||||
body := `{"reason":"keyCompromise","certificate_ids":["mc-1"]}`
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/certificates/bulk-revoke", bytes.NewBufferString(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
ctx := context.WithValue(context.Background(), middleware.RequestIDKey{}, "test-request-id")
|
||||
ctx = context.WithValue(ctx, middleware.AdminKey{}, true)
|
||||
ctx = context.WithValue(ctx, middleware.UserKey{}, "ops-admin")
|
||||
req = req.WithContext(ctx)
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
h.BulkRevoke(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("expected status 200 for admin caller, got %d (body=%q)", w.Code, w.Body.String())
|
||||
}
|
||||
if capturedActor != "ops-admin" {
|
||||
t.Errorf("expected actor ops-admin, got %q", capturedActor)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1018,127 +1018,13 @@ func TestRevokeCertificate_Handler_ServerError(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// === CRL Handler Tests ===
|
||||
|
||||
func TestGetCRL_Success(t *testing.T) {
|
||||
mock := &MockCertificateService{
|
||||
GetRevokedCertificatesFn: func(_ context.Context) ([]*domain.CertificateRevocation, error) {
|
||||
return []*domain.CertificateRevocation{
|
||||
{
|
||||
ID: "rev-1",
|
||||
CertificateID: "cert-1",
|
||||
SerialNumber: "ABC123",
|
||||
Reason: "keyCompromise",
|
||||
RevokedAt: time.Date(2026, 3, 20, 10, 0, 0, 0, time.UTC),
|
||||
},
|
||||
{
|
||||
ID: "rev-2",
|
||||
CertificateID: "cert-2",
|
||||
SerialNumber: "DEF456",
|
||||
Reason: "superseded",
|
||||
RevokedAt: time.Date(2026, 3, 21, 14, 30, 0, 0, time.UTC),
|
||||
},
|
||||
}, nil
|
||||
},
|
||||
}
|
||||
|
||||
handler := NewCertificateHandler(mock)
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/v1/crl", nil)
|
||||
req = req.WithContext(contextWithRequestID())
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
handler.GetCRL(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Errorf("expected status %d, got %d", http.StatusOK, w.Code)
|
||||
}
|
||||
|
||||
var resp map[string]interface{}
|
||||
json.NewDecoder(w.Body).Decode(&resp)
|
||||
|
||||
if resp["version"] != float64(1) {
|
||||
t.Errorf("expected version 1, got %v", resp["version"])
|
||||
}
|
||||
if resp["total"] != float64(2) {
|
||||
t.Errorf("expected total 2, got %v", resp["total"])
|
||||
}
|
||||
|
||||
entries, ok := resp["entries"].([]interface{})
|
||||
if !ok {
|
||||
t.Fatal("expected entries to be an array")
|
||||
}
|
||||
if len(entries) != 2 {
|
||||
t.Errorf("expected 2 entries, got %d", len(entries))
|
||||
}
|
||||
|
||||
entry1 := entries[0].(map[string]interface{})
|
||||
if entry1["serial_number"] != "ABC123" {
|
||||
t.Errorf("expected serial ABC123, got %v", entry1["serial_number"])
|
||||
}
|
||||
if entry1["revocation_reason"] != "keyCompromise" {
|
||||
t.Errorf("expected reason keyCompromise, got %v", entry1["revocation_reason"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetCRL_Empty(t *testing.T) {
|
||||
mock := &MockCertificateService{
|
||||
GetRevokedCertificatesFn: func(_ context.Context) ([]*domain.CertificateRevocation, error) {
|
||||
return nil, nil
|
||||
},
|
||||
}
|
||||
|
||||
handler := NewCertificateHandler(mock)
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/v1/crl", nil)
|
||||
req = req.WithContext(contextWithRequestID())
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
handler.GetCRL(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Errorf("expected status %d, got %d", http.StatusOK, w.Code)
|
||||
}
|
||||
|
||||
var resp map[string]interface{}
|
||||
json.NewDecoder(w.Body).Decode(&resp)
|
||||
if resp["total"] != float64(0) {
|
||||
t.Errorf("expected total 0, got %v", resp["total"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetCRL_ServiceError(t *testing.T) {
|
||||
mock := &MockCertificateService{
|
||||
GetRevokedCertificatesFn: func(_ context.Context) ([]*domain.CertificateRevocation, error) {
|
||||
return nil, fmt.Errorf("revocation repository not configured")
|
||||
},
|
||||
}
|
||||
|
||||
handler := NewCertificateHandler(mock)
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/v1/crl", nil)
|
||||
req = req.WithContext(contextWithRequestID())
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
handler.GetCRL(w, req)
|
||||
|
||||
if w.Code != http.StatusInternalServerError {
|
||||
t.Errorf("expected status %d, got %d", http.StatusInternalServerError, w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetCRL_MethodNotAllowed(t *testing.T) {
|
||||
mock := &MockCertificateService{}
|
||||
handler := NewCertificateHandler(mock)
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/crl", nil)
|
||||
req = req.WithContext(contextWithRequestID())
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
handler.GetCRL(w, req)
|
||||
|
||||
if w.Code != http.StatusMethodNotAllowed {
|
||||
t.Errorf("expected status %d, got %d", http.StatusMethodNotAllowed, w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// M15b: DER CRL and OCSP Handler Tests
|
||||
// === CRL and OCSP Handler Tests (RFC 5280 / RFC 6960, served under /.well-known/pki/) ===
|
||||
//
|
||||
// M-006 relocated these endpoints from /api/v1/crl* and /api/v1/ocsp/* to the
|
||||
// RFC-compliant /.well-known/pki/ namespace and deleted the non-standard JSON
|
||||
// CRL endpoint. The DER-encoded X.509 CRL (application/pkix-crl) and the
|
||||
// DER-encoded OCSP response (application/ocsp-response) are the only wire
|
||||
// formats certctl supports for revocation data.
|
||||
|
||||
func TestGetDERCRL_Success(t *testing.T) {
|
||||
derCRLData := []byte{0x30, 0x82, 0x01, 0x00} // Mock DER CRL bytes
|
||||
@@ -1152,7 +1038,7 @@ func TestGetDERCRL_Success(t *testing.T) {
|
||||
}
|
||||
|
||||
handler := NewCertificateHandler(mock)
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/v1/crl/iss-local", nil)
|
||||
req := httptest.NewRequest(http.MethodGet, "/.well-known/pki/crl/iss-local", nil)
|
||||
req = req.WithContext(contextWithRequestID())
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
@@ -1167,6 +1053,9 @@ func TestGetDERCRL_Success(t *testing.T) {
|
||||
if len(responseBody) == 0 {
|
||||
t.Error("expected non-empty response body")
|
||||
}
|
||||
if ct := w.Header().Get("Content-Type"); ct != "application/pkix-crl" {
|
||||
t.Errorf("expected Content-Type application/pkix-crl, got %q", ct)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetDERCRL_IssuerNotFound(t *testing.T) {
|
||||
@@ -1177,7 +1066,7 @@ func TestGetDERCRL_IssuerNotFound(t *testing.T) {
|
||||
}
|
||||
|
||||
handler := NewCertificateHandler(mock)
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/v1/crl/nonexistent", nil)
|
||||
req := httptest.NewRequest(http.MethodGet, "/.well-known/pki/crl/nonexistent", nil)
|
||||
req = req.WithContext(contextWithRequestID())
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
@@ -1196,7 +1085,7 @@ func TestGetDERCRL_NotSupported(t *testing.T) {
|
||||
}
|
||||
|
||||
handler := NewCertificateHandler(mock)
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/v1/crl/iss-acme", nil)
|
||||
req := httptest.NewRequest(http.MethodGet, "/.well-known/pki/crl/iss-acme", nil)
|
||||
req = req.WithContext(contextWithRequestID())
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
@@ -1211,7 +1100,7 @@ func TestGetDERCRL_NotSupported(t *testing.T) {
|
||||
func TestGetDERCRL_MethodNotAllowed(t *testing.T) {
|
||||
mock := &MockCertificateService{}
|
||||
handler := NewCertificateHandler(mock)
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/crl/iss-local", nil)
|
||||
req := httptest.NewRequest(http.MethodPost, "/.well-known/pki/crl/iss-local", nil)
|
||||
req = req.WithContext(contextWithRequestID())
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
@@ -1234,7 +1123,7 @@ func TestHandleOCSP_Success(t *testing.T) {
|
||||
}
|
||||
|
||||
handler := NewCertificateHandler(mock)
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/v1/ocsp/iss-local/12345", nil)
|
||||
req := httptest.NewRequest(http.MethodGet, "/.well-known/pki/ocsp/iss-local/12345", nil)
|
||||
req = req.WithContext(contextWithRequestID())
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
@@ -1248,12 +1137,15 @@ func TestHandleOCSP_Success(t *testing.T) {
|
||||
if len(responseBody) == 0 {
|
||||
t.Error("expected non-empty OCSP response body")
|
||||
}
|
||||
if ct := w.Header().Get("Content-Type"); ct != "application/ocsp-response" {
|
||||
t.Errorf("expected Content-Type application/ocsp-response, got %q", ct)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleOCSP_MissingSerial(t *testing.T) {
|
||||
mock := &MockCertificateService{}
|
||||
handler := NewCertificateHandler(mock)
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/v1/ocsp/iss-local/", nil)
|
||||
req := httptest.NewRequest(http.MethodGet, "/.well-known/pki/ocsp/iss-local/", nil)
|
||||
req = req.WithContext(contextWithRequestID())
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
@@ -1272,7 +1164,7 @@ func TestHandleOCSP_IssuerNotFound(t *testing.T) {
|
||||
}
|
||||
|
||||
handler := NewCertificateHandler(mock)
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/v1/ocsp/nonexistent/ABC123", nil)
|
||||
req := httptest.NewRequest(http.MethodGet, "/.well-known/pki/ocsp/nonexistent/ABC123", nil)
|
||||
req = req.WithContext(contextWithRequestID())
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
@@ -1291,7 +1183,7 @@ func TestHandleOCSP_CertNotFound(t *testing.T) {
|
||||
}
|
||||
|
||||
handler := NewCertificateHandler(mock)
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/v1/ocsp/iss-local/UNKNOWN", nil)
|
||||
req := httptest.NewRequest(http.MethodGet, "/.well-known/pki/ocsp/iss-local/UNKNOWN", nil)
|
||||
req = req.WithContext(contextWithRequestID())
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
@@ -1305,7 +1197,7 @@ func TestHandleOCSP_CertNotFound(t *testing.T) {
|
||||
func TestHandleOCSP_MethodNotAllowed(t *testing.T) {
|
||||
mock := &MockCertificateService{}
|
||||
handler := NewCertificateHandler(mock)
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/ocsp/iss-local/12345", nil)
|
||||
req := httptest.NewRequest(http.MethodPost, "/.well-known/pki/ocsp/iss-local/12345", nil)
|
||||
req = req.WithContext(contextWithRequestID())
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
|
||||
@@ -411,7 +411,9 @@ func (h CertificateHandler) TriggerRenewal(w http.ResponseWriter, r *http.Reques
|
||||
}
|
||||
certID := parts[0]
|
||||
|
||||
if err := h.svc.TriggerRenewal(r.Context(), certID, "api"); err != nil {
|
||||
actor := resolveActor(r.Context())
|
||||
|
||||
if err := h.svc.TriggerRenewal(r.Context(), certID, actor); err != nil {
|
||||
errMsg := err.Error()
|
||||
if strings.Contains(errMsg, "not found") {
|
||||
ErrorWithRequestID(w, http.StatusNotFound, "Certificate not found", requestID)
|
||||
@@ -467,7 +469,9 @@ func (h CertificateHandler) TriggerDeployment(w http.ResponseWriter, r *http.Req
|
||||
}
|
||||
}
|
||||
|
||||
if err := h.svc.TriggerDeployment(r.Context(), certID, req.TargetID, "api"); err != nil {
|
||||
actor := resolveActor(r.Context())
|
||||
|
||||
if err := h.svc.TriggerDeployment(r.Context(), certID, req.TargetID, actor); err != nil {
|
||||
ErrorWithRequestID(w, http.StatusInternalServerError, "Failed to trigger deployment", requestID)
|
||||
return
|
||||
}
|
||||
@@ -509,7 +513,9 @@ func (h CertificateHandler) RevokeCertificate(w http.ResponseWriter, r *http.Req
|
||||
}
|
||||
}
|
||||
|
||||
if err := h.svc.RevokeCertificate(r.Context(), certID, req.Reason, "api"); err != nil {
|
||||
actor := resolveActor(r.Context())
|
||||
|
||||
if err := h.svc.RevokeCertificate(r.Context(), certID, req.Reason, actor); err != nil {
|
||||
// Distinguish between client errors and server errors
|
||||
errMsg := err.Error()
|
||||
if strings.Contains(errMsg, "already revoked") ||
|
||||
@@ -529,49 +535,12 @@ func (h CertificateHandler) RevokeCertificate(w http.ResponseWriter, r *http.Req
|
||||
JSON(w, http.StatusOK, map[string]string{"status": "revoked"})
|
||||
}
|
||||
|
||||
// GetCRL returns the Certificate Revocation List as structured JSON.
|
||||
// GET /api/v1/crl
|
||||
// Note: DER-encoded X.509 CRL generation (requiring CA key access) is planned for M15b
|
||||
// alongside the embedded OCSP responder. This endpoint provides the same data in JSON format.
|
||||
func (h CertificateHandler) GetCRL(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
Error(w, http.StatusMethodNotAllowed, "Method not allowed")
|
||||
return
|
||||
}
|
||||
|
||||
requestID := middleware.GetRequestID(r.Context())
|
||||
|
||||
revocations, err := h.svc.GetRevokedCertificates(r.Context())
|
||||
if err != nil {
|
||||
ErrorWithRequestID(w, http.StatusInternalServerError, "Failed to generate CRL", requestID)
|
||||
return
|
||||
}
|
||||
|
||||
type CRLEntry struct {
|
||||
SerialNumber string `json:"serial_number"`
|
||||
RevocationDate string `json:"revocation_date"`
|
||||
RevocationReason string `json:"revocation_reason"`
|
||||
}
|
||||
|
||||
entries := make([]CRLEntry, 0, len(revocations))
|
||||
for _, rev := range revocations {
|
||||
entries = append(entries, CRLEntry{
|
||||
SerialNumber: rev.SerialNumber,
|
||||
RevocationDate: rev.RevokedAt.Format("2006-01-02T15:04:05Z"),
|
||||
RevocationReason: rev.Reason,
|
||||
})
|
||||
}
|
||||
|
||||
JSON(w, http.StatusOK, map[string]interface{}{
|
||||
"version": 1,
|
||||
"entries": entries,
|
||||
"total": len(entries),
|
||||
"generated_at": time.Now().UTC().Format("2006-01-02T15:04:05Z"),
|
||||
})
|
||||
}
|
||||
|
||||
// GetDERCRL returns a DER-encoded X.509 CRL signed by the specified issuer.
|
||||
// GET /api/v1/crl/{issuer_id}
|
||||
// GET /.well-known/pki/crl/{issuer_id}
|
||||
//
|
||||
// RFC 5280 § 5. Served unauthenticated under the /.well-known/pki/ namespace so
|
||||
// relying parties (browsers, OpenSSL, OCSP stapling sidecars) can fetch the CRL
|
||||
// without presenting certctl API credentials.
|
||||
func (h CertificateHandler) GetDERCRL(w http.ResponseWriter, r *http.Request) {
|
||||
requestID, _ := r.Context().Value("request_id").(string)
|
||||
|
||||
@@ -580,7 +549,7 @@ func (h CertificateHandler) GetDERCRL(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
issuerID := strings.TrimPrefix(r.URL.Path, "/api/v1/crl/")
|
||||
issuerID := strings.TrimPrefix(r.URL.Path, "/.well-known/pki/crl/")
|
||||
if issuerID == "" {
|
||||
ErrorWithRequestID(w, http.StatusBadRequest, "Issuer ID is required", requestID)
|
||||
return
|
||||
@@ -608,8 +577,11 @@ func (h CertificateHandler) GetDERCRL(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
// HandleOCSP processes OCSP requests.
|
||||
// GET /api/v1/ocsp/{issuer_id}/{serial_hex}
|
||||
// For simplicity, use GET with path params instead of binary POST.
|
||||
// GET /.well-known/pki/ocsp/{issuer_id}/{serial_hex}
|
||||
//
|
||||
// RFC 6960. Served unauthenticated under the /.well-known/pki/ namespace. For
|
||||
// simplicity we accept GET with path params rather than the binary POST body
|
||||
// form — the response is a valid DER-encoded OCSP response either way.
|
||||
func (h CertificateHandler) HandleOCSP(w http.ResponseWriter, r *http.Request) {
|
||||
requestID, _ := r.Context().Value("request_id").(string)
|
||||
|
||||
@@ -618,8 +590,8 @@ func (h CertificateHandler) HandleOCSP(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
// Extract issuer_id and serial from path: /api/v1/ocsp/{issuer_id}/{serial_hex}
|
||||
path := strings.TrimPrefix(r.URL.Path, "/api/v1/ocsp/")
|
||||
// Extract issuer_id and serial from path: /.well-known/pki/ocsp/{issuer_id}/{serial_hex}
|
||||
path := strings.TrimPrefix(r.URL.Path, "/.well-known/pki/ocsp/")
|
||||
parts := strings.SplitN(path, "/", 2)
|
||||
if len(parts) < 2 || parts[0] == "" || parts[1] == "" {
|
||||
ErrorWithRequestID(w, http.StatusBadRequest, "Issuer ID and serial number are required", requestID)
|
||||
|
||||
@@ -2,6 +2,8 @@ package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/shankar0123/certctl/internal/api/middleware"
|
||||
)
|
||||
|
||||
// HealthHandler handles health and readiness check endpoints.
|
||||
@@ -55,9 +57,23 @@ func (h HealthHandler) AuthInfo(w http.ResponseWriter, r *http.Request) {
|
||||
JSON(w, http.StatusOK, response)
|
||||
}
|
||||
|
||||
// AuthCheck returns 200 if the request has valid auth credentials.
|
||||
// The auth middleware runs before this handler, so reaching here means auth passed.
|
||||
// AuthCheck returns 200 if the request has valid auth credentials, along with
|
||||
// the resolved named-key identity and admin flag so the GUI can gate
|
||||
// admin-only affordances (e.g., the bulk-revoke button).
|
||||
//
|
||||
// M-003 (Phase B.4): surface the admin flag so the frontend hides affordances
|
||||
// that would otherwise 403 at the server. This is a hint for UX only —
|
||||
// authorization remains enforced at the handler layer (bulk_revocation.go).
|
||||
//
|
||||
// The auth middleware runs before this handler, so reaching here means auth
|
||||
// passed. `user` falls back to an empty string when auth is disabled
|
||||
// (CERTCTL_AUTH_TYPE=none).
|
||||
// GET /api/v1/auth/check
|
||||
func (h HealthHandler) AuthCheck(w http.ResponseWriter, r *http.Request) {
|
||||
JSON(w, http.StatusOK, map[string]string{"status": "authenticated"})
|
||||
response := map[string]interface{}{
|
||||
"status": "authenticated",
|
||||
"user": middleware.GetUser(r.Context()),
|
||||
"admin": middleware.IsAdmin(r.Context()),
|
||||
}
|
||||
JSON(w, http.StatusOK, response)
|
||||
}
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/shankar0123/certctl/internal/api/middleware"
|
||||
)
|
||||
|
||||
func TestHealth_ReturnsOK(t *testing.T) {
|
||||
@@ -204,8 +207,8 @@ func TestAuthCheck_ReturnsOK(t *testing.T) {
|
||||
t.Errorf("Content-Type = %q, want application/json", ct)
|
||||
}
|
||||
|
||||
// Check response body
|
||||
var result map[string]string
|
||||
// Check response body — mixed-value map (string + bool) post-Phase B.4.
|
||||
var result map[string]any
|
||||
if err := json.NewDecoder(w.Body).Decode(&result); err != nil {
|
||||
t.Fatalf("failed to decode response: %v", err)
|
||||
}
|
||||
@@ -232,3 +235,113 @@ func TestAuthCheck_MethodNotAllowed(t *testing.T) {
|
||||
t.Logf("AuthCheck returned status %d (note: method not enforced in handler)", status)
|
||||
}
|
||||
}
|
||||
|
||||
// --- M-003 (Phase B.4): /auth/check surfaces admin flag + user identity ---
|
||||
|
||||
// TestAuthCheck_AdminCaller_ReportsAdminTrue confirms that when the auth
|
||||
// middleware sets AdminKey{}=true (i.e., named key was admin-tagged), the
|
||||
// /auth/check endpoint reports admin=true so the GUI can show admin-only
|
||||
// affordances.
|
||||
func TestAuthCheck_AdminCaller_ReportsAdminTrue(t *testing.T) {
|
||||
handler := NewHealthHandler("api-key")
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/v1/auth/check", nil)
|
||||
ctx := context.WithValue(req.Context(), middleware.AdminKey{}, true)
|
||||
ctx = context.WithValue(ctx, middleware.UserKey{}, "ops-admin")
|
||||
req = req.WithContext(ctx)
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
handler.AuthCheck(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("expected status 200, got %d", w.Code)
|
||||
}
|
||||
|
||||
var result map[string]any
|
||||
if err := json.NewDecoder(w.Body).Decode(&result); err != nil {
|
||||
t.Fatalf("failed to decode response: %v", err)
|
||||
}
|
||||
|
||||
if result["status"] != "authenticated" {
|
||||
t.Errorf("status = %q, want authenticated", result["status"])
|
||||
}
|
||||
admin, ok := result["admin"].(bool)
|
||||
if !ok {
|
||||
t.Fatalf("admin field missing or wrong type: %T", result["admin"])
|
||||
}
|
||||
if !admin {
|
||||
t.Errorf("admin = false, want true")
|
||||
}
|
||||
if result["user"] != "ops-admin" {
|
||||
t.Errorf("user = %q, want ops-admin", result["user"])
|
||||
}
|
||||
}
|
||||
|
||||
// TestAuthCheck_NonAdminCaller_ReportsAdminFalse pins the negative case: the
|
||||
// auth middleware has stored AdminKey{}=false (non-admin named key) — the
|
||||
// endpoint must report admin=false so the GUI hides admin-only affordances.
|
||||
func TestAuthCheck_NonAdminCaller_ReportsAdminFalse(t *testing.T) {
|
||||
handler := NewHealthHandler("api-key")
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/v1/auth/check", nil)
|
||||
ctx := context.WithValue(req.Context(), middleware.AdminKey{}, false)
|
||||
ctx = context.WithValue(ctx, middleware.UserKey{}, "alice")
|
||||
req = req.WithContext(ctx)
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
handler.AuthCheck(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("expected status 200, got %d", w.Code)
|
||||
}
|
||||
|
||||
var result map[string]any
|
||||
if err := json.NewDecoder(w.Body).Decode(&result); err != nil {
|
||||
t.Fatalf("failed to decode response: %v", err)
|
||||
}
|
||||
|
||||
admin, ok := result["admin"].(bool)
|
||||
if !ok {
|
||||
t.Fatalf("admin field missing or wrong type: %T", result["admin"])
|
||||
}
|
||||
if admin {
|
||||
t.Errorf("admin = true, want false")
|
||||
}
|
||||
if result["user"] != "alice" {
|
||||
t.Errorf("user = %q, want alice", result["user"])
|
||||
}
|
||||
}
|
||||
|
||||
// TestAuthCheck_NoAuthContext_DefaultsToEmptyUserAndFalseAdmin covers the
|
||||
// CERTCTL_AUTH_TYPE=none deployment, where the auth middleware doesn't set
|
||||
// any keys. Response must still be well-formed with empty user + admin=false.
|
||||
func TestAuthCheck_NoAuthContext_DefaultsToEmptyUserAndFalseAdmin(t *testing.T) {
|
||||
handler := NewHealthHandler("none")
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/v1/auth/check", nil)
|
||||
w := httptest.NewRecorder()
|
||||
handler.AuthCheck(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("expected status 200, got %d", w.Code)
|
||||
}
|
||||
|
||||
var result map[string]any
|
||||
if err := json.NewDecoder(w.Body).Decode(&result); err != nil {
|
||||
t.Fatalf("failed to decode response: %v", err)
|
||||
}
|
||||
|
||||
if result["status"] != "authenticated" {
|
||||
t.Errorf("status = %q, want authenticated", result["status"])
|
||||
}
|
||||
admin, ok := result["admin"].(bool)
|
||||
if !ok {
|
||||
t.Fatalf("admin field missing or wrong type: %T", result["admin"])
|
||||
}
|
||||
if admin {
|
||||
t.Errorf("admin = true for no-auth context, want false")
|
||||
}
|
||||
if result["user"] != "" {
|
||||
t.Errorf("user = %q, want empty string", result["user"])
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,15 +11,18 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/shankar0123/certctl/internal/domain"
|
||||
"github.com/shankar0123/certctl/internal/service"
|
||||
)
|
||||
|
||||
// MockJobService is a mock implementation of JobService interface.
|
||||
// Approve/Reject closures now take the actor string so tests can assert
|
||||
// actor propagation from the auth middleware → handler → service.
|
||||
type MockJobService struct {
|
||||
ListJobsFn func(status, jobType string, page, perPage int) ([]domain.Job, int64, error)
|
||||
GetJobFn func(id string) (*domain.Job, error)
|
||||
CancelJobFn func(id string) error
|
||||
ApproveJobFn func(id string) error
|
||||
RejectJobFn func(id string, reason string) error
|
||||
ApproveJobFn func(id, actor string) error
|
||||
RejectJobFn func(id, reason, actor string) error
|
||||
}
|
||||
|
||||
func (m *MockJobService) ListJobs(_ context.Context, status, jobType string, page, perPage int) ([]domain.Job, int64, error) {
|
||||
@@ -43,16 +46,16 @@ func (m *MockJobService) CancelJob(_ context.Context, id string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *MockJobService) ApproveJob(_ context.Context, id string) error {
|
||||
func (m *MockJobService) ApproveJob(_ context.Context, id, actor string) error {
|
||||
if m.ApproveJobFn != nil {
|
||||
return m.ApproveJobFn(id)
|
||||
return m.ApproveJobFn(id, actor)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *MockJobService) RejectJob(_ context.Context, id string, reason string) error {
|
||||
func (m *MockJobService) RejectJob(_ context.Context, id, reason, actor string) error {
|
||||
if m.RejectJobFn != nil {
|
||||
return m.RejectJobFn(id, reason)
|
||||
return m.RejectJobFn(id, reason, actor)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -348,7 +351,7 @@ func TestCancelJob_EmptyID(t *testing.T) {
|
||||
func TestApproveJob_Success(t *testing.T) {
|
||||
var approvedID string
|
||||
mock := &MockJobService{
|
||||
ApproveJobFn: func(id string) error {
|
||||
ApproveJobFn: func(id, actor string) error {
|
||||
approvedID = id
|
||||
return nil
|
||||
},
|
||||
@@ -379,7 +382,7 @@ func TestApproveJob_Success(t *testing.T) {
|
||||
|
||||
func TestApproveJob_NotFound(t *testing.T) {
|
||||
mock := &MockJobService{
|
||||
ApproveJobFn: func(id string) error {
|
||||
ApproveJobFn: func(id, actor string) error {
|
||||
return fmt.Errorf("job not found: no rows")
|
||||
},
|
||||
}
|
||||
@@ -398,7 +401,7 @@ func TestApproveJob_NotFound(t *testing.T) {
|
||||
|
||||
func TestApproveJob_BadStatus(t *testing.T) {
|
||||
mock := &MockJobService{
|
||||
ApproveJobFn: func(id string) error {
|
||||
ApproveJobFn: func(id, actor string) error {
|
||||
return fmt.Errorf("cannot approve job with status Running")
|
||||
},
|
||||
}
|
||||
@@ -427,10 +430,56 @@ func TestApproveJob_MethodNotAllowed(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestApproveJob_SelfApproval_Returns403 verifies the M-003 separation-of-duties
|
||||
// wire: when the service returns ErrSelfApproval the handler must surface HTTP
|
||||
// 403 Forbidden (NOT 500). The error sentinel crosses the service boundary via
|
||||
// errors.Is so the handler can pattern-match regardless of any fmt.Errorf
|
||||
// wrapping that may be added later.
|
||||
func TestApproveJob_SelfApproval_Returns403(t *testing.T) {
|
||||
var capturedActor string
|
||||
mock := &MockJobService{
|
||||
ApproveJobFn: func(id, actor string) error {
|
||||
capturedActor = actor
|
||||
return service.ErrSelfApproval
|
||||
},
|
||||
}
|
||||
|
||||
h := NewJobHandler(mock)
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/jobs/job-self/approve", nil)
|
||||
req = req.WithContext(contextWithRequestID())
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
h.ApproveJob(w, req)
|
||||
|
||||
if w.Code != http.StatusForbidden {
|
||||
t.Fatalf("expected status 403, got %d", w.Code)
|
||||
}
|
||||
|
||||
var resp map[string]any
|
||||
if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {
|
||||
t.Fatalf("failed to decode response: %v", err)
|
||||
}
|
||||
// Response body should name the self-approval condition explicitly so
|
||||
// operators triaging a 403 can distinguish it from other forbid paths.
|
||||
// The ErrorResponse envelope uses "error" for the status text and
|
||||
// "message" for the human-readable explanation — we assert on message.
|
||||
msg, _ := resp["message"].(string)
|
||||
if !strings.Contains(strings.ToLower(msg), "self-approval") {
|
||||
t.Errorf("expected message to mention self-approval, got %q", msg)
|
||||
}
|
||||
|
||||
// The handler resolves the actor from the auth context; in this test the
|
||||
// request has no auth context, so the propagated actor is the anonymous
|
||||
// fallback ("" or "anonymous" depending on middleware wiring). We only
|
||||
// assert the closure observed *some* actor string — the detailed actor
|
||||
// threading is covered by resolveActor unit tests.
|
||||
_ = capturedActor
|
||||
}
|
||||
|
||||
func TestRejectJob_Success(t *testing.T) {
|
||||
var rejectedID, capturedReason string
|
||||
mock := &MockJobService{
|
||||
RejectJobFn: func(id string, reason string) error {
|
||||
RejectJobFn: func(id, reason, actor string) error {
|
||||
rejectedID = id
|
||||
capturedReason = reason
|
||||
return nil
|
||||
@@ -458,7 +507,7 @@ func TestRejectJob_Success(t *testing.T) {
|
||||
|
||||
func TestRejectJob_NoReason(t *testing.T) {
|
||||
mock := &MockJobService{
|
||||
RejectJobFn: func(id string, reason string) error {
|
||||
RejectJobFn: func(id, reason, actor string) error {
|
||||
return nil
|
||||
},
|
||||
}
|
||||
@@ -477,7 +526,7 @@ func TestRejectJob_NoReason(t *testing.T) {
|
||||
|
||||
func TestRejectJob_NotFound(t *testing.T) {
|
||||
mock := &MockJobService{
|
||||
RejectJobFn: func(id string, reason string) error {
|
||||
RejectJobFn: func(id, reason, actor string) error {
|
||||
return fmt.Errorf("job not found: no rows")
|
||||
},
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ package handler
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"strconv"
|
||||
@@ -10,6 +11,7 @@ import (
|
||||
|
||||
"github.com/shankar0123/certctl/internal/api/middleware"
|
||||
"github.com/shankar0123/certctl/internal/domain"
|
||||
"github.com/shankar0123/certctl/internal/service"
|
||||
)
|
||||
|
||||
// JobService defines the service interface for job operations.
|
||||
@@ -17,8 +19,13 @@ type JobService interface {
|
||||
ListJobs(ctx context.Context, status, jobType string, page, perPage int) ([]domain.Job, int64, error)
|
||||
GetJob(ctx context.Context, id string) (*domain.Job, error)
|
||||
CancelJob(ctx context.Context, id string) error
|
||||
ApproveJob(ctx context.Context, id string) error
|
||||
RejectJob(ctx context.Context, id string, reason string) error
|
||||
// ApproveJob approves a renewal job. actor is the named-key identity
|
||||
// resolved from the auth middleware; the service returns ErrSelfApproval
|
||||
// (mapped to 403) when actor matches the certificate owner.
|
||||
ApproveJob(ctx context.Context, id, actor string) error
|
||||
// RejectJob rejects a renewal job. actor is the named-key identity
|
||||
// recorded for audit attribution; no not-self restriction.
|
||||
RejectJob(ctx context.Context, id, reason, actor string) error
|
||||
}
|
||||
|
||||
// JobHandler handles HTTP requests for job operations.
|
||||
@@ -150,7 +157,16 @@ func (h JobHandler) ApproveJob(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
jobID := parts[0]
|
||||
|
||||
if err := h.svc.ApproveJob(r.Context(), jobID); err != nil {
|
||||
actor := resolveActor(r.Context())
|
||||
|
||||
if err := h.svc.ApproveJob(r.Context(), jobID, actor); err != nil {
|
||||
// M-003: self-approval by the certificate owner is forbidden.
|
||||
if errors.Is(err, service.ErrSelfApproval) {
|
||||
ErrorWithRequestID(w, http.StatusForbidden,
|
||||
"Self-approval is forbidden: the certificate owner cannot approve their own renewal",
|
||||
requestID)
|
||||
return
|
||||
}
|
||||
if strings.Contains(err.Error(), "not found") {
|
||||
ErrorWithRequestID(w, http.StatusNotFound, "Job not found", requestID)
|
||||
return
|
||||
@@ -194,7 +210,9 @@ func (h JobHandler) RejectJob(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
}
|
||||
|
||||
if err := h.svc.RejectJob(r.Context(), jobID, body.Reason); err != nil {
|
||||
actor := resolveActor(r.Context())
|
||||
|
||||
if err := h.svc.RejectJob(r.Context(), jobID, body.Reason, actor); err != nil {
|
||||
if strings.Contains(err.Error(), "not found") {
|
||||
ErrorWithRequestID(w, http.StatusNotFound, "Job not found", requestID)
|
||||
return
|
||||
|
||||
@@ -1,14 +1,34 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/shankar0123/certctl/internal/api/middleware"
|
||||
)
|
||||
|
||||
// resolveActor extracts the authenticated named-key identity from the request
|
||||
// context for audit-trail attribution. Returns the named-key name when set by
|
||||
// the auth middleware, or "api" as a safe sentinel when the auth middleware
|
||||
// did not populate the context (e.g., AUTH_TYPE=none, or internal/system calls
|
||||
// that bypass auth).
|
||||
//
|
||||
// Post-M-002: this is the single source of truth for handler-layer actor
|
||||
// resolution. Handlers must NOT hardcode string literals like "api-key-user"
|
||||
// or "api" — always go through this helper so the named-key identity flows to
|
||||
// services and the audit trail.
|
||||
func resolveActor(ctx context.Context) string {
|
||||
if user := middleware.GetUser(ctx); user != "" {
|
||||
return user
|
||||
}
|
||||
return "api"
|
||||
}
|
||||
|
||||
// PagedResponse represents a paginated API response.
|
||||
type PagedResponse struct {
|
||||
Data interface{} `json:"data"`
|
||||
|
||||
Reference in New Issue
Block a user