acme-server: key rollover + revocation + ARI (Phase 4/7)

Closes the RFC 8555 + RFC 9773 surface beyond the issuance happy-path:
  - POST /acme/profile/<id>/key-change   (RFC 8555 §7.3.5)
  - POST /acme/profile/<id>/revoke-cert  (RFC 8555 §7.6)
  - GET  /acme/profile/<id>/renewal-info/<cert-id>  (RFC 9773 ARI)

After this commit, ACME clients can rotate account keys, revoke certs
through the ACME surface (rather than only via the certctl GUI/API),
and fetch ARI for proactive renewal scheduling.

Architecture:
  - Key rollover: outer JWS verified against the registered account key
    (existing kid path); the inner JWS — embedded as the outer's payload
    — verified against the embedded NEW jwk in a new dedicated routine
    (ParseAndVerifyKeyChangeInner) that enforces RFC 8555 §7.3.5
    inner-only invariants: MUST use jwk + MUST NOT use kid, payload
    .account == outer.kid, payload.oldKey thumbprint-equals registered.
    A single WithinTx swaps the stored thumbprint+pem and writes the
    audit row. Concurrent-rollover safety via SELECT…FOR UPDATE on the
    conflicting account row in UpdateAccountJWKWithTx; the loser
    observes the winner's new thumbprint and is told to retry (409).
  - Revocation: two auth paths. kid → AccountOwnsCertificate single-
    indexed COUNT lookup over acme_orders. jwk → constant-time RFC 7638
    thumbprint compare against the cert's pubkey. Both paths route
    through service.RevocationSvc.RevokeCertificateWithActor so the
    existing CRL/OCSP refresh + audit + metrics pipeline applies. RFC
    5280 §5.3.1 numeric reason codes clamp to certctl's
    domain.ValidRevocationReasons; codes 8 (removeFromCRL) + 10
    (aACompromise) clamp to 'unspecified' since they aren't in the set.
  - ARI is GET-only and unauth per RFC 9773 §4. Cert-id wire shape is
    base64url(AKI).base64url(serial); ParseARICertID strict-decodes,
    SerialHex emits the canonical certctl-shape lowercase-no-leading-
    zeros hex used in certificate_versions.serial_number.
    ComputeRenewalWindow has 3 branches: bound RenewalPolicy →
    [notAfter - days, notAfter - days/2]; no policy → last 33% of
    validity; past expiry → [now, now + 1d] (renew immediately).
    Retry-After honors CERTCTL_ACME_SERVER_ARI_POLL_INTERVAL.

What ships:
  - internal/api/acme/{keychange,ari}.go (+ phase4_test.go: 15 tests).
  - internal/api/acme/order.go: RevokeCertRequest wire shape.
  - internal/api/handler/acme.go: KeyChange, RevokeCert, RenewalInfo
    + 11 new writeServiceError mappings.
  - internal/repository/postgres/acme.go: UpdateAccountJWKWithTx (FOR
    UPDATE + expectedOldThumbprint precondition; ErrACMEAccountKey-
    ConcurrentUpdate sentinel) + AccountOwnsCertificate.
  - internal/service/acme.go: RotateAccountKey + RevokeCert +
    RenewalInfo; CertificateRevoker + RenewalPolicyLookup interfaces;
    SetRevocationDelegate + SetRenewalPolicyLookup wiring; 11 new
    sentinels; 6 new metrics.
  - internal/service/acme_phase4_test.go: service-layer tests for
    RotateAccountKey (happy + duplicate-key) + RevokeCert (kid mismatch
    + jwk mismatch + jwk happy + already-revoked + reason-clamping) +
    RenewalInfo (disabled + bad cert-id).
  - internal/api/router/router.go: 6 new register calls (3 per-profile
    + 3 shorthand). Router parity exceptions extended in lockstep
    (in-tree SpecParityExceptions + CI-only openapi-handler-exceptions
    .yaml).
  - cmd/server/main.go: SetRevocationDelegate(revocationSvc) +
    SetRenewalPolicyLookup(renewalPolicyRepo) at startup.
  - internal/config/config.go: CERTCTL_ACME_SERVER_ARI_ENABLED (default
    true) + CERTCTL_ACME_SERVER_ARI_POLL_INTERVAL (default 6h);
    BuildDirectory's ariEnabled flag now flips on under
    cfg.ARIEnabled.
  - docs/acme-server.md: phase status flipped to Phase 4; endpoints
    table grows 6 rows (3 per-profile + 3 shorthand); FAQ section
    appended explaining how to rotate keys, revoke certs, and consume
    ARI.

Tests:
  - 'go vet ./...' clean across the repo.
  - 'go test -short -count=1 ./...' green across every package.
  - phase4_test.go covers: keychange happy-path + 5 negatives +
    MapKeyChangeErrorToProblem coverage; ARI cert-id round-trip + 6
    malformed cases + BuildARICertID from a generated cert; window-
    math 3 branches.
  - service-layer tests confirm: RotateAccountKey atomically swaps the
    thumbprint (verifies persisted state) and rejects duplicate keys;
    RevokeCert routes through the stub RevocationSvc with the right
    actor string + reason on the jwk path, rejects mismatched keys,
    rejects already-revoked certs, clamps reason codes correctly;
    RenewalInfo respects ARIEnabled + cert-id format.

Engineering history: cowork/WORKSPACE-CHANGELOG.md 'ACME-Server-4'.
This commit is contained in:
shankar0123
2026-05-03 16:51:06 +00:00
parent 62513ad12f
commit 4dc8d3fa5b
16 changed files with 2210 additions and 17 deletions
+224
View File
@@ -0,0 +1,224 @@
// Copyright (c) certctl
// SPDX-License-Identifier: BSL-1.1
package acme
import (
"crypto/x509"
"encoding/base64"
"encoding/hex"
"encoding/pem"
"errors"
"fmt"
"math/big"
"strings"
"time"
"github.com/shankar0123/certctl/internal/domain"
)
// Phase 4 — RFC 9773 ACME Renewal Information.
//
// RFC 9773 §4.1: a client computes the cert-id as
//
// base64url-no-pad(authorityKeyIdentifier) || "." || base64url-no-pad(serial)
//
// and GETs /acme/.../renewal-info/<cert-id>. The server responds with a
// JSON document carrying a `suggestedWindow` (start, end) the client
// SHOULD plan its renewal inside, plus an optional `explanationURL`.
// Response also carries a Retry-After header (RFC 9773 §4.2) hinting
// at the next-poll cadence.
//
// This file:
//
// - parses the cert-id wire format → (akiBytes, serialBytes).
// - converts the serial bytes to a hex string in the canonical
// certctl shape (lowercase, no leading zeros, matching how
// internal/repository/postgres/certificate.go stores them).
// - computes the suggested-window from a cert's NotAfter and an
// optional bound RenewalPolicy (last 33% of validity if no policy
// is bound).
// RenewalInfoResponse is the JSON document returned by the renewal-
// info endpoint per RFC 9773 §4.1.
type RenewalInfoResponse struct {
SuggestedWindow RenewalWindow `json:"suggestedWindow"`
ExplanationURL string `json:"explanationURL,omitempty"`
}
// RenewalWindow is the embedded {start, end} pair. RFC 9773 mandates
// start ≤ end; the server is responsible for emitting RFC 3339 UTC
// timestamps.
type RenewalWindow struct {
Start time.Time `json:"start"`
End time.Time `json:"end"`
}
// ARICertID is the parsed shape of an RFC 9773 §4.1 cert-id —
// authorityKeyIdentifier and serial bytes after base64url-no-pad
// decoding. Callers compare against the certificate they already have
// in the database; AKI is informational on the server side because
// certctl's serial-uniqueness invariant is per-issuer.
type ARICertID struct {
// AKI is the raw bytes of the certificate's authorityKeyIdentifier
// extension.
AKI []byte
// Serial is the raw bytes of the certificate's serial number, in
// big-endian unsigned-integer form.
Serial []byte
}
// SerialHex returns the canonical certctl-shape hex representation of
// the serial number — lowercase, no leading zeros (matches what's
// stored in certificate_versions.serial_number).
func (a ARICertID) SerialHex() string {
if len(a.Serial) == 0 {
return ""
}
n := new(big.Int).SetBytes(a.Serial)
if n.Sign() == 0 {
return "0"
}
return strings.ToLower(n.Text(16))
}
// AKIHex returns the AKI as a lowercase hex string. Useful for logging
// + future per-AKI lookup paths.
func (a ARICertID) AKIHex() string {
return strings.ToLower(hex.EncodeToString(a.AKI))
}
// Sentinel errors. ChooseProblem in writeServiceError translates the
// not-found cases to RFC 7807 + RFC 8555 §6.7 problems.
var (
ErrARICertIDMalformed = errors.New("acme ari: cert-id is not <aki>.<serial>")
ErrARICertIDDecodeAKI = errors.New("acme ari: cert-id AKI is not valid base64url")
ErrARICertIDDecodeSeria = errors.New("acme ari: cert-id serial is not valid base64url")
ErrARICertIDEmpty = errors.New("acme ari: cert-id has empty AKI or serial")
)
// ParseARICertID decodes an RFC 9773 §4.1 cert-id. The wire format is
// strictly base64url-NO-PADDING; rfc9773 §4.1 forbids regular base64.
//
// Common malformations:
// - missing or extra `.` separator → ErrARICertIDMalformed.
// - either side fails base64url decode → ErrARICertIDDecode*.
// - either side decodes to empty → ErrARICertIDEmpty.
func ParseARICertID(certID string) (*ARICertID, error) {
parts := strings.Split(certID, ".")
if len(parts) != 2 {
return nil, fmt.Errorf("%w: got %d parts", ErrARICertIDMalformed, len(parts))
}
if parts[0] == "" || parts[1] == "" {
return nil, ErrARICertIDEmpty
}
aki, err := base64.RawURLEncoding.DecodeString(parts[0])
if err != nil {
return nil, fmt.Errorf("%w: %v", ErrARICertIDDecodeAKI, err)
}
serial, err := base64.RawURLEncoding.DecodeString(parts[1])
if err != nil {
return nil, fmt.Errorf("%w: %v", ErrARICertIDDecodeSeria, err)
}
if len(aki) == 0 || len(serial) == 0 {
return nil, ErrARICertIDEmpty
}
return &ARICertID{AKI: aki, Serial: serial}, nil
}
// BuildARICertID is the inverse of ParseARICertID — useful for tests
// and operator tools that want to construct a cert-id from a leaf cert.
//
// The input is the leaf certificate's PEM. We extract the
// authorityKeyIdentifier extension and the serial number, then
// base64url-no-pad-encode each + join with a `.`.
func BuildARICertID(certPEM string) (string, error) {
block, _ := pem.Decode([]byte(certPEM))
if block == nil {
return "", fmt.Errorf("acme ari: pem decode failed")
}
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
return "", fmt.Errorf("acme ari: parse cert: %w", err)
}
if len(cert.AuthorityKeyId) == 0 {
return "", fmt.Errorf("acme ari: certificate has no authorityKeyIdentifier extension")
}
if cert.SerialNumber == nil {
return "", fmt.Errorf("acme ari: certificate has no serial number")
}
akiB64 := base64.RawURLEncoding.EncodeToString(cert.AuthorityKeyId)
serialB64 := base64.RawURLEncoding.EncodeToString(cert.SerialNumber.Bytes())
return akiB64 + "." + serialB64, nil
}
// ComputeRenewalWindow returns the RFC 9773 suggestedWindow for a
// (cert, optional renewal-policy) pair.
//
// Algorithm:
//
// - When policy is non-nil and policy.RenewalWindowDays > 0: the
// window starts at NotAfter - RenewalWindowDays + spans half of
// RenewalWindowDays. So a 30-day-renewal-window cert with NotAfter
// 2026-06-30 emits start=2026-05-31, end=2026-06-15. This matches
// boulder's default ARI behavior + ensures a Let's-Encrypt-shaped
// client can plan its renewals exactly inside our renewal window.
// - When policy is nil OR RenewalWindowDays ≤ 0: the window is the
// last 33% of validity. So a cert with NotBefore 2026-01-01 +
// NotAfter 2026-04-01 (90d validity) emits start=2026-03-01 (30d
// before expiry), end=2026-03-21 (10d before expiry).
// - When the cert is past NotAfter: the window starts at "now" and
// ends at "now + 1 day" so a client polling on an expired cert
// gets a "renew immediately" answer rather than a window in the
// past.
//
// Returns (start, end). start ≤ end is invariant.
func ComputeRenewalWindow(cert *domain.ManagedCertificate, version *domain.CertificateVersion, policy *domain.RenewalPolicy, now time.Time) (time.Time, time.Time) {
if cert == nil {
return time.Time{}, time.Time{}
}
notAfter := cert.ExpiresAt.UTC()
notBefore := notAfter
if version != nil && !version.NotBefore.IsZero() {
notBefore = version.NotBefore.UTC()
}
// Past expiry: emit a 1-day "renew now" window.
if !now.IsZero() && now.UTC().After(notAfter) {
nowUTC := now.UTC()
return nowUTC, nowUTC.Add(24 * time.Hour)
}
if policy != nil && policy.RenewalWindowDays > 0 {
windowDays := time.Duration(policy.RenewalWindowDays) * 24 * time.Hour
start := notAfter.Add(-windowDays)
end := start.Add(windowDays / 2)
// Defensive: never emit start in the past from "now".
if !now.IsZero() && start.Before(now.UTC()) {
start = now.UTC()
}
if end.Before(start) {
end = start
}
return start, end
}
// No policy → last 33% of validity.
validity := notAfter.Sub(notBefore)
if validity <= 0 {
// Degenerate cert (nb >= na). Use a 1-day default window
// ending at notAfter.
return notAfter.Add(-24 * time.Hour), notAfter
}
thirty3 := validity / 3
start := notAfter.Add(-thirty3)
// End is 1/3 before expiry → midpoint of the renewal third.
end := notAfter.Add(-thirty3 / 3)
if !now.IsZero() && start.Before(now.UTC()) {
start = now.UTC()
}
if end.Before(start) {
end = start
}
return start, end
}
+272
View File
@@ -0,0 +1,272 @@
// Copyright (c) certctl
// SPDX-License-Identifier: BSL-1.1
package acme
import (
"crypto/subtle"
"encoding/json"
"errors"
"fmt"
jose "github.com/go-jose/go-jose/v4"
)
// Phase 4 — RFC 8555 §7.3.5 key rollover.
//
// The wire shape is a doubly-signed JWS:
//
// JWS-outer signed by the OLD account key (kid = account URL):
// protected: { alg, kid, nonce, url }
// payload: <JWS-inner-as-bytes>
//
// JWS-inner signed by the NEW account key (jwk = newkey):
// protected: { alg, jwk, url=<same key-change URL> }
// payload: { account: <kid-URL>, oldKey: <OLD JWK> }
//
// The handler runs the existing VerifyJWS pipeline against the outer
// (kid path), then hands the resulting Payload bytes to ParseAndVerify-
// KeyChangeInner so the inner is processed in isolation. Two key
// distinctions vs. the outer:
//
// - The inner JWS does NOT carry a `nonce` header. Per RFC 8555 §7.3.5
// the outer's nonce is the only nonce; the inner is a self-contained
// proof-of-possession blob.
// - The inner JWS uses `jwk` not `kid` and the verifier must succeed
// when the embedded `jwk` itself is the verification key.
//
// This matches what go-jose's lego implementation, cert-manager, and
// boulder all expect.
// KeyChangeInnerPayload is the parsed body of the inner JWS — RFC 8555
// §7.3.5 mandates exactly two fields.
type KeyChangeInnerPayload struct {
// Account is the kid URL of the account whose key is being rotated.
// MUST equal the outer's `kid` header. Mismatch → keyChange's
// "account" field doesn't match outer.kid.
Account string `json:"account"`
// OldKey is the JWK currently on file for the account. The server
// asserts this matches what we have in the database (byte-equal
// canonicalized) so a stale rollover request can't slip through.
OldKey *jose.JSONWebKey `json:"oldKey"`
}
// KeyChangeInner is the verified inner JWS — fields the service layer
// needs to commit the rollover.
type KeyChangeInner struct {
// NewJWK is the JWK the inner JWS is signed by. After verification
// this is the key the account's row will be updated to.
NewJWK *jose.JSONWebKey
// Payload is the inner's parsed JSON: { account, oldKey }.
Payload KeyChangeInnerPayload
// URL is the inner protected-header `url` value, asserted equal to
// the outer's URL.
URL string
// Algorithm is the negotiated alg the inner was signed with.
Algorithm string
}
// Sentinel errors. Each maps to an RFC 8555 §6.7 problem type via the
// service's writeServiceError; tests assert via errors.Is.
var (
ErrKeyChangeInnerMalformed = errors.New("acme keychange: inner JWS malformed")
ErrKeyChangeInnerAlgRejected = errors.New("acme keychange: inner JWS uses disallowed signature algorithm")
ErrKeyChangeInnerMissingJWK = errors.New("acme keychange: inner JWS protected header MUST contain `jwk`")
ErrKeyChangeInnerForbidsKID = errors.New("acme keychange: inner JWS MUST NOT contain `kid` (use `jwk`)")
ErrKeyChangeInnerInvalidJWK = errors.New("acme keychange: inner JWS embedded JWK is invalid")
ErrKeyChangeInnerURLMissing = errors.New("acme keychange: inner JWS protected header `url` is required")
ErrKeyChangeInnerURLMismatch = errors.New("acme keychange: inner JWS `url` does not match outer JWS `url`")
ErrKeyChangeInnerSignatureBad = errors.New("acme keychange: inner JWS signature did not verify against embedded JWK")
ErrKeyChangeInnerPayloadParse = errors.New("acme keychange: inner JWS payload is not parseable JSON")
ErrKeyChangeInnerAccountMismatch = errors.New("acme keychange: inner JWS payload `account` does not match outer JWS `kid`")
ErrKeyChangeInnerOldKeyMissing = errors.New("acme keychange: inner JWS payload missing `oldKey`")
ErrKeyChangeInnerOldKeyMismatch = errors.New("acme keychange: inner JWS payload `oldKey` does not match registered account key")
)
// ParseAndVerifyKeyChangeInner parses the inner JWS bytes (i.e. the
// outer JWS's verified payload), runs the same allow-list +
// signature-verification pipeline as VerifyJWS, and asserts the inner-
// only invariants from RFC 8555 §7.3.5 (must use `jwk`, must NOT use
// `kid`, URL must match).
//
// Caller passes:
//
// - innerBytes: the outer JWS's verified payload (the inner JWS in
// compact serialization).
// - outerKID: the outer JWS's `kid` header value. The inner's payload
// `account` field MUST equal this.
// - outerURL: the outer JWS's `url` header value. The inner's
// protected-header `url` MUST equal this.
// - registeredOldJWK: the JWK currently stored on the account row.
// The inner's payload `oldKey` MUST canonicalize-equal this.
//
// Returns the verified KeyChangeInner on success, or one of the
// sentinel errors above on any validation failure.
func ParseAndVerifyKeyChangeInner(innerBytes []byte, outerKID, outerURL string, registeredOldJWK *jose.JSONWebKey) (*KeyChangeInner, error) {
// Parse against the same allow-list that VerifyJWS uses.
jws, err := jose.ParseSigned(string(innerBytes), AllowedSignatureAlgorithms)
if err != nil {
return nil, fmt.Errorf("%w: %v", ErrKeyChangeInnerMalformed, err)
}
if len(jws.Signatures) != 1 {
return nil, fmt.Errorf("%w: multi-signature inner JWS", ErrKeyChangeInnerMalformed)
}
sig := jws.Signatures[0]
if !algorithmAllowed(sig.Protected.Algorithm) {
return nil, fmt.Errorf("%w: %s", ErrKeyChangeInnerAlgRejected, sig.Protected.Algorithm)
}
// RFC 8555 §7.3.5: the inner MUST use `jwk` and MUST NOT use `kid`.
if sig.Protected.KeyID != "" {
return nil, ErrKeyChangeInnerForbidsKID
}
jwk := sig.Protected.JSONWebKey
if jwk == nil {
return nil, ErrKeyChangeInnerMissingJWK
}
if !jwk.Valid() {
return nil, ErrKeyChangeInnerInvalidJWK
}
// URL header MUST equal the outer's URL.
innerURL, err := extractStringHeader(sig.Protected.ExtraHeaders, "url")
if err != nil {
return nil, ErrKeyChangeInnerURLMissing
}
if innerURL == "" {
return nil, ErrKeyChangeInnerURLMissing
}
if innerURL != outerURL {
return nil, fmt.Errorf("%w: inner=%q outer=%q", ErrKeyChangeInnerURLMismatch, innerURL, outerURL)
}
// Verify the inner signature against the embedded jwk.
verifiedPayload, err := jws.Verify(jwk.Key)
if err != nil {
return nil, fmt.Errorf("%w: %v", ErrKeyChangeInnerSignatureBad, err)
}
// Parse the inner payload.
var payload KeyChangeInnerPayload
if err := json.Unmarshal(verifiedPayload, &payload); err != nil {
return nil, fmt.Errorf("%w: %v", ErrKeyChangeInnerPayloadParse, err)
}
// `account` MUST equal outer's kid.
if payload.Account != outerKID {
return nil, fmt.Errorf("%w: payload=%q outer.kid=%q",
ErrKeyChangeInnerAccountMismatch, payload.Account, outerKID)
}
// `oldKey` MUST be present and canonicalize-equal to registered.
if payload.OldKey == nil {
return nil, ErrKeyChangeInnerOldKeyMissing
}
if !payload.OldKey.Valid() {
return nil, fmt.Errorf("%w: oldKey did not validate", ErrKeyChangeInnerOldKeyMismatch)
}
eq, err := jwksThumbprintEqual(payload.OldKey, registeredOldJWK)
if err != nil {
return nil, fmt.Errorf("%w: thumbprint compare: %v", ErrKeyChangeInnerOldKeyMismatch, err)
}
if !eq {
return nil, ErrKeyChangeInnerOldKeyMismatch
}
return &KeyChangeInner{
NewJWK: jwk,
Payload: payload,
URL: innerURL,
Algorithm: sig.Protected.Algorithm,
}, nil
}
// jwksThumbprintEqual compares two JWKs by RFC 7638 thumbprint, which
// is the canonical identity for a public key. We deliberately compare
// thumbprints rather than serialized bytes because go-jose may emit
// fields in different orders for "equal" keys.
//
// Returns (true, nil) when both thumbprints exist and match in
// constant time; (false, err) on any thumbprint computation error;
// (false, nil) when the thumbprints differ.
func jwksThumbprintEqual(a, b *jose.JSONWebKey) (bool, error) {
if a == nil || b == nil {
return false, nil
}
tA, err := JWKThumbprint(a)
if err != nil {
return false, err
}
tB, err := JWKThumbprint(b)
if err != nil {
return false, err
}
return subtle.ConstantTimeCompare([]byte(tA), []byte(tB)) == 1, nil
}
// MapKeyChangeErrorToProblem renders an inner-JWS validation error as
// an RFC 7807 + RFC 8555 §6.7 Problem the handler emits via
// WriteProblem.
//
// All inner-JWS errors map to operator-friendly problem types. The
// detail string is a concise summary; the full err.Error() context is
// suppressed to avoid leaking internal-state details (master-prompt
// criterion #10).
func MapKeyChangeErrorToProblem(err error) Problem {
switch {
case errors.Is(err, ErrKeyChangeInnerSignatureBad),
errors.Is(err, ErrKeyChangeInnerOldKeyMismatch):
// Both indicate "you don't actually possess the rollover key
// pair" — treat as unauthorized per RFC 8555 §7.3.5.
return Problem{
Type: "urn:ietf:params:acme:error:unauthorized",
Detail: "key rollover proof failed: " + plainCause(err),
Status: 401,
}
case errors.Is(err, ErrKeyChangeInnerURLMismatch),
errors.Is(err, ErrKeyChangeInnerURLMissing):
return Problem{
Type: "urn:ietf:params:acme:error:unauthorized",
Detail: "key rollover inner URL: " + plainCause(err),
Status: 401,
}
case errors.Is(err, ErrKeyChangeInnerAlgRejected):
return Malformed("key rollover inner JWS uses disallowed algorithm")
case errors.Is(err, ErrKeyChangeInnerForbidsKID):
return Malformed("key rollover inner JWS MUST use `jwk`, not `kid`")
case errors.Is(err, ErrKeyChangeInnerMissingJWK),
errors.Is(err, ErrKeyChangeInnerInvalidJWK):
return Malformed("key rollover inner JWS missing or invalid `jwk`")
case errors.Is(err, ErrKeyChangeInnerAccountMismatch):
return Malformed("key rollover inner `account` does not match outer kid")
case errors.Is(err, ErrKeyChangeInnerOldKeyMissing):
return Malformed("key rollover inner missing `oldKey`")
case errors.Is(err, ErrKeyChangeInnerPayloadParse):
return Malformed("key rollover inner payload is not valid JSON")
case errors.Is(err, ErrKeyChangeInnerMalformed):
return Malformed("key rollover inner JWS malformed")
default:
return Malformed("key rollover request rejected")
}
}
// plainCause extracts the leaf error text without leaking the full
// wrap chain. Used by MapKeyChangeErrorToProblem to keep the operator-
// facing detail concise.
func plainCause(err error) string {
if err == nil {
return ""
}
// Walk to the leaf cause; emit its message verbatim.
for {
next := errors.Unwrap(err)
if next == nil {
return err.Error()
}
err = next
}
}
+9
View File
@@ -90,6 +90,15 @@ type FinalizeRequest struct {
CSR string `json:"csr"`
}
// RevokeCertRequest is the payload shape RFC 8555 §7.6 mandates for
// revoke-cert. `certificate` is the base64url-DER of the leaf cert
// being revoked; `reason` is an optional RFC 5280 §5.3.1 numeric reason
// code (defaults to 0/unspecified when absent).
type RevokeCertRequest struct {
Certificate string `json:"certificate"`
Reason int `json:"reason,omitempty"`
}
// AuthorizationResponseJSON is the wire shape RFC 8555 §7.1.4 mandates
// for the authz GET (POST-as-GET) response.
type AuthorizationResponseJSON struct {
+362
View File
@@ -0,0 +1,362 @@
// Copyright (c) certctl
// SPDX-License-Identifier: BSL-1.1
package acme
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"crypto/x509/pkix"
"encoding/base64"
"encoding/json"
"encoding/pem"
"errors"
"math/big"
"strings"
"testing"
"time"
jose "github.com/go-jose/go-jose/v4"
"github.com/shankar0123/certctl/internal/domain"
)
// --- Test fixtures + helpers -------------------------------------------
func newTestRSAJWK(t *testing.T) (*rsa.PrivateKey, *jose.JSONWebKey) {
t.Helper()
priv, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
t.Fatalf("rsa.GenerateKey: %v", err)
}
jwk := &jose.JSONWebKey{Key: priv.Public(), Algorithm: string(jose.RS256), Use: "sig"}
return priv, jwk
}
func newTestECDSAJWK(t *testing.T) (*ecdsa.PrivateKey, *jose.JSONWebKey) {
t.Helper()
priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
t.Fatalf("ecdsa.GenerateKey: %v", err)
}
jwk := &jose.JSONWebKey{Key: priv.Public(), Algorithm: string(jose.ES256), Use: "sig"}
return priv, jwk
}
// signWithEmbeddedJWK builds an RFC-7515-compatible compact-serialized JWS with
// the given protected header + payload, signed by signer. Used for
// constructing inner-key-change blobs in tests.
func signWithEmbeddedJWK(t *testing.T, signer interface{}, alg jose.SignatureAlgorithm, payload []byte, headers map[jose.HeaderKey]interface{}, embedJWK *jose.JSONWebKey) string {
t.Helper()
opts := &jose.SignerOptions{ExtraHeaders: headers}
if embedJWK != nil {
opts = opts.WithHeader("jwk", embedJWK)
}
sigSigner, err := jose.NewSigner(jose.SigningKey{Algorithm: alg, Key: signer}, opts)
if err != nil {
t.Fatalf("NewSigner: %v", err)
}
obj, err := sigSigner.Sign(payload)
if err != nil {
t.Fatalf("Sign: %v", err)
}
out, err := obj.CompactSerialize()
if err != nil {
t.Fatalf("CompactSerialize: %v", err)
}
return out
}
// --- KeyChange tests ----------------------------------------------------
func TestParseAndVerifyKeyChangeInner_HappyPath(t *testing.T) {
_, oldJWK := newTestRSAJWK(t)
newPriv, newJWK := newTestECDSAJWK(t)
url := "https://example.com/acme/profile/p1/key-change"
kid := "https://example.com/acme/profile/p1/account/acme-acc-abc"
payloadJSON, err := json.Marshal(KeyChangeInnerPayload{
Account: kid,
OldKey: oldJWK,
})
if err != nil {
t.Fatalf("marshal payload: %v", err)
}
headers := map[jose.HeaderKey]interface{}{"url": url}
innerBytes := signWithEmbeddedJWK(t, newPriv, jose.ES256, payloadJSON, headers, newJWK)
got, err := ParseAndVerifyKeyChangeInner([]byte(innerBytes), kid, url, oldJWK)
if err != nil {
t.Fatalf("ParseAndVerifyKeyChangeInner: %v", err)
}
if got.Payload.Account != kid {
t.Errorf("payload.Account = %q, want %q", got.Payload.Account, kid)
}
if got.URL != url {
t.Errorf("URL = %q, want %q", got.URL, url)
}
if got.NewJWK == nil {
t.Errorf("NewJWK is nil")
}
}
func TestParseAndVerifyKeyChangeInner_OldKeyMismatch(t *testing.T) {
_, oldJWK := newTestRSAJWK(t)
_, otherJWK := newTestRSAJWK(t)
newPriv, newJWK := newTestECDSAJWK(t)
url := "https://example.com/acme/profile/p1/key-change"
kid := "https://example.com/acme/profile/p1/account/acme-acc-abc"
// payload claims an oldKey that doesn't match what's registered.
payloadJSON, _ := json.Marshal(KeyChangeInnerPayload{Account: kid, OldKey: otherJWK})
headers := map[jose.HeaderKey]interface{}{"url": url}
innerBytes := signWithEmbeddedJWK(t, newPriv, jose.ES256, payloadJSON, headers, newJWK)
_, err := ParseAndVerifyKeyChangeInner([]byte(innerBytes), kid, url, oldJWK)
if !errors.Is(err, ErrKeyChangeInnerOldKeyMismatch) {
t.Errorf("got err=%v, want ErrKeyChangeInnerOldKeyMismatch", err)
}
}
func TestParseAndVerifyKeyChangeInner_AccountMismatch(t *testing.T) {
_, oldJWK := newTestRSAJWK(t)
newPriv, newJWK := newTestECDSAJWK(t)
url := "https://example.com/acme/profile/p1/key-change"
outerKID := "https://example.com/acme/profile/p1/account/acme-acc-abc"
// payload.Account does NOT equal outer.kid.
payloadJSON, _ := json.Marshal(KeyChangeInnerPayload{
Account: "https://example.com/acme/profile/p1/account/acme-acc-DIFFERENT",
OldKey: oldJWK,
})
headers := map[jose.HeaderKey]interface{}{"url": url}
innerBytes := signWithEmbeddedJWK(t, newPriv, jose.ES256, payloadJSON, headers, newJWK)
_, err := ParseAndVerifyKeyChangeInner([]byte(innerBytes), outerKID, url, oldJWK)
if !errors.Is(err, ErrKeyChangeInnerAccountMismatch) {
t.Errorf("got err=%v, want ErrKeyChangeInnerAccountMismatch", err)
}
}
func TestParseAndVerifyKeyChangeInner_URLMismatch(t *testing.T) {
_, oldJWK := newTestRSAJWK(t)
newPriv, newJWK := newTestECDSAJWK(t)
innerURL := "https://example.com/acme/profile/p1/key-change"
outerURL := "https://example.com/acme/profile/p1/key-change-different"
kid := "https://example.com/acme/profile/p1/account/acme-acc-abc"
payloadJSON, _ := json.Marshal(KeyChangeInnerPayload{Account: kid, OldKey: oldJWK})
headers := map[jose.HeaderKey]interface{}{"url": innerURL}
innerBytes := signWithEmbeddedJWK(t, newPriv, jose.ES256, payloadJSON, headers, newJWK)
_, err := ParseAndVerifyKeyChangeInner([]byte(innerBytes), kid, outerURL, oldJWK)
if !errors.Is(err, ErrKeyChangeInnerURLMismatch) {
t.Errorf("got err=%v, want ErrKeyChangeInnerURLMismatch", err)
}
}
func TestParseAndVerifyKeyChangeInner_BadSignature(t *testing.T) {
_, oldJWK := newTestRSAJWK(t)
newPriv, newJWK := newTestECDSAJWK(t)
_, otherJWK := newTestECDSAJWK(t) // different key embedded vs. signer
url := "https://example.com/acme/profile/p1/key-change"
kid := "https://example.com/acme/profile/p1/account/acme-acc-abc"
payloadJSON, _ := json.Marshal(KeyChangeInnerPayload{Account: kid, OldKey: oldJWK})
headers := map[jose.HeaderKey]interface{}{"url": url}
// Sign with newPriv but embed otherJWK — verification against the
// embedded jwk will fail since the signer didn't possess otherJWK's
// private key.
innerBytes := signWithEmbeddedJWK(t, newPriv, jose.ES256, payloadJSON, headers, otherJWK)
_, err := ParseAndVerifyKeyChangeInner([]byte(innerBytes), kid, url, oldJWK)
if !errors.Is(err, ErrKeyChangeInnerSignatureBad) {
t.Errorf("got err=%v, want ErrKeyChangeInnerSignatureBad", err)
}
_ = newJWK
}
func TestParseAndVerifyKeyChangeInner_MalformedJWS(t *testing.T) {
_, oldJWK := newTestRSAJWK(t)
_, err := ParseAndVerifyKeyChangeInner([]byte("not-a-jws"), "kid", "url", oldJWK)
if !errors.Is(err, ErrKeyChangeInnerMalformed) {
t.Errorf("got err=%v, want ErrKeyChangeInnerMalformed", err)
}
}
func TestParseAndVerifyKeyChangeInner_MissingURL(t *testing.T) {
_, oldJWK := newTestRSAJWK(t)
newPriv, newJWK := newTestECDSAJWK(t)
url := "https://example.com/acme/profile/p1/key-change"
kid := "https://example.com/acme/profile/p1/account/acme-acc-abc"
payloadJSON, _ := json.Marshal(KeyChangeInnerPayload{Account: kid, OldKey: oldJWK})
// No `url` header.
innerBytes := signWithEmbeddedJWK(t, newPriv, jose.ES256, payloadJSON, nil, newJWK)
_, err := ParseAndVerifyKeyChangeInner([]byte(innerBytes), kid, url, oldJWK)
if !errors.Is(err, ErrKeyChangeInnerURLMissing) {
t.Errorf("got err=%v, want ErrKeyChangeInnerURLMissing", err)
}
}
func TestMapKeyChangeErrorToProblem_Coverage(t *testing.T) {
cases := []struct {
err error
wantType string
}{
{ErrKeyChangeInnerSignatureBad, "urn:ietf:params:acme:error:unauthorized"},
{ErrKeyChangeInnerOldKeyMismatch, "urn:ietf:params:acme:error:unauthorized"},
{ErrKeyChangeInnerAccountMismatch, "urn:ietf:params:acme:error:malformed"},
{ErrKeyChangeInnerForbidsKID, "urn:ietf:params:acme:error:malformed"},
{ErrKeyChangeInnerMissingJWK, "urn:ietf:params:acme:error:malformed"},
{ErrKeyChangeInnerOldKeyMissing, "urn:ietf:params:acme:error:malformed"},
{ErrKeyChangeInnerURLMismatch, "urn:ietf:params:acme:error:unauthorized"},
{ErrKeyChangeInnerMalformed, "urn:ietf:params:acme:error:malformed"},
}
for _, c := range cases {
got := MapKeyChangeErrorToProblem(c.err)
if got.Type != c.wantType {
t.Errorf("err=%v: got type %q, want %q", c.err, got.Type, c.wantType)
}
}
}
// --- ARI tests ----------------------------------------------------------
func TestParseARICertID_Roundtrip(t *testing.T) {
aki := []byte{0xde, 0xad, 0xbe, 0xef, 0x01, 0x02}
serial := []byte{0x12, 0x34, 0x56, 0x78}
certID := base64.RawURLEncoding.EncodeToString(aki) + "." + base64.RawURLEncoding.EncodeToString(serial)
got, err := ParseARICertID(certID)
if err != nil {
t.Fatalf("ParseARICertID: %v", err)
}
if string(got.AKI) != string(aki) {
t.Errorf("AKI: got %x, want %x", got.AKI, aki)
}
if string(got.Serial) != string(serial) {
t.Errorf("Serial: got %x, want %x", got.Serial, serial)
}
// SerialHex must match canonical certctl shape.
wantSerialHex := "12345678"
if got.SerialHex() != wantSerialHex {
t.Errorf("SerialHex: got %q, want %q", got.SerialHex(), wantSerialHex)
}
}
func TestParseARICertID_Malformed(t *testing.T) {
cases := []struct {
name string
certID string
wantErr error
}{
{"missing dot", "abc123nodot", ErrARICertIDMalformed},
{"too many dots", "a.b.c", ErrARICertIDMalformed},
{"empty aki", ".YWJj", ErrARICertIDEmpty},
{"empty serial", "YWJj.", ErrARICertIDEmpty},
{"non-base64 aki", "!!!!.YWJj", ErrARICertIDDecodeAKI},
{"non-base64 serial", "YWJj.!!!!", ErrARICertIDDecodeSeria},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
_, err := ParseARICertID(c.certID)
if !errors.Is(err, c.wantErr) {
t.Errorf("got err=%v, want %v", err, c.wantErr)
}
})
}
}
func TestBuildARICertID_FromGeneratedCert(t *testing.T) {
// Build a self-signed cert with an explicit AKI and serial.
priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
t.Fatalf("genkey: %v", err)
}
template := &x509.Certificate{
SerialNumber: big.NewInt(0x12345678),
Subject: pkix.Name{CommonName: "test"},
NotBefore: time.Now(),
NotAfter: time.Now().Add(24 * time.Hour),
AuthorityKeyId: []byte{0xde, 0xad, 0xbe, 0xef},
BasicConstraintsValid: true,
IsCA: true,
}
der, err := x509.CreateCertificate(rand.Reader, template, template, &priv.PublicKey, priv)
if err != nil {
t.Fatalf("CreateCertificate: %v", err)
}
certPEM := string(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}))
certID, err := BuildARICertID(certPEM)
if err != nil {
t.Fatalf("BuildARICertID: %v", err)
}
parts := strings.Split(certID, ".")
if len(parts) != 2 {
t.Fatalf("got %d parts, want 2", len(parts))
}
wantAKI := base64.RawURLEncoding.EncodeToString([]byte{0xde, 0xad, 0xbe, 0xef})
if parts[0] != wantAKI {
t.Errorf("AKI part: got %q, want %q", parts[0], wantAKI)
}
}
func TestComputeRenewalWindow_WithPolicy(t *testing.T) {
now := time.Date(2026, 5, 1, 0, 0, 0, 0, time.UTC)
notAfter := time.Date(2026, 7, 1, 0, 0, 0, 0, time.UTC) // 61 days out
cert := &domain.ManagedCertificate{ExpiresAt: notAfter}
version := &domain.CertificateVersion{
NotBefore: time.Date(2026, 4, 1, 0, 0, 0, 0, time.UTC),
NotAfter: notAfter,
}
policy := &domain.RenewalPolicy{RenewalWindowDays: 30}
start, end := ComputeRenewalWindow(cert, version, policy, now)
wantStart := notAfter.Add(-30 * 24 * time.Hour) // 2026-06-01
wantEnd := wantStart.Add(15 * 24 * time.Hour) // 2026-06-16
if !start.Equal(wantStart) {
t.Errorf("start: got %v, want %v", start, wantStart)
}
if !end.Equal(wantEnd) {
t.Errorf("end: got %v, want %v", end, wantEnd)
}
}
func TestComputeRenewalWindow_NoPolicy_LastThird(t *testing.T) {
now := time.Date(2026, 5, 1, 0, 0, 0, 0, time.UTC)
notBefore := time.Date(2026, 4, 1, 0, 0, 0, 0, time.UTC)
notAfter := time.Date(2026, 7, 1, 0, 0, 0, 0, time.UTC) // 91-day validity
cert := &domain.ManagedCertificate{ExpiresAt: notAfter}
version := &domain.CertificateVersion{NotBefore: notBefore, NotAfter: notAfter}
start, end := ComputeRenewalWindow(cert, version, nil, now)
// Validity = 91 days; thirty3 ~30d, end_offset = 10d. Start is in
// the future from `now` (Jun 2026), so no clamp.
if start.Before(now) {
t.Errorf("start before now: got %v", start)
}
if !end.After(start) && !end.Equal(start) {
t.Errorf("end before start: start=%v end=%v", start, end)
}
}
func TestComputeRenewalWindow_PastExpiry_RenewNow(t *testing.T) {
now := time.Date(2026, 8, 1, 0, 0, 0, 0, time.UTC)
notAfter := time.Date(2026, 7, 1, 0, 0, 0, 0, time.UTC) // 1 month ago
cert := &domain.ManagedCertificate{ExpiresAt: notAfter}
start, end := ComputeRenewalWindow(cert, nil, nil, now)
// Expect a "renew now" 1-day window starting at now.
if !start.Equal(now) {
t.Errorf("start: got %v, want %v", start, now)
}
if want := now.Add(24 * time.Hour); !end.Equal(want) {
t.Errorf("end: got %v, want %v", end, want)
}
}