mirror of
https://github.com/shankar0123/certctl.git
synced 2026-06-07 18:01:37 +00:00
c351bba41a
Closes the issuance loop in trust_authenticated mode (commitsec88a61+44a85d6wired 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".
162 lines
6.5 KiB
Go
162 lines
6.5 KiB
Go
// Copyright (c) certctl
|
|
// SPDX-License-Identifier: BSL-1.1
|
|
|
|
package domain
|
|
|
|
import "time"
|
|
|
|
// ACMEAccount mirrors a row in the acme_accounts table (RFC 8555 §7.1.2).
|
|
// The (ProfileID, JWKThumbprint) pair is unique per the migration's
|
|
// UNIQUE constraint — RFC 8555 §7.3.1 idempotent semantics — so the
|
|
// new-account endpoint maps a re-registration of an existing key onto
|
|
// the original account row rather than creating a duplicate.
|
|
//
|
|
// JWKPEM is the public-only JWK serialized via api/acme.JWKToPEM (a
|
|
// PEM-wrapped JSON envelope). Stored as TEXT in the column for diff-
|
|
// friendliness; the verifier round-trips through ParseJWKFromPEM at
|
|
// request time.
|
|
type ACMEAccount struct {
|
|
AccountID string `json:"account_id"`
|
|
JWKThumbprint string `json:"jwk_thumbprint"`
|
|
JWKPEM string `json:"jwk_pem"`
|
|
Contact []string `json:"contact,omitempty"`
|
|
Status ACMEAccountStatus `json:"status"`
|
|
ProfileID string `json:"profile_id"`
|
|
OwnerID string `json:"owner_id,omitempty"`
|
|
CreatedAt time.Time `json:"created_at"`
|
|
UpdatedAt time.Time `json:"updated_at"`
|
|
}
|
|
|
|
// ACMEAccountStatus is the closed enum for acme_accounts.status. The
|
|
// migration's CHECK constraint is implicit (the migration uses TEXT
|
|
// without a CHECK; service-layer validation owns the value-set).
|
|
type ACMEAccountStatus string
|
|
|
|
const (
|
|
// ACMEAccountStatusValid is the default for newly-created accounts.
|
|
// JWS-authenticated requests are accepted only when the bound
|
|
// account is `valid`.
|
|
ACMEAccountStatusValid ACMEAccountStatus = "valid"
|
|
// ACMEAccountStatusDeactivated marks an account the client
|
|
// voluntarily retired via POST /acme/.../account/<id> with
|
|
// payload {"status": "deactivated"} (RFC 8555 §7.3.6). Future
|
|
// JWS-authenticated requests using this account's kid are
|
|
// rejected with `unauthorized`.
|
|
ACMEAccountStatusDeactivated ACMEAccountStatus = "deactivated"
|
|
// ACMEAccountStatusRevoked marks an account the operator
|
|
// administratively retired (e.g. after detecting a compromised
|
|
// 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"
|
|
)
|