mirror of
https://github.com/shankar0123/certctl.git
synced 2026-06-07 16:51:31 +00:00
3287e174dc
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.
230 lines
6.6 KiB
Go
230 lines
6.6 KiB
Go
package handler
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"io"
|
|
"net/http"
|
|
"strconv"
|
|
"strings"
|
|
|
|
"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.
|
|
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 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.
|
|
type JobHandler struct {
|
|
svc JobService
|
|
}
|
|
|
|
// NewJobHandler creates a new JobHandler with a service dependency.
|
|
func NewJobHandler(svc JobService) JobHandler {
|
|
return JobHandler{svc: svc}
|
|
}
|
|
|
|
// ListJobs lists jobs with optional filtering by status and type.
|
|
// GET /api/v1/jobs?status=Pending&type=Renewal&page=1&per_page=50
|
|
func (h JobHandler) ListJobs(w http.ResponseWriter, r *http.Request) {
|
|
if r.Method != http.MethodGet {
|
|
Error(w, http.StatusMethodNotAllowed, "Method not allowed")
|
|
return
|
|
}
|
|
|
|
requestID := middleware.GetRequestID(r.Context())
|
|
|
|
query := r.URL.Query()
|
|
status := query.Get("status")
|
|
jobType := query.Get("type")
|
|
|
|
page := 1
|
|
perPage := 50
|
|
if p := query.Get("page"); p != "" {
|
|
if parsed, err := strconv.Atoi(p); err == nil && parsed > 0 {
|
|
page = parsed
|
|
}
|
|
}
|
|
if pp := query.Get("per_page"); pp != "" {
|
|
if parsed, err := strconv.Atoi(pp); err == nil && parsed > 0 && parsed <= 500 {
|
|
perPage = parsed
|
|
}
|
|
}
|
|
|
|
jobs, total, err := h.svc.ListJobs(r.Context(), status, jobType, page, perPage)
|
|
if err != nil {
|
|
ErrorWithRequestID(w, http.StatusInternalServerError, "Failed to list jobs", requestID)
|
|
return
|
|
}
|
|
|
|
response := PagedResponse{
|
|
Data: jobs,
|
|
Total: total,
|
|
Page: page,
|
|
PerPage: perPage,
|
|
}
|
|
|
|
JSON(w, http.StatusOK, response)
|
|
}
|
|
|
|
// GetJob retrieves a single job by ID.
|
|
// GET /api/v1/jobs/{id}
|
|
func (h JobHandler) GetJob(w http.ResponseWriter, r *http.Request) {
|
|
if r.Method != http.MethodGet {
|
|
Error(w, http.StatusMethodNotAllowed, "Method not allowed")
|
|
return
|
|
}
|
|
|
|
requestID := middleware.GetRequestID(r.Context())
|
|
|
|
id := strings.TrimPrefix(r.URL.Path, "/api/v1/jobs/")
|
|
parts := strings.Split(id, "/")
|
|
if len(parts) == 0 || parts[0] == "" {
|
|
ErrorWithRequestID(w, http.StatusBadRequest, "Job ID is required", requestID)
|
|
return
|
|
}
|
|
id = parts[0]
|
|
|
|
job, err := h.svc.GetJob(r.Context(), id)
|
|
if err != nil {
|
|
ErrorWithRequestID(w, http.StatusNotFound, "Job not found", requestID)
|
|
return
|
|
}
|
|
|
|
JSON(w, http.StatusOK, job)
|
|
}
|
|
|
|
// CancelJob cancels a job.
|
|
// POST /api/v1/jobs/{id}/cancel
|
|
func (h JobHandler) CancelJob(w http.ResponseWriter, r *http.Request) {
|
|
if r.Method != http.MethodPost {
|
|
Error(w, http.StatusMethodNotAllowed, "Method not allowed")
|
|
return
|
|
}
|
|
|
|
requestID := middleware.GetRequestID(r.Context())
|
|
|
|
// Extract job ID from path /api/v1/jobs/{id}/cancel
|
|
path := strings.TrimPrefix(r.URL.Path, "/api/v1/jobs/")
|
|
parts := strings.Split(path, "/")
|
|
if len(parts) < 2 || parts[0] == "" {
|
|
ErrorWithRequestID(w, http.StatusBadRequest, "Job ID is required", requestID)
|
|
return
|
|
}
|
|
jobID := parts[0]
|
|
|
|
if err := h.svc.CancelJob(r.Context(), jobID); err != nil {
|
|
ErrorWithRequestID(w, http.StatusInternalServerError, "Failed to cancel job", requestID)
|
|
return
|
|
}
|
|
|
|
response := map[string]string{
|
|
"status": "job_cancelled",
|
|
}
|
|
|
|
JSON(w, http.StatusOK, response)
|
|
}
|
|
|
|
// ApproveJob approves a renewal job awaiting approval.
|
|
// POST /api/v1/jobs/{id}/approve
|
|
func (h JobHandler) ApproveJob(w http.ResponseWriter, r *http.Request) {
|
|
if r.Method != http.MethodPost {
|
|
Error(w, http.StatusMethodNotAllowed, "Method not allowed")
|
|
return
|
|
}
|
|
|
|
requestID := middleware.GetRequestID(r.Context())
|
|
|
|
path := strings.TrimPrefix(r.URL.Path, "/api/v1/jobs/")
|
|
parts := strings.Split(path, "/")
|
|
if len(parts) < 2 || parts[0] == "" {
|
|
ErrorWithRequestID(w, http.StatusBadRequest, "Job ID is required", requestID)
|
|
return
|
|
}
|
|
jobID := parts[0]
|
|
|
|
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
|
|
}
|
|
if strings.Contains(err.Error(), "cannot approve") {
|
|
ErrorWithRequestID(w, http.StatusBadRequest, err.Error(), requestID)
|
|
return
|
|
}
|
|
ErrorWithRequestID(w, http.StatusInternalServerError, "Failed to approve job", requestID)
|
|
return
|
|
}
|
|
|
|
JSON(w, http.StatusOK, map[string]string{"status": "job_approved"})
|
|
}
|
|
|
|
// RejectJob rejects a renewal job awaiting approval.
|
|
// POST /api/v1/jobs/{id}/reject
|
|
func (h JobHandler) RejectJob(w http.ResponseWriter, r *http.Request) {
|
|
if r.Method != http.MethodPost {
|
|
Error(w, http.StatusMethodNotAllowed, "Method not allowed")
|
|
return
|
|
}
|
|
|
|
requestID := middleware.GetRequestID(r.Context())
|
|
|
|
path := strings.TrimPrefix(r.URL.Path, "/api/v1/jobs/")
|
|
parts := strings.Split(path, "/")
|
|
if len(parts) < 2 || parts[0] == "" {
|
|
ErrorWithRequestID(w, http.StatusBadRequest, "Job ID is required", requestID)
|
|
return
|
|
}
|
|
jobID := parts[0]
|
|
|
|
var body struct {
|
|
Reason string `json:"reason"`
|
|
}
|
|
if r.Body != nil && r.Body != http.NoBody {
|
|
if err := json.NewDecoder(r.Body).Decode(&body); err != nil && err != io.EOF {
|
|
ErrorWithRequestID(w, http.StatusBadRequest, "Invalid request body", requestID)
|
|
return
|
|
}
|
|
}
|
|
|
|
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
|
|
}
|
|
if strings.Contains(err.Error(), "cannot reject") {
|
|
ErrorWithRequestID(w, http.StatusBadRequest, err.Error(), requestID)
|
|
return
|
|
}
|
|
ErrorWithRequestID(w, http.StatusInternalServerError, "Failed to reject job", requestID)
|
|
return
|
|
}
|
|
|
|
JSON(w, http.StatusOK, map[string]string{"status": "job_rejected"})
|
|
}
|