acme-server: orders + authorizations + finalize + cert download (Phase 2/7)

Closes the issuance loop in trust_authenticated mode (commits ec88a61
+ 44a85d6 wired the foundation + JWS-verified account resource).
After this commit, an ACME client running against a profile with
acme_auth_mode='trust_authenticated' end-to-end-issues a real cert:

  POST /acme/profile/<id>/new-order      → 201 + order URL (status=ready)
  POST /acme/profile/<id>/order/<oid>    → POST-as-GET fetch
  POST /acme/profile/<id>/order/<oid>/finalize  → 200 + status=valid + cert URL
  POST /acme/profile/<id>/cert/<cid>     → 200 + PEM chain

Profiles with acme_auth_mode='challenge' get the same code path with
authz/challenge rows in `pending` state until Phase 3's validators
wire up. The mode is read from the bound profile's column at request
time, NOT cached at server start — operators flipping the column via
SQL take effect on the next order without restart.

Architecture (the load-bearing part):
  - Finalize routes through service.CertificateService.Create — the
    canonical certctl issuance entry point that wraps the
    managed_certificates row insert + audit row in s.tx.WithinTx.
    RenewalPolicy / CertificateProfile / per-issuer-type Prometheus
    metrics / audit rows all apply uniformly to ACME-issued certs via
    the same code path that already serves EST/SCEP/agent/REST issuance.
  - Identifier validation runs BEFORE order creation. Rejected
    identifiers return RFC 7807 with per-identifier subproblems and
    create no order row.
  - Source stamp on managed_certificates: domain.CertificateSourceACME.
    Operators bulk-revoke ACME-issued certs by filtering on Source=ACME.
  - 3-step atomicity boundary documented in code + this commit msg:
    (A) WithinTx-A marks order processing + audit row.
    (B) IssuerConnector.IssueCertificate + CertificateService.Create
        (each in its own WithinTx — Create wraps cert row + audit
        atomically).
    (C) WithinTx-C creates certificate_versions row + transitions order
        to valid + sets certificate_id + audit row.
    The brief window between B and C can leave a managed_certificates
    row whose order is still in `processing`. Phase 5's GC scheduler
    reconciles. Documented inline.

What ships:
  - internal/api/acme/order.go: OrderResponseJSON + AuthorizationResponseJSON
    + ChallengeResponseJSON + NewOrderRequest + FinalizeRequest wire
    shapes; ValidateIdentifiers (Phase 2 syntactic checks, dns-only);
    CSRMatchesIdentifiers (RFC 8555 §7.4 strict equality, case-folded).
  - internal/domain/acme.go: ACMEOrder + ACMEAuthorization + ACMEChallenge
    + ACMEIdentifier + ACMEProblem domain types + closed status enums
    for each (order: pending|ready|processing|valid|invalid; authz:
    pending|valid|invalid|deactivated|expired|revoked; challenge:
    pending|processing|valid|invalid; challenge type: http-01|dns-01|
    tls-alpn-01).
  - internal/domain/profile.go: new ACMEAuthMode field reading from
    certificate_profiles.acme_auth_mode (added in migration 25).
  - internal/domain/certificate.go: new CertificateSourceACME enum value.
  - internal/repository/postgres/profile.go: extended SELECT/scanProfile
    to read the per-profile acme_auth_mode column with a COALESCE
    default of trust_authenticated.
  - internal/repository/postgres/acme.go: full order/authz/challenge
    CRUD (CreateOrderWithTx + GetOrderByID + UpdateOrderWithTx +
    CreateAuthzWithTx + GetAuthzByID + ListAuthzsByOrder +
    ListChallengesByAuthz + CreateChallengeWithTx) with proper
    sql.NullTime + JSONB handling. scanACMEOrder /
    scanACMEAuthz / scanACMEChallenge helpers.
  - internal/service/acme.go: extended ACMERepo interface; new
    SetIssuancePipeline wires certificateService + certificateRepo +
    issuerRegistry. CreateOrder (auth-mode-dispatched: trust_authenticated
    auto-marks order ready + authz valid + 1 placeholder http-01
    challenge valid; challenge mode keeps everything pending). LookupOrder
    (with account-ownership assertion). LookupAuthz. ListAuthzsByOrder.
    FinalizeOrder (3-step atomicity boundary as above; CSR-vs-order
    SAN strict-equality check before issuance; persists FinalizeOrderResult
    {Order, CertID}). LookupCertificate. randIDSuffix + base32encode
    helpers for the human-readable acme-ord-* / acme-authz-* /
    acme-chall-* prefixes (CLAUDE.md "TEXT primary keys with human-
    readable prefixes" architecture decision). 8 new per-op metrics.
  - internal/service/acme_test.go: extended fakeACMERepo with Phase 2
    interface stubs; new orderTrackingRepo for observable persistence;
    2 new tests asserting trust_authenticated → auto-ready/valid and
    challenge → stays-pending.
  - internal/api/handler/acme.go: NewOrder + Order + OrderFinalize +
    Authz + Cert handler methods. orderURL / authzURL / certURL /
    challengeURLBuilder helpers; marshalOrderForResponse fetches
    per-order authzs to populate the URL list. parseOptionalTime for
    notBefore / notAfter.
  - internal/api/handler/acme_handler_test.go: extended mockACMEService
    with Phase 2 method stubs; 4 new handler tests (NewOrder happy +
    rejected-identifier + OrderFinalize bad-CSR + Cert happy).
  - internal/api/router/router.go: 10 new Register calls (5 per-profile
    + 5 shorthand) for new-order, order/{ord_id}, order/{ord_id}/finalize,
    authz/{authz_id}, cert/{cert_id}.
  - internal/api/router/openapi_parity_test.go + api/openapi-handler-exceptions.yaml:
    10 new exception entries.
  - cmd/server/main.go: SetIssuancePipeline at startup, threading
    certificateService + certificateRepo + issuerRegistry into ACMEService.
  - docs/acme-server.md: phase status updated; endpoints table grows
    5 rows for new-order/order/finalize/authz/cert (per-profile +
    shorthand variants); new section "Finalize routing through
    CertificateService.Create" documenting the 3-step atomicity
    boundary + the actor-string convention `acme:<account-id>`.

Tests: ACME package + service + handler + router + config + domain
all green under -short. New cases:
  - TestCreateOrder_TrustAuthenticated_AutoReady (asserts auto-ready
    transition + valid-status authz/challenge + audit row + metric bump).
  - TestCreateOrder_ChallengeMode_StaysPending (asserts pending-status
    cascading authz/challenge for challenge mode).
  - TestACMEHandler_NewOrder_HappyPath (asserts 201 + Location +
    finalize URL shape).
  - TestACMEHandler_NewOrder_RejectedIdentifier (asserts 400 + RFC 7807
    rejectedIdentifier + per-identifier subproblems for type=ip).
  - TestACMEHandler_OrderFinalize_BadCSR (asserts 400 + badCSR for
    non-base64 CSR field).
  - TestACMEHandler_Cert_HappyPath (asserts 200 + PEM content-type +
    PEM chain in body).

Engineering history: cowork/WORKSPACE-CHANGELOG.md "ACME-Server-2".
This commit is contained in:
shankar0123
2026-05-03 13:46:10 +00:00
parent a05a7d3dad
commit c351bba41a
15 changed files with 2179 additions and 28 deletions
+252
View File
@@ -0,0 +1,252 @@
// Copyright (c) certctl
// SPDX-License-Identifier: BSL-1.1
package acme
import (
"crypto/x509"
"errors"
"fmt"
"strings"
"time"
"github.com/shankar0123/certctl/internal/domain"
)
// OrderResponseJSON is the wire shape RFC 8555 §7.1.3 mandates for the
// new-order response + the per-order POST-as-GET response.
//
// Each URL field is the per-profile path the handler computes from the
// inbound request; service-layer code does not see *http.Request, so
// the handler does the URL composition.
type OrderResponseJSON struct {
Status string `json:"status"`
Expires string `json:"expires,omitempty"`
NotBefore string `json:"notBefore,omitempty"`
NotAfter string `json:"notAfter,omitempty"`
Identifiers []IdentifierJSON `json:"identifiers"`
Authorizations []string `json:"authorizations"`
Finalize string `json:"finalize"`
Certificate string `json:"certificate,omitempty"`
Error *Problem `json:"error,omitempty"`
}
// IdentifierJSON is the wire shape for an identifier (RFC 8555 §9.7.7).
// Wire field names differ from the domain struct's JSON tags only on
// case, so we keep separate types to keep the protocol surface clean.
type IdentifierJSON struct {
Type string `json:"type"`
Value string `json:"value"`
}
// MarshalOrder renders an ACMEOrder in RFC 8555 §7.1.3 wire shape.
//
// authzURLs / finalizeURL / certURL are computed by the handler from
// the inbound request (scheme + host + per-profile path). Phase 2:
// authzURLs has one entry per identifier; finalizeURL is the order's
// finalize endpoint; certURL is populated only when status=valid.
func MarshalOrder(order *domain.ACMEOrder, authzURLs []string, finalizeURL, certURL string) OrderResponseJSON {
out := OrderResponseJSON{
Status: string(order.Status),
Expires: order.ExpiresAt.UTC().Format(time.RFC3339),
Identifiers: make([]IdentifierJSON, 0, len(order.Identifiers)),
Authorizations: authzURLs,
Finalize: finalizeURL,
}
if order.NotBefore != nil {
out.NotBefore = order.NotBefore.UTC().Format(time.RFC3339)
}
if order.NotAfter != nil {
out.NotAfter = order.NotAfter.UTC().Format(time.RFC3339)
}
for _, id := range order.Identifiers {
out.Identifiers = append(out.Identifiers, IdentifierJSON{Type: id.Type, Value: id.Value})
}
if certURL != "" && order.Status == domain.ACMEOrderStatusValid {
out.Certificate = certURL
}
if order.Error != nil {
out.Error = &Problem{
Type: order.Error.Type,
Detail: order.Error.Detail,
Status: order.Error.Status,
}
}
return out
}
// NewOrderRequest is the payload shape RFC 8555 §7.4 mandates for a
// new-order POST. The handler json.Unmarshals VerifiedRequest.Payload
// into this struct after JWS verify succeeds.
type NewOrderRequest struct {
Identifiers []IdentifierJSON `json:"identifiers"`
NotBefore string `json:"notBefore,omitempty"`
NotAfter string `json:"notAfter,omitempty"`
}
// FinalizeRequest is the payload shape RFC 8555 §7.4 mandates for the
// finalize POST. csr is the base64url-encoded DER of a PKCS#10 CSR.
type FinalizeRequest struct {
CSR string `json:"csr"`
}
// AuthorizationResponseJSON is the wire shape RFC 8555 §7.1.4 mandates
// for the authz GET (POST-as-GET) response.
type AuthorizationResponseJSON struct {
Identifier IdentifierJSON `json:"identifier"`
Status string `json:"status"`
Expires string `json:"expires,omitempty"`
Wildcard bool `json:"wildcard,omitempty"`
Challenges []ChallengeResponseJSON `json:"challenges"`
}
// ChallengeResponseJSON is the wire shape RFC 8555 §8 mandates for a
// challenge object (embedded in authz, or returned by POST to a
// challenge URL).
type ChallengeResponseJSON struct {
Type string `json:"type"`
URL string `json:"url"`
Status string `json:"status"`
Token string `json:"token"`
Validated string `json:"validated,omitempty"`
Error *Problem `json:"error,omitempty"`
}
// MarshalAuthorization renders an ACMEAuthorization in RFC 8555 wire shape.
// challengeURLBuilder maps each challenge ID to its per-profile URL
// (handler-computed); identifiers stay as-is.
func MarshalAuthorization(authz *domain.ACMEAuthorization, challengeURLBuilder func(challengeID string) string) AuthorizationResponseJSON {
out := AuthorizationResponseJSON{
Identifier: IdentifierJSON{Type: authz.Identifier.Type, Value: authz.Identifier.Value},
Status: string(authz.Status),
Expires: authz.ExpiresAt.UTC().Format(time.RFC3339),
Wildcard: authz.Wildcard,
Challenges: make([]ChallengeResponseJSON, 0, len(authz.Challenges)),
}
for i := range authz.Challenges {
ch := &authz.Challenges[i]
j := ChallengeResponseJSON{
Type: string(ch.Type),
URL: challengeURLBuilder(ch.ChallengeID),
Status: string(ch.Status),
Token: ch.Token,
}
if ch.ValidatedAt != nil {
j.Validated = ch.ValidatedAt.UTC().Format(time.RFC3339)
}
if ch.Error != nil {
j.Error = &Problem{Type: ch.Error.Type, Detail: ch.Error.Detail, Status: ch.Error.Status}
}
out.Challenges = append(out.Challenges, j)
}
return out
}
// ErrIdentifierTypeUnsupported is returned when ValidateIdentifiers
// encounters a non-DNS identifier type. RFC 8555 §9.7.7 reserves
// `type` for future expansion; Phase 2 supports `dns` only.
var ErrIdentifierTypeUnsupported = errors.New("acme: identifier type not supported (Phase 2: dns only)")
// ErrIdentifierEmpty is returned for an identifier with an empty
// value; the spec requires non-empty strings.
var ErrIdentifierEmpty = errors.New("acme: identifier value is empty")
// ValidateIdentifiers checks the structural invariants RFC 8555 §7.4
// requires (non-empty value, supported type) and returns per-identifier
// rejected entries on failure. Per-profile-policy rejection (SAN
// allowlist, lifetime cap) is the service layer's job; this function
// is the syntactic check only.
//
// Returns nil + nil ids on full acceptance. On rejection, returns the
// list of rejected identifiers with their reason as RFC 8555 §6.7
// subproblems (rejectedIdentifier).
func ValidateIdentifiers(ids []IdentifierJSON) []Problem {
if len(ids) == 0 {
return []Problem{Malformed("new-order requires at least one identifier")}
}
var problems []Problem
for _, id := range ids {
switch strings.ToLower(id.Type) {
case "dns":
if id.Value == "" {
problems = append(problems, Problem{
Type: "urn:ietf:params:acme:error:rejectedIdentifier",
Detail: "identifier value is empty",
Status: 400,
Identifier: &Identifier{Type: id.Type, Value: id.Value},
})
}
default:
problems = append(problems, Problem{
Type: "urn:ietf:params:acme:error:rejectedIdentifier",
Detail: fmt.Sprintf("identifier type %q is not supported (Phase 2: dns only)", id.Type),
Status: 400,
Identifier: &Identifier{Type: id.Type, Value: id.Value},
})
}
}
return problems
}
// CSRMatchesIdentifiers asserts the CSR's DNS-name set (Subject CN +
// Subject Alternative Names) equals the order's identifier set,
// case-folded for DNS comparison.
//
// RFC 8555 §7.4 finalize: "The CSR MUST indicate the exact same set of
// requested identifiers as the initial newOrder request." Case-fold
// the comparison so a CSR with `Example.com` matches an order with
// `example.com` (DNS is case-insensitive per RFC 1035 §2.3.3).
//
// Returns nil on match. On mismatch, returns a Problem typed as
// urn:ietf:params:acme:error:badCSR.
func CSRMatchesIdentifiers(csr *x509.CertificateRequest, identifiers []domain.ACMEIdentifier) *Problem {
csrSet := make(map[string]struct{})
if csr.Subject.CommonName != "" {
csrSet[strings.ToLower(csr.Subject.CommonName)] = struct{}{}
}
for _, dns := range csr.DNSNames {
csrSet[strings.ToLower(dns)] = struct{}{}
}
orderSet := make(map[string]struct{})
for _, id := range identifiers {
if id.Type != "dns" {
continue
}
orderSet[strings.ToLower(id.Value)] = struct{}{}
}
if len(csrSet) != len(orderSet) {
p := Problem{
Type: "urn:ietf:params:acme:error:badCSR",
Detail: fmt.Sprintf("CSR identifier count (%d) differs from order identifier count (%d)", len(csrSet), len(orderSet)),
Status: 400,
}
return &p
}
for k := range orderSet {
if _, ok := csrSet[k]; !ok {
p := Problem{
Type: "urn:ietf:params:acme:error:badCSR",
Detail: fmt.Sprintf("CSR is missing the order identifier %q", k),
Status: 400,
}
return &p
}
}
return nil
}
// HasWildcard returns true when any identifier is a wildcard. RFC 8555
// §7.1.3 marks the order's authz wildcard:true when the corresponding
// identifier starts with "*."; Phase 2 supports the trust_authenticated
// path (which auto-marks authz valid), so wildcard-aware challenge
// dispatch is Phase 3's concern.
func HasWildcard(ids []domain.ACMEIdentifier) bool {
for _, id := range ids {
if strings.HasPrefix(id.Value, "*.") {
return true
}
}
return false
}
+383
View File
@@ -5,10 +5,14 @@ package handler
import (
"context"
"crypto/x509"
"encoding/base64"
"encoding/json"
"encoding/pem"
"errors"
"io"
"net/http"
"time"
jose "github.com/go-jose/go-jose/v4"
@@ -38,6 +42,13 @@ type ACMEService interface {
LookupAccount(ctx context.Context, accountID string) (*domain.ACMEAccount, error)
UpdateAccount(ctx context.Context, accountID string, contact []string) (*domain.ACMEAccount, error)
DeactivateAccount(ctx context.Context, accountID string) (*domain.ACMEAccount, error)
// Phase 2 — orders + finalize + authz + cert download.
CreateOrder(ctx context.Context, accountID, profileID string, identifiers []domain.ACMEIdentifier, notBefore, notAfter *time.Time) (*domain.ACMEOrder, error)
LookupOrder(ctx context.Context, orderID, accountID string) (*domain.ACMEOrder, error)
LookupAuthz(ctx context.Context, authzID string) (*domain.ACMEAuthorization, error)
ListAuthzsByOrder(ctx context.Context, orderID string) ([]*domain.ACMEAuthorization, error)
FinalizeOrder(ctx context.Context, accountID, orderID, profileID string, csr *x509.CertificateRequest, csrPEM string) (*service.FinalizeOrderResult, error)
LookupCertificate(ctx context.Context, certID, accountID string) (string, error)
}
// ACMEHandler exposes the ACME server's RFC 8555 endpoints under the
@@ -182,6 +193,26 @@ func writeServiceError(w http.ResponseWriter, err error) {
case errors.Is(err, service.ErrACMEAccountDoesNotExist):
acme.WriteProblem(w, acme.AccountDoesNotExist(
"no account exists for this JWK; submit a new-account request without onlyReturnExisting"))
case errors.Is(err, service.ErrACMEOrderNotFound), errors.Is(err, service.ErrACMEAuthzNotFound), errors.Is(err, service.ErrACMECertificateNotFound):
acme.WriteProblem(w, acme.Problem{
Type: "urn:ietf:params:acme:error:malformed",
Detail: "resource not found",
Status: http.StatusNotFound,
})
case errors.Is(err, service.ErrACMEOrderUnauthorized):
acme.WriteProblem(w, acme.Problem{
Type: "urn:ietf:params:acme:error:unauthorized",
Detail: "account does not own this resource",
Status: http.StatusUnauthorized,
})
case errors.Is(err, service.ErrACMEOrderNotReady):
acme.WriteProblem(w, acme.Problem{
Type: "urn:ietf:params:acme:error:orderNotReady",
Detail: "order is not in the `ready` state; complete authorizations first",
Status: http.StatusForbidden,
})
case errors.Is(err, service.ErrACMEUnsupportedAuthMode), errors.Is(err, service.ErrACMEFinalizeUnconfigured):
acme.WriteProblem(w, acme.ServerInternal("ACME server is not fully configured; contact the operator"))
default:
// Avoid leaking internal error text per master-prompt
// criterion #10 (operator-actionable errors with no info
@@ -410,3 +441,355 @@ func trimBody(b []byte) []byte {
}
return b
}
// --- Phase 2 — orders + finalize + authz + cert handlers ---------------
// NewOrder handles POST /acme/profile/{id}/new-order (RFC 8555 §7.4).
// JWS path: kid (registered account).
func (h ACMEHandler) NewOrder(w http.ResponseWriter, r *http.Request) {
profileID := r.PathValue("id")
requestURL := h.requestURL(r)
body, err := io.ReadAll(io.LimitReader(r.Body, MaxJWSBodyBytes+1))
if err != nil {
acme.WriteProblem(w, acme.Malformed("could not read request body"))
return
}
if len(body) > MaxJWSBodyBytes {
acme.WriteProblem(w, acme.Malformed("request body too large"))
return
}
verified, err := h.svc.VerifyJWS(r.Context(), body, requestURL, false /*expectNewAccount*/, h.accountKID(r, profileID))
if err != nil {
acme.WriteProblem(w, acme.MapJWSErrorToProblem(err))
return
}
if verified.Account == nil {
acme.WriteProblem(w, acme.MapJWSErrorToProblem(acme.ErrJWSAccountNotFound))
return
}
var req acme.NewOrderRequest
if err := json.Unmarshal(verified.Payload, &req); err != nil {
acme.WriteProblem(w, acme.Malformed("could not parse new-order payload"))
return
}
// Identifier validation runs BEFORE order creation. Rejected
// identifiers do NOT create an acme_orders row.
if probs := acme.ValidateIdentifiers(req.Identifiers); len(probs) > 0 {
// Multi-rejection → wrap in subproblems.
w.Header().Set("Content-Type", acme.ProblemContentType)
w.WriteHeader(http.StatusBadRequest)
_ = json.NewEncoder(w).Encode(acme.Problem{
Type: "urn:ietf:params:acme:error:rejectedIdentifier",
Detail: "one or more identifiers were rejected",
Status: http.StatusBadRequest,
Subproblems: probs,
})
return
}
// Translate wire shape to domain shape.
domainIDs := make([]domain.ACMEIdentifier, 0, len(req.Identifiers))
for _, id := range req.Identifiers {
domainIDs = append(domainIDs, domain.ACMEIdentifier{Type: id.Type, Value: id.Value})
}
notBefore := parseOptionalTime(req.NotBefore)
notAfter := parseOptionalTime(req.NotAfter)
order, err := h.svc.CreateOrder(r.Context(), verified.Account.AccountID, profileID, domainIDs, notBefore, notAfter)
if err != nil {
writeServiceError(w, err)
return
}
if nonce, err := h.svc.IssueNonce(r.Context()); err == nil {
w.Header().Set("Replay-Nonce", nonce)
}
w.Header().Set("Location", h.orderURL(r, profileID, order.OrderID))
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
_ = json.NewEncoder(w).Encode(h.marshalOrderForResponse(r, profileID, order))
}
// Order handles POST /acme/profile/{id}/order/{ord_id} (RFC 8555 §7.4
// POST-as-GET — empty payload returns the current order state).
func (h ACMEHandler) Order(w http.ResponseWriter, r *http.Request) {
profileID := r.PathValue("id")
orderID := r.PathValue("ord_id")
requestURL := h.requestURL(r)
body, err := io.ReadAll(io.LimitReader(r.Body, MaxJWSBodyBytes+1))
if err != nil {
acme.WriteProblem(w, acme.Malformed("could not read request body"))
return
}
if len(body) > MaxJWSBodyBytes {
acme.WriteProblem(w, acme.Malformed("request body too large"))
return
}
verified, err := h.svc.VerifyJWS(r.Context(), body, requestURL, false, h.accountKID(r, profileID))
if err != nil {
acme.WriteProblem(w, acme.MapJWSErrorToProblem(err))
return
}
if verified.Account == nil {
acme.WriteProblem(w, acme.MapJWSErrorToProblem(acme.ErrJWSAccountNotFound))
return
}
order, err := h.svc.LookupOrder(r.Context(), orderID, verified.Account.AccountID)
if err != nil {
writeServiceError(w, err)
return
}
if nonce, err := h.svc.IssueNonce(r.Context()); err == nil {
w.Header().Set("Replay-Nonce", nonce)
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
_ = json.NewEncoder(w).Encode(h.marshalOrderForResponse(r, profileID, order))
}
// OrderFinalize handles POST /acme/profile/{id}/order/{ord_id}/finalize
// (RFC 8555 §7.4). Payload carries the base64url-DER CSR.
func (h ACMEHandler) OrderFinalize(w http.ResponseWriter, r *http.Request) {
profileID := r.PathValue("id")
orderID := r.PathValue("ord_id")
requestURL := h.requestURL(r)
body, err := io.ReadAll(io.LimitReader(r.Body, MaxJWSBodyBytes+1))
if err != nil {
acme.WriteProblem(w, acme.Malformed("could not read request body"))
return
}
if len(body) > MaxJWSBodyBytes {
acme.WriteProblem(w, acme.Malformed("request body too large"))
return
}
verified, err := h.svc.VerifyJWS(r.Context(), body, requestURL, false, h.accountKID(r, profileID))
if err != nil {
acme.WriteProblem(w, acme.MapJWSErrorToProblem(err))
return
}
if verified.Account == nil {
acme.WriteProblem(w, acme.MapJWSErrorToProblem(acme.ErrJWSAccountNotFound))
return
}
var req acme.FinalizeRequest
if err := json.Unmarshal(verified.Payload, &req); err != nil {
acme.WriteProblem(w, acme.Malformed("could not parse finalize payload"))
return
}
csrDER, err := base64.RawURLEncoding.DecodeString(req.CSR)
if err != nil {
acme.WriteProblem(w, acme.Problem{
Type: "urn:ietf:params:acme:error:badCSR",
Detail: "csr field is not valid base64url",
Status: http.StatusBadRequest,
})
return
}
csr, err := x509.ParseCertificateRequest(csrDER)
if err != nil {
acme.WriteProblem(w, acme.Problem{
Type: "urn:ietf:params:acme:error:badCSR",
Detail: "csr did not parse as a valid PKCS#10",
Status: http.StatusBadRequest,
})
return
}
csrPEM := string(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE REQUEST", Bytes: csrDER}))
result, err := h.svc.FinalizeOrder(r.Context(), verified.Account.AccountID, orderID, profileID, csr, csrPEM)
if err != nil {
writeServiceError(w, err)
return
}
if nonce, err := h.svc.IssueNonce(r.Context()); err == nil {
w.Header().Set("Replay-Nonce", nonce)
}
w.Header().Set("Location", h.orderURL(r, profileID, result.Order.OrderID))
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
_ = json.NewEncoder(w).Encode(h.marshalOrderForResponse(r, profileID, result.Order))
}
// Authz handles POST /acme/profile/{id}/authz/{authz_id} (RFC 8555
// §7.5 POST-as-GET).
func (h ACMEHandler) Authz(w http.ResponseWriter, r *http.Request) {
profileID := r.PathValue("id")
authzID := r.PathValue("authz_id")
requestURL := h.requestURL(r)
body, err := io.ReadAll(io.LimitReader(r.Body, MaxJWSBodyBytes+1))
if err != nil {
acme.WriteProblem(w, acme.Malformed("could not read request body"))
return
}
if len(body) > MaxJWSBodyBytes {
acme.WriteProblem(w, acme.Malformed("request body too large"))
return
}
verified, err := h.svc.VerifyJWS(r.Context(), body, requestURL, false, h.accountKID(r, profileID))
if err != nil {
acme.WriteProblem(w, acme.MapJWSErrorToProblem(err))
return
}
if verified.Account == nil {
acme.WriteProblem(w, acme.MapJWSErrorToProblem(acme.ErrJWSAccountNotFound))
return
}
authz, err := h.svc.LookupAuthz(r.Context(), authzID)
if err != nil {
writeServiceError(w, err)
return
}
if nonce, err := h.svc.IssueNonce(r.Context()); err == nil {
w.Header().Set("Replay-Nonce", nonce)
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
_ = json.NewEncoder(w).Encode(acme.MarshalAuthorization(authz, h.challengeURLBuilder(r, profileID)))
}
// Cert handles POST /acme/profile/{id}/cert/{cert_id} (RFC 8555 §7.4.2
// POST-as-GET cert download). Returns the PEM chain.
func (h ACMEHandler) Cert(w http.ResponseWriter, r *http.Request) {
profileID := r.PathValue("id")
certID := r.PathValue("cert_id")
requestURL := h.requestURL(r)
body, err := io.ReadAll(io.LimitReader(r.Body, MaxJWSBodyBytes+1))
if err != nil {
acme.WriteProblem(w, acme.Malformed("could not read request body"))
return
}
if len(body) > MaxJWSBodyBytes {
acme.WriteProblem(w, acme.Malformed("request body too large"))
return
}
verified, err := h.svc.VerifyJWS(r.Context(), body, requestURL, false, h.accountKID(r, profileID))
if err != nil {
acme.WriteProblem(w, acme.MapJWSErrorToProblem(err))
return
}
if verified.Account == nil {
acme.WriteProblem(w, acme.MapJWSErrorToProblem(acme.ErrJWSAccountNotFound))
return
}
pemChain, err := h.svc.LookupCertificate(r.Context(), certID, verified.Account.AccountID)
if err != nil {
writeServiceError(w, err)
return
}
if nonce, err := h.svc.IssueNonce(r.Context()); err == nil {
w.Header().Set("Replay-Nonce", nonce)
}
w.Header().Set("Content-Type", "application/pem-certificate-chain")
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(pemChain))
}
// orderURL composes the per-order URL for Location headers and the
// finalize URL embedded in the order JSON.
func (h ACMEHandler) orderURL(r *http.Request, profileID, orderID string) string {
scheme := "https"
if r.TLS == nil {
scheme = "http"
}
prefix := scheme + "://" + r.Host
if profileID != "" {
prefix += "/acme/profile/" + profileID
} else {
prefix += "/acme"
}
return prefix + "/order/" + orderID
}
func (h ACMEHandler) authzURL(r *http.Request, profileID, authzID string) string {
scheme := "https"
if r.TLS == nil {
scheme = "http"
}
prefix := scheme + "://" + r.Host
if profileID != "" {
prefix += "/acme/profile/" + profileID
} else {
prefix += "/acme"
}
return prefix + "/authz/" + authzID
}
func (h ACMEHandler) certURL(r *http.Request, profileID, certID string) string {
scheme := "https"
if r.TLS == nil {
scheme = "http"
}
prefix := scheme + "://" + r.Host
if profileID != "" {
prefix += "/acme/profile/" + profileID
} else {
prefix += "/acme"
}
return prefix + "/cert/" + certID
}
// challengeURLBuilder returns a closure for MarshalAuthorization to
// compute per-challenge URLs.
func (h ACMEHandler) challengeURLBuilder(r *http.Request, profileID string) func(challengeID string) string {
scheme := "https"
if r.TLS == nil {
scheme = "http"
}
prefix := scheme + "://" + r.Host
if profileID != "" {
prefix += "/acme/profile/" + profileID
} else {
prefix += "/acme"
}
return func(challengeID string) string { return prefix + "/challenge/" + challengeID }
}
// marshalOrderForResponse builds the OrderResponseJSON for an order,
// fetching the per-order authzs to populate the URL list. The cert URL
// is populated only when status=valid + certificate_id is set.
func (h ACMEHandler) marshalOrderForResponse(r *http.Request, profileID string, order *domain.ACMEOrder) acme.OrderResponseJSON {
authzs, _ := h.svc.ListAuthzsByOrder(r.Context(), order.OrderID)
authzURLs := make([]string, 0, len(authzs))
for _, a := range authzs {
authzURLs = append(authzURLs, h.authzURL(r, profileID, a.AuthzID))
}
finalize := h.orderURL(r, profileID, order.OrderID) + "/finalize"
certURL := ""
if order.CertificateID != "" {
certURL = h.certURL(r, profileID, order.CertificateID)
}
return acme.MarshalOrder(order, authzURLs, finalize, certURL)
}
// parseOptionalTime parses an RFC 3339 string; returns nil on empty or
// parse failure (the latter is best-effort — the spec leaves notBefore
// / notAfter as advisory).
func parseOptionalTime(s string) *time.Time {
if s == "" {
return nil
}
t, err := time.Parse(time.RFC3339, s)
if err != nil {
return nil
}
return &t
}
+201
View File
@@ -6,12 +6,14 @@ package handler
import (
"bytes"
"context"
"crypto/x509"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
jose "github.com/go-jose/go-jose/v4"
@@ -31,6 +33,13 @@ type mockACMEService struct {
LookupAccountFn func(ctx context.Context, accountID string) (*domain.ACMEAccount, error)
UpdateAccountFn func(ctx context.Context, accountID string, contact []string) (*domain.ACMEAccount, error)
DeactivateAccountFn func(ctx context.Context, accountID string) (*domain.ACMEAccount, error)
// Phase 2.
CreateOrderFn func(ctx context.Context, accountID, profileID string, identifiers []domain.ACMEIdentifier, notBefore, notAfter *time.Time) (*domain.ACMEOrder, error)
LookupOrderFn func(ctx context.Context, orderID, accountID string) (*domain.ACMEOrder, error)
LookupAuthzFn func(ctx context.Context, authzID string) (*domain.ACMEAuthorization, error)
ListAuthzsByOrderFn func(ctx context.Context, orderID string) ([]*domain.ACMEAuthorization, error)
FinalizeOrderFn func(ctx context.Context, accountID, orderID, profileID string, csr *x509.CertificateRequest, csrPEM string) (*service.FinalizeOrderResult, error)
LookupCertificateFn func(ctx context.Context, certID, accountID string) (string, error)
}
func (m *mockACMEService) BuildDirectory(ctx context.Context, profileID, baseURL string) (*acme.Directory, error) {
@@ -82,6 +91,48 @@ func (m *mockACMEService) DeactivateAccount(ctx context.Context, accountID strin
return nil, errors.New("DeactivateAccount not stubbed")
}
func (m *mockACMEService) CreateOrder(ctx context.Context, accountID, profileID string, identifiers []domain.ACMEIdentifier, notBefore, notAfter *time.Time) (*domain.ACMEOrder, error) {
if m.CreateOrderFn != nil {
return m.CreateOrderFn(ctx, accountID, profileID, identifiers, notBefore, notAfter)
}
return nil, errors.New("CreateOrder not stubbed")
}
func (m *mockACMEService) LookupOrder(ctx context.Context, orderID, accountID string) (*domain.ACMEOrder, error) {
if m.LookupOrderFn != nil {
return m.LookupOrderFn(ctx, orderID, accountID)
}
return nil, errors.New("LookupOrder not stubbed")
}
func (m *mockACMEService) LookupAuthz(ctx context.Context, authzID string) (*domain.ACMEAuthorization, error) {
if m.LookupAuthzFn != nil {
return m.LookupAuthzFn(ctx, authzID)
}
return nil, errors.New("LookupAuthz not stubbed")
}
func (m *mockACMEService) ListAuthzsByOrder(ctx context.Context, orderID string) ([]*domain.ACMEAuthorization, error) {
if m.ListAuthzsByOrderFn != nil {
return m.ListAuthzsByOrderFn(ctx, orderID)
}
return nil, nil
}
func (m *mockACMEService) FinalizeOrder(ctx context.Context, accountID, orderID, profileID string, csr *x509.CertificateRequest, csrPEM string) (*service.FinalizeOrderResult, error) {
if m.FinalizeOrderFn != nil {
return m.FinalizeOrderFn(ctx, accountID, orderID, profileID, csr, csrPEM)
}
return nil, errors.New("FinalizeOrder not stubbed")
}
func (m *mockACMEService) LookupCertificate(ctx context.Context, certID, accountID string) (string, error) {
if m.LookupCertificateFn != nil {
return m.LookupCertificateFn(ctx, certID, accountID)
}
return "", errors.New("LookupCertificate not stubbed")
}
// newACMETestServer wires the ACMEHandler against the mock + a stdlib
// ServeMux configured exactly the way internal/api/router/router.go
// does it in production. Routes:
@@ -101,6 +152,11 @@ func newACMETestServer(t *testing.T, mock *mockACMEService) *httptest.Server {
mux.HandleFunc("GET /acme/profile/{id}/new-nonce", h.NewNonce)
mux.HandleFunc("POST /acme/profile/{id}/new-account", h.NewAccount)
mux.HandleFunc("POST /acme/profile/{id}/account/{acc_id}", h.Account)
mux.HandleFunc("POST /acme/profile/{id}/new-order", h.NewOrder)
mux.HandleFunc("POST /acme/profile/{id}/order/{ord_id}", h.Order)
mux.HandleFunc("POST /acme/profile/{id}/order/{ord_id}/finalize", h.OrderFinalize)
mux.HandleFunc("POST /acme/profile/{id}/authz/{authz_id}", h.Authz)
mux.HandleFunc("POST /acme/profile/{id}/cert/{cert_id}", h.Cert)
mux.HandleFunc("GET /acme/directory", h.Directory)
mux.HandleFunc("HEAD /acme/new-nonce", h.NewNonce)
mux.HandleFunc("GET /acme/new-nonce", h.NewNonce)
@@ -539,3 +595,148 @@ func TestACMEHandler_Account_PostAsGet(t *testing.T) {
t.Errorf("status = %d, want 200 (POST-as-GET)", resp.StatusCode)
}
}
// --- Phase 2 — orders + finalize handler smoke -------------------------
func TestACMEHandler_NewOrder_HappyPath(t *testing.T) {
mock := &mockACMEService{
VerifyJWSFn: stubVerifiedReq(
acme.NewOrderRequest{Identifiers: []acme.IdentifierJSON{{Type: "dns", Value: "example.com"}}},
&domain.ACMEAccount{AccountID: "acme-acc-X", Status: domain.ACMEAccountStatusValid, ProfileID: "prof-corp"},
nil,
),
CreateOrderFn: func(ctx context.Context, accountID, profileID string, identifiers []domain.ACMEIdentifier, notBefore, notAfter *time.Time) (*domain.ACMEOrder, error) {
return &domain.ACMEOrder{
OrderID: "acme-ord-001",
AccountID: accountID,
Identifiers: identifiers,
Status: domain.ACMEOrderStatusReady,
ExpiresAt: time.Now().Add(24 * time.Hour),
}, nil
},
ListAuthzsByOrderFn: func(ctx context.Context, orderID string) ([]*domain.ACMEAuthorization, error) {
return []*domain.ACMEAuthorization{
{AuthzID: "acme-authz-001", OrderID: orderID, Status: domain.ACMEAuthzStatusValid},
}, nil
},
}
srv := newACMETestServer(t, mock)
defer srv.Close()
resp, err := http.Post(srv.URL+"/acme/profile/prof-corp/new-order", "application/jose+json", bytes.NewReader([]byte("ignored-by-mock")))
if err != nil {
t.Fatalf("Post: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusCreated {
t.Errorf("status = %d, want 201", resp.StatusCode)
}
if got := resp.Header.Get("Location"); !strings.Contains(got, "/order/acme-ord-001") {
t.Errorf("Location = %q", got)
}
var body acme.OrderResponseJSON
if err := json.NewDecoder(resp.Body).Decode(&body); err != nil {
t.Fatalf("Decode: %v", err)
}
if body.Status != "ready" {
t.Errorf("status = %q (trust_authenticated should auto-ready)", body.Status)
}
if len(body.Authorizations) != 1 || !strings.Contains(body.Authorizations[0], "/authz/acme-authz-001") {
t.Errorf("authorizations = %v", body.Authorizations)
}
if !strings.HasSuffix(body.Finalize, "/order/acme-ord-001/finalize") {
t.Errorf("finalize = %q", body.Finalize)
}
}
func TestACMEHandler_NewOrder_RejectedIdentifier(t *testing.T) {
mock := &mockACMEService{
VerifyJWSFn: stubVerifiedReq(
acme.NewOrderRequest{Identifiers: []acme.IdentifierJSON{{Type: "ip", Value: "10.0.0.1"}}},
&domain.ACMEAccount{AccountID: "acme-acc-X", Status: domain.ACMEAccountStatusValid, ProfileID: "prof-corp"},
nil,
),
}
srv := newACMETestServer(t, mock)
defer srv.Close()
resp, err := http.Post(srv.URL+"/acme/profile/prof-corp/new-order", "application/jose+json", bytes.NewReader([]byte("x")))
if err != nil {
t.Fatalf("Post: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusBadRequest {
t.Errorf("status = %d, want 400 (rejected identifier)", resp.StatusCode)
}
var p acme.Problem
_ = json.NewDecoder(resp.Body).Decode(&p)
if p.Type != "urn:ietf:params:acme:error:rejectedIdentifier" {
t.Errorf("Problem.Type = %q", p.Type)
}
if len(p.Subproblems) == 0 {
t.Error("expected subproblems for per-identifier rejection")
}
}
func TestACMEHandler_OrderFinalize_BadCSR(t *testing.T) {
mock := &mockACMEService{
VerifyJWSFn: stubVerifiedReq(
acme.FinalizeRequest{CSR: "not-base64!!!"},
&domain.ACMEAccount{AccountID: "acme-acc-X", Status: domain.ACMEAccountStatusValid, ProfileID: "prof-corp"},
nil,
),
}
srv := newACMETestServer(t, mock)
defer srv.Close()
resp, err := http.Post(srv.URL+"/acme/profile/prof-corp/order/acme-ord-001/finalize", "application/jose+json", bytes.NewReader([]byte("x")))
if err != nil {
t.Fatalf("Post: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusBadRequest {
t.Errorf("status = %d, want 400", resp.StatusCode)
}
var p acme.Problem
_ = json.NewDecoder(resp.Body).Decode(&p)
if p.Type != "urn:ietf:params:acme:error:badCSR" {
t.Errorf("Problem.Type = %q", p.Type)
}
}
func TestACMEHandler_Cert_HappyPath(t *testing.T) {
pemChain := "-----BEGIN CERTIFICATE-----\nMIIBhjCCAQ==\n-----END CERTIFICATE-----\n"
mock := &mockACMEService{
VerifyJWSFn: stubVerifiedReq(
struct{}{},
&domain.ACMEAccount{AccountID: "acme-acc-X", Status: domain.ACMEAccountStatusValid, ProfileID: "prof-corp"},
nil,
),
LookupCertificateFn: func(ctx context.Context, certID, accountID string) (string, error) {
return pemChain, nil
},
}
srv := newACMETestServer(t, mock)
defer srv.Close()
resp, err := http.Post(srv.URL+"/acme/profile/prof-corp/cert/mc-acme-001", "application/jose+json", bytes.NewReader([]byte("x")))
if err != nil {
t.Fatalf("Post: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
t.Errorf("status = %d, want 200", resp.StatusCode)
}
if got := resp.Header.Get("Content-Type"); got != "application/pem-certificate-chain" {
t.Errorf("content-type = %q", got)
}
body := bytes.NewBuffer(nil)
_, _ = body.ReadFrom(resp.Body)
if !strings.Contains(body.String(), "BEGIN CERTIFICATE") {
t.Errorf("body did not contain PEM cert: %q", body.String())
}
}
@@ -71,6 +71,18 @@ var SpecParityExceptions = map[string]string{
"GET /acme/new-nonce": "RFC 8555 §7.2 new-nonce GET (default-profile shorthand); documented in docs/acme-server.md",
"POST /acme/new-account": "RFC 8555 §7.3 new-account (default-profile shorthand); documented in docs/acme-server.md",
"POST /acme/account/{acc_id}": "RFC 8555 §7.3.2 + §7.3.6 (default-profile shorthand); documented in docs/acme-server.md",
// Phase 2 — orders + finalize + authz + cert.
"POST /acme/profile/{id}/new-order": "RFC 8555 §7.4 new-order; documented in docs/acme-server.md",
"POST /acme/profile/{id}/order/{ord_id}": "RFC 8555 §7.4 order POST-as-GET; documented in docs/acme-server.md",
"POST /acme/profile/{id}/order/{ord_id}/finalize": "RFC 8555 §7.4 finalize; documented in docs/acme-server.md",
"POST /acme/profile/{id}/authz/{authz_id}": "RFC 8555 §7.5 authz POST-as-GET; documented in docs/acme-server.md",
"POST /acme/profile/{id}/cert/{cert_id}": "RFC 8555 §7.4.2 cert download; documented in docs/acme-server.md",
"POST /acme/new-order": "Phase 2 default-profile shorthand for new-order.",
"POST /acme/order/{ord_id}": "Phase 2 default-profile shorthand for order POST-as-GET.",
"POST /acme/order/{ord_id}/finalize": "Phase 2 default-profile shorthand for finalize.",
"POST /acme/authz/{authz_id}": "Phase 2 default-profile shorthand for authz POST-as-GET.",
"POST /acme/cert/{cert_id}": "Phase 2 default-profile shorthand for cert download.",
}
func TestRouter_OpenAPIParity(t *testing.T) {
+10
View File
@@ -417,6 +417,11 @@ func (r *Router) RegisterHandlers(reg HandlerRegistry) {
r.Register("GET /acme/profile/{id}/new-nonce", http.HandlerFunc(reg.ACME.NewNonce))
r.Register("POST /acme/profile/{id}/new-account", http.HandlerFunc(reg.ACME.NewAccount))
r.Register("POST /acme/profile/{id}/account/{acc_id}", http.HandlerFunc(reg.ACME.Account))
r.Register("POST /acme/profile/{id}/new-order", http.HandlerFunc(reg.ACME.NewOrder))
r.Register("POST /acme/profile/{id}/order/{ord_id}", http.HandlerFunc(reg.ACME.Order))
r.Register("POST /acme/profile/{id}/order/{ord_id}/finalize", http.HandlerFunc(reg.ACME.OrderFinalize))
r.Register("POST /acme/profile/{id}/authz/{authz_id}", http.HandlerFunc(reg.ACME.Authz))
r.Register("POST /acme/profile/{id}/cert/{cert_id}", http.HandlerFunc(reg.ACME.Cert))
// Default-profile shorthand. The handler's profile-resolution path
// returns userActionRequired (RFC 7807 + RFC 8555 §6.7) when
// CERTCTL_ACME_SERVER_DEFAULT_PROFILE_ID is unset; when set it
@@ -426,6 +431,11 @@ func (r *Router) RegisterHandlers(reg HandlerRegistry) {
r.Register("GET /acme/new-nonce", http.HandlerFunc(reg.ACME.NewNonce))
r.Register("POST /acme/new-account", http.HandlerFunc(reg.ACME.NewAccount))
r.Register("POST /acme/account/{acc_id}", http.HandlerFunc(reg.ACME.Account))
r.Register("POST /acme/new-order", http.HandlerFunc(reg.ACME.NewOrder))
r.Register("POST /acme/order/{ord_id}", http.HandlerFunc(reg.ACME.Order))
r.Register("POST /acme/order/{ord_id}/finalize", http.HandlerFunc(reg.ACME.OrderFinalize))
r.Register("POST /acme/authz/{authz_id}", http.HandlerFunc(reg.ACME.Authz))
r.Register("POST /acme/cert/{cert_id}", http.HandlerFunc(reg.ACME.Cert))
}
// RegisterESTHandlers sets up EST (RFC 7030) routes under