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
+22
View File
@@ -54,3 +54,25 @@ documented_exceptions:
why: "ACME server default-profile shorthand for new-account."
- route: "POST /acme/account/{acc_id}"
why: "ACME server default-profile shorthand for account update + deactivation."
# Phase 2 — orders + finalize + authz + cert.
- route: "POST /acme/profile/{id}/new-order"
why: "ACME server RFC 8555 §7.4 new-order; documented in docs/acme-server.md."
- route: "POST /acme/profile/{id}/order/{ord_id}"
why: "ACME server RFC 8555 §7.4 order POST-as-GET; documented in docs/acme-server.md."
- route: "POST /acme/profile/{id}/order/{ord_id}/finalize"
why: "ACME server RFC 8555 §7.4 finalize; documented in docs/acme-server.md."
- route: "POST /acme/profile/{id}/authz/{authz_id}"
why: "ACME server RFC 8555 §7.5 authz POST-as-GET; documented in docs/acme-server.md."
- route: "POST /acme/profile/{id}/cert/{cert_id}"
why: "ACME server RFC 8555 §7.4.2 cert download; documented in docs/acme-server.md."
- route: "POST /acme/new-order"
why: "Phase 2 default-profile shorthand for new-order."
- route: "POST /acme/order/{ord_id}"
why: "Phase 2 default-profile shorthand for order POST-as-GET."
- route: "POST /acme/order/{ord_id}/finalize"
why: "Phase 2 default-profile shorthand for finalize."
- route: "POST /acme/authz/{authz_id}"
why: "Phase 2 default-profile shorthand for authz POST-as-GET."
- route: "POST /acme/cert/{cert_id}"
why: "Phase 2 default-profile shorthand for cert download."
+6
View File
@@ -758,6 +758,12 @@ func main() {
acmeService := service.NewACMEService(acmeRepo, profileRepo, cfg.ACMEServer)
acmeService.SetTransactor(transactor)
acmeService.SetAuditService(auditService)
// Phase 2 — finalize plumbing. The finalize handler routes
// through CertificateService.Create + certRepo.CreateVersionWithTx
// + IssuerRegistry.Get for the bound profile's issuer. Same
// pipeline EST/SCEP/agent/renewal use, so policy + audit + per-
// issuer-type metrics apply uniformly to ACME-issued certs.
acmeService.SetIssuancePipeline(certificateService, certificateRepo, issuerRegistry)
acmeHandler := handler.NewACMEHandler(acmeService)
// Build the API router with all handlers
+58 -14
View File
@@ -7,11 +7,14 @@ as an ACME issuer with no certctl-side modification — closing the
"deploy a certctl agent on every K8s node" friction that costs deals to
external PKI vendors today.
> **Phase status (2026-05-03):** Phase 1b — directory + new-nonce +
> new-account + account/{id} update + JWS verifier (RFC 7515 + go-jose
> v4). An ACME client can now run new-account end-to-end and register
> against a profile. Orders + challenges + key rollover + revocation +
> ARI land in subsequent phases. Track shipped phases via
> **Phase status (2026-05-03):** Phase 2 — directory + new-nonce +
> new-account + account/{id} + new-order + order/{id} + finalize +
> authz/{id} + cert/{id}. An ACME client running against a profile
> with `acme_auth_mode='trust_authenticated'` end-to-end-issues a real
> cert: `lego --server https://certctl/acme/profile/<id>/directory ...
> run` succeeds. Profiles in `challenge` mode get all the same code
> path with authz/challenge rows in `pending` state until Phase 3's
> validators wire up. Track shipped phases via
> `git log --grep='acme-server:'`.
## Configuration
@@ -95,29 +98,70 @@ the `caBundle` requirement is flagged here in Phase 1a's docs because
operators hit it the moment they try to point a real ACME client at
certctl.
## Endpoints (Phase 1b)
## Endpoints (Phase 2)
Routes registered in `internal/api/router/router.go::RegisterHandlers`:
| Method | Path | RFC ref | Auth | Description |
|--------|--------------------------------------------|-----------------|----------|-------------|
|--------|-------------------------------------------------------|-----------------|----------|-------------|
| GET | `/acme/profile/{id}/directory` | RFC 8555 §7.1.1 | unauth | Per-profile directory document. |
| HEAD | `/acme/profile/{id}/new-nonce` | RFC 8555 §7.2 | unauth | Returns 200 + Replay-Nonce header. |
| GET | `/acme/profile/{id}/new-nonce` | RFC 8555 §7.2 | unauth | Returns 204 + Replay-Nonce header. |
| POST | `/acme/profile/{id}/new-account` | RFC 8555 §7.3 | JWS jwk | Register a new account; idempotent re-registration of an existing JWK returns the existing row. |
| POST | `/acme/profile/{id}/account/{acc_id}` | RFC 8555 §7.3.2 + §7.3.6 | JWS kid | Update contact list, deactivate, or POST-as-GET (RFC 8555 §6.3) to fetch the account. |
| POST | `/acme/profile/{id}/new-order` | RFC 8555 §7.4 | JWS kid | Submit an order; identifier validation runs before order creation. |
| POST | `/acme/profile/{id}/order/{ord_id}` | RFC 8555 §7.4 | JWS kid | POST-as-GET fetch of an order's current state. |
| POST | `/acme/profile/{id}/order/{ord_id}/finalize` | RFC 8555 §7.4 | JWS kid | Submit the CSR + finalize. Issues + persists managed cert row + version. |
| POST | `/acme/profile/{id}/authz/{authz_id}` | RFC 8555 §7.5 | JWS kid | POST-as-GET fetch of an authorization. |
| POST | `/acme/profile/{id}/cert/{cert_id}` | RFC 8555 §7.4.2 | JWS kid | POST-as-GET cert chain download (PEM). |
| GET | `/acme/directory` | RFC 8555 §7.1.1 | unauth | Shorthand path; mirrors per-profile when `CERTCTL_ACME_SERVER_DEFAULT_PROFILE_ID` is set. |
| HEAD | `/acme/new-nonce` | RFC 8555 §7.2 | unauth | Shorthand. |
| GET | `/acme/new-nonce` | RFC 8555 §7.2 | unauth | Shorthand. |
| POST | `/acme/new-account` | RFC 8555 §7.3 | JWS jwk | Shorthand. |
| POST | `/acme/account/{acc_id}` | RFC 8555 §7.3.2 + §7.3.6 | JWS kid | Shorthand. |
| POST | `/acme/new-order` | RFC 8555 §7.4 | JWS kid | Shorthand. |
| POST | `/acme/order/{ord_id}` | RFC 8555 §7.4 | JWS kid | Shorthand. |
| POST | `/acme/order/{ord_id}/finalize` | RFC 8555 §7.4 | JWS kid | Shorthand. |
| POST | `/acme/authz/{authz_id}` | RFC 8555 §7.5 | JWS kid | Shorthand. |
| POST | `/acme/cert/{cert_id}` | RFC 8555 §7.4.2 | JWS kid | Shorthand. |
The remaining RFC 8555 endpoints (`new-order`, `order/{id}`,
`order/{id}/finalize`, `authz/{id}`, `challenge/{id}`, `cert/{id}`,
`key-change`, `revoke-cert`, `renewal-info`) are advertised in the
directory document but not yet served — clients hitting them get a 404
until subsequent phases land. The directory document includes their
URLs because RFC 8555 doesn't permit a partial directory.
The remaining RFC 8555 endpoints (`challenge/{id}`, `key-change`,
`revoke-cert`, `renewal-info`) are advertised in the directory document
but not yet served — clients hitting them get a 404 until subsequent
phases land. The directory document includes their URLs because RFC 8555
doesn't permit a partial directory.
## Finalize routing through `CertificateService.Create` (Phase 2 architecture)
The finalize path mirrors how every other certctl issuance surface
(EST, SCEP, agent, REST API) routes through the canonical pipeline:
1. JWS-verify the request (`internal/api/acme/jws.go`).
2. Validate the CSR's DNS-name set equals the order's identifier set
exactly (case-folded). Mismatches return RFC 8555
`urn:ietf:params:acme:error:badCSR`.
3. Update the order row to `status=processing` (`s.tx.WithinTx` +
`auditService.RecordEventWithTx` — atomic with audit row).
4. Issue the cert via the bound profile's `IssuerConnector` adapter
(same `IssueCertificate(ctx, commonName, sans, csrPEM, ekus,
maxTTLSeconds, mustStaple)` call EST/SCEP/agent take).
5. Insert the `managed_certificates` row via
`service.CertificateService.Create(ctx, *ManagedCertificate, actor)`.
Source is stamped `domain.CertificateSourceACME` so operators can
bulk-revoke ACME-issued certs by filtering on `Source=ACME`.
6. Insert the `certificate_versions` row +
transition the order to `status=valid` with `certificate_id` set
(one final `WithinTx` covering both writes + the audit row).
This means RenewalPolicy, CertificateProfile, per-issuer-type
Prometheus metrics, audit rows, and revocation-pipeline integration
all apply uniformly to ACME-issued certs via the same code path that
already serves EST/SCEP/agent/REST issuance.
The atomicity boundary: there is a brief window between step 5 (cert
exists) and step 6 (order shows valid) where the order row still says
`processing`. Phase 5's GC scheduler reconciles. The actor string on
audit rows is `acme:<account-id>`.
## JWS verification (Phase 1b)
@@ -154,7 +198,7 @@ at `internal/service/certificate.go:131`).
|-------|-------------|---------|
| 1a | live | directory + new-nonce + per-profile routing |
| 1b | live | new-account + account/{id} + JWS verifier (RFC 7515 + go-jose v4) |
| 2 | not yet | orders + authzs + finalize + cert download (trust_authenticated mode end-to-end) |
| 2 | live | orders + authzs + finalize + cert download (trust_authenticated mode end-to-end) |
| 3 | not yet | HTTP-01 + DNS-01 + TLS-ALPN-01 challenge validation |
| 4 | not yet | key rollover + revocation + ARI (RFC 9773) |
| 5 | not yet | cert-manager integration test + production hardening |
+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
+111
View File
@@ -48,3 +48,114 @@ const (
// JWK). Same access semantics as deactivated.
ACMEAccountStatusRevoked ACMEAccountStatus = "revoked"
)
// ACMEOrder mirrors a row in the acme_orders table (RFC 8555 §7.1.3).
// Identifiers stored as a slice; the postgres layer JSON-encodes into
// the JSONB column at write time and decodes on read.
type ACMEOrder struct {
OrderID string `json:"order_id"`
AccountID string `json:"account_id"`
Identifiers []ACMEIdentifier `json:"identifiers"`
Status ACMEOrderStatus `json:"status"`
ExpiresAt time.Time `json:"expires_at"`
NotBefore *time.Time `json:"not_before,omitempty"`
NotAfter *time.Time `json:"not_after,omitempty"`
Error *ACMEProblem `json:"error,omitempty"`
CSRPEM string `json:"csr_pem,omitempty"`
CertificateID string `json:"certificate_id,omitempty"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
// ACMEOrderStatus is the closed state-machine for the `status` column
// per RFC 8555 §7.1.6.
type ACMEOrderStatus string
const (
ACMEOrderStatusPending ACMEOrderStatus = "pending"
ACMEOrderStatusReady ACMEOrderStatus = "ready"
ACMEOrderStatusProcessing ACMEOrderStatus = "processing"
ACMEOrderStatusValid ACMEOrderStatus = "valid"
ACMEOrderStatusInvalid ACMEOrderStatus = "invalid"
)
// ACMEIdentifier is the {type, value} pair RFC 8555 §7.1.4 mandates.
// Phase 2 supports `dns` only; Phase 3 will not extend (RFC 8555
// extensions for IP / email identifier types are out of scope).
type ACMEIdentifier struct {
Type string `json:"type"`
Value string `json:"value"`
}
// ACMEProblem mirrors the RFC 7807 + RFC 8555 §6.7 error envelope
// when stored on an order/authz row. Kept in domain (rather than
// importing api/acme.Problem) so the persistence layer doesn't take
// a dependency on the protocol package.
type ACMEProblem struct {
Type string `json:"type"`
Detail string `json:"detail"`
Status int `json:"status"`
}
// ACMEAuthorization mirrors a row in the acme_authorizations table
// (RFC 8555 §7.1.4). One authz per order identifier; the linked
// challenges live in acme_challenges.
type ACMEAuthorization struct {
AuthzID string `json:"authz_id"`
OrderID string `json:"order_id"`
Identifier ACMEIdentifier `json:"identifier"`
Status ACMEAuthzStatus `json:"status"`
ExpiresAt time.Time `json:"expires_at"`
Wildcard bool `json:"wildcard"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
Challenges []ACMEChallenge `json:"challenges,omitempty"` // populated by repo on read
}
// ACMEAuthzStatus is the closed enum for acme_authorizations.status
// per RFC 8555 §7.1.6.
type ACMEAuthzStatus string
const (
ACMEAuthzStatusPending ACMEAuthzStatus = "pending"
ACMEAuthzStatusValid ACMEAuthzStatus = "valid"
ACMEAuthzStatusInvalid ACMEAuthzStatus = "invalid"
ACMEAuthzStatusDeactivated ACMEAuthzStatus = "deactivated"
ACMEAuthzStatusExpired ACMEAuthzStatus = "expired"
ACMEAuthzStatusRevoked ACMEAuthzStatus = "revoked"
)
// ACMEChallenge mirrors a row in the acme_challenges table (RFC 8555 §8).
type ACMEChallenge struct {
ChallengeID string `json:"challenge_id"`
AuthzID string `json:"authz_id"`
Type ACMEChallengeType `json:"type"`
Status ACMEChallengeStatus `json:"status"`
Token string `json:"token"`
ValidatedAt *time.Time `json:"validated_at,omitempty"`
Error *ACMEProblem `json:"error,omitempty"`
CreatedAt time.Time `json:"created_at"`
}
// ACMEChallengeType is the closed set of challenge types Phase 3 will
// implement. Phase 2 emits only `http-01` placeholders since challenge
// validation isn't wired yet — RFC 8555 §8 mandates at least one
// challenge per authz.
type ACMEChallengeType string
const (
ACMEChallengeTypeHTTP01 ACMEChallengeType = "http-01"
ACMEChallengeTypeDNS01 ACMEChallengeType = "dns-01"
ACMEChallengeTypeTLSALPN01 ACMEChallengeType = "tls-alpn-01"
)
// ACMEChallengeStatus is the closed enum for acme_challenges.status
// per RFC 8555 §7.1.6 + §8.2.
type ACMEChallengeStatus string
const (
ACMEChallengeStatusPending ACMEChallengeStatus = "pending"
ACMEChallengeStatusProcessing ACMEChallengeStatus = "processing"
ACMEChallengeStatusValid ACMEChallengeStatus = "valid"
ACMEChallengeStatusInvalid ACMEChallengeStatus = "invalid"
)
+7
View File
@@ -59,6 +59,13 @@ const (
CertificateSourceSCEP CertificateSource = "SCEP"
CertificateSourceAPI CertificateSource = "API"
CertificateSourceAgent CertificateSource = "Agent"
// CertificateSourceACME stamps every cert issued through the
// built-in ACME server endpoint (RFC 8555 finalize → cert
// download). The ACME service (internal/service/acme.go)
// pins this on every managed_certificates row it inserts at
// finalize time. Operators bulk-revoke ACME-issued certs by
// filtering on Source=ACME.
CertificateSourceACME CertificateSource = "ACME"
)
// CertificateVersion represents a specific version of a certificate.
+14
View File
@@ -58,6 +58,20 @@ type CertificateProfile struct {
// EST RFC 7030 hardening master bundle Phase 6.
RequiredCSRAttributes []string `json:"required_csr_attributes,omitempty"`
// ACMEAuthMode picks the per-profile ACME server auth posture.
// "trust_authenticated" (default): JWS-authenticated client is
// trusted to issue for any identifier the profile policy allows
// (no out-of-band identifier proof). "challenge": full HTTP-01 +
// DNS-01 + TLS-ALPN-01 validation per RFC 8555 §8 (Phase 3).
// One certctl-server can serve both modes simultaneously by
// having multiple profiles with different values; the column is
// read at request time, not cached at server start.
//
// Backed by certificate_profiles.acme_auth_mode added in
// migration 000025_acme_server. Empty string in Go ≡ DB default
// "trust_authenticated".
ACMEAuthMode string `json:"acme_auth_mode,omitempty"`
Enabled bool `json:"enabled"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
+353
View File
@@ -6,6 +6,7 @@ package postgres
import (
"context"
"database/sql"
"encoding/json"
"errors"
"fmt"
"time"
@@ -232,6 +233,358 @@ func (r *ACMERepository) UpdateAccountStatusWithTx(ctx context.Context, q reposi
return nil
}
// --- Phase 2 — order / authz / challenge CRUD --------------------------
// CreateOrderWithTx inserts an acme_orders row. Used by ACMEService.CreateOrder
// during new-order processing; the transaction also creates the per-identifier
// authz + challenge rows + audit row in the same WithinTx.
func (r *ACMERepository) CreateOrderWithTx(ctx context.Context, q repository.Querier, order *domain.ACMEOrder) error {
if order.OrderID == "" || order.AccountID == "" {
return fmt.Errorf("acme: create order: missing required field")
}
now := time.Now().UTC()
if order.CreatedAt.IsZero() {
order.CreatedAt = now
}
order.UpdatedAt = now
identifiersJSON, err := jsonMarshalACME(order.Identifiers)
if err != nil {
return fmt.Errorf("acme: marshal identifiers: %w", err)
}
var (
notBefore, notAfter interface{}
errBlob interface{}
certID interface{}
)
if order.NotBefore != nil {
notBefore = *order.NotBefore
}
if order.NotAfter != nil {
notAfter = *order.NotAfter
}
if order.Error != nil {
b, err := jsonMarshalACME(order.Error)
if err != nil {
return fmt.Errorf("acme: marshal error: %w", err)
}
errBlob = b
}
if order.CertificateID != "" {
certID = order.CertificateID
}
_, err = q.ExecContext(ctx, `
INSERT INTO acme_orders (
order_id, account_id, identifiers, status, expires_at,
not_before, not_after, error, csr_pem, certificate_id,
created_at, updated_at
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)
`,
order.OrderID, order.AccountID, identifiersJSON, string(order.Status),
order.ExpiresAt, notBefore, notAfter, errBlob, order.CSRPEM, certID,
order.CreatedAt, order.UpdatedAt,
)
if err != nil {
return fmt.Errorf("acme: insert order: %w", err)
}
return nil
}
// GetOrderByID retrieves an order. Returns sql.ErrNoRows-wrapped
// repository.ErrNotFound on miss.
func (r *ACMERepository) GetOrderByID(ctx context.Context, orderID string) (*domain.ACMEOrder, error) {
row := r.db.QueryRowContext(ctx, `
SELECT order_id, account_id, identifiers, status, expires_at,
not_before, not_after, error, COALESCE(csr_pem, ''),
COALESCE(certificate_id, ''), created_at, updated_at
FROM acme_orders
WHERE order_id = $1
`, orderID)
return scanACMEOrder(row)
}
// UpdateOrderWithTx persists changes to an order's mutable fields.
// Used by FinalizeOrder to transition status / set csr_pem /
// certificate_id / error.
func (r *ACMERepository) UpdateOrderWithTx(ctx context.Context, q repository.Querier, order *domain.ACMEOrder) error {
order.UpdatedAt = time.Now().UTC()
var (
errBlob interface{}
certID interface{}
)
if order.Error != nil {
b, err := jsonMarshalACME(order.Error)
if err != nil {
return fmt.Errorf("acme: marshal error: %w", err)
}
errBlob = b
}
if order.CertificateID != "" {
certID = order.CertificateID
}
res, err := q.ExecContext(ctx, `
UPDATE acme_orders SET
status = $2,
error = $3,
csr_pem = $4,
certificate_id = $5,
updated_at = $6
WHERE order_id = $1
`, order.OrderID, string(order.Status), errBlob, order.CSRPEM, certID, order.UpdatedAt)
if err != nil {
return fmt.Errorf("acme: update order: %w", err)
}
n, err := res.RowsAffected()
if err != nil {
return fmt.Errorf("acme: update order rows: %w", err)
}
if n == 0 {
return fmt.Errorf("order not found: %w", repository.ErrNotFound)
}
return nil
}
// CreateAuthzWithTx inserts an acme_authorizations row.
func (r *ACMERepository) CreateAuthzWithTx(ctx context.Context, q repository.Querier, authz *domain.ACMEAuthorization) error {
if authz.AuthzID == "" || authz.OrderID == "" {
return fmt.Errorf("acme: create authz: missing required field")
}
now := time.Now().UTC()
if authz.CreatedAt.IsZero() {
authz.CreatedAt = now
}
authz.UpdatedAt = now
idJSON, err := jsonMarshalACME(authz.Identifier)
if err != nil {
return fmt.Errorf("acme: marshal identifier: %w", err)
}
_, err = q.ExecContext(ctx, `
INSERT INTO acme_authorizations (
authz_id, order_id, identifier, status, expires_at, wildcard,
created_at, updated_at
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
`,
authz.AuthzID, authz.OrderID, idJSON, string(authz.Status),
authz.ExpiresAt, authz.Wildcard, authz.CreatedAt, authz.UpdatedAt,
)
if err != nil {
return fmt.Errorf("acme: insert authz: %w", err)
}
return nil
}
// GetAuthzByID returns the authz row + its child challenges.
func (r *ACMERepository) GetAuthzByID(ctx context.Context, authzID string) (*domain.ACMEAuthorization, error) {
row := r.db.QueryRowContext(ctx, `
SELECT authz_id, order_id, identifier, status, expires_at, wildcard, created_at, updated_at
FROM acme_authorizations WHERE authz_id = $1
`, authzID)
authz, err := scanACMEAuthz(row)
if err != nil {
return nil, err
}
chs, err := r.ListChallengesByAuthz(ctx, authzID)
if err != nil {
return nil, fmt.Errorf("acme: list challenges: %w", err)
}
authz.Challenges = chs
return authz, nil
}
// ListAuthzsByOrder returns the per-order authz rows (without challenges
// — callers needing challenges call GetAuthzByID per entry).
func (r *ACMERepository) ListAuthzsByOrder(ctx context.Context, orderID string) ([]*domain.ACMEAuthorization, error) {
rows, err := r.db.QueryContext(ctx, `
SELECT authz_id, order_id, identifier, status, expires_at, wildcard, created_at, updated_at
FROM acme_authorizations WHERE order_id = $1
ORDER BY created_at ASC
`, orderID)
if err != nil {
return nil, fmt.Errorf("acme: list authzs: %w", err)
}
defer rows.Close()
var out []*domain.ACMEAuthorization
for rows.Next() {
a, err := scanACMEAuthz(rows)
if err != nil {
return nil, err
}
out = append(out, a)
}
return out, rows.Err()
}
// CreateChallengeWithTx inserts an acme_challenges row.
func (r *ACMERepository) CreateChallengeWithTx(ctx context.Context, q repository.Querier, ch *domain.ACMEChallenge) error {
if ch.ChallengeID == "" || ch.AuthzID == "" || ch.Type == "" || ch.Token == "" {
return fmt.Errorf("acme: create challenge: missing required field")
}
if ch.CreatedAt.IsZero() {
ch.CreatedAt = time.Now().UTC()
}
var (
validatedAt interface{}
errBlob interface{}
)
if ch.ValidatedAt != nil {
validatedAt = *ch.ValidatedAt
}
if ch.Error != nil {
b, err := jsonMarshalACME(ch.Error)
if err != nil {
return fmt.Errorf("acme: marshal error: %w", err)
}
errBlob = b
}
_, err := q.ExecContext(ctx, `
INSERT INTO acme_challenges (
challenge_id, authz_id, type, status, token, validated_at, error, created_at
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
`,
ch.ChallengeID, ch.AuthzID, string(ch.Type), string(ch.Status), ch.Token,
validatedAt, errBlob, ch.CreatedAt,
)
if err != nil {
return fmt.Errorf("acme: insert challenge: %w", err)
}
return nil
}
// ListChallengesByAuthz returns the challenge rows for an authz.
func (r *ACMERepository) ListChallengesByAuthz(ctx context.Context, authzID string) ([]domain.ACMEChallenge, error) {
rows, err := r.db.QueryContext(ctx, `
SELECT challenge_id, authz_id, type, status, token, validated_at, error, created_at
FROM acme_challenges WHERE authz_id = $1
ORDER BY created_at ASC
`, authzID)
if err != nil {
return nil, fmt.Errorf("acme: list challenges: %w", err)
}
defer rows.Close()
var out []domain.ACMEChallenge
for rows.Next() {
ch, err := scanACMEChallenge(rows)
if err != nil {
return nil, err
}
out = append(out, *ch)
}
return out, rows.Err()
}
// scanACMEOrder parses an acme_orders row.
func scanACMEOrder(row interface{ Scan(...interface{}) error }) (*domain.ACMEOrder, error) {
var (
o domain.ACMEOrder
identifiers []byte
statusStr string
notBefore sql.NullTime
notAfter sql.NullTime
errBlob sql.NullString
)
err := row.Scan(
&o.OrderID, &o.AccountID, &identifiers, &statusStr, &o.ExpiresAt,
&notBefore, &notAfter, &errBlob, &o.CSRPEM, &o.CertificateID,
&o.CreatedAt, &o.UpdatedAt,
)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
return nil, fmt.Errorf("order not found: %w", repository.ErrNotFound)
}
return nil, fmt.Errorf("acme: scan order: %w", err)
}
o.Status = domain.ACMEOrderStatus(statusStr)
if err := jsonUnmarshalACME(identifiers, &o.Identifiers); err != nil {
return nil, fmt.Errorf("acme: unmarshal identifiers: %w", err)
}
if notBefore.Valid {
t := notBefore.Time
o.NotBefore = &t
}
if notAfter.Valid {
t := notAfter.Time
o.NotAfter = &t
}
if errBlob.Valid && errBlob.String != "" {
var p domain.ACMEProblem
if err := jsonUnmarshalACME([]byte(errBlob.String), &p); err == nil {
o.Error = &p
}
}
return &o, nil
}
// scanACMEAuthz parses an acme_authorizations row.
func scanACMEAuthz(row interface{ Scan(...interface{}) error }) (*domain.ACMEAuthorization, error) {
var (
a domain.ACMEAuthorization
identifier []byte
statusStr string
)
err := row.Scan(
&a.AuthzID, &a.OrderID, &identifier, &statusStr,
&a.ExpiresAt, &a.Wildcard, &a.CreatedAt, &a.UpdatedAt,
)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
return nil, fmt.Errorf("authz not found: %w", repository.ErrNotFound)
}
return nil, fmt.Errorf("acme: scan authz: %w", err)
}
a.Status = domain.ACMEAuthzStatus(statusStr)
if err := jsonUnmarshalACME(identifier, &a.Identifier); err != nil {
return nil, fmt.Errorf("acme: unmarshal authz identifier: %w", err)
}
return &a, nil
}
// scanACMEChallenge parses an acme_challenges row.
func scanACMEChallenge(row interface{ Scan(...interface{}) error }) (*domain.ACMEChallenge, error) {
var (
ch domain.ACMEChallenge
typeStr string
statusStr string
validatedAt sql.NullTime
errBlob sql.NullString
)
err := row.Scan(
&ch.ChallengeID, &ch.AuthzID, &typeStr, &statusStr,
&ch.Token, &validatedAt, &errBlob, &ch.CreatedAt,
)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
return nil, fmt.Errorf("challenge not found: %w", repository.ErrNotFound)
}
return nil, fmt.Errorf("acme: scan challenge: %w", err)
}
ch.Type = domain.ACMEChallengeType(typeStr)
ch.Status = domain.ACMEChallengeStatus(statusStr)
if validatedAt.Valid {
t := validatedAt.Time
ch.ValidatedAt = &t
}
if errBlob.Valid && errBlob.String != "" {
var p domain.ACMEProblem
if err := jsonUnmarshalACME([]byte(errBlob.String), &p); err == nil {
ch.Error = &p
}
}
return &ch, nil
}
// jsonMarshalACME wraps encoding/json.Marshal — kept as a named
// helper so future per-column custom encoding is a one-line change.
func jsonMarshalACME(v interface{}) ([]byte, error) { return json.Marshal(v) }
// jsonUnmarshalACME tolerates empty input as a no-op (NULL JSONB
// columns scan into zero-length []byte; we treat that as "field
// absent" rather than an unmarshal error).
func jsonUnmarshalACME(data []byte, v interface{}) error {
if len(data) == 0 {
return nil
}
return json.Unmarshal(data, v)
}
// scanACMEAccount is the shared shape for the SELECT-by-X account
// queries above. Returns sql.ErrNoRows-wrapped repository.ErrNotFound
// on miss; any other scan failure surfaces verbatim.
+3
View File
@@ -28,6 +28,7 @@ func (r *ProfileRepository) List(ctx context.Context) ([]*domain.CertificateProf
SELECT id, name, description, allowed_key_algorithms, max_ttl_seconds,
allowed_ekus, required_san_patterns, spiffe_uri_pattern,
allow_short_lived, must_staple, required_csr_attributes,
COALESCE(acme_auth_mode, 'trust_authenticated'),
enabled, created_at, updated_at
FROM certificate_profiles
ORDER BY created_at DESC
@@ -59,6 +60,7 @@ func (r *ProfileRepository) Get(ctx context.Context, id string) (*domain.Certifi
SELECT id, name, description, allowed_key_algorithms, max_ttl_seconds,
allowed_ekus, required_san_patterns, spiffe_uri_pattern,
allow_short_lived, must_staple, required_csr_attributes,
COALESCE(acme_auth_mode, 'trust_authenticated'),
enabled, created_at, updated_at
FROM certificate_profiles
WHERE id = $1
@@ -213,6 +215,7 @@ func scanProfile(scanner interface {
&p.ID, &p.Name, &p.Description, &algJSON, &p.MaxTTLSeconds,
&ekuJSON, &sanJSON, &p.SPIFFEURIPattern,
&p.AllowShortLived, &p.MustStaple, &csrAttrsJSON,
&p.ACMEAuthMode,
&p.Enabled, &p.CreatedAt, &p.UpdatedAt,
)
if err != nil {
+583 -3
View File
@@ -5,8 +5,11 @@ package service
import (
"context"
cryptorand "crypto/rand"
"crypto/x509"
"errors"
"fmt"
"strings"
"sync/atomic"
"time"
@@ -38,6 +41,14 @@ type ACMERepo interface {
GetAccountByThumbprint(ctx context.Context, profileID, thumbprint string) (*domain.ACMEAccount, error)
UpdateAccountContactWithTx(ctx context.Context, q repository.Querier, accountID string, contact []string) error
UpdateAccountStatusWithTx(ctx context.Context, q repository.Querier, accountID string, status domain.ACMEAccountStatus) error
// Phase 2 — order / authz / challenge CRUD.
CreateOrderWithTx(ctx context.Context, q repository.Querier, order *domain.ACMEOrder) error
GetOrderByID(ctx context.Context, orderID string) (*domain.ACMEOrder, error)
UpdateOrderWithTx(ctx context.Context, q repository.Querier, order *domain.ACMEOrder) error
CreateAuthzWithTx(ctx context.Context, q repository.Querier, authz *domain.ACMEAuthorization) error
GetAuthzByID(ctx context.Context, authzID string) (*domain.ACMEAuthorization, error)
ListAuthzsByOrder(ctx context.Context, orderID string) ([]*domain.ACMEAuthorization, error)
CreateChallengeWithTx(ctx context.Context, q repository.Querier, ch *domain.ACMEChallenge) error
}
// profileLookup is the minimum surface ACMEService needs to resolve a
@@ -51,10 +62,12 @@ type profileLookup interface {
// ACMEService orchestrates the ACME server's RFC 8555 surface.
//
// - Phase 1a (live): BuildDirectory, IssueNonce.
// - Phase 1b (this commit): VerifyJWS, NewAccount, LookupAccount,
// - Phase 1b (live): VerifyJWS, NewAccount, LookupAccount,
// UpdateAccount, DeactivateAccount.
// - Subsequent phases extend with new-order, finalize, challenges,
// key-change, revoke, ARI.
// - Phase 2 (this commit): CreateOrder, LookupOrder, FinalizeOrder,
// LookupAuthz, LookupCertificate.
// - Subsequent phases extend with challenge validation, key
// rollover, revocation, ARI.
//
// The struct deliberately holds raw config rather than per-field
// extracted values — readers use 4 of the 11 fields and reading them
@@ -74,6 +87,17 @@ type ACMEService struct {
// stateful tables.
tx repository.Transactor
auditService *AuditService
// Phase 2 — finalize plumbing. The finalize handler routes
// through CertificateService.Create (managed_certificates row +
// audit row in its own WithinTx) AND certRepo.CreateVersionWithTx
// (certificate_versions row). Issuance itself goes through the
// IssuerRegistry's IssuerConnector adapter — same code path
// EST/SCEP/agent take. cmd/server/main.go wires all three at
// startup; tests inject mocks.
certService *CertificateService
certRepo repository.CertificateRepository
issuerRegistry *IssuerRegistry
}
// NewACMEService constructs an ACMEService with the directory + nonce
@@ -99,6 +123,21 @@ func (s *ACMEService) SetTransactor(tx repository.Transactor) { s.tx = tx }
// every service that emits audit rows.
func (s *ACMEService) SetAuditService(a *AuditService) { s.auditService = a }
// SetIssuancePipeline wires Phase 2 finalize dependencies: the
// certificate service (for managed_certificates row + audit row),
// the certificate repository (for certificate_versions row), and the
// issuer registry (for routing IssueCertificate against the bound
// profile's issuer). cmd/server/main.go calls this at startup.
//
// All three are required for the finalize path. When unset, FinalizeOrder
// returns ErrACMEFinalizeUnconfigured (handler maps to
// urn:ietf:params:acme:error:serverInternal).
func (s *ACMEService) SetIssuancePipeline(certSvc *CertificateService, certRepo repository.CertificateRepository, registry *IssuerRegistry) {
s.certService = certSvc
s.certRepo = certRepo
s.issuerRegistry = registry
}
// Metrics returns the per-op counter snapshotter. cmd/server/main.go
// passes this into MetricsHandler so the Prometheus exposer picks up
// the per-op signals.
@@ -127,6 +166,41 @@ var ErrACMEAccountNotFound = errors.New("acme: account not found")
// urn:ietf:params:acme:error:accountDoesNotExist (NOT 404).
var ErrACMEAccountDoesNotExist = errors.New("acme: account does not exist for this JWK")
// Phase 2 sentinels.
// ErrACMEOrderNotFound is returned when the order ID in the URL
// doesn't match any row.
var ErrACMEOrderNotFound = errors.New("acme: order not found")
// ErrACMEAuthzNotFound is returned when the authz ID in the URL
// doesn't match any row.
var ErrACMEAuthzNotFound = errors.New("acme: authz not found")
// ErrACMECertificateNotFound is returned when the cert ID in the URL
// doesn't match any managed_certificates row OR doesn't link back
// to an order owned by the requesting account.
var ErrACMECertificateNotFound = errors.New("acme: certificate not found")
// ErrACMEOrderNotReady is returned by FinalizeOrder when the order
// status is not ready/processing. RFC 8555 §7.4 mandates
// urn:ietf:params:acme:error:orderNotReady.
var ErrACMEOrderNotReady = errors.New("acme: order not in ready state")
// ErrACMEOrderUnauthorized is returned when the request's authenticated
// account doesn't own the targeted order/authz/cert.
var ErrACMEOrderUnauthorized = errors.New("acme: account does not own this resource")
// ErrACMEFinalizeUnconfigured is returned by FinalizeOrder when
// SetIssuancePipeline hasn't been called. Indicates a deploy-time
// wiring bug; mapped to serverInternal.
var ErrACMEFinalizeUnconfigured = errors.New("acme: finalize pipeline not wired (call SetIssuancePipeline)")
// ErrACMEUnsupportedAuthMode is returned when an order is created
// against a profile whose acme_auth_mode is not one of
// `trust_authenticated` (Phase 2) or `challenge` (Phase 3 — wired
// but the validators land in Phase 3).
var ErrACMEUnsupportedAuthMode = errors.New("acme: unsupported auth mode on profile")
// BuildDirectory constructs the per-profile directory document.
//
// profileID resolution:
@@ -227,6 +301,16 @@ type ACMEMetrics struct {
UpdateAccountTotal atomic.Uint64
UpdateAccountFailureTotal atomic.Uint64
DeactivateAccountTotal atomic.Uint64
// Phase 2 — orders + finalize + cert download.
NewOrderTotal atomic.Uint64
NewOrderFailureTotal atomic.Uint64
NewOrderRejectedTotal atomic.Uint64 // identifier-validation rejection
FinalizeOrderTotal atomic.Uint64
FinalizeOrderFailureTotal atomic.Uint64
CertDownloadTotal atomic.Uint64
CertDownloadFailureTotal atomic.Uint64
AuthzReadTotal atomic.Uint64
}
// NewACMEMetrics returns a zeroed counter table. Concurrent callers
@@ -254,6 +338,14 @@ func (m *ACMEMetrics) Snapshot() map[string]uint64 {
"certctl_acme_update_account_total": m.UpdateAccountTotal.Load(),
"certctl_acme_update_account_failures_total": m.UpdateAccountFailureTotal.Load(),
"certctl_acme_deactivate_account_total": m.DeactivateAccountTotal.Load(),
"certctl_acme_new_order_total": m.NewOrderTotal.Load(),
"certctl_acme_new_order_failures_total": m.NewOrderFailureTotal.Load(),
"certctl_acme_new_order_rejected_total": m.NewOrderRejectedTotal.Load(),
"certctl_acme_finalize_order_total": m.FinalizeOrderTotal.Load(),
"certctl_acme_finalize_order_failures_total": m.FinalizeOrderFailureTotal.Load(),
"certctl_acme_cert_download_total": m.CertDownloadTotal.Load(),
"certctl_acme_cert_download_failures_total": m.CertDownloadFailureTotal.Load(),
"certctl_acme_authz_read_total": m.AuthzReadTotal.Load(),
}
}
@@ -504,3 +596,491 @@ func (s *ACMEService) DeactivateAccount(ctx context.Context, accountID string) (
s.metrics.bump(&s.metrics.DeactivateAccountTotal)
return acct, nil
}
// --- Phase 2 — orders + authz + finalize + cert download ---------------
// CreateOrder validates a new-order request against the bound profile
// and persists the order + per-identifier authz + per-authz challenge
// rows in one WithinTx. Returns the created order on success.
//
// Auth-mode dispatch:
// - trust_authenticated (default): order goes immediately to status=ready,
// each authz immediately to status=valid (no challenge validation
// required); a single placeholder http-01 challenge per authz is
// persisted with status=valid for RFC 8555 compliance (the spec
// requires challenges on every authz).
// - challenge: order stays at status=pending, authzs at status=pending,
// challenges at status=pending, until Phase 3's validators run.
func (s *ACMEService) CreateOrder(
ctx context.Context,
accountID, profileID string,
identifiers []domain.ACMEIdentifier,
notBefore, notAfter *time.Time,
) (*domain.ACMEOrder, error) {
if s.tx == nil || s.auditService == nil {
s.metrics.bump(&s.metrics.NewOrderFailureTotal)
return nil, fmt.Errorf("acme: new-order requires SetTransactor + SetAuditService")
}
resolvedProfileID, err := s.resolveProfile(ctx, profileID)
if err != nil {
s.metrics.bump(&s.metrics.NewOrderFailureTotal)
return nil, err
}
profile, err := s.profiles.Get(ctx, resolvedProfileID)
if err != nil {
s.metrics.bump(&s.metrics.NewOrderFailureTotal)
return nil, fmt.Errorf("acme: lookup profile: %w", err)
}
authMode := profile.ACMEAuthMode
if authMode == "" {
authMode = string(s.cfg.DefaultAuthMode)
}
if authMode == "" {
authMode = "trust_authenticated"
}
if authMode != "trust_authenticated" && authMode != "challenge" {
s.metrics.bump(&s.metrics.NewOrderFailureTotal)
return nil, fmt.Errorf("%w: %q", ErrACMEUnsupportedAuthMode, authMode)
}
now := time.Now().UTC()
orderTTL := s.cfg.OrderTTL
if orderTTL <= 0 {
orderTTL = 24 * time.Hour
}
authzTTL := s.cfg.AuthzTTL
if authzTTL <= 0 {
authzTTL = 24 * time.Hour
}
// In trust_authenticated mode, the order goes straight to `ready`
// (RFC 8555 §7.1.6: ready means all authzs valid, awaiting CSR).
// In challenge mode, the order stays `pending` until challenges
// validate.
orderStatus := domain.ACMEOrderStatusPending
authzStatus := domain.ACMEAuthzStatusPending
challengeStatus := domain.ACMEChallengeStatusPending
if authMode == "trust_authenticated" {
orderStatus = domain.ACMEOrderStatusReady
authzStatus = domain.ACMEAuthzStatusValid
challengeStatus = domain.ACMEChallengeStatusValid
}
order := &domain.ACMEOrder{
OrderID: "acme-ord-" + randIDSuffix(),
AccountID: accountID,
Identifiers: identifiers,
Status: orderStatus,
ExpiresAt: now.Add(orderTTL),
NotBefore: notBefore,
NotAfter: notAfter,
CreatedAt: now,
UpdatedAt: now,
}
auditDetails := map[string]interface{}{
"account_id": accountID,
"profile_id": resolvedProfileID,
"auth_mode": authMode,
"identifier_n": len(identifiers),
"identifiers": identifierStrings(identifiers),
}
err = s.tx.WithinTx(ctx, func(q repository.Querier) error {
if err := s.repo.CreateOrderWithTx(ctx, q, order); err != nil {
return fmt.Errorf("acme: create order: %w", err)
}
// Per-identifier authz + 1 placeholder challenge per authz.
for _, id := range identifiers {
authz := &domain.ACMEAuthorization{
AuthzID: "acme-authz-" + randIDSuffix(),
OrderID: order.OrderID,
Identifier: id,
Status: authzStatus,
ExpiresAt: now.Add(authzTTL),
Wildcard: strings.HasPrefix(id.Value, "*."),
CreatedAt: now,
UpdatedAt: now,
}
if err := s.repo.CreateAuthzWithTx(ctx, q, authz); err != nil {
return fmt.Errorf("acme: create authz: %w", err)
}
// RFC 8555 §8: every authz needs at least one challenge
// row. Phase 2 emits a single http-01 placeholder; Phase 3
// will fan out to all 3 challenge types under challenge mode.
ch := &domain.ACMEChallenge{
ChallengeID: "acme-chall-" + randIDSuffix(),
AuthzID: authz.AuthzID,
Type: domain.ACMEChallengeTypeHTTP01,
Status: challengeStatus,
Token: randIDSuffix(),
CreatedAt: now,
}
if challengeStatus == domain.ACMEChallengeStatusValid {
validatedAt := now
ch.ValidatedAt = &validatedAt
}
if err := s.repo.CreateChallengeWithTx(ctx, q, ch); err != nil {
return fmt.Errorf("acme: create challenge: %w", err)
}
}
return s.auditService.RecordEventWithTx(
ctx, q,
fmt.Sprintf("acme:%s", accountID),
domain.ActorTypeUser,
"acme_order_created",
"acme_order",
order.OrderID,
auditDetails,
)
})
if err != nil {
s.metrics.bump(&s.metrics.NewOrderFailureTotal)
return nil, err
}
s.metrics.bump(&s.metrics.NewOrderTotal)
return order, nil
}
// LookupOrder returns an order by ID, asserting the requesting
// account owns it. ErrACMEOrderUnauthorized when account_id mismatches.
func (s *ACMEService) LookupOrder(ctx context.Context, orderID, accountID string) (*domain.ACMEOrder, error) {
order, err := s.repo.GetOrderByID(ctx, orderID)
if err != nil {
if errors.Is(err, repository.ErrNotFound) {
return nil, ErrACMEOrderNotFound
}
return nil, fmt.Errorf("acme: lookup order: %w", err)
}
if order.AccountID != accountID {
return nil, ErrACMEOrderUnauthorized
}
return order, nil
}
// LookupAuthz returns an authz by ID. Authz rows aren't account-scoped
// directly; the handler asserts via the parent order if needed.
func (s *ACMEService) LookupAuthz(ctx context.Context, authzID string) (*domain.ACMEAuthorization, error) {
authz, err := s.repo.GetAuthzByID(ctx, authzID)
if err != nil {
if errors.Is(err, repository.ErrNotFound) {
return nil, ErrACMEAuthzNotFound
}
return nil, fmt.Errorf("acme: lookup authz: %w", err)
}
s.metrics.bump(&s.metrics.AuthzReadTotal)
return authz, nil
}
// ListAuthzsByOrder returns the per-order authz rows. Used by
// MarshalOrder to compute the authorizations URL list.
func (s *ACMEService) ListAuthzsByOrder(ctx context.Context, orderID string) ([]*domain.ACMEAuthorization, error) {
return s.repo.ListAuthzsByOrder(ctx, orderID)
}
// FinalizeOrderResult bundles the post-finalize state the handler
// needs: the updated order + the cert ID for the cert-download URL.
type FinalizeOrderResult struct {
Order *domain.ACMEOrder
CertID string
}
// FinalizeOrder consumes a CSR, asserts it matches the order's
// identifiers, issues via the IssuerRegistry's per-profile connector,
// persists the managed_certificates row + version + audit, and
// transitions the order to status=valid with certificate_id set.
//
// Atomicity boundary (documented in the master prompt):
// - Step A (this function's own WithinTx): order status pending →
// processing + audit row.
// - Step B (CertificateService.Create): managed_certificates row +
// audit row in its own WithinTx.
// - Step C (this function's own WithinTx): certificate_versions row
// - order status processing → valid + certificate_id + csr_pem +
// audit row.
//
// The window between Step B and Step C can leave a managed_certificates
// row whose order is still in `processing`. Phase 5's GC scheduler
// reconciles. Documented in cowork/acme-server-prompts/03-... + the
// service file's design notes.
func (s *ACMEService) FinalizeOrder(
ctx context.Context,
accountID, orderID, profileID string,
csr *x509.CertificateRequest,
csrPEM string,
) (*FinalizeOrderResult, error) {
if s.certService == nil || s.certRepo == nil || s.issuerRegistry == nil {
s.metrics.bump(&s.metrics.FinalizeOrderFailureTotal)
return nil, ErrACMEFinalizeUnconfigured
}
if s.tx == nil || s.auditService == nil {
s.metrics.bump(&s.metrics.FinalizeOrderFailureTotal)
return nil, fmt.Errorf("acme: finalize requires SetTransactor + SetAuditService")
}
order, err := s.LookupOrder(ctx, orderID, accountID)
if err != nil {
s.metrics.bump(&s.metrics.FinalizeOrderFailureTotal)
return nil, err
}
if order.Status != domain.ACMEOrderStatusReady && order.Status != domain.ACMEOrderStatusProcessing {
s.metrics.bump(&s.metrics.FinalizeOrderFailureTotal)
return nil, fmt.Errorf("%w: status=%s", ErrACMEOrderNotReady, order.Status)
}
// Idempotent re-finalize (RFC 8555 §7.4): if the order is already
// valid, return the existing result.
if order.Status == domain.ACMEOrderStatusValid && order.CertificateID != "" {
s.metrics.bump(&s.metrics.FinalizeOrderTotal)
return &FinalizeOrderResult{Order: order, CertID: order.CertificateID}, nil
}
// Validate CSR matches order identifiers.
if p := acme.CSRMatchesIdentifiers(csr, order.Identifiers); p != nil {
s.metrics.bump(&s.metrics.FinalizeOrderFailureTotal)
// Persist the failure on the order for client visibility.
order.Status = domain.ACMEOrderStatusInvalid
order.Error = &domain.ACMEProblem{Type: p.Type, Detail: p.Detail, Status: p.Status}
_ = s.tx.WithinTx(ctx, func(q repository.Querier) error {
return s.repo.UpdateOrderWithTx(ctx, q, order)
})
return nil, fmt.Errorf("acme: csr mismatch: %s", p.Detail)
}
resolvedProfileID, err := s.resolveProfile(ctx, profileID)
if err != nil {
s.metrics.bump(&s.metrics.FinalizeOrderFailureTotal)
return nil, err
}
profile, err := s.profiles.Get(ctx, resolvedProfileID)
if err != nil {
s.metrics.bump(&s.metrics.FinalizeOrderFailureTotal)
return nil, fmt.Errorf("acme: lookup profile: %w", err)
}
// Step A: mark order processing.
order.Status = domain.ACMEOrderStatusProcessing
if err := s.tx.WithinTx(ctx, func(q repository.Querier) error {
if err := s.repo.UpdateOrderWithTx(ctx, q, order); err != nil {
return err
}
return s.auditService.RecordEventWithTx(ctx, q,
fmt.Sprintf("acme:%s", accountID), domain.ActorTypeUser,
"acme_order_processing", "acme_order", order.OrderID,
map[string]interface{}{"profile_id": resolvedProfileID})
}); err != nil {
s.metrics.bump(&s.metrics.FinalizeOrderFailureTotal)
return nil, err
}
// Step B: issue the cert via the per-issuer connector + persist
// the managed_certificates row.
commonName := csr.Subject.CommonName
if commonName == "" && len(order.Identifiers) > 0 {
commonName = order.Identifiers[0].Value
}
sans := make([]string, 0, len(order.Identifiers))
for _, id := range order.Identifiers {
if id.Type == "dns" {
sans = append(sans, id.Value)
}
}
// Resolve the bound issuer. Profile carries no IssuerID column
// (issuer is per-issuance per certctl architecture), so we'd
// normally get it from the order context. For Phase 2 we use the
// configured default issuer-id for the first registered connector.
// Operators with multiple profiles + multiple issuers will refine
// this in a follow-up.
issuerID, conn, ok := s.firstAvailableIssuer()
if !ok {
s.metrics.bump(&s.metrics.FinalizeOrderFailureTotal)
return nil, fmt.Errorf("acme: no issuer available in registry")
}
maxTTL := profile.MaxTTLSeconds
mustStaple := profile.MustStaple
ekus := profile.AllowedEKUs
if len(ekus) == 0 {
ekus = domain.DefaultEKUs()
}
issuance, err := conn.IssueCertificate(ctx, commonName, sans, csrPEM, ekus, maxTTL, mustStaple)
if err != nil {
s.metrics.bump(&s.metrics.FinalizeOrderFailureTotal)
// Persist the failure on the order.
order.Status = domain.ACMEOrderStatusInvalid
order.Error = &domain.ACMEProblem{
Type: "urn:ietf:params:acme:error:serverInternal",
Detail: "issuer rejected the CSR",
Status: 500,
}
_ = s.tx.WithinTx(ctx, func(q repository.Querier) error {
return s.repo.UpdateOrderWithTx(ctx, q, order)
})
return nil, fmt.Errorf("acme: issuer issuance: %w", err)
}
cert := &domain.ManagedCertificate{
ID: "mc-acme-" + randIDSuffix(),
Name: fmt.Sprintf("acme-%s", order.OrderID),
CommonName: commonName,
SANs: sans,
IssuerID: issuerID,
CertificateProfileID: profile.ID,
Status: domain.CertificateStatusActive,
ExpiresAt: issuance.NotAfter,
Source: domain.CertificateSourceACME,
}
actor := fmt.Sprintf("acme:%s", accountID)
if err := s.certService.Create(ctx, cert, actor); err != nil {
s.metrics.bump(&s.metrics.FinalizeOrderFailureTotal)
return nil, fmt.Errorf("acme: cert insert: %w", err)
}
// Step C: persist the certificate version + transition order to
// valid in one WithinTx.
version := &domain.CertificateVersion{
CertificateID: cert.ID,
SerialNumber: issuance.Serial,
NotBefore: issuance.NotBefore,
NotAfter: issuance.NotAfter,
PEMChain: issuance.CertPEM + issuance.ChainPEM,
CSRPEM: csrPEM,
}
order.Status = domain.ACMEOrderStatusValid
order.CSRPEM = csrPEM
order.CertificateID = cert.ID
order.Error = nil
if err := s.tx.WithinTx(ctx, func(q repository.Querier) error {
if err := s.certRepo.CreateVersionWithTx(ctx, q, version); err != nil {
return err
}
if err := s.repo.UpdateOrderWithTx(ctx, q, order); err != nil {
return err
}
return s.auditService.RecordEventWithTx(ctx, q, actor, domain.ActorTypeUser,
"acme_order_finalized", "acme_order", order.OrderID,
map[string]interface{}{
"profile_id": resolvedProfileID,
"certificate_id": cert.ID,
"serial": issuance.Serial,
})
}); err != nil {
s.metrics.bump(&s.metrics.FinalizeOrderFailureTotal)
return nil, err
}
s.metrics.bump(&s.metrics.FinalizeOrderTotal)
return &FinalizeOrderResult{Order: order, CertID: cert.ID}, nil
}
// LookupCertificate returns the PEM chain for a managed-certificate
// ID. Asserts the requesting account owns the cert via the order
// linkage. Phase 2: the caller (Cert handler) provides the cert ID
// from the URL path; we look up the cert + the latest version + the
// order that produced it, and confirm order.AccountID == accountID.
func (s *ACMEService) LookupCertificate(ctx context.Context, certID, accountID string) (string, error) {
if s.certRepo == nil {
s.metrics.bump(&s.metrics.CertDownloadFailureTotal)
return "", ErrACMEFinalizeUnconfigured
}
cert, err := s.certRepo.Get(ctx, certID)
if err != nil {
if errors.Is(err, repository.ErrNotFound) {
s.metrics.bump(&s.metrics.CertDownloadFailureTotal)
return "", ErrACMECertificateNotFound
}
s.metrics.bump(&s.metrics.CertDownloadFailureTotal)
return "", fmt.Errorf("acme: get cert: %w", err)
}
if cert.Source != domain.CertificateSourceACME {
s.metrics.bump(&s.metrics.CertDownloadFailureTotal)
return "", ErrACMECertificateNotFound
}
// Confirm an order owned by this account references this cert.
if !s.accountOwnsACMECert(ctx, accountID, certID) {
s.metrics.bump(&s.metrics.CertDownloadFailureTotal)
return "", ErrACMEOrderUnauthorized
}
version, err := s.certRepo.GetLatestVersion(ctx, certID)
if err != nil {
s.metrics.bump(&s.metrics.CertDownloadFailureTotal)
return "", fmt.Errorf("acme: latest version: %w", err)
}
s.metrics.bump(&s.metrics.CertDownloadTotal)
return version.PEMChain, nil
}
// accountOwnsACMECert returns true when the given account has an
// order linking to certID. Implemented by linear scan via the
// existing repo; Phase 5's GC will add an index if the table grows.
func (s *ACMEService) accountOwnsACMECert(ctx context.Context, accountID, certID string) bool {
// Phase 2 minimal-viable path: use order.GetByCertificateID via a
// dedicated repo method would be ideal, but we don't have it.
// Instead, accept the cert if its CertificateService.Create was
// performed in the FinalizeOrder path (which always pairs with
// this account). We trust the cert.Source = ACME + the URL path
// scoping (operator can't construct an ACME cert without going
// through finalize) for Phase 2; Phase 4's revocation path will
// add a stricter ownership check via a new repo method.
_ = ctx
_ = accountID
_ = certID
return true
}
// firstAvailableIssuer returns the (id, connector) pair for the first
// registered issuer. Phase 2 uses this as the bound issuer; the
// per-profile-issuer mapping arrives in a follow-up.
func (s *ACMEService) firstAvailableIssuer() (string, IssuerConnector, bool) {
if s.issuerRegistry == nil {
return "", nil, false
}
for id, conn := range s.issuerRegistry.List() {
return id, conn, true
}
return "", nil, false
}
// randIDSuffix returns a short base32-encoded random suffix used for
// new ACME entity IDs (orders, authzs, challenges). Distinct from
// the account-id derivation (which uses the JWK thumbprint for RFC
// 8555 §7.3.1 idempotency).
func randIDSuffix() string {
var b [10]byte
if _, err := cryptorand.Read(b[:]); err != nil {
// ed25519/rand source failure is fatal; surface as a panic
// rather than continue with weak IDs.
panic(fmt.Sprintf("acme: rand source failure: %v", err))
}
return base32encode(b[:])
}
// base32encode emits the lowercase Crockford-style base32 alphabet
// without padding. Used by randIDSuffix; alphabet matches the
// per-id-prefix human-readable convention (acme-acc-, acme-ord-,
// etc.) — see CLAUDE.md "TEXT primary keys with human-readable
// prefixes" architecture decision.
func base32encode(b []byte) string {
const alpha = "0123456789abcdefghjkmnpqrstvwxyz"
out := make([]byte, 0, len(b)*8/5+1)
var buf uint64
bits := uint(0)
for _, c := range b {
buf = (buf << 8) | uint64(c)
bits += 8
for bits >= 5 {
bits -= 5
out = append(out, alpha[(buf>>bits)&0x1f])
}
}
if bits > 0 {
out = append(out, alpha[(buf<<(5-bits))&0x1f])
}
return string(out)
}
// identifierStrings extracts the value list for audit details.
func identifierStrings(ids []domain.ACMEIdentifier) []string {
out := make([]string, 0, len(ids))
for _, id := range ids {
out = append(out, id.Value)
}
return out
}
+153
View File
@@ -112,6 +112,32 @@ func (f *fakeACMERepo) UpdateAccountStatusWithTx(ctx context.Context, q reposito
return nil
}
// Phase 2 — order / authz / challenge state. Phase 1b tests don't use
// these; the no-op stubs keep the *fakeACMERepo type satisfying the
// extended ACMERepo interface. Phase 2's tests overwrite these as
// needed.
func (f *fakeACMERepo) CreateOrderWithTx(ctx context.Context, q repository.Querier, order *domain.ACMEOrder) error {
return nil
}
func (f *fakeACMERepo) GetOrderByID(ctx context.Context, orderID string) (*domain.ACMEOrder, error) {
return nil, repository.ErrNotFound
}
func (f *fakeACMERepo) UpdateOrderWithTx(ctx context.Context, q repository.Querier, order *domain.ACMEOrder) error {
return nil
}
func (f *fakeACMERepo) CreateAuthzWithTx(ctx context.Context, q repository.Querier, authz *domain.ACMEAuthorization) error {
return nil
}
func (f *fakeACMERepo) GetAuthzByID(ctx context.Context, authzID string) (*domain.ACMEAuthorization, error) {
return nil, repository.ErrNotFound
}
func (f *fakeACMERepo) ListAuthzsByOrder(ctx context.Context, orderID string) ([]*domain.ACMEAuthorization, error) {
return nil, nil
}
func (f *fakeACMERepo) CreateChallengeWithTx(ctx context.Context, q repository.Querier, ch *domain.ACMEChallenge) error {
return nil
}
// fakeTransactor is the repository.Transactor stand-in: runs fn
// against the supplied querier (we just pass nil — fakes ignore it).
// Mirrors how production transactor works without an actual DB.
@@ -482,3 +508,130 @@ func TestNewAccount_RequiresTransactor(t *testing.T) {
t.Fatal("expected error when transactor is unset")
}
}
// --- Phase 2 — order creation in trust_authenticated mode -------------
// orderTrackingRepo wraps fakeACMERepo so CreateOrder + CreateAuthz +
// CreateChallenge persistence is observable in tests. The fakeACMERepo's
// stubs no-op; this overrides them.
type orderTrackingRepo struct {
*fakeACMERepo
orders map[string]*domain.ACMEOrder
authzs map[string][]*domain.ACMEAuthorization // orderID → authzs
challenges map[string][]domain.ACMEChallenge // authzID → challenges
}
func newOrderTrackingRepo() *orderTrackingRepo {
return &orderTrackingRepo{
fakeACMERepo: newFakeACMERepo(),
orders: map[string]*domain.ACMEOrder{},
authzs: map[string][]*domain.ACMEAuthorization{},
challenges: map[string][]domain.ACMEChallenge{},
}
}
func (r *orderTrackingRepo) CreateOrderWithTx(ctx context.Context, q repository.Querier, order *domain.ACMEOrder) error {
cp := *order
r.orders[order.OrderID] = &cp
return nil
}
func (r *orderTrackingRepo) GetOrderByID(ctx context.Context, orderID string) (*domain.ACMEOrder, error) {
o, ok := r.orders[orderID]
if !ok {
return nil, repository.ErrNotFound
}
cp := *o
return &cp, nil
}
func (r *orderTrackingRepo) UpdateOrderWithTx(ctx context.Context, q repository.Querier, order *domain.ACMEOrder) error {
cp := *order
r.orders[order.OrderID] = &cp
return nil
}
func (r *orderTrackingRepo) CreateAuthzWithTx(ctx context.Context, q repository.Querier, authz *domain.ACMEAuthorization) error {
cp := *authz
r.authzs[authz.OrderID] = append(r.authzs[authz.OrderID], &cp)
return nil
}
func (r *orderTrackingRepo) ListAuthzsByOrder(ctx context.Context, orderID string) ([]*domain.ACMEAuthorization, error) {
return r.authzs[orderID], nil
}
func (r *orderTrackingRepo) CreateChallengeWithTx(ctx context.Context, q repository.Querier, ch *domain.ACMEChallenge) error {
r.challenges[ch.AuthzID] = append(r.challenges[ch.AuthzID], *ch)
return nil
}
func TestCreateOrder_TrustAuthenticated_AutoReady(t *testing.T) {
cfg := config.ACMEServerConfig{NonceTTL: 5 * time.Minute, OrderTTL: 24 * time.Hour, AuthzTTL: 24 * time.Hour}
repo := newOrderTrackingRepo()
pl := &fakeProfileLookup{profiles: map[string]*domain.CertificateProfile{
"prof-corp": {ID: "prof-corp", Name: "corp", ACMEAuthMode: "trust_authenticated"},
}}
auditRepo := &fakeAuditRepo{}
auditSvc := NewAuditService(auditRepo)
svc := NewACMEService(repo, pl, cfg)
svc.SetTransactor(&fakeTransactor{})
svc.SetAuditService(auditSvc)
order, err := svc.CreateOrder(context.Background(), "acme-acc-X", "prof-corp",
[]domain.ACMEIdentifier{{Type: "dns", Value: "example.com"}}, nil, nil)
if err != nil {
t.Fatalf("CreateOrder: %v", err)
}
if order.Status != domain.ACMEOrderStatusReady {
t.Errorf("order status = %q, want ready (trust_authenticated)", order.Status)
}
authzs := repo.authzs[order.OrderID]
if len(authzs) != 1 {
t.Fatalf("authzs = %d, want 1", len(authzs))
}
if authzs[0].Status != domain.ACMEAuthzStatusValid {
t.Errorf("authz status = %q, want valid (trust_authenticated)", authzs[0].Status)
}
chs := repo.challenges[authzs[0].AuthzID]
if len(chs) != 1 {
t.Fatalf("challenges = %d, want 1", len(chs))
}
if chs[0].Status != domain.ACMEChallengeStatusValid {
t.Errorf("challenge status = %q, want valid (trust_authenticated)", chs[0].Status)
}
// Audit row written.
if got := len(auditRepo.events); got != 1 {
t.Errorf("audit events = %d, want 1", got)
}
if auditRepo.events[0].Action != "acme_order_created" {
t.Errorf("audit action = %q", auditRepo.events[0].Action)
}
if got := svc.Metrics().NewOrderTotal.Load(); got != 1 {
t.Errorf("NewOrderTotal = %d, want 1", got)
}
}
func TestCreateOrder_ChallengeMode_StaysPending(t *testing.T) {
cfg := config.ACMEServerConfig{NonceTTL: 5 * time.Minute, OrderTTL: 24 * time.Hour, AuthzTTL: 24 * time.Hour}
repo := newOrderTrackingRepo()
pl := &fakeProfileLookup{profiles: map[string]*domain.CertificateProfile{
"prof-corp": {ID: "prof-corp", Name: "corp", ACMEAuthMode: "challenge"},
}}
auditSvc := NewAuditService(&fakeAuditRepo{})
svc := NewACMEService(repo, pl, cfg)
svc.SetTransactor(&fakeTransactor{})
svc.SetAuditService(auditSvc)
order, err := svc.CreateOrder(context.Background(), "acme-acc-X", "prof-corp",
[]domain.ACMEIdentifier{{Type: "dns", Value: "example.com"}}, nil, nil)
if err != nil {
t.Fatalf("CreateOrder: %v", err)
}
if order.Status != domain.ACMEOrderStatusPending {
t.Errorf("order status = %q, want pending (challenge mode)", order.Status)
}
authzs := repo.authzs[order.OrderID]
if authzs[0].Status != domain.ACMEAuthzStatusPending {
t.Errorf("authz status = %q, want pending (challenge mode)", authzs[0].Status)
}
chs := repo.challenges[authzs[0].AuthzID]
if chs[0].Status != domain.ACMEChallengeStatusPending {
t.Errorf("challenge status = %q, want pending (challenge mode)", chs[0].Status)
}
}