carlos / platform Public

console: import a certificate for a custom domain (#1429)

PUT and DELETE /api/cli/apps/{account}/{app}/domains/{host}/cert. A
platform operator imports a certificate and key they already hold for a
live exact claim of the app, so edges can serve it before DNS moves.

Gates in order: domainsGate, principalPlatformOperator (403), host
shape (400), the claim (exists, this account and app, not pending, not
a catch-all or wildcard claim; else the neutral 404). No service role,
refused for linked credentials, and not registered on a host-claim
console (gateNoHostClaim), which cannot detach an alias either.

validateImport is pure: one unencrypted key (PKCS #8, PKCS #1, SEC 1)
and nothing else; RSA 2048-4096 or ECDSA P-256/P-384; 1-5 certificates;
key matches leaf; leaf not a CA; NotBefore <= now and NotAfter more than
7 days on; Verify for server auth and the host against the Mozilla roots
(x509roots/fallback/bundle); wildcard-only coverage needs
allow_wildcard. Every refusal is a fixed sentence (domaincert_copy.go).

The console stores what it verified at control/certs/<host>+import
(domains.EncodeImport: binding, PKCS #8 key, leaf and intermediates,
no root) with a create-or-replace CAS. Answers and audit rows carry the
leaf's SHA-256, issuer CN, SAN count and expiry, never key bytes. The
per-host read adds imported_cert when an import bound to this claim
acquisition exists.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 01a8140c80d3ade73c9515cc23de91526f811fb6 parent a9451dd
8 files changed, +1,340 −3
  • internal/console/apidomaincert.go +484 −0
  • internal/console/apidomaincert_test.go +772 −0
  • internal/console/apidomains.go +8 −2
  • internal/console/domaincert_copy.go +51 −0
  • internal/console/linkedpolicy.go +2 −0
  • internal/console/routedecls.go +7 −0
  • internal/console/server.go +3 −0
  • internal/console/svcroutes_test.go +13 −1
diff --git a/internal/console/apidomaincert.go b/internal/console/apidomaincert.go
new file mode 100644
index 000000000..293e7e441
--- /dev/null
+++ b/internal/console/apidomaincert.go
@@ -0,0 +1,484 @@
+package console
+
+// Imported certificates for custom domains (#1429, design
+// docs/superpowers/specs/2026-11-25-cert-import-1429-design.md). A
+// platform operator who already holds a valid certificate and key for an
+// attached hostname imports them, so every edge serves the name before its
+// DNS points here. The door validates everything before it writes, and
+// writes only what it verified, re-encoded: a binding block that ties the
+// import to this claim acquisition, the key as PKCS #8, the leaf and the
+// intermediates Verify used. The operator's own bytes are never stored,
+// logged, audited or echoed: every refusal is a fixed sentence
+// (domaincert_copy.go).
+
+import (
+ "bytes"
+ "context"
+ "crypto"
+ "crypto/ecdsa"
+ "crypto/elliptic"
+ "crypto/rsa"
+ "crypto/sha256"
+ "crypto/x509"
+ "encoding/hex"
+ "encoding/json"
+ "encoding/pem"
+ "errors"
+ "fmt"
+ "io"
+ "log"
+ "net/http"
+ "os"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/carlosframework/platform/internal/domains"
+ "github.com/carlosframework/platform/internal/release"
+ "golang.org/x/crypto/x509roots/fallback/bundle"
+)
+
+// certImportMaxBody caps the request: two PEM texts, a chain of at most
+// five certificates and one key, fit in a fraction of it.
+const certImportMaxBody = 64 << 10
+
+// certImportMaxChain is the most CERTIFICATE blocks the certificate text
+// may hold, leaf included.
+const certImportMaxChain = 5
+
+// certImportMinLife is how long the leaf must still have to run: an import
+// that expires within the week is not worth a DNS move.
+const certImportMinLife = 7 * 24 * time.Hour
+
+// The refusals, one per check, so callers and tests branch with errors.Is.
+var (
+ errCertKeyMissing = errors.New(certKeyMissing)
+ errCertKeyEncrypted = errors.New(certKeyEncrypted)
+ errCertKeyExtra = errors.New(certKeyExtra)
+ errCertKeyUnreadable = errors.New(certKeyUnreadable)
+ errCertKeyAlgorithm = errors.New(certKeyAlgorithm)
+ errCertChainMissing = errors.New(certChainMissing)
+ errCertChainTooLong = errors.New(certChainTooLong)
+ errCertChainExtra = errors.New(certChainExtra)
+ errCertChainUnreadable = errors.New(certChainUnreadable)
+ errCertKeyMismatch = errors.New(certKeyMismatch)
+ errCertLeafIsCA = errors.New(certLeafIsCA)
+ errCertNotYetValid = errors.New(certNotYetValid)
+ errCertExpiresSoon = errors.New(certExpiresSoon)
+ errCertWrongName = errors.New(certWrongName)
+ errCertWrongUsage = errors.New(certWrongUsage)
+ errCertChainExpired = errors.New(certChainExpired)
+ errCertNotTrusted = errors.New(certNotTrusted)
+ errCertWildcardOnly = errors.New(certWildcardOnly)
+)
+
+// importRoots is the Mozilla root set from x509roots/fallback/bundle, not
+// the console host's store: what a browser trusts is the bar, whatever the
+// console's own machine happens to carry. Built once.
+var importRoots = sync.OnceValue(func() *x509.CertPool {
+ pool := x509.NewCertPool()
+ for r := range bundle.Roots() {
+ c, err := x509.ParseCertificate(r.Certificate)
+ if err != nil {
+ continue
+ }
+ pool.AddCertWithConstraint(c, r.Constraint)
+ }
+ return pool
+})
+
+// certImportRootPool is the door's root set: the server's test seam when
+// set, else the public roots.
+func (s *Server) certImportRootPool() *x509.CertPool {
+ if s.certImportRoots != nil {
+ return s.certImportRoots
+ }
+ return importRoots()
+}
+
+// importVerified is what validateImport proved and what the door stores.
+type importVerified struct {
+ leaf *x509.Certificate
+ pkcs8 []byte // the key, re-encoded
+ chain [][]byte // leaf first, then the intermediates Verify used; never the root
+ wildcard bool // the host is covered only through a wildcard SAN
+}
+
+// validateImport runs every check of the spec's Validation section, in
+// order, before anything is written. It returns one of the errCert*
+// sentences and nothing else: no error carries input bytes.
+func validateImport(host string, certPEM, keyPEM []byte, allowWildcard bool, roots *x509.CertPool, now time.Time) (importVerified, error) {
+ key, err := parseImportKey(keyPEM)
+ if err != nil {
+ return importVerified{}, err
+ }
+ if err := checkKeyAlgorithm(key.Public()); err != nil {
+ return importVerified{}, err
+ }
+ certs, err := parseImportChain(certPEM)
+ if err != nil {
+ return importVerified{}, err
+ }
+ leaf := certs[0]
+ pub, ok := leaf.PublicKey.(interface{ Equal(crypto.PublicKey) bool })
+ if !ok || !pub.Equal(key.Public()) {
+ return importVerified{}, errCertKeyMismatch
+ }
+ if leaf.IsCA {
+ return importVerified{}, errCertLeafIsCA
+ }
+ if now.Before(leaf.NotBefore) {
+ return importVerified{}, errCertNotYetValid
+ }
+ if !leaf.NotAfter.After(now.Add(certImportMinLife)) {
+ return importVerified{}, errCertExpiresSoon
+ }
+ inter := x509.NewCertPool()
+ for _, c := range certs[1:] {
+ inter.AddCert(c)
+ }
+ chains, err := leaf.Verify(x509.VerifyOptions{
+ DNSName: host, Intermediates: inter, Roots: roots, CurrentTime: now,
+ KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
+ })
+ if err != nil {
+ return importVerified{}, verifyRefusal(err)
+ }
+ // The shortest chain Verify found, minus its anchor. A chain of one is
+ // the leaf as its own root: nothing a public authority issued.
+ best := chains[0]
+ for _, c := range chains[1:] {
+ if len(c) < len(best) {
+ best = c
+ }
+ }
+ if len(best) < 2 {
+ return importVerified{}, errCertNotTrusted
+ }
+ chain := make([][]byte, 0, len(best)-1)
+ for _, c := range best[:len(best)-1] {
+ chain = append(chain, c.Raw)
+ }
+ wildcard := !exactSAN(leaf, host)
+ if wildcard && !allowWildcard {
+ return importVerified{}, errCertWildcardOnly
+ }
+ pkcs8, err := x509.MarshalPKCS8PrivateKey(key)
+ if err != nil {
+ return importVerified{}, errCertKeyUnreadable
+ }
+ return importVerified{leaf: leaf, pkcs8: pkcs8, chain: chain, wildcard: wildcard}, nil
+}
+
+// parseImportKey reads the key text: exactly one unencrypted private key
+// block (PKCS #8, PKCS #1 RSA or SEC 1 EC) and no other block. Text
+// outside the blocks is ignored.
+func parseImportKey(keyPEM []byte) (crypto.Signer, error) {
+ var keys []*pem.Block
+ others := 0
+ for rest := keyPEM; ; {
+ var b *pem.Block
+ b, rest = pem.Decode(rest)
+ if b == nil {
+ break
+ }
+ if b.Type == "ENCRYPTED PRIVATE KEY" || strings.Contains(b.Headers["Proc-Type"], "ENCRYPTED") {
+ return nil, errCertKeyEncrypted
+ }
+ if strings.HasSuffix(b.Type, "PRIVATE KEY") {
+ keys = append(keys, b)
+ } else {
+ others++
+ }
+ }
+ if len(keys) == 0 {
+ return nil, errCertKeyMissing
+ }
+ if len(keys) > 1 || others > 0 {
+ return nil, errCertKeyExtra
+ }
+ var key any
+ var err error
+ switch keys[0].Type {
+ case "PRIVATE KEY":
+ key, err = x509.ParsePKCS8PrivateKey(keys[0].Bytes)
+ case "RSA PRIVATE KEY":
+ key, err = x509.ParsePKCS1PrivateKey(keys[0].Bytes)
+ case "EC PRIVATE KEY":
+ key, err = x509.ParseECPrivateKey(keys[0].Bytes)
+ default:
+ return nil, errCertKeyUnreadable
+ }
+ if err != nil {
+ return nil, errCertKeyUnreadable
+ }
+ signer, ok := key.(crypto.Signer)
+ if !ok {
+ return nil, errCertKeyAlgorithm
+ }
+ return signer, nil
+}
+
+// checkKeyAlgorithm admits RSA of 2048 to 4096 bits and ECDSA on P-256
+// or P-384, the keys every edge's TLS stack serves well, and nothing else.
+func checkKeyAlgorithm(pub crypto.PublicKey) error {
+ switch k := pub.(type) {
+ case *rsa.PublicKey:
+ if bits := k.N.BitLen(); bits >= 2048 && bits <= 4096 {
+ return nil
+ }
+ case *ecdsa.PublicKey:
+ if k.Curve == elliptic.P256() || k.Curve == elliptic.P384() {
+ return nil
+ }
+ }
+ return errCertKeyAlgorithm
+}
+
+// parseImportChain reads the certificate text: one to five CERTIFICATE
+// blocks, leaf first, and no other block.
+func parseImportChain(certPEM []byte) ([]*x509.Certificate, error) {
+ var certs []*x509.Certificate
+ rest := certPEM
+ for {
+ var b *pem.Block
+ b, rest = pem.Decode(rest)
+ if b == nil {
+ break
+ }
+ if b.Type != "CERTIFICATE" || len(b.Headers) != 0 {
+ return nil, errCertChainExtra
+ }
+ if len(certs) == certImportMaxChain {
+ return nil, errCertChainTooLong
+ }
+ c, err := x509.ParseCertificate(b.Bytes)
+ if err != nil {
+ return nil, errCertChainUnreadable
+ }
+ certs = append(certs, c)
+ }
+ if len(certs) == 0 {
+ return nil, errCertChainMissing
+ }
+ return certs, nil
+}
+
+// verifyRefusal maps a Verify failure to the sentence for its kind.
+func verifyRefusal(err error) error {
+ var hostErr x509.HostnameError
+ if errors.As(err, &hostErr) {
+ return errCertWrongName
+ }
+ var invalid x509.CertificateInvalidError
+ if errors.As(err, &invalid) {
+ switch invalid.Reason {
+ case x509.IncompatibleUsage:
+ return errCertWrongUsage
+ case x509.Expired:
+ return errCertChainExpired
+ }
+ }
+ return errCertNotTrusted
+}
+
+// exactSAN reports whether a DNS SAN of leaf names host itself, not
+// through a wildcard.
+func exactSAN(leaf *x509.Certificate, host string) bool {
+ for _, n := range leaf.DNSNames {
+ if strings.EqualFold(strings.TrimSuffix(n, "."), host) {
+ return true
+ }
+ }
+ return false
+}
+
+// certSummary is what an answer, and the per-host read, say about an
+// import: never key or certificate bytes.
+type certSummary struct {
+ Host string `json:"host"`
+ SHA256 string `json:"sha256"`
+ Issuer string `json:"issuer"`
+ SANs int `json:"sans"`
+ NotAfter string `json:"not_after"`
+ Wildcard bool `json:"wildcard"`
+}
+
+func summarizeCert(host string, leaf *x509.Certificate) certSummary {
+ sum := sha256.Sum256(leaf.Raw)
+ return certSummary{
+ Host: host, SHA256: hex.EncodeToString(sum[:]), Issuer: leaf.Issuer.CommonName,
+ SANs: len(leaf.DNSNames), NotAfter: leaf.NotAfter.UTC().Format(time.RFC3339),
+ Wildcard: !exactSAN(leaf, host),
+ }
+}
+
+// importKey is host's import entry in the deployment bucket.
+func importKey(host string) string { return "control/certs/" + domains.ImportName(host) }
+
+// putImportCAS is create-or-replace with compare-and-swap, the shape of the
+// edge's putCAS (internal/edge/certsync.go): read the etag, put on it,
+// and on a lost race read again, three times at most.
+func putImportCAS(ctx context.Context, s release.Store, key string, body []byte) error {
+ for attempt := 0; attempt < 3; attempt++ {
+ _, etag, err := s.Get(ctx, key)
+ switch {
+ case errors.Is(err, os.ErrNotExist):
+ etag = ""
+ case err != nil:
+ return fmt.Errorf("get %s: %w", key, err)
+ }
+ if _, err := s.Put(ctx, key, body, etag); err == nil {
+ return nil
+ } else if !errors.Is(err, release.ErrCASConflict) {
+ return fmt.Errorf("put %s: %w", key, err)
+ }
+ }
+ return fmt.Errorf("%s: lost CAS race three times", key)
+}
+
+// certDoorGate is gates 1 to 3 of both verbs: the domains family's gate,
+// a platform operator, and a live exact claim this app holds. ok is false
+// once it has answered.
+func (s *Server) certDoorGate(w http.ResponseWriter, r *http.Request) (p Principal, acct *Account, app, host string, claim *domains.Claim, ctx context.Context, cancel context.CancelFunc, ok bool) {
+ p, acct, app, ok = s.domainsGate(w, r)
+ if !ok {
+ return
+ }
+ ok = false
+ if !s.principalPlatformOperator(p) {
+ jsonError(w, http.StatusForbidden, certOperatorOnly)
+ return
+ }
+ // Shape-checked before any key is built from it, as detach does: a
+ // {host} arrives percent-decoded.
+ host, valid := domains.NormalizeAliasHost(r.PathValue("host"))
+ if !valid || strings.HasPrefix(host, "*.") {
+ jsonError(w, http.StatusBadRequest, "invalid hostname")
+ return
+ }
+ ctx, cancel = context.WithTimeout(r.Context(), instanceStoreTimeout)
+ c, err := domains.GetClaim(ctx, s.cfg.Releases, host)
+ if err != nil && !errors.Is(err, os.ErrNotExist) {
+ cancel()
+ log.Printf("console: domain cert %s/%s %s: claim: %v", acct.Sqid, app, host, err)
+ jsonError(w, http.StatusBadGateway, certReadFailed)
+ return
+ }
+ if err != nil || c == nil || c.Account != acct.Sqid || c.App != app || c.Pending || c.Instances ||
+ strings.HasPrefix(c.Host, "*.") {
+ cancel()
+ jsonError(w, http.StatusNotFound, certNoSuchHost)
+ return
+ }
+ return p, acct, app, host, c, ctx, cancel, true
+}
+
+// handleAPIDomainCertImport is PUT .../domains/{host}/cert.
+func (s *Server) handleAPIDomainCertImport(w http.ResponseWriter, r *http.Request) {
+ p, acct, app, host, claim, ctx, cancel, ok := s.certDoorGate(w, r)
+ if !ok {
+ return
+ }
+ defer cancel()
+ // The body is never logged, and no refusal below repeats any of it.
+ raw, err := io.ReadAll(http.MaxBytesReader(w, r.Body, certImportMaxBody))
+ if err != nil {
+ var tooLarge *http.MaxBytesError
+ if errors.As(err, &tooLarge) {
+ jsonError(w, http.StatusRequestEntityTooLarge, certBodyTooLarge)
+ return
+ }
+ jsonError(w, http.StatusBadRequest, certBodyUnreadable)
+ return
+ }
+ var in struct {
+ Cert string `json:"cert"`
+ Key string `json:"key"`
+ AllowWildcard bool `json:"allow_wildcard"`
+ }
+ if err := json.NewDecoder(bytes.NewReader(raw)).Decode(&in); err != nil {
+ jsonError(w, http.StatusBadRequest, certBodyUnreadable)
+ return
+ }
+ v, err := validateImport(host, []byte(in.Cert), []byte(in.Key), in.AllowWildcard, s.certImportRootPool(), time.Now())
+ if err != nil {
+ jsonError(w, http.StatusBadRequest, err.Error())
+ return
+ }
+ entry := domains.EncodeImport(domains.ImportBinding{
+ Host: host, Account: acct.Sqid, App: app, ClaimCreated: claim.CreatedAt,
+ }, v.pkcs8, v.chain)
+ // What the edges will parse is what was verified; a mismatch here is
+ // this file's bug, never the caller's input.
+ if _, _, err := domains.ParseImport(entry); err != nil {
+ log.Printf("console: domain cert import %s/%s %s: entry does not parse", acct.Sqid, app, host)
+ jsonError(w, http.StatusInternalServerError, certWriteFailed)
+ return
+ }
+ if err := putImportCAS(ctx, s.cfg.Releases, importKey(host), entry); err != nil {
+ log.Printf("console: domain cert import %s/%s %s: %v", acct.Sqid, app, host, err)
+ jsonError(w, http.StatusBadGateway, certWriteFailed)
+ return
+ }
+ sum := summarizeCert(host, v.leaf)
+ detail := fmt.Sprintf(certAuditImport, host, sum.SHA256, sum.Issuer, sum.NotAfter)
+ if in.AllowWildcard {
+ detail += certAuditWildcard
+ }
+ s.audit(acct, app, auditActor(p, acct), "domain-cert-import", detail)
+ writeJSON(w, http.StatusOK, sum)
+}
+
+// handleAPIDomainCertRemove is DELETE .../domains/{host}/cert. A missing
+// import is 200 with removed false and no Activity row.
+func (s *Server) handleAPIDomainCertRemove(w http.ResponseWriter, r *http.Request) {
+ p, acct, app, host, _, ctx, cancel, ok := s.certDoorGate(w, r)
+ if !ok {
+ return
+ }
+ defer cancel()
+ key := importKey(host)
+ raw, _, err := s.cfg.Releases.Get(ctx, key)
+ if errors.Is(err, os.ErrNotExist) {
+ writeJSON(w, http.StatusOK, map[string]any{"host": host, "removed": false})
+ return
+ }
+ if err != nil {
+ log.Printf("console: domain cert remove %s/%s %s: %v", acct.Sqid, app, host, err)
+ jsonError(w, http.StatusBadGateway, certReadFailed)
+ return
+ }
+ if err := s.cfg.Releases.Delete(ctx, key); err != nil {
+ log.Printf("console: domain cert remove %s/%s %s: %v", acct.Sqid, app, host, err)
+ jsonError(w, http.StatusBadGateway, certRemoveFailed)
+ return
+ }
+ detail := fmt.Sprintf(certAuditRemoveUnknown, host)
+ if _, pair, err := domains.ParseImport(raw); err == nil {
+ sum := summarizeCert(host, pair.Leaf)
+ detail = fmt.Sprintf(certAuditRemove, host, sum.SHA256, sum.Issuer, sum.NotAfter)
+ }
+ s.audit(acct, app, auditActor(p, acct), "domain-cert-remove", detail)
+ writeJSON(w, http.StatusOK, map[string]any{"host": host, "removed": true})
+}
+
+// importedCertSummary is the per-host read's imported_cert: the import
+// for c's host when one exists, parses and is bound to this very claim
+// acquisition; nil otherwise, a read failure included (the read answers
+// without it rather than failing).
+func (s *Server) importedCertSummary(ctx context.Context, c domains.Claim) *certSummary {
+ raw, _, err := s.cfg.Releases.Get(ctx, importKey(c.Host))
+ if err != nil {
+ if !errors.Is(err, os.ErrNotExist) {
+ log.Printf("console: api domain get %s: imported cert: %v", c.Host, err)
+ }
+ return nil
+ }
+ b, pair, err := domains.ParseImport(raw)
+ if err != nil || !b.Matches(c) {
+ return nil
+ }
+ sum := summarizeCert(c.Host, pair.Leaf)
+ return &sum
+}
diff --git a/internal/console/apidomaincert_test.go b/internal/console/apidomaincert_test.go
new file mode 100644
index 000000000..767415e54
--- /dev/null
+++ b/internal/console/apidomaincert_test.go
@@ -0,0 +1,772 @@
+package console
+
+// The imported-certificate door (apidomaincert.go, #1429): the gates in
+// order, every validation refusal, what is stored, and that no byte of the
+// key ever comes back out in an answer, an Activity row or a log line.
+
+import (
+ "context"
+ "crypto"
+ "crypto/ecdsa"
+ "crypto/ed25519"
+ "crypto/elliptic"
+ "crypto/rand"
+ "crypto/rsa"
+ "crypto/sha256"
+ "crypto/x509"
+ "crypto/x509/pkix"
+ "encoding/hex"
+ "encoding/json"
+ "encoding/pem"
+ "errors"
+ "math/big"
+ "net/http"
+ "os"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/domains"
+)
+
+// ---- a fixture CA: root, intermediate, leaves ----------------------------
+
+type certFixture struct {
+ root, inter *x509.Certificate
+ rootKey, interKey crypto.Signer
+ roots *x509.CertPool
+}
+
+func newSerial(t *testing.T) *big.Int {
+ t.Helper()
+ n, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 62))
+ if err != nil {
+ t.Fatal(err)
+ }
+ return n
+}
+
+func p256(t *testing.T) *ecdsa.PrivateKey {
+ t.Helper()
+ k, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return k
+}
+
+func mustCert(t *testing.T, tmpl, parent *x509.Certificate, pub crypto.PublicKey, signer crypto.Signer) *x509.Certificate {
+ t.Helper()
+ der, err := x509.CreateCertificate(rand.Reader, tmpl, parent, pub, signer)
+ if err != nil {
+ t.Fatal(err)
+ }
+ c, err := x509.ParseCertificate(der)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return c
+}
+
+func newCertFixture(t *testing.T) *certFixture {
+ t.Helper()
+ now := time.Now()
+ f := &certFixture{rootKey: p256(t), interKey: p256(t)}
+ rootTmpl := &x509.Certificate{
+ SerialNumber: newSerial(t), Subject: pkix.Name{CommonName: "Fixture Root"},
+ NotBefore: now.Add(-48 * time.Hour), NotAfter: now.Add(10 * 365 * 24 * time.Hour),
+ IsCA: true, BasicConstraintsValid: true, KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign,
+ }
+ f.root = mustCert(t, rootTmpl, rootTmpl, f.rootKey.Public(), f.rootKey)
+ f.inter = f.intermediate(t, now.Add(-24*time.Hour), now.Add(5*365*24*time.Hour), f.interKey)
+ f.roots = x509.NewCertPool()
+ f.roots.AddCert(f.root)
+ return f
+}
+
+func (f *certFixture) intermediate(t *testing.T, notBefore, notAfter time.Time, key crypto.Signer) *x509.Certificate {
+ t.Helper()
+ return mustCert(t, &x509.Certificate{
+ SerialNumber: newSerial(t), Subject: pkix.Name{CommonName: "Fixture Issuing CA"},
+ NotBefore: notBefore, NotAfter: notAfter,
+ IsCA: true, BasicConstraintsValid: true, KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign,
+ }, f.root, key.Public(), f.rootKey)
+}
+
+type leafOpts struct {
+ names []string
+ notBefore time.Time // zero: an hour ago
+ notAfter time.Time // zero: 60 days on
+ isCA bool
+ eku []x509.ExtKeyUsage // nil: server auth
+ key crypto.Signer // nil: a new P-256 key
+ parent *x509.Certificate // nil: the intermediate
+ parentKey crypto.Signer
+ selfSign bool
+}
+
+func (f *certFixture) leaf(t *testing.T, o leafOpts) (*x509.Certificate, crypto.Signer) {
+ t.Helper()
+ now := time.Now()
+ if o.notBefore.IsZero() {
+ o.notBefore = now.Add(-time.Hour)
+ }
+ if o.notAfter.IsZero() {
+ o.notAfter = now.Add(60 * 24 * time.Hour)
+ }
+ if o.eku == nil {
+ o.eku = []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}
+ }
+ if o.key == nil {
+ o.key = p256(t)
+ }
+ if o.parent == nil {
+ o.parent, o.parentKey = f.inter, f.interKey
+ }
+ tmpl := &x509.Certificate{
+ SerialNumber: newSerial(t), Subject: pkix.Name{CommonName: o.names[0]},
+ DNSNames: o.names, NotBefore: o.notBefore, NotAfter: o.notAfter,
+ ExtKeyUsage: o.eku, KeyUsage: x509.KeyUsageDigitalSignature,
+ BasicConstraintsValid: true, IsCA: o.isCA,
+ }
+ if o.isCA {
+ tmpl.KeyUsage |= x509.KeyUsageCertSign
+ }
+ parent, signer := o.parent, o.parentKey
+ if o.selfSign {
+ parent, signer = tmpl, o.key
+ }
+ return mustCert(t, tmpl, parent, o.key.Public(), signer), o.key
+}
+
+func pemCerts(certs ...*x509.Certificate) []byte {
+ var out []byte
+ for _, c := range certs {
+ out = append(out, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: c.Raw})...)
+ }
+ return out
+}
+
+func pemPKCS8(t *testing.T, k crypto.Signer) []byte {
+ t.Helper()
+ der, err := x509.MarshalPKCS8PrivateKey(k)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: der})
+}
+
+func pemSEC1(t *testing.T, k *ecdsa.PrivateKey) []byte {
+ t.Helper()
+ der, err := x509.MarshalECPrivateKey(k)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: der})
+}
+
+// ---- the pure validation ------------------------------------------------
+
+func TestValidateImportAccepts(t *testing.T) {
+ f := newCertFixture(t)
+ now := time.Now()
+ host := "tickets.example.com"
+
+ leaf, key := f.leaf(t, leafOpts{names: []string{host, "www.example.com"}})
+ v, err := validateImport(host, pemCerts(leaf, f.inter), pemPKCS8(t, key), false, f.roots, now)
+ if err != nil {
+ t.Fatalf("a good P-256 import: %v", err)
+ }
+ if v.wildcard || len(v.chain) != 2 || string(v.chain[0]) != string(leaf.Raw) || string(v.chain[1]) != string(f.inter.Raw) {
+ t.Fatalf("verified = wildcard %v, %d certs; want exact, leaf then intermediate", v.wildcard, len(v.chain))
+ }
+ if _, err := x509.ParsePKCS8PrivateKey(v.pkcs8); err != nil {
+ t.Fatalf("stored key is not PKCS #8: %v", err)
+ }
+
+ // The root sent along (a "fullchain" with the root in it) is dropped:
+ // the chain Verify used, minus its anchor.
+ if v, err := validateImport(host, pemCerts(leaf, f.inter, f.root), pemPKCS8(t, key), false, f.roots, now); err != nil || len(v.chain) != 2 {
+ t.Fatalf("leaf+intermediate+root = %d certs, %v; want 2, nil", len(v.chain), err)
+ }
+
+ // SEC 1 and PKCS #1 keys are accepted and re-encoded as PKCS #8.
+ ec := key.(*ecdsa.PrivateKey)
+ if v, err := validateImport(host, pemCerts(leaf, f.inter), pemSEC1(t, ec), false, f.roots, now); err != nil {
+ t.Fatalf("SEC 1 key: %v", err)
+ } else if _, err := x509.ParsePKCS8PrivateKey(v.pkcs8); err != nil {
+ t.Fatalf("SEC 1 key not re-encoded as PKCS #8: %v", err)
+ }
+ rk, err := rsa.GenerateKey(rand.Reader, 2048)
+ if err != nil {
+ t.Fatal(err)
+ }
+ rleaf, _ := f.leaf(t, leafOpts{names: []string{host}, key: rk})
+ pk1 := pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(rk)})
+ if _, err := validateImport(host, pemCerts(rleaf, f.inter), pk1, false, f.roots, now); err != nil {
+ t.Fatalf("RSA 2048 PKCS #1 key: %v", err)
+ }
+
+ // P-384 is accepted.
+ k384, err := ecdsa.GenerateKey(elliptic.P384(), rand.Reader)
+ if err != nil {
+ t.Fatal(err)
+ }
+ l384, _ := f.leaf(t, leafOpts{names: []string{host}, key: k384})
+ if _, err := validateImport(host, pemCerts(l384, f.inter), pemPKCS8(t, k384), false, f.roots, now); err != nil {
+ t.Fatalf("P-384: %v", err)
+ }
+
+ // Text around the blocks (openssl's "Bag Attributes") is ignored and
+ // never kept.
+ stray := []byte("Bag Attributes\n localKeyID: 01 02 03\nsubject=/CN=tickets.example.com\n")
+ certText := append(append([]byte{}, stray...), pemCerts(leaf, f.inter)...)
+ keyText := append(append([]byte{}, stray...), pemPKCS8(t, key)...)
+ if _, err := validateImport(host, certText, keyText, false, f.roots, now); err != nil {
+ t.Fatalf("PEM with text around it: %v", err)
+ }
+}
+
+func TestValidateImportWildcard(t *testing.T) {
+ f := newCertFixture(t)
+ now := time.Now()
+ host := "tickets.example.com"
+ wleaf, wkey := f.leaf(t, leafOpts{names: []string{"*.example.com"}})
+ if _, err := validateImport(host, pemCerts(wleaf, f.inter), pemPKCS8(t, wkey), false, f.roots, now); !errors.Is(err, errCertWildcardOnly) {
+ t.Fatalf("wildcard-only without the flag = %v, want the wildcard refusal", err)
+ }
+ v, err := validateImport(host, pemCerts(wleaf, f.inter), pemPKCS8(t, wkey), true, f.roots, now)
+ if err != nil || !v.wildcard {
+ t.Fatalf("wildcard-only with the flag = wildcard %v, %v; want true, nil", v.wildcard, err)
+ }
+ // An exact SAN beside a wildcard is not a wildcard import.
+ both, bkey := f.leaf(t, leafOpts{names: []string{"*.example.com", "TICKETS.example.com"}})
+ v, err = validateImport(host, pemCerts(both, f.inter), pemPKCS8(t, bkey), false, f.roots, now)
+ if err != nil || v.wildcard {
+ t.Fatalf("exact SAN beside a wildcard = wildcard %v, %v; want false, nil", v.wildcard, err)
+ }
+}
+
+func TestValidateImportRefusals(t *testing.T) {
+ f := newCertFixture(t)
+ now := time.Now()
+ host := "tickets.example.com"
+ leaf, key := f.leaf(t, leafOpts{names: []string{host}})
+ good := pemCerts(leaf, f.inter)
+ goodKey := pemPKCS8(t, key)
+ _, otherKey := f.leaf(t, leafOpts{names: []string{host}})
+
+ rsa1024, err := rsa.GenerateKey(rand.Reader, 1024)
+ if err != nil {
+ t.Fatal(err)
+ }
+ l1024, _ := f.leaf(t, leafOpts{names: []string{host}, key: rsa1024})
+ k521, err := ecdsa.GenerateKey(elliptic.P521(), rand.Reader)
+ if err != nil {
+ t.Fatal(err)
+ }
+ l521, _ := f.leaf(t, leafOpts{names: []string{host}, key: k521})
+ _, edPriv, err := ed25519.GenerateKey(rand.Reader)
+ if err != nil {
+ t.Fatal(err)
+ }
+ led, _ := f.leaf(t, leafOpts{names: []string{host}, key: edPriv})
+
+ encrypted := pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY",
+ Headers: map[string]string{"Proc-Type": "4,ENCRYPTED", "DEK-Info": "AES-128-CBC,00"}, Bytes: []byte{1, 2, 3}})
+ encPKCS8 := pem.EncodeToMemory(&pem.Block{Type: "ENCRYPTED PRIVATE KEY", Bytes: []byte{1, 2, 3}})
+ garbageKey := pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: []byte("not a key")})
+ garbageCert := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: []byte("not a cert")})
+ ecParams := pem.EncodeToMemory(&pem.Block{Type: "EC PARAMETERS", Bytes: []byte{6, 8, 42, 134, 72, 206, 61, 3, 1, 7}})
+
+ caLeaf, caKey := f.leaf(t, leafOpts{names: []string{host}, isCA: true})
+ early, earlyKey := f.leaf(t, leafOpts{names: []string{host}, notBefore: now.Add(time.Hour)})
+ soon, soonKey := f.leaf(t, leafOpts{names: []string{host}, notAfter: now.Add(6 * 24 * time.Hour)})
+ wrong, wrongKey := f.leaf(t, leafOpts{names: []string{"other.example.com"}})
+ client, clientKey := f.leaf(t, leafOpts{names: []string{host}, eku: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth}})
+ self, selfKey := f.leaf(t, leafOpts{names: []string{host}, selfSign: true})
+ oldInterKey := p256(t)
+ oldInter := f.intermediate(t, now.Add(-90*24*time.Hour), now.Add(-time.Hour), oldInterKey)
+ underOld, underOldKey := f.leaf(t, leafOpts{names: []string{host}, parent: oldInter, parentKey: oldInterKey,
+ notBefore: now.Add(-2 * time.Hour)})
+
+ cases := []struct {
+ name string
+ cert, key []byte
+ want error
+ }{
+ {"no key", good, nil, errCertKeyMissing},
+ {"only a certificate in the key text", good, good, errCertKeyMissing},
+ {"encrypted PEM key", good, encrypted, errCertKeyEncrypted},
+ {"encrypted PKCS #8 key", good, encPKCS8, errCertKeyEncrypted},
+ {"two keys", good, append(append([]byte{}, goodKey...), goodKey...), errCertKeyExtra},
+ {"a key and a certificate", good, append(append([]byte{}, goodKey...), good...), errCertKeyExtra},
+ {"a key and EC parameters", good, append(append([]byte{}, ecParams...), goodKey...), errCertKeyExtra},
+ {"unreadable key", good, garbageKey, errCertKeyUnreadable},
+ {"RSA 1024", pemCerts(l1024, f.inter), pemPKCS8(t, rsa1024), errCertKeyAlgorithm},
+ {"ECDSA P-521", pemCerts(l521, f.inter), pemPKCS8(t, k521), errCertKeyAlgorithm},
+ {"Ed25519", pemCerts(led, f.inter), pemPKCS8(t, edPriv), errCertKeyAlgorithm},
+ {"no certificate", nil, goodKey, errCertChainMissing},
+ {"six certificates", pemCerts(leaf, f.inter, f.inter, f.inter, f.inter, f.root), goodKey, errCertChainTooLong},
+ {"a key in the certificate text", append(append([]byte{}, good...), goodKey...), goodKey, errCertChainExtra},
+ {"unreadable certificate", garbageCert, goodKey, errCertChainUnreadable},
+ {"key does not match", good, pemPKCS8(t, otherKey), errCertKeyMismatch},
+ {"leaf is a CA", pemCerts(caLeaf, f.inter), pemPKCS8(t, caKey), errCertLeafIsCA},
+ {"not valid yet", pemCerts(early, f.inter), pemPKCS8(t, earlyKey), errCertNotYetValid},
+ {"expires within seven days", pemCerts(soon, f.inter), pemPKCS8(t, soonKey), errCertExpiresSoon},
+ {"wrong name", pemCerts(wrong, f.inter), pemPKCS8(t, wrongKey), errCertWrongName},
+ {"client auth only", pemCerts(client, f.inter), pemPKCS8(t, clientKey), errCertWrongUsage},
+ {"self-signed", pemCerts(self), pemPKCS8(t, selfKey), errCertNotTrusted},
+ {"intermediate missing", pemCerts(leaf), goodKey, errCertNotTrusted},
+ {"intermediate expired", pemCerts(underOld, oldInter), pemPKCS8(t, underOldKey), errCertChainExpired},
+ }
+ for _, c := range cases {
+ _, err := validateImport(host, c.cert, c.key, false, f.roots, now)
+ if !errors.Is(err, c.want) {
+ t.Errorf("%s: got %v, want %v", c.name, err, c.want)
+ }
+ }
+
+ // The fixture root is not in the production root set, so a chain to it
+ // is refused there.
+ if _, err := validateImport(host, good, goodKey, false, importRoots(), now); !errors.Is(err, errCertNotTrusted) {
+ t.Errorf("fixture chain against the public roots = %v, want not trusted", err)
+ }
+ // An expiry exactly seven days on is refused: it must be MORE than
+ // seven days away.
+ if _, err := validateImport(host, good, goodKey, false, f.roots, leaf.NotAfter.Add(-7*24*time.Hour)); !errors.Is(err, errCertExpiresSoon) {
+ t.Errorf("expiry exactly seven days on = %v, want the expiry refusal", err)
+ }
+}
+
+// TestCheckKeyAlgorithm covers the sizes no test can afford to generate:
+// an RSA 8192 key takes the better part of a minute to make, and the rule
+// is about the public half alone.
+func TestCheckKeyAlgorithm(t *testing.T) {
+ rsaOf := func(bits int) *rsa.PublicKey {
+ return &rsa.PublicKey{N: new(big.Int).Add(new(big.Int).Lsh(big.NewInt(1), uint(bits-1)), big.NewInt(1)), E: 65537}
+ }
+ k384, _ := ecdsa.GenerateKey(elliptic.P384(), rand.Reader)
+ k521, _ := ecdsa.GenerateKey(elliptic.P521(), rand.Reader)
+ for _, c := range []struct {
+ name string
+ pub crypto.PublicKey
+ ok bool
+ }{
+ {"RSA 2048", rsaOf(2048), true},
+ {"RSA 3072", rsaOf(3072), true},
+ {"RSA 4096", rsaOf(4096), true},
+ {"RSA 2047", rsaOf(2047), false},
+ {"RSA 4097", rsaOf(4097), false},
+ {"RSA 8192", rsaOf(8192), false},
+ {"P-256", p256(t).Public(), true},
+ {"P-384", k384.Public(), true},
+ {"P-521", k521.Public(), false},
+ } {
+ err := checkKeyAlgorithm(c.pub)
+ if (err == nil) != c.ok {
+ t.Errorf("%s: %v, want ok=%v", c.name, err, c.ok)
+ }
+ if err != nil && !errors.Is(err, errCertKeyAlgorithm) {
+ t.Errorf("%s: %v, want the key algorithm refusal", c.name, err)
+ }
+ }
+}
+
+func TestImportRootsIsThePublicSet(t *testing.T) {
+ //lint:ignore SA1019 counting the roots only; this pool is built from the bundle, not the system
+ if n := len(importRoots().Subjects()); n < 100 {
+ t.Fatalf("production root pool has %d roots, want the Mozilla set", n)
+ }
+}
+
+// ---- the door -----------------------------------------------------------
+
+func certURL(fx *consoleFixture, acct, app, host string) string {
+ return domainsURL(fx, acct, app) + "/" + host + "/cert"
+}
+
+func certBody(cert, key []byte, allowWildcard bool) string {
+ b, err := json.Marshal(map[string]any{"cert": string(cert), "key": string(key), "allow_wildcard": allowWildcard})
+ if err != nil {
+ panic(err)
+ }
+ return string(b)
+}
+
+func putClaim(t *testing.T, fx *consoleFixture, c domains.Claim) {
+ t.Helper()
+ c.Schema = 1
+ if c.CreatedAt == "" {
+ c.CreatedAt = time.Now().UTC().Format(time.RFC3339Nano)
+ }
+ raw, err := json.Marshal(c)
+ if err != nil {
+ t.Fatal(err)
+ }
+ _, etag, _ := fx.rel.Get(context.Background(), domains.ClaimKey(c.Host))
+ if _, err := fx.rel.Put(context.Background(), domains.ClaimKey(c.Host), raw, etag); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func importAbsent(t *testing.T, fx *consoleFixture, host string) {
+ t.Helper()
+ if _, _, err := fx.rel.Get(context.Background(), "control/certs/"+domains.ImportName(host)); !errors.Is(err, os.ErrNotExist) {
+ t.Fatalf("import for %s exists (err=%v), want none", host, err)
+ }
+}
+
+func storedImport(t *testing.T, fx *consoleFixture, host string) []byte {
+ t.Helper()
+ raw, _, err := fx.rel.Get(context.Background(), "control/certs/"+domains.ImportName(host))
+ if err != nil {
+ t.Fatalf("import for %s: %v", host, err)
+ }
+ return raw
+}
+
+type certDoorFixture struct {
+ fx *consoleFixture
+ alice, paul string
+ ca *certFixture
+ claim domains.Claim
+ leaf *x509.Certificate
+ key crypto.Signer
+}
+
+// newCertDoorFixture is the platform fixture (paul owns the ops account,
+// so he is a platform operator; alice is a member) with the fixture CA's
+// root as the door's root set and tickets.example.com claimed by titogo.
+func newCertDoorFixture(t *testing.T, code string) *certDoorFixture {
+ t.Helper()
+ fx, alice, paul := platformFixture(t, code)
+ d := &certDoorFixture{fx: fx, alice: alice, paul: paul, ca: newCertFixture(t)}
+ fx.srv.certImportRoots = d.ca.roots
+ d.claim = domains.Claim{Host: "tickets.example.com", Account: "bab", App: "titogo", Route: "go.tito.io",
+ CreatedAt: "2026-11-20T10:00:00Z"}
+ putClaim(t, fx, d.claim)
+ d.leaf, d.key = d.ca.leaf(t, leafOpts{names: []string{"tickets.example.com"}})
+ return d
+}
+
+type certAnswer struct {
+ Host string `json:"host"`
+ SHA256 string `json:"sha256"`
+ Issuer string `json:"issuer"`
+ SANs int `json:"sans"`
+ NotAfter string `json:"not_after"`
+ Wildcard bool `json:"wildcard"`
+}
+
+func TestCertImportStoresWhatItVerified(t *testing.T) {
+ d := newCertDoorFixture(t, "code-cert-store")
+ fx := d.fx
+ ec := d.key.(*ecdsa.PrivateKey)
+ stray := "Bag Attributes\n friendlyName: stray-marker-1429\n"
+ certText := stray + string(pemCerts(d.leaf, d.ca.inter, d.ca.root))
+ keyText := stray + string(pemSEC1(t, ec))
+ code, _, out := rawReq(t, http.MethodPut, certURL(fx, "bab", "titogo", "tickets.example.com"), d.paul,
+ certBody([]byte(certText), []byte(keyText), false))
+ if code != http.StatusOK {
+ t.Fatalf("import = %d %s, want 200", code, out)
+ }
+ var got certAnswer
+ if err := json.Unmarshal([]byte(out), &got); err != nil {
+ t.Fatal(err)
+ }
+ sum := sha256.Sum256(d.leaf.Raw)
+ want := certAnswer{Host: "tickets.example.com", SHA256: hex.EncodeToString(sum[:]), Issuer: "Fixture Issuing CA",
+ SANs: 1, NotAfter: d.leaf.NotAfter.UTC().Format(time.RFC3339), Wildcard: false}
+ if got != want {
+ t.Fatalf("answer = %+v, want %+v", got, want)
+ }
+
+ raw := storedImport(t, fx, "tickets.example.com")
+ b, pair, err := domains.ParseImport(raw)
+ if err != nil {
+ t.Fatalf("stored entry does not parse: %v", err)
+ }
+ if b != (domains.ImportBinding{Host: "tickets.example.com", Account: "bab", App: "titogo", ClaimCreated: d.claim.CreatedAt}) {
+ t.Fatalf("binding = %+v", b)
+ }
+ if !b.Matches(d.claim) {
+ t.Fatalf("binding %+v does not match its claim", b)
+ }
+ if len(pair.Certificate) != 2 || string(pair.Certificate[0]) != string(d.leaf.Raw) || string(pair.Certificate[1]) != string(d.ca.inter.Raw) {
+ t.Fatalf("stored chain has %d certs, want leaf then intermediate (no root)", len(pair.Certificate))
+ }
+ s := string(raw)
+ if strings.Contains(s, "stray-marker-1429") || strings.Contains(s, "Bag Attributes") || strings.Contains(s, "EC PRIVATE KEY") {
+ t.Fatalf("stored entry keeps the operator's text:\n%s", s)
+ }
+ if !strings.Contains(s, "-----BEGIN PRIVATE KEY-----") {
+ t.Fatal("stored key is not PKCS #8")
+ }
+
+ // A re-import replaces it.
+ leaf2, key2 := d.ca.leaf(t, leafOpts{names: []string{"tickets.example.com"}})
+ if code, _, out := rawReq(t, http.MethodPut, certURL(fx, "bab", "titogo", "tickets.example.com"), d.paul,
+ certBody(pemCerts(leaf2, d.ca.inter), pemPKCS8(t, key2), false)); code != http.StatusOK {
+ t.Fatalf("re-import = %d %s", code, out)
+ }
+ if _, pair, err := domains.ParseImport(storedImport(t, fx, "tickets.example.com")); err != nil || string(pair.Certificate[0]) != string(leaf2.Raw) {
+ t.Fatalf("re-import did not replace the entry (err %v)", err)
+ }
+
+ events, err := fx.st.Events(OpsAccountID, "titogo", 50)
+ if err != nil {
+ t.Fatal(err)
+ }
+ n := 0
+ for _, e := range events {
+ if e.Action == "domain-cert-import" {
+ n++
+ if e.Address != "paul@keymail.dev" || !strings.Contains(e.Detail, "tickets.example.com") ||
+ !strings.Contains(e.Detail, "Fixture Issuing CA") || strings.Contains(e.Detail, "allow-wildcard") {
+ t.Errorf("audit row = %+v", e)
+ }
+ }
+ }
+ if n != 2 {
+ t.Fatalf("%d domain-cert-import rows, want 2", n)
+ }
+}
+
+func TestCertImportWildcardFlag(t *testing.T) {
+ d := newCertDoorFixture(t, "code-cert-wild")
+ fx := d.fx
+ wleaf, wkey := d.ca.leaf(t, leafOpts{names: []string{"*.example.com", "example.com"}})
+ u := certURL(fx, "bab", "titogo", "tickets.example.com")
+ code, _, out := rawReq(t, http.MethodPut, u, d.paul, certBody(pemCerts(wleaf, d.ca.inter), pemPKCS8(t, wkey), false))
+ if code != http.StatusBadRequest || jsonErrorText(t, out) != certWildcardOnly {
+ t.Fatalf("wildcard without the flag = %d %s, want 400 %q", code, out, certWildcardOnly)
+ }
+ importAbsent(t, fx, "tickets.example.com")
+ code, _, out = rawReq(t, http.MethodPut, u, d.paul, certBody(pemCerts(wleaf, d.ca.inter), pemPKCS8(t, wkey), true))
+ if code != http.StatusOK {
+ t.Fatalf("wildcard with the flag = %d %s", code, out)
+ }
+ var got certAnswer
+ if err := json.Unmarshal([]byte(out), &got); err != nil || !got.Wildcard || got.SANs != 2 {
+ t.Fatalf("answer = %+v (%v), want wildcard, 2 SANs", got, err)
+ }
+ b, _, err := domains.ParseImport(storedImport(t, fx, "tickets.example.com"))
+ if err != nil || b.Host != "tickets.example.com" {
+ t.Fatalf("binding %+v, %v: want it bound to the one exact host", b, err)
+ }
+ events, _ := fx.st.Events(OpsAccountID, "titogo", 50)
+ found := false
+ for _, e := range events {
+ if e.Action == "domain-cert-import" && strings.HasSuffix(e.Detail, "(allow-wildcard)") {
+ found = true
+ }
+ }
+ if !found {
+ t.Fatal("no audit row marked (allow-wildcard)")
+ }
+}
+
+// TestCertImportGates: every caller and claim the door refuses, in order,
+// and nothing written by any of them.
+func TestCertImportGates(t *testing.T) {
+ d := newCertDoorFixture(t, "code-cert-gates")
+ fx := d.fx
+ body := certBody(pemCerts(d.leaf, d.ca.inter), pemPKCS8(t, d.key), false)
+ notFound := canonicalNotFound(t)
+
+ // Gate 1: a non-member gets the family's byte-identical 404, on both
+ // verbs.
+ eve := cliToken(t, fx, "eve@keymail.dev", "code-cert-gates-eve")
+ for _, m := range []string{http.MethodPut, http.MethodDelete} {
+ code, h, out := rawReq(t, m, certURL(fx, "bab", "titogo", "tickets.example.com"), eve, body)
+ assertNotFound(t, "non-member "+m, notFound, code, h, out)
+ }
+ // A service credential, even one the operator minted, never reaches it.
+ tok, err := fx.st.NewAppToken(OpsAccountID, "titogo", "paul@keymail.dev", "signup", time.Now())
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, m := range []string{http.MethodPut, http.MethodDelete} {
+ if code, _, out := rawReq(t, m, certURL(fx, "bab", "titogo", "tickets.example.com"), tok, body); code == http.StatusOK {
+ t.Errorf("app token %s = %d %s, want refused", m, code, out)
+ }
+ }
+ // Gate 2: a member who is not a platform operator.
+ for _, m := range []string{http.MethodPut, http.MethodDelete} {
+ code, _, out := rawReq(t, m, certURL(fx, "bab", "titogo", "tickets.example.com"), d.alice, body)
+ if code != http.StatusForbidden || jsonErrorText(t, out) != certOperatorOnly {
+ t.Errorf("member %s = %d %s, want 403 %q", m, code, out, certOperatorOnly)
+ }
+ }
+ // A malformed host is a 400 before anything is read.
+ for _, bad := range []string{"bad_host", "..%2F..%2Fcerts"} {
+ if code, _, out := rawReq(t, http.MethodPut, certURL(fx, "bab", "titogo", bad), d.paul, body); code != http.StatusBadRequest {
+ t.Errorf("host %q = %d %s, want 400", bad, code, out)
+ }
+ }
+ // Gate 3: the claim. Missing, another app's, another account's,
+ // pending and a wildcard claim all read as the same neutral 404.
+ putClaim(t, fx, domains.Claim{Host: "other-app.example.com", Account: "bab", App: "widgets", Route: "w.example.net"})
+ putClaim(t, fx, domains.Claim{Host: "theirs.example.com", Account: "cdef", App: "titogo", Route: "w.example.net"})
+ putClaim(t, fx, domains.Claim{Host: "pending.example.com", Account: "bab", App: "titogo", Route: "go.tito.io", Pending: true})
+ for _, host := range []string{"never.example.com", "other-app.example.com", "theirs.example.com", "pending.example.com"} {
+ leaf, key := d.ca.leaf(t, leafOpts{names: []string{host}})
+ for _, m := range []string{http.MethodPut, http.MethodDelete} {
+ code, _, out := rawReq(t, m, certURL(fx, "bab", "titogo", host), d.paul,
+ certBody(pemCerts(leaf, d.ca.inter), pemPKCS8(t, key), false))
+ if code != http.StatusNotFound || jsonErrorText(t, out) != certNoSuchHost {
+ t.Errorf("%s %s = %d %s, want 404 %q", m, host, code, out, certNoSuchHost)
+ }
+ }
+ importAbsent(t, fx, host)
+ }
+ importAbsent(t, fx, "tickets.example.com")
+
+ // A refused import writes nothing and answers 400.
+ _, otherKey := d.ca.leaf(t, leafOpts{names: []string{"tickets.example.com"}})
+ code, _, out := rawReq(t, http.MethodPut, certURL(fx, "bab", "titogo", "tickets.example.com"), d.paul,
+ certBody(pemCerts(d.leaf, d.ca.inter), pemPKCS8(t, otherKey), false))
+ if code != http.StatusBadRequest || jsonErrorText(t, out) != certKeyMismatch {
+ t.Fatalf("mismatched key = %d %s, want 400 %q", code, out, certKeyMismatch)
+ }
+ importAbsent(t, fx, "tickets.example.com")
+
+ // Over 64 KiB is refused before it is parsed.
+ big := strings.Repeat("A", 70<<10)
+ code, _, out = rawReq(t, http.MethodPut, certURL(fx, "bab", "titogo", "tickets.example.com"), d.paul,
+ certBody([]byte(big), pemPKCS8(t, d.key), false))
+ if code != http.StatusRequestEntityTooLarge || jsonErrorText(t, out) != certBodyTooLarge {
+ t.Fatalf("oversized body = %d %s, want 413", code, out)
+ }
+ // Not JSON.
+ code, _, out = rawReq(t, http.MethodPut, certURL(fx, "bab", "titogo", "tickets.example.com"), d.paul, "not json")
+ if code != http.StatusBadRequest || jsonErrorText(t, out) != certBodyUnreadable {
+ t.Fatalf("non-JSON body = %d %s, want 400 %q", code, out, certBodyUnreadable)
+ }
+ importAbsent(t, fx, "tickets.example.com")
+}
+
+// TestCertImportNeverLeaksTheKey: no answer, Activity row or log line
+// carries any run of the key's PEM text, on success, on refusal or on
+// removal.
+func TestCertImportNeverLeaksTheKey(t *testing.T) {
+ logs := captureLog(t)
+ d := newCertDoorFixture(t, "code-cert-leak")
+ fx := d.fx
+ keyPEM := pemPKCS8(t, d.key)
+ var outputs []string
+ send := func(method, body string) {
+ _, _, out := rawReq(t, method, certURL(fx, "bab", "titogo", "tickets.example.com"), d.paul, body)
+ outputs = append(outputs, out)
+ }
+ _, otherKey := d.ca.leaf(t, leafOpts{names: []string{"tickets.example.com"}})
+ send(http.MethodPut, certBody(pemCerts(d.leaf, d.ca.inter), keyPEM, false)) // success
+ send(http.MethodPut, certBody(pemCerts(d.leaf, d.ca.inter), append(keyPEM, keyPEM...), false)) // two keys
+ send(http.MethodPut, certBody(keyPEM, keyPEM, false)) // key as cert
+ send(http.MethodPut, certBody(pemCerts(d.leaf, d.ca.inter), pemPKCS8(t, otherKey), false)) // mismatch
+ send(http.MethodPut, `{"cert": "`+strings.ReplaceAll(string(keyPEM), "\n", "")+`", "key": 7}`) // bad JSON
+ _, _, out := rawReq(t, http.MethodGet, domainGetURL(fx, "bab", "titogo", "tickets.example.com"), d.paul, "")
+ outputs = append(outputs, out)
+ send(http.MethodDelete, "")
+
+ events, err := fx.st.Events(OpsAccountID, "titogo", 50)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, e := range events {
+ outputs = append(outputs, e.Detail)
+ }
+ outputs = append(outputs, logs.String())
+
+ // Every 16-character run of the key's base64 body.
+ block, _ := pem.Decode(keyPEM)
+ body := strings.ReplaceAll(string(pem.EncodeToMemory(&pem.Block{Type: "X", Bytes: block.Bytes})), "\n", "")
+ body = strings.TrimSuffix(strings.TrimPrefix(body, "-----BEGIN X-----"), "-----END X-----")
+ if len(body) < 64 {
+ t.Fatalf("key body too short to test (%d)", len(body))
+ }
+ for i := 0; i+16 <= len(body); i++ {
+ run := body[i : i+16]
+ for _, o := range outputs {
+ if strings.Contains(o, run) {
+ t.Fatalf("output carries key text %q:\n%s", run, o)
+ }
+ }
+ }
+ for _, o := range outputs {
+ if strings.Contains(o, "PRIVATE KEY") {
+ t.Fatalf("output names a PEM key block:\n%s", o)
+ }
+ }
+}
+
+func TestCertRemoveAndGet(t *testing.T) {
+ d := newCertDoorFixture(t, "code-cert-remove")
+ fx := d.fx
+ u := certURL(fx, "bab", "titogo", "tickets.example.com")
+
+ getImported := func() map[string]any {
+ t.Helper()
+ code, _, out := rawReq(t, http.MethodGet, domainGetURL(fx, "bab", "titogo", "tickets.example.com"), d.alice, "")
+ if code != http.StatusOK {
+ t.Fatalf("get = %d %s", code, out)
+ }
+ var got map[string]any
+ if err := json.Unmarshal([]byte(out), &got); err != nil {
+ t.Fatal(err)
+ }
+ ic, _ := got["imported_cert"].(map[string]any)
+ return ic
+ }
+ if ic := getImported(); ic != nil {
+ t.Fatalf("imported_cert before any import = %v, want absent", ic)
+ }
+
+ // Removing an import that is not there is 200, removed false, and
+ // writes no Activity row.
+ code, _, out := rawReq(t, http.MethodDelete, u, d.paul, "")
+ if code != http.StatusOK || out != `{"host":"tickets.example.com","removed":false}`+"\n" {
+ t.Fatalf("remove of nothing = %d %q", code, out)
+ }
+
+ if code, _, out := rawReq(t, http.MethodPut, u, d.paul, certBody(pemCerts(d.leaf, d.ca.inter), pemPKCS8(t, d.key), false)); code != http.StatusOK {
+ t.Fatalf("import = %d %s", code, out)
+ }
+ ic := getImported()
+ sum := sha256.Sum256(d.leaf.Raw)
+ if ic == nil || ic["sha256"] != hex.EncodeToString(sum[:]) || ic["issuer"] != "Fixture Issuing CA" ||
+ ic["not_after"] != d.leaf.NotAfter.UTC().Format(time.RFC3339) || ic["host"] != "tickets.example.com" {
+ t.Fatalf("imported_cert = %v", ic)
+ }
+
+ // An import bound to an earlier acquisition of the name is not shown.
+ putClaim(t, fx, domains.Claim{Host: "tickets.example.com", Account: "bab", App: "titogo", Route: "go.tito.io",
+ CreatedAt: "2026-11-24T10:00:00Z"})
+ if ic := getImported(); ic != nil {
+ t.Fatalf("imported_cert for a re-acquired claim = %v, want absent", ic)
+ }
+ putClaim(t, fx, d.claim)
+
+ code, _, out = rawReq(t, http.MethodDelete, u, d.paul, "")
+ if code != http.StatusOK || out != `{"host":"tickets.example.com","removed":true}`+"\n" {
+ t.Fatalf("remove = %d %q", code, out)
+ }
+ importAbsent(t, fx, "tickets.example.com")
+ if ic := getImported(); ic != nil {
+ t.Fatalf("imported_cert after remove = %v, want absent", ic)
+ }
+ events, _ := fx.st.Events(OpsAccountID, "titogo", 50)
+ n := 0
+ for _, e := range events {
+ if e.Action == "domain-cert-remove" {
+ n++
+ if !strings.Contains(e.Detail, hex.EncodeToString(sum[:])) {
+ t.Errorf("remove row = %q, want the removed leaf's sha256", e.Detail)
+ }
+ }
+ }
+ if n != 1 {
+ t.Fatalf("%d domain-cert-remove rows, want 1 (only the effective removal)", n)
+ }
+}
diff --git a/internal/console/apidomains.go b/internal/console/apidomains.go
index 8331fe835..f34fb5336 100644
--- a/internal/console/apidomains.go
+++ b/internal/console/apidomains.go
@@ -1653,7 +1653,7 @@ func (s *Server) handleAPIDomainGet(w http.ResponseWriter, r *http.Request) {
return
}
now := time.Now()
- writeJSON(w, http.StatusOK, map[string]any{
+ answer := map[string]any{
"domain": s.domainItem(ctx, *c, aliasReadings(ctx, s.cfg.Releases, now),
warmRecord(ctx, s.cfg.Releases, c.Host), s.dnsTargets(ctx), now,
c.Wildcard && s.delegationZone != ""),
@@ -1675,7 +1675,13 @@ func (s *Server) handleAPIDomainGet(w http.ResponseWriter, r *http.Request) {
// state (Claim.Paths is omitempty), and a client should not have to
// tell a nil from a {} to loop over it.
"paths": pathsOrEmpty(c.Paths),
- })
+ }
+ // An imported certificate (#1429), when one is bound to this claim:
+ // its issuer, SHA-256 and expiry, never its bytes. Absent otherwise.
+ if ic := s.importedCertSummary(ctx, *c); ic != nil {
+ answer["imported_cert"] = ic
+ }
+ writeJSON(w, http.StatusOK, answer)
}
// teamClaimSnapshotInScope judges, for a team request, the claim snapshot a
diff --git a/internal/console/domaincert_copy.go b/internal/console/domaincert_copy.go
new file mode 100644
index 000000000..fa1700071
--- /dev/null
+++ b/internal/console/domaincert_copy.go
@@ -0,0 +1,51 @@
+package console
+
+// Every sentence the imported-certificate door (apidomaincert.go, #1429)
+// can answer with or write to an Activity row, in one place for review.
+// None of them carries a byte of what the caller sent: each refusal names
+// the check that failed, never the input.
+
+const (
+ // certNoSuchHost is the domains family's neutral not-found, the same
+ // bytes detach and the per-host read answer.
+ certNoSuchHost = "no such hostname"
+
+ // certOperatorOnly answers a signed-in member who is not a platform
+ // operator.
+ certOperatorOnly = "only a platform operator (an ops account owner, or an address on CARLOS_SYSTEM_OPERATORS) can import or remove a certificate"
+
+ certBodyTooLarge = "the certificate and key are too large. Send at most 64 KiB"
+ certBodyUnreadable = `send a JSON body with "cert" and "key" fields holding PEM text`
+
+ certKeyMissing = "the key file holds no private key"
+ certKeyEncrypted = "the private key is protected by a passphrase. Export it without one and try again"
+ certKeyExtra = "the key file must hold one private key and nothing else"
+ certKeyUnreadable = "the private key could not be read. Use a PEM key in PKCS #8, PKCS #1 or SEC 1 form"
+ certKeyAlgorithm = "the private key must be RSA with 2048 to 4096 bits, or ECDSA on P-256 or P-384"
+
+ certChainMissing = "the certificate file holds no certificate"
+ certChainTooLong = "the certificate file holds more than five certificates"
+ certChainExtra = "the certificate file must hold only certificates, with the one for the hostname first"
+ certChainUnreadable = "a certificate in the certificate file could not be read"
+
+ certKeyMismatch = "the key does not match the certificate"
+ certLeafIsCA = "the first certificate is a CA certificate. Put the certificate for the hostname first"
+ certNotYetValid = "the certificate is not valid yet"
+ certExpiresSoon = "the certificate expires within seven days. Import a renewed one"
+ certWrongName = "the certificate does not cover this hostname"
+ certWrongUsage = "the certificate is not issued for use by web servers"
+ certChainExpired = "a certificate in the chain has expired or is not valid yet"
+ certNotTrusted = "the certificate does not lead to a publicly trusted authority. Include the intermediate certificates after it. Self-signed and private certificates are not accepted"
+ certWildcardOnly = "the certificate covers this hostname only through a wildcard. Import it again with --allow-wildcard to use it for this hostname"
+
+ certReadFailed = "could not read the hostname. Try again"
+ certWriteFailed = "could not save the certificate. Try again"
+ certRemoveFailed = "could not remove the certificate. Try again"
+
+ // The Activity rows. %s are the host, the leaf's SHA-256 (hex), the
+ // issuer's common name and the expiry (RFC 3339).
+ certAuditImport = "imported a certificate for %s: sha256 %s, issued by %s, expires %s"
+ certAuditRemove = "removed the imported certificate for %s: sha256 %s, issued by %s, expires %s"
+ certAuditRemoveUnknown = "removed the imported certificate for %s"
+ certAuditWildcard = " (allow-wildcard)"
+)
diff --git a/internal/console/linkedpolicy.go b/internal/console/linkedpolicy.go
index dc80548c4..723c55e24 100644
--- a/internal/console/linkedpolicy.go
+++ b/internal/console/linkedpolicy.go
@@ -89,6 +89,8 @@ var linkedPolicies = map[string]linkedPolicy{
"GET /api/cli/apps/{account}/{app}/domains/{host}": linkedRefuseDomains,
"GET /api/cli/apps/{account}/{app}/domains/{host}/placements": linkedRefuseDomains,
"PUT /api/cli/apps/{account}/{app}/domains/{host}/placements": linkedRefuseDomains,
+ "PUT /api/cli/apps/{account}/{app}/domains/{host}/cert": linkedRefuseDomains,
+ "DELETE /api/cli/apps/{account}/{app}/domains/{host}/cert": linkedRefuseDomains,
"POST /api/cli/apps/{account}/{app}/domains": linkedRefuseDomains,
"DELETE /api/cli/apps/{account}/{app}/domains/{host}": linkedRefuseDomains,
"PUT /api/cli/apps/{account}/{app}/domains/{host}/paths": linkedRefuseDomains,
diff --git a/internal/console/routedecls.go b/internal/console/routedecls.go
index 31cb7ace6..28ba17b87 100644
--- a/internal/console/routedecls.go
+++ b/internal/console/routedecls.go
@@ -901,6 +901,13 @@ var routeDecls = []routeDecl{
// served in every region and its capabilities for the claim's life, and
// a team credential (no team set here) cannot reach it either.
{Pattern: "PUT /api/cli/apps/{account}/{app}/domains/{host}/placements", Kind: kindCLI, Allow: svcrole.Set{}, Handler: (*Server).handleAPIDomainPlacementsPut},
+ // Imported certificates (#1429, apidomaincert.go): a platform
+ // operator's act on a hostname their account holds, before its DNS
+ // moves. A person only: no service role, and no team set. Not on a
+ // host-claim console, which cannot detach an alias either: an import
+ // is bound to a claim acquisition that console does not manage.
+ {Pattern: "PUT /api/cli/apps/{account}/{app}/domains/{host}/cert", Kind: kindCLI, Gate: gateNoHostClaim, Allow: svcrole.Set{}, Handler: (*Server).handleAPIDomainCertImport},
+ {Pattern: "DELETE /api/cli/apps/{account}/{app}/domains/{host}/cert", Kind: kindCLI, Gate: gateNoHostClaim, Allow: svcrole.Set{}, Handler: (*Server).handleAPIDomainCertRemove},
{Pattern: "POST /api/cli/apps/{account}/{app}/domains", Kind: kindCLIScoped, Allow: svcrole.Allow(svcrole.Publish, svcrole.Instance), Target: scopeDomainBody, Handler: (*Server).handleAPIDomainAttach},
// The account's domains (apidomainbuy.go, Plan 2a): a person who is any
// member, not gated on buying, since a domain registered elsewhere needs
diff --git a/internal/console/server.go b/internal/console/server.go
index 650dcfaad..378d3d91f 100644
--- a/internal/console/server.go
+++ b/internal/console/server.go
@@ -1760,6 +1760,9 @@ type Server struct {
seenMu sync.Mutex
seen map[string]time.Time
lastSeenWrites atomic.Int64
+ // certImportRoots, when set (tests only), is the imported-certificate
+ // door's root set in place of the public roots (apidomaincert.go).
+ certImportRoots *x509.CertPool
}
// edgeFoldTTL is how long one fold of the deployment's edges files stands
diff --git a/internal/console/svcroutes_test.go b/internal/console/svcroutes_test.go
index fc9b0cda2..96e318dce 100644
--- a/internal/console/svcroutes_test.go
+++ b/internal/console/svcroutes_test.go
@@ -367,6 +367,9 @@ var closedDoors = []string{
// capabilities for the claim's life. A person's act: no credential the
// app holds, and no team credential, may make a name regional.
"PUT /api/cli/apps/{account}/{app}/domains/{host}/placements",
+ // Imported certificates (#1429): a platform operator's act, a person's.
+ "PUT /api/cli/apps/{account}/{app}/domains/{host}/cert",
+ "DELETE /api/cli/apps/{account}/{app}/domains/{host}/cert",
// `carlos system` (apisystem.go): what the whole deployment RUNS. The
// same cut as the mint and fleet doors, taken over the substrate every
// tenant sits inside rather than over one account's credentials, so it
@@ -486,6 +489,14 @@ var domainBuyDoors = []string{
"POST /api/cli/system/domains/purchases/{id}/resolve",
}
+// domainCertDoors are closed doors (in closedDoors) that a host-claim
+// console does not register: it cannot detach an alias, and an import is
+// bound to a claim acquisition it does not manage.
+var domainCertDoors = []string{
+ "PUT /api/cli/apps/{account}/{app}/domains/{host}/cert",
+ "DELETE /api/cli/apps/{account}/{app}/domains/{host}/cert",
+}
+
// TestEveryCLIDoorNamesItsRoles is the default-deny guarantee for the
// /api/cli/ half. A door declared plain would not appear in cliRoles at
// all (and the scan refuses it); a door declared with an accidental empty Set
@@ -554,6 +565,7 @@ func TestEveryCLIDoorNamesItsRoles(t *testing.T) {
{movesDoors, "gateMoves"},
{demoOperatorDoors, "gateNoHostClaim"},
{domainBuyDoors, "gateNoHostClaim"},
+ {domainCertDoors, "gateNoHostClaim"},
} {
for _, pattern := range c.doors {
g, ok := cliGate[pattern]
@@ -604,7 +616,7 @@ func TestEveryCLIDoorNamesItsRoles(t *testing.T) {
roles := tc.hostClaim && tc.regionHA
if tc.hostClaim {
wantClosed = append(wantClosed, hostClaimDoors...)
- wantClosed = slices.DeleteFunc(wantClosed, func(d string) bool { return slices.Contains(domainBuyDoors, d) })
+ wantClosed = slices.DeleteFunc(wantClosed, func(d string) bool { return slices.Contains(domainBuyDoors, d) || slices.Contains(domainCertDoors, d) })
}
if roles {
wantClosed = append(wantClosed, regionHADoors...)