edge: serve imported certificates and reconcile their bindings (#1429)
The mirror parses control/certs/<host>+import entries with domains.ParseImport into their own snapshot map, never into certs, keeps the disk copy identical to the bucket's (rewritten whenever bytes differ), and after every successful listing deletes *+import files the listing did not return. A failed listing, or a listed key whose Get failed, deletes nothing. The backfill skips imports. A handshake layer between the mirror and the wildcard wrapper (after perHostCert, so the warm never sees it) serves a usable import from mirror memory to a hello no usable CARLOS entry suits, for a deployment host; an acme-tls/1 hello always passes through. The issuer's HostPolicy refuses a name the mirror holds a usable import for until some box, this one included, publishes it pointing. An issuer-only reconcile deletes, with DeleteIfMatch on the mirror's ETag, imports whose claim binding no longer holds, at most five a pass.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
5 files changed,
+1,500
−9
internal/edge/certimport.go+392 −0internal/edge/certimport_e2e_test.go+191 −0internal/edge/certimport_test.go+816 −0internal/edge/certsync.go+89 −9internal/edge/edge.go+12 −0
diff --git a/internal/edge/certimport.go b/internal/edge/certimport.go| new file mode 100644 |
| index 000000000..50c03e5e7 |
| --- /dev/null |
| +++ b/internal/edge/certimport.go |
| @@ -0,0 +1,392 @@ |
| +package edge |
| + |
| +// Imported certificates for custom domains (#1429; spec |
| +// docs/superpowers/specs/2026-11-25-cert-import-1429-design.md). An operator |
| +// imports a certificate and key for an attached name whose zone we do not |
| +// control, so every edge can serve it before the name's DNS moves here. The |
| +// console writes control/certs/<host>+import (domains.EncodeImport); this |
| +// file is the edge's half: |
| +// |
| +// - the mirror keeps every +import entry in its own snapshot map |
| +// (certSnapshot.imports), never in certs, so the ordinary serving layers |
| +// (certificate, localCertificate, autocert) can never hand one out; |
| +// - wrapImported serves an import, from mirror memory only, to a hello no |
| +// usable CARLOS certificate suits, for a deployment host; |
| +// - pruneLocalImports keeps this box's disk copies identical to the |
| +// bucket's listing (the edges-file writer reads them to publish early); |
| +// - importReconciler, on the issuer, deletes every import whose claim |
| +// binding no longer holds. |
| +// |
| +// The issuer's HostPolicy half (no order before some box publishes the name |
| +// pointing) is in issuerHostPolicyAt. |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "crypto/tls" |
| + "errors" |
| + "fmt" |
| + "log" |
| + "os" |
| + "path/filepath" |
| + "slices" |
| + "strings" |
| + "sync" |
| + "time" |
| + |
| + "golang.org/x/crypto/acme" |
| + "golang.org/x/crypto/acme/autocert" |
| + |
| + "github.com/carlosframework/platform/internal/domains" |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +// importEntry is one mirrored import: its binding and key pair (cert nil when |
| +// the entry does not parse, binding then zero) and the ETag the mirror read |
| +// it at ("" = unknown: a failed read carried an older copy forward). |
| +type importEntry struct { |
| + binding domains.ImportBinding |
| + cert *tls.Certificate |
| + etag string |
| +} |
| + |
| +// importCacheName reports whether a cache name is an imported certificate's. |
| +func importCacheName(name string) bool { return strings.HasSuffix(name, domains.ImportSuffix) } |
| + |
| +// parseImportEntry parses one +import body for the snapshot. A body that does |
| +// not parse is kept with a nil cert, so the issuer's reconcile can see it and |
| +// remove it; the log line names the entry, never its bytes. |
| +func parseImportEntry(name string, body []byte) importEntry { |
| + b, cert, err := domains.ParseImport(body) |
| + if err != nil { |
| + log.Printf("certsync: imported certificate entry %q does not parse — not served; the issuer's reconcile removes it", name) |
| + return importEntry{} |
| + } |
| + return importEntry{binding: b, cert: cert} |
| +} |
| + |
| +// usableImport returns the import that would serve host right now, or nil. |
| +func (s *certSnapshot) usableImport(host string, now time.Time) *tls.Certificate { |
| + if s == nil || host == "" { |
| + return nil |
| + } |
| + e, ok := s.imports[domains.ImportName(host)] |
| + if !ok || !domains.ImportUsable(e.binding, e.cert, host, now) { |
| + return nil |
| + } |
| + return e.cert |
| +} |
| + |
| +// holdsUsableImport reports whether the mirror's snapshot holds an import |
| +// that would serve host right now. Nil-safe. |
| +func (m *certMirror) holdsUsableImport(host string, now time.Time) bool { |
| + if m == nil { |
| + return false |
| + } |
| + return m.snapshot().usableImport(host, now) != nil |
| +} |
| + |
| +// imports is the current snapshot's import map. Read-only: the snapshot is |
| +// immutable once published. |
| +func (m *certMirror) imports() map[string]importEntry { |
| + return m.snapshot().imports |
| +} |
| + |
| +// wrapImported is the import layer of the handshake chain. edge.go puts it |
| +// above the mirror's wrapGetCertificate and below the wildcard wrapper, and |
| +// AFTER capturing perHostCert, so the cert warm (which calls perHostCert) |
| +// never sees an import and keeps ordering CARLOS's own certificate. |
| +// |
| +// In order: |
| +// |
| +// - a hello offering only acme-tls/1 goes to the inner chain: a |
| +// tls-alpn-01 validation must reach its token certificate; |
| +// - a usable CARLOS entry (<host> or <host>+rsa, in date, naming the host) |
| +// that the hello supports wins: pass through; |
| +// - else a usable import the hello supports, for a deployment host (this |
| +// box routes it, or some box's edges file homes it exactly), is served; |
| +// - else pass through. |
| +// |
| +// Imports come from mirror memory only, never the local disk, so a removed |
| +// import is never served by a box that has listed since. deployed nil |
| +// serves no import at all. |
| +func (m *certMirror) wrapImported(inner func(*tls.ClientHelloInfo) (*tls.Certificate, error), deployed func(string) bool) func(*tls.ClientHelloInfo) (*tls.Certificate, error) { |
| + return func(hello *tls.ClientHelloInfo) (*tls.Certificate, error) { |
| + if len(hello.SupportedProtos) == 1 && hello.SupportedProtos[0] == acme.ALPNProto { |
| + return inner(hello) |
| + } |
| + name := serverName(hello.ServerName) |
| + snap := m.snapshot() |
| + imp := snap.usableImport(name, time.Now()) |
| + if imp == nil { |
| + return inner(hello) |
| + } |
| + for _, key := range [2]string{name, name + "+rsa"} { |
| + if c := snap.certs[key]; usableFor(c, name) && hello.SupportsCertificate(c) == nil { |
| + return inner(hello) |
| + } |
| + } |
| + if hello.SupportsCertificate(imp) != nil || deployed == nil || !deployed(name) { |
| + return inner(hello) |
| + } |
| + return imp, nil |
| + } |
| +} |
| + |
| +// pruneLocalImports deletes every regular *+import file in this box's cert |
| +// cache directory whose key the last SUCCESSFUL listing did not return |
| +// (listed holds the listed cache names). A key that was listed but could not |
| +// be read is in listed, so its disk copy stays; a failed listing never |
| +// reaches here. Only a DirCache can be enumerated; any other cache is left |
| +// alone. Under refreshMu. |
| +func (m *certMirror) pruneLocalImports(listed map[string]bool) { |
| + dir, ok := m.local.(autocert.DirCache) |
| + if !ok { |
| + return |
| + } |
| + entries, err := os.ReadDir(string(dir)) |
| + if err != nil { |
| + if !errors.Is(err, os.ErrNotExist) { |
| + log.Printf("certsync: cannot read the local cert cache to remove withdrawn imports: %v", err) |
| + } |
| + return |
| + } |
| + m.syncMu.Lock() |
| + defer m.syncMu.Unlock() |
| + for _, ent := range entries { |
| + name := ent.Name() |
| + if !ent.Type().IsRegular() || !importCacheName(name) || listed[name] { |
| + continue |
| + } |
| + if err := os.Remove(filepath.Join(string(dir), name)); err != nil && !errors.Is(err, os.ErrNotExist) { |
| + log.Printf("certsync: removing the withdrawn import %q from the local cert cache failed: %v — retried on the next listing", name, err) |
| + continue |
| + } |
| + delete(m.synced, name) |
| + log.Printf("certsync: removed the withdrawn import %q from the local cert cache", name) |
| + } |
| +} |
| + |
| +// reconcileLocalImport writes one import into the local cache by IDENTITY: |
| +// whenever the local copy's bytes differ from the bucket's, or the local |
| +// entry is not a regular file, whatever the expiry dates say. The cache's |
| +// Put writes mode 0600 (autocert.DirCache: a temp file, then a rename). |
| +func (m *certMirror) reconcileLocalImport(ctx context.Context, name string, body []byte) error { |
| + regular := true |
| + if dir, ok := m.local.(autocert.DirCache); ok { |
| + if fi, err := os.Lstat(filepath.Join(string(dir), name)); err == nil && !fi.Mode().IsRegular() { |
| + regular = false |
| + } |
| + } |
| + local, err := m.local.Get(ctx, name) |
| + if err != nil && !errors.Is(err, autocert.ErrCacheMiss) && regular { |
| + return fmt.Errorf("read %q: %w", name, err) |
| + } |
| + if err == nil && regular && bytes.Equal(local, body) { |
| + return nil |
| + } |
| + if err := m.local.Put(ctx, name, body); err != nil { |
| + return fmt.Errorf("write %q: %w", name, err) |
| + } |
| + return nil |
| +} |
| + |
| +// ---- the issuer's reconcile ------------------------------------------------- |
| + |
| +const ( |
| + // importReconcileInterval is the reconcile's cadence: the longest an |
| + // import can outlive the claim acquisition it was made for. |
| + importReconcileInterval = time.Minute |
| + // importReconcileDeletesPerPass bounds one pass's deletes, attempts |
| + // included: a bug here removes at most this many before the log says so. |
| + importReconcileDeletesPerPass = 5 |
| +) |
| + |
| +// importReconciler deletes imports whose claim binding no longer holds: the |
| +// claim is gone, pending, an instance catch-all, held by another account or |
| +// app, or re-acquired (another created_at), or the entry carries no readable |
| +// binding. It is the one cleanup for every detach path. Issuer only; each |
| +// delete is conditional on the ETag the mirror read, so an import rewritten |
| +// since is never removed by a stale view, and a store that cannot delete |
| +// conditionally deletes nothing. |
| +type importReconciler struct { |
| + store release.Store |
| + issuer IssuerGate |
| + // claims is one listing of the deployment's claims, plus the ones it |
| + // listed but could not read (domains.ClaimCache.ListWithUnread). |
| + claims func(context.Context) ([]domains.Claim, []domains.UnreadClaim, error) |
| + // imports is the mirror snapshot's import map. |
| + imports func() map[string]importEntry |
| + |
| + mu sync.Mutex |
| + // removed is the ETag each name was deleted at, so a mirror that has not |
| + // listed since does not make the next pass delete and log it again. |
| + removed map[string]string |
| + lastLog time.Time |
| +} |
| + |
| +// newImportReconciler arms the reconcile on a box with a deployment store |
| +// and a mirror. Its gate is STRICT: an edge with no issuer gate handed down |
| +// (a hand-run `carlos edge` with a bucket) is ungated for serving but is not |
| +// the deployment's issuer, and deletes nothing. |
| +func (e *Edge) newImportReconciler(mirror *certMirror) *importReconciler { |
| + if e.staticStore == nil || mirror == nil { |
| + return nil |
| + } |
| + store := e.staticStore |
| + cc := &domains.ClaimCache{} |
| + return &importReconciler{ |
| + store: store, |
| + issuer: func() (context.Context, bool) { |
| + if e.issuer == nil { |
| + return nil, false |
| + } |
| + return e.issuer() |
| + }, |
| + claims: func(ctx context.Context) ([]domains.Claim, []domains.UnreadClaim, error) { |
| + return cc.ListWithUnread(ctx, store) |
| + }, |
| + imports: mirror.imports, |
| + removed: map[string]string{}, |
| + } |
| +} |
| + |
| +func (r *importReconciler) run() { |
| + for { |
| + r.pass(context.Background()) |
| + time.Sleep(importReconcileInterval) |
| + } |
| +} |
| + |
| +// pass is one reconcile: nothing unless this box is the issuer and the |
| +// mirror holds an import, then one claims listing and at most |
| +// importReconcileDeletesPerPass conditional deletes. |
| +func (r *importReconciler) pass(ctx context.Context) { |
| + held, ok := r.issuer() |
| + if !ok { |
| + return |
| + } |
| + // The imports are read BEFORE the claims: the console writes a claim |
| + // before the import bound to it, so every import seen here has its claim |
| + // in the listing below. |
| + imports := r.imports() |
| + r.forget(imports) |
| + if len(imports) == 0 { |
| + return |
| + } |
| + cctx, cancel := context.WithTimeout(held, time.Minute) |
| + claims, unread, err := r.claims(cctx) |
| + cancel() |
| + if err != nil { |
| + // A failed listing is not "no claims": nothing is deleted. |
| + r.logFailure("edge: import reconcile: reading the domain claims failed: %v — no import is removed until it reads again", err) |
| + return |
| + } |
| + byHost := make(map[string]domains.Claim, len(claims)) |
| + for _, c := range claims { |
| + byHost[c.Host] = c |
| + } |
| + undecided := make(map[string]bool, len(unread)) |
| + for _, u := range unread { |
| + undecided[u.Host] = true |
| + } |
| + names := make([]string, 0, len(imports)) |
| + for name := range imports { |
| + names = append(names, name) |
| + } |
| + slices.Sort(names) |
| + attempts := 0 |
| + for _, name := range names { |
| + ie := imports[name] |
| + host, reason := staleImport(name, ie, byHost, undecided) |
| + if reason == "" || ie.etag == "" || r.alreadyRemoved(name, ie.etag) { |
| + continue |
| + } |
| + if attempts >= importReconcileDeletesPerPass { |
| + return |
| + } |
| + attempts++ |
| + dctx, cancel := context.WithTimeout(held, certPublishTimeout) |
| + err := release.DeleteIfMatch(dctx, r.store, certKey(name), ie.etag) |
| + cancel() |
| + if err != nil { |
| + // Unsupported, a CAS refusal (rewritten since the mirror read it), |
| + // or a store error: nothing was deleted; the next pass decides |
| + // again from a fresh view. |
| + r.logFailure("edge: import reconcile: removing the import for %s left it in place: %v — retried next pass", host, err) |
| + continue |
| + } |
| + r.mu.Lock() |
| + r.removed[name] = ie.etag |
| + r.mu.Unlock() |
| + log.Printf("edge: import reconcile: removed the imported certificate for %s: %s", host, reason) |
| + } |
| +} |
| + |
| +// staleImport decides one import: the host it is for, and why it must go |
| +// ("" = it stays, or this pass cannot decide). |
| +func staleImport(name string, ie importEntry, claims map[string]domains.Claim, undecided map[string]bool) (host, reason string) { |
| + host, ok := domains.ImportHost(name) |
| + if !ok { |
| + return strings.TrimSuffix(name, domains.ImportSuffix), "the entry's name is not a hostname" |
| + } |
| + if ie.cert == nil { |
| + return host, "the entry has no readable binding" |
| + } |
| + b := ie.binding |
| + if b.Host != host { |
| + return host, "the binding names another host" |
| + } |
| + if undecided[host] { |
| + // Listed but unreadable: not "gone". |
| + return host, "" |
| + } |
| + c, ok := claims[host] |
| + switch { |
| + case !ok: |
| + return host, "no claim holds the name" |
| + case b.Matches(c): |
| + return host, "" |
| + case c.Pending: |
| + return host, "the claim is pending" |
| + case c.Instances || strings.HasPrefix(c.Host, "*."): |
| + return host, "the claim is not an exact name" |
| + case c.Account != b.Account: |
| + return host, "the claim is held by another account" |
| + case c.App != b.App: |
| + return host, "the claim is held by another app" |
| + default: |
| + return host, "the claim was detached and attached again" |
| + } |
| +} |
| + |
| +func (r *importReconciler) alreadyRemoved(name, etag string) bool { |
| + r.mu.Lock() |
| + defer r.mu.Unlock() |
| + return r.removed[name] == etag |
| +} |
| + |
| +// forget drops the removed memo for names the mirror no longer holds. |
| +func (r *importReconciler) forget(imports map[string]importEntry) { |
| + r.mu.Lock() |
| + defer r.mu.Unlock() |
| + for name := range r.removed { |
| + if _, ok := imports[name]; !ok { |
| + delete(r.removed, name) |
| + } |
| + } |
| +} |
| + |
| +// logFailure says a failure at most hourly: it would otherwise repeat every |
| +// minute for as long as the bucket or the condition holds. |
| +func (r *importReconciler) logFailure(format string, args ...any) { |
| + r.mu.Lock() |
| + quiet := !r.lastLog.IsZero() && time.Since(r.lastLog) < time.Hour |
| + if !quiet { |
| + r.lastLog = time.Now() |
| + } |
| + r.mu.Unlock() |
| + if !quiet { |
| + log.Printf(format, args...) |
| + } |
| +} |
diff --git a/internal/edge/certimport_e2e_test.go b/internal/edge/certimport_e2e_test.go| new file mode 100644 |
| index 000000000..0fb0555b4 |
| --- /dev/null |
| +++ b/internal/edge/certimport_e2e_test.go |
| @@ -0,0 +1,191 @@ |
| +package edge |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "crypto/tls" |
| + "crypto/x509" |
| + "errors" |
| + "net" |
| + "os" |
| + "path/filepath" |
| + "testing" |
| + |
| + "golang.org/x/crypto/acme/autocert" |
| + |
| + "github.com/carlosframework/platform/internal/domains" |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +// #1429, end to end across an issuer that is the imported name's home box |
| +// (edge A, annie) and a second edge that does not route the name (edge B, |
| +// betty), on one bucket, each wired as RunWithActivatorReady wires it: the |
| +// import layer above the mirror over autocert, perHostCert captured below it. |
| +// |
| +// Import -> both edges serve it before the name points, the issuer refuses |
| +// to order; the home box publishes it pointing -> the issuer allows it and |
| +// the warm's order lands a CARLOS ECDSA certificate (validated through edge |
| +// B); CARLOS's certificate then serves every client it suits while the RSA |
| +// import still serves an RSA-only client; removal -> edge B stops serving the |
| +// import after its next listing and its disk copy is gone. |
| +func TestImportE2EServeBeforePointingThenCarlosThenRemoval(t *testing.T) { |
| + e2eQuietLogs(t) |
| + bucket := t.TempDir() |
| + fake := newFakeACME(t) |
| + importCA := newE2ECA(t) |
| + shared := release.NewDirStore(bucket) |
| + |
| + edgeB := newE2EEdge(t, bucket, false, fake.directoryURL(), "other.acct.apps.test") |
| + fake.validateAgainst(edgeB.serveHTTP(t)) |
| + edgeA := newE2EEdge(t, bucket, true, fake.directoryURL(), importPrimary, importHost) |
| + edgeA.serveHTTP(t) |
| + |
| + // The home box's own edges file: the alias published early, not pointing |
| + // (what internal/host's writer does for an alias with a usable import). |
| + putJSON(t, shared, "control/edges/annie.json", ownFile(false)) |
| + homesA, homesB := newHomeMap(shared, "annie"), newHomeMap(shared, "betty") |
| + refreshHomeMap(t, homesA) |
| + refreshHomeMap(t, homesB) |
| + edgeA.edge.homes.Store(homesA) |
| + edgeB.edge.homes.Store(homesB) |
| + |
| + // The import layer, as edge.go composes it. |
| + full := map[*e2eEdge]func(*tls.ClientHelloInfo) (*tls.Certificate, error){} |
| + perHost := map[*e2eEdge]func(*tls.ClientHelloInfo) (*tls.Certificate, error){} |
| + for _, b := range []*e2eEdge{edgeA, edgeB} { |
| + perHost[b] = b.getCert |
| + full[b] = b.mirror.wrapImported(b.getCert, b.edge.deploymentHost) |
| + b.tlsConfig.GetCertificate = full[b] |
| + } |
| + lnA, lnB := edgeA.serveTLS(t), edgeB.serveTLS(t) |
| + |
| + rsaImport := goodImport(t, importCA, importHost, true) |
| + importLeaf := leafOfImport(t, rsaImport) |
| + putBucket(t, shared, domains.ImportName(importHost), rsaImport) |
| + for _, b := range []*e2eEdge{edgeA, edgeB} { |
| + refreshMirror(t, b.mirror) |
| + } |
| + |
| + roots := x509.NewCertPool() |
| + roots.AddCert(fake.root) |
| + roots.AddCert(importCA.root) |
| + modern := func(ln net.Listener) (*x509.Certificate, error) { |
| + st, err := e2eDial(ln, importHost, roots) |
| + if err != nil { |
| + return nil, err |
| + } |
| + return st.PeerCertificates[0], nil |
| + } |
| + rsaOnly := func(ln net.Listener) (*x509.Certificate, error) { |
| + conn, err := tls.Dial("tcp", ln.Addr().String(), &tls.Config{ServerName: importHost, RootCAs: roots, |
| + MinVersion: tls.VersionTLS12, MaxVersion: tls.VersionTLS12, |
| + CipherSuites: []uint16{tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256}}) |
| + if err != nil { |
| + return nil, err |
| + } |
| + defer conn.Close() |
| + return conn.ConnectionState().PeerCertificates[0], nil |
| + } |
| + mustServe := func(t *testing.T, label string, dial func(net.Listener) (*x509.Certificate, error), ln net.Listener, want *x509.Certificate) { |
| + t.Helper() |
| + got, err := dial(ln) |
| + if err != nil { |
| + t.Fatalf("%s: handshake failed: %v", label, err) |
| + } |
| + if !got.Equal(want) { |
| + t.Fatalf("%s: served %q (issuer %q), want the other certificate", label, got.Subject.CommonName, got.Issuer.CommonName) |
| + } |
| + } |
| + |
| + t.Run("before pointing both edges serve the import and nothing orders", func(t *testing.T) { |
| + if edgeB.edge.Allowed(importHost) || !edgeB.edge.deploymentHost(importHost) { |
| + t.Fatal("test bug: edge B must know the name only from the home box's edges file") |
| + } |
| + mustServe(t, "B modern", modern, lnB, importLeaf) |
| + mustServe(t, "B RSA-only", rsaOnly, lnB, importLeaf) |
| + mustServe(t, "A modern", modern, lnA, importLeaf) |
| + mustServe(t, "A RSA-only", rsaOnly, lnA, importLeaf) |
| + if err := edgeA.edge.issuerHostPolicy()(context.Background(), importHost); !errors.Is(err, errImportNotPointing) { |
| + t.Fatalf("issuer HostPolicy before pointing = %v; want the refusal", err) |
| + } |
| + if accounts, orders := fake.counts(); accounts+orders != 0 { |
| + t.Fatalf("the CA saw %d accounts and %d orders before the name points", accounts, orders) |
| + } |
| + }) |
| + |
| + t.Run("the disk copy is on the non-issuer, mode 0600", func(t *testing.T) { |
| + p := filepath.Join(localDir(t, edgeB), domains.ImportName(importHost)) |
| + fi, err := os.Lstat(p) |
| + if err != nil || !fi.Mode().IsRegular() || fi.Mode().Perm() != 0o600 { |
| + t.Fatalf("disk copy: %v, %v", fi, err) |
| + } |
| + }) |
| + |
| + t.Run("an acme-tls/1 hello passes through", func(t *testing.T) { |
| + if c, _ := full[edgeB](alpnHello(importHost)); c != nil && bytes.Equal(c.Certificate[0], importLeaf.Raw) { |
| + t.Fatal("a tls-alpn-01 hello was served the import") |
| + } |
| + }) |
| + |
| + // The DNS sweep stamps the alias pointing on the home box. |
| + putJSON(t, shared, "control/edges/annie.json", ownFile(true)) |
| + refreshHomeMap(t, homesA) |
| + refreshHomeMap(t, homesB) |
| + |
| + var minted *tls.Certificate |
| + t.Run("after pointing the warm's order lands CARLOS's certificate", func(t *testing.T) { |
| + if err := edgeA.edge.issuerHostPolicy()(context.Background(), importHost); err != nil { |
| + t.Fatalf("issuer HostPolicy after pointing = %v; want allowed", err) |
| + } |
| + c, err := perHost[edgeA](ecdsaHello(importHost)) |
| + if err != nil { |
| + t.Fatalf("the warm's order failed: %v", err) |
| + } |
| + fake.checkFaults(t) |
| + if c.Leaf == nil || c.Leaf.CheckSignatureFrom(fake.root) != nil { |
| + t.Fatal("the warm's call did not return CARLOS's own certificate") |
| + } |
| + minted = c |
| + }) |
| + if minted == nil { |
| + t.FailNow() |
| + } |
| + for _, b := range []*e2eEdge{edgeA, edgeB} { |
| + refreshMirror(t, b.mirror) |
| + } |
| + |
| + t.Run("CARLOS preferred where it suits, the RSA import for RSA-only clients", func(t *testing.T) { |
| + mustServe(t, "B modern", modern, lnB, minted.Leaf) |
| + mustServe(t, "A modern", modern, lnA, minted.Leaf) |
| + mustServe(t, "B RSA-only", rsaOnly, lnB, importLeaf) |
| + mustServe(t, "A RSA-only", rsaOnly, lnA, importLeaf) |
| + }) |
| + |
| + t.Run("removal stops serving after the next listing and removes the disk copy", func(t *testing.T) { |
| + if err := shared.Delete(context.Background(), certKey(domains.ImportName(importHost))); err != nil { |
| + t.Fatal(err) |
| + } |
| + refreshMirror(t, edgeB.mirror) |
| + if got, err := rsaOnly(lnB); err == nil && got.Equal(importLeaf) { |
| + t.Fatal("edge B still serves a removed import") |
| + } |
| + mustServe(t, "B modern", modern, lnB, minted.Leaf) |
| + if _, err := os.Lstat(filepath.Join(localDir(t, edgeB), domains.ImportName(importHost))); !errors.Is(err, os.ErrNotExist) { |
| + t.Fatalf("the disk copy survived the removal: %v", err) |
| + } |
| + _, wrote := edgeB.store.snapshot() |
| + if len(wrote) != 0 { |
| + t.Fatalf("the non-issuer wrote %v to the bucket", wrote) |
| + } |
| + }) |
| +} |
| + |
| +// localDir is an e2e edge's local cert cache directory. |
| +func localDir(t *testing.T, b *e2eEdge) string { |
| + t.Helper() |
| + d, ok := b.local.(autocert.DirCache) |
| + if !ok { |
| + t.Fatal("test bug: the e2e edge's local cache is a DirCache") |
| + } |
| + return string(d) |
| +} |
diff --git a/internal/edge/certimport_test.go b/internal/edge/certimport_test.go| new file mode 100644 |
| index 000000000..3288530db |
| --- /dev/null |
| +++ b/internal/edge/certimport_test.go |
| @@ -0,0 +1,816 @@ |
| +package edge |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "crypto" |
| + "crypto/ecdsa" |
| + "crypto/elliptic" |
| + "crypto/rand" |
| + "crypto/rsa" |
| + "crypto/tls" |
| + "crypto/x509" |
| + "crypto/x509/pkix" |
| + "encoding/pem" |
| + "errors" |
| + "log" |
| + "math/big" |
| + "os" |
| + "path/filepath" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "golang.org/x/crypto/acme/autocert" |
| + |
| + "github.com/carlosframework/platform/internal/domains" |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +// Imported certificates (#1429), the edge's half: the mirror, the handshake |
| +// layer, the issuer's HostPolicy and the issuer's reconcile. |
| + |
| +const ( |
| + importHost = "billing.import.test" |
| + importAccount = "acct" |
| + importApp = "app" |
| + importCreated = "2026-11-25T09:00:00Z" |
| +) |
| + |
| +func importBinding(host string) domains.ImportBinding { |
| + return domains.ImportBinding{Host: host, Account: importAccount, App: importApp, ClaimCreated: importCreated} |
| +} |
| + |
| +var ( |
| + importRSAOnce sync.Once |
| + importRSAKey *rsa.PrivateKey |
| +) |
| + |
| +// testImportRSAKey is one 2048-bit key for every RSA import in the package's |
| +// tests: generating one per test costs more than the test. |
| +func testImportRSAKey(t *testing.T) *rsa.PrivateKey { |
| + t.Helper() |
| + importRSAOnce.Do(func() { |
| + k, err := rsa.GenerateKey(rand.Reader, 2048) |
| + if err != nil { |
| + panic(err) |
| + } |
| + importRSAKey = k |
| + }) |
| + return importRSAKey |
| +} |
| + |
| +// importPEM is an import entry exactly as the console writes it: binding, |
| +// PKCS#8 key, then the leaf, issued by ca for host and valid in |
| +// [notBefore, notAfter]. |
| +func importPEM(t *testing.T, ca *e2eCA, b domains.ImportBinding, host string, rsaKey bool, notBefore, notAfter time.Time) []byte { |
| + t.Helper() |
| + var priv crypto.Signer |
| + if rsaKey { |
| + priv = testImportRSAKey(t) |
| + } else { |
| + k, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + priv = k |
| + } |
| + serial, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 96)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + tmpl := &x509.Certificate{ |
| + SerialNumber: serial, |
| + Subject: pkix.Name{CommonName: host}, |
| + DNSNames: []string{host}, |
| + NotBefore: notBefore, |
| + NotAfter: notAfter, |
| + KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment, |
| + ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, |
| + } |
| + der, err := x509.CreateCertificate(rand.Reader, tmpl, ca.root, priv.Public(), ca.key) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + pkcs8, err := x509.MarshalPKCS8PrivateKey(priv) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return domains.EncodeImport(b, pkcs8, [][]byte{der}) |
| +} |
| + |
| +// goodImport is a current import for host bound to the test claim. |
| +func goodImport(t *testing.T, ca *e2eCA, host string, rsaKey bool) []byte { |
| + t.Helper() |
| + return importPEM(t, ca, importBinding(host), host, rsaKey, time.Now().Add(-time.Hour), time.Now().Add(60*24*time.Hour)) |
| +} |
| + |
| +func leafOfImport(t *testing.T, body []byte) *x509.Certificate { |
| + t.Helper() |
| + _, c, err := domains.ParseImport(body) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return c.Leaf |
| +} |
| + |
| +// modernHello is a TLS 1.3 client that takes ECDSA and RSA (PSS) alike. |
| +func modernHello(host string) *tls.ClientHelloInfo { |
| + return &tls.ClientHelloInfo{ |
| + ServerName: host, |
| + SupportedVersions: []uint16{tls.VersionTLS13, tls.VersionTLS12}, |
| + SignatureSchemes: []tls.SignatureScheme{tls.ECDSAWithP256AndSHA256, tls.PSSWithSHA256, tls.PKCS1WithSHA256}, |
| + SupportedCurves: []tls.CurveID{tls.X25519, tls.CurveP256}, |
| + CipherSuites: []uint16{tls.TLS_AES_128_GCM_SHA256, tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, |
| + tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256}, |
| + } |
| +} |
| + |
| +// rsaOnlyHello is a TLS 1.2 client with RSA cipher suites only: it cannot use |
| +// an ECDSA certificate. |
| +func rsaOnlyHello(host string) *tls.ClientHelloInfo { |
| + return &tls.ClientHelloInfo{ |
| + ServerName: host, |
| + SupportedVersions: []uint16{tls.VersionTLS12}, |
| + SignatureSchemes: []tls.SignatureScheme{tls.PKCS1WithSHA256, tls.PSSWithSHA256}, |
| + SupportedCurves: []tls.CurveID{tls.CurveP256}, |
| + CipherSuites: []uint16{tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256}, |
| + } |
| +} |
| + |
| +var errInnerProbe = errors.New("inner chain") |
| + |
| +// innerProbe stands in for the chain below the import layer and counts the |
| +// hellos that reach it. |
| +type innerProbe struct { |
| + mu sync.Mutex |
| + calls int |
| +} |
| + |
| +func (p *innerProbe) get(*tls.ClientHelloInfo) (*tls.Certificate, error) { |
| + p.mu.Lock() |
| + p.calls++ |
| + p.mu.Unlock() |
| + return nil, errInnerProbe |
| +} |
| + |
| +func (p *innerProbe) count() int { |
| + p.mu.Lock() |
| + defer p.mu.Unlock() |
| + return p.calls |
| +} |
| + |
| +func refreshMirror(t *testing.T, m *certMirror) { |
| + t.Helper() |
| + if err := m.Refresh(context.Background()); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +func deployedOnly(hosts ...string) func(string) bool { |
| + return func(h string) bool { |
| + for _, x := range hosts { |
| + if x == h { |
| + return true |
| + } |
| + } |
| + return false |
| + } |
| +} |
| + |
| +// ---- the mirror ------------------------------------------------------------- |
| + |
| +// An import is parsed with its binding into its own map, never into certs, |
| +// so no ordinary layer (the mirror's certificate, the local last resort, |
| +// autocert) can serve it. |
| +func TestImportMirrorParsesIntoItsOwnMap(t *testing.T) { |
| + ca := newE2ECA(t) |
| + s := release.NewDirStore(t.TempDir()) |
| + body := goodImport(t, ca, importHost, false) |
| + putBucket(t, s, domains.ImportName(importHost), body) |
| + local := autocert.DirCache(t.TempDir()) |
| + m := newCertMirror(s, local) |
| + refreshMirror(t, m) |
| + |
| + snap := m.snapshot() |
| + ie, ok := snap.imports[domains.ImportName(importHost)] |
| + if !ok || ie.cert == nil || ie.binding != importBinding(importHost) { |
| + t.Fatalf("import entry = %+v, %v; want parsed with its binding", ie, ok) |
| + } |
| + if ie.etag == "" { |
| + t.Fatal("the import's ETag must be kept for the reconcile's conditional delete") |
| + } |
| + for name := range snap.certs { |
| + if strings.HasSuffix(name, domains.ImportSuffix) { |
| + t.Fatalf("certs holds %q; imports must never be in the ordinary map", name) |
| + } |
| + } |
| + if c := m.certificate(importHost, false); c != nil { |
| + t.Fatal("the mirror's ordinary lookup served an import") |
| + } |
| + if c := m.localCertificate(context.Background(), importHost, true); c != nil { |
| + t.Fatal("the local last resort served an import") |
| + } |
| + got, err := os.ReadFile(filepath.Join(string(local), domains.ImportName(importHost))) |
| + if err != nil || !bytes.Equal(got, body) { |
| + t.Fatalf("local copy = %v; want the bucket's bytes", err) |
| + } |
| + fi, err := os.Stat(filepath.Join(string(local), domains.ImportName(importHost))) |
| + if err != nil || fi.Mode().Perm() != 0o600 { |
| + t.Fatalf("local copy mode = %v, %v; want 0600", fi.Mode().Perm(), err) |
| + } |
| +} |
| + |
| +// The ordinary parse path never reports an import as a broken certificate; a |
| +// broken import is reported once, by name, with no bytes. |
| +func TestImportMirrorParseLogs(t *testing.T) { |
| + ca := newE2ECA(t) |
| + s := release.NewDirStore(t.TempDir()) |
| + putBucket(t, s, domains.ImportName(importHost), goodImport(t, ca, importHost, false)) |
| + broken := hostCertPEM(t, "broken.import.test", time.Now().Add(24*time.Hour)) // no binding block |
| + putBucket(t, s, domains.ImportName("broken.import.test"), broken) |
| + var buf bytes.Buffer |
| + log.SetOutput(&buf) |
| + t.Cleanup(func() { log.SetOutput(os.Stderr) }) |
| + m := newCertMirror(s, nil) |
| + refreshMirror(t, m) |
| + out := buf.String() |
| + if strings.Contains(out, "does not parse as a certificate") { |
| + t.Fatalf("an import went through the ordinary parse:\n%s", out) |
| + } |
| + if !strings.Contains(out, `"broken.import.test+import" does not parse`) { |
| + t.Fatalf("a broken import must be reported by name:\n%s", out) |
| + } |
| + if strings.Contains(out, "BEGIN") { |
| + t.Fatalf("a log line carries PEM bytes:\n%s", out) |
| + } |
| + if ie, ok := m.snapshot().imports[domains.ImportName("broken.import.test")]; !ok || ie.cert != nil { |
| + t.Fatalf("broken import = %+v, %v; want kept with no certificate, for the reconcile", ie, ok) |
| + } |
| +} |
| + |
| +// The disk copy follows the bucket by identity: a re-import with the same or |
| +// an EARLIER expiry still replaces it. |
| +func TestImportMirrorReplacesTheDiskCopyByIdentity(t *testing.T) { |
| + ca := newE2ECA(t) |
| + s := release.NewDirStore(t.TempDir()) |
| + local := autocert.DirCache(t.TempDir()) |
| + m := newCertMirror(s, local) |
| + name := domains.ImportName(importHost) |
| + notAfter := time.Now().Add(60 * 24 * time.Hour) |
| + first := importPEM(t, ca, importBinding(importHost), importHost, false, time.Now().Add(-time.Hour), notAfter) |
| + putBucket(t, s, name, first) |
| + refreshMirror(t, m) |
| + for _, tc := range []struct { |
| + label string |
| + notAfter time.Time |
| + }{ |
| + {"equal expiry", notAfter}, |
| + {"earlier expiry", notAfter.Add(-20 * 24 * time.Hour)}, |
| + } { |
| + next := importPEM(t, ca, importBinding(importHost), importHost, false, time.Now().Add(-time.Hour), tc.notAfter) |
| + putBucket(t, s, name, next) |
| + refreshMirror(t, m) |
| + got, err := os.ReadFile(filepath.Join(string(local), name)) |
| + if err != nil || !bytes.Equal(got, next) { |
| + t.Fatalf("%s: the disk copy was not replaced (%v)", tc.label, err) |
| + } |
| + } |
| +} |
| + |
| +// failGetStore fails Get for one key: listed, unreadable. |
| +type failGetStore struct { |
| + release.Store |
| + key string |
| +} |
| + |
| +func (f failGetStore) Get(ctx context.Context, key string) ([]byte, string, error) { |
| + if key == f.key { |
| + return nil, "", errors.New("bucket blip") |
| + } |
| + return f.Store.Get(ctx, key) |
| +} |
| + |
| +// A disk copy whose key the listing no longer returns is deleted, by the full |
| +// rebuild and by the changed-only read; a failed listing and a listed key |
| +// whose Get failed delete nothing. |
| +func TestImportMirrorDeletesUnlistedDiskCopies(t *testing.T) { |
| + ca := newE2ECA(t) |
| + name := domains.ImportName(importHost) |
| + body := goodImport(t, ca, importHost, false) |
| + setup := func(t *testing.T) (*release.DirStore, autocert.DirCache) { |
| + s := release.NewDirStore(t.TempDir()) |
| + putBucket(t, s, name, body) |
| + putBucket(t, s, "keep.import.test", hostCertPEM(t, "keep.import.test", time.Now().Add(80*24*time.Hour))) |
| + local := autocert.DirCache(t.TempDir()) |
| + // A stray import the bucket never held, and an unrelated local entry. |
| + if err := local.Put(context.Background(), "stray.import.test+import", body); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := local.Put(context.Background(), "own.import.test", []byte("ordinary")); err != nil { |
| + t.Fatal(err) |
| + } |
| + return s, local |
| + } |
| + exists := func(local autocert.DirCache, n string) bool { |
| + _, err := os.Lstat(filepath.Join(string(local), n)) |
| + return err == nil |
| + } |
| + |
| + t.Run("full rebuild", func(t *testing.T) { |
| + s, local := setup(t) |
| + m := newCertMirror(s, local) |
| + refreshMirror(t, m) |
| + if exists(local, "stray.import.test+import") { |
| + t.Fatal("an import the listing never returned is still on disk") |
| + } |
| + if !exists(local, name) || !exists(local, "own.import.test") { |
| + t.Fatal("the listed import or an ordinary entry was removed") |
| + } |
| + if err := s.Delete(context.Background(), certKey(name)); err != nil { |
| + t.Fatal(err) |
| + } |
| + refreshMirror(t, m) |
| + if exists(local, name) { |
| + t.Fatal("a withdrawn import is still on disk after a full rebuild") |
| + } |
| + }) |
| + |
| + t.Run("changed-only read", func(t *testing.T) { |
| + s, local := setup(t) |
| + m := newCertMirror(s, local) |
| + refreshMirror(t, m) |
| + if err := s.Delete(context.Background(), certKey(name)); err != nil { |
| + t.Fatal(err) |
| + } |
| + m.refreshMu.Lock() |
| + err := m.refreshChanged(context.Background(), 1) |
| + m.refreshMu.Unlock() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if exists(local, name) { |
| + t.Fatal("a withdrawn import is still on disk after a changed-only read") |
| + } |
| + if m.holdsUsableImport(importHost, time.Now()) { |
| + t.Fatal("a withdrawn import is still in the snapshot") |
| + } |
| + }) |
| + |
| + t.Run("failed listing", func(t *testing.T) { |
| + s, local := setup(t) |
| + fs := &listFailingStore{Store: s} |
| + m := newCertMirror(fs, local) |
| + refreshMirror(t, m) |
| + if err := local.Put(context.Background(), "stray.import.test+import", body); err != nil { |
| + t.Fatal(err) |
| + } |
| + fs.setFail(true) |
| + if err := m.Refresh(context.Background()); err == nil { |
| + t.Fatal("a failed listing must fail the refresh") |
| + } |
| + if !exists(local, "stray.import.test+import") || !exists(local, name) { |
| + t.Fatal("a failed listing deleted a disk copy") |
| + } |
| + }) |
| + |
| + t.Run("listed but unreadable", func(t *testing.T) { |
| + s, local := setup(t) |
| + if err := local.Put(context.Background(), name, body); err != nil { |
| + t.Fatal(err) |
| + } |
| + // A fresh mirror (a box that just booted): no previous copy to carry. |
| + m := newCertMirror(failGetStore{Store: s, key: certKey(name)}, local) |
| + refreshMirror(t, m) |
| + if !exists(local, name) { |
| + t.Fatal("a listed import whose Get failed was deleted from disk") |
| + } |
| + if exists(local, "stray.import.test+import") { |
| + t.Fatal("the same pass must still remove an unlisted import") |
| + } |
| + }) |
| +} |
| + |
| +// The backfill never republishes an import, whatever the box's disk holds. |
| +func TestImportNeverBackfilled(t *testing.T) { |
| + ca := newE2ECA(t) |
| + s := release.NewDirStore(t.TempDir()) |
| + local := autocert.DirCache(t.TempDir()) |
| + if err := local.Put(context.Background(), domains.ImportName(importHost), goodImport(t, ca, importHost, false)); err != nil { |
| + t.Fatal(err) |
| + } |
| + m := newCertMirror(s, local) |
| + m.mayBackfill = func() bool { return true } |
| + m.issuing = func() bool { return true } |
| + m.allowed = func(string) bool { return true } |
| + m.backfill(context.Background()) |
| + if _, err := certStoreGet(t, s, certKey(domains.ImportName(importHost))); !errors.Is(err, os.ErrNotExist) { |
| + t.Fatalf("an import was backfilled into the bucket (%v)", err) |
| + } |
| +} |
| + |
| +// ---- the handshake layer ---------------------------------------------------- |
| + |
| +func importLayer(t *testing.T, s release.Store, deployed func(string) bool) (func(*tls.ClientHelloInfo) (*tls.Certificate, error), *innerProbe, *certMirror) { |
| + t.Helper() |
| + m := newCertMirror(s, nil) |
| + refreshMirror(t, m) |
| + p := &innerProbe{} |
| + return m.wrapImported(p.get, deployed), p, m |
| +} |
| + |
| +// A usable import is served to a hello no CARLOS certificate suits, for a |
| +// deployment host; a tls-alpn-01 hello always reaches the inner chain. |
| +func TestImportServedAndALPNPassesThrough(t *testing.T) { |
| + ca := newE2ECA(t) |
| + s := release.NewDirStore(t.TempDir()) |
| + body := goodImport(t, ca, importHost, false) |
| + putBucket(t, s, domains.ImportName(importHost), body) |
| + get, probe, _ := importLayer(t, s, deployedOnly(importHost)) |
| + |
| + c, err := get(modernHello(importHost)) |
| + if err != nil || c == nil || !c.Leaf.Equal(leafOfImport(t, body)) { |
| + t.Fatalf("modern hello: %v, %v; want the import", c != nil, err) |
| + } |
| + // Normalized like every other layer. |
| + if c, err := get(modernHello("BILLING.Import.TEST")); err != nil || c == nil { |
| + t.Fatalf("an upper-case SNI was not served the import: %v", err) |
| + } |
| + if n := probe.count(); n != 0 { |
| + t.Fatalf("the inner chain was consulted %d time(s)", n) |
| + } |
| + alpn := modernHello(importHost) |
| + alpn.SupportedProtos = []string{"acme-tls/1"} |
| + if _, err := get(alpn); !errors.Is(err, errInnerProbe) { |
| + t.Fatalf("an acme-tls/1 hello = %v; want it passed to the inner chain", err) |
| + } |
| +} |
| + |
| +// CARLOS's own certificate wins for every hello it suits; an RSA import still |
| +// serves the RSA-only hello an ECDSA CARLOS certificate cannot. |
| +func TestImportCarlosWinsWhenCompatible(t *testing.T) { |
| + ca := newE2ECA(t) |
| + s := release.NewDirStore(t.TempDir()) |
| + rsaImport := goodImport(t, ca, importHost, true) |
| + putBucket(t, s, domains.ImportName(importHost), rsaImport) |
| + putBucket(t, s, importHost, hostCertPEM(t, importHost, time.Now().Add(80*24*time.Hour))) // ECDSA |
| + get, probe, _ := importLayer(t, s, deployedOnly(importHost)) |
| + |
| + if _, err := get(modernHello(importHost)); !errors.Is(err, errInnerProbe) { |
| + t.Fatalf("an ECDSA-capable hello = %v; want the CARLOS certificate (the inner chain)", err) |
| + } |
| + c, err := get(rsaOnlyHello(importHost)) |
| + if err != nil || c == nil || !c.Leaf.Equal(leafOfImport(t, rsaImport)) { |
| + t.Fatalf("an RSA-only hello: %v; want the RSA import", err) |
| + } |
| + if n := probe.count(); n != 1 { |
| + t.Fatalf("inner chain calls = %d, want 1", n) |
| + } |
| +} |
| + |
| +// A CARLOS +rsa entry the hello supports wins over an RSA import too. |
| +func TestImportCarlosRSAEntryWins(t *testing.T) { |
| + ca := newE2ECA(t) |
| + s := release.NewDirStore(t.TempDir()) |
| + putBucket(t, s, domains.ImportName(importHost), goodImport(t, ca, importHost, true)) |
| + key := testImportRSAKey(t) |
| + tmpl := &x509.Certificate{SerialNumber: big.NewInt(9), Subject: pkix.Name{CommonName: importHost}, DNSNames: []string{importHost}, |
| + NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(80 * 24 * time.Hour), |
| + KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}} |
| + der, err := x509.CreateCertificate(rand.Reader, tmpl, ca.root, &key.PublicKey, ca.key) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var buf bytes.Buffer |
| + pkcs8, _ := x509.MarshalPKCS8PrivateKey(key) |
| + _ = pem.Encode(&buf, &pem.Block{Type: "PRIVATE KEY", Bytes: pkcs8}) |
| + _ = pem.Encode(&buf, &pem.Block{Type: "CERTIFICATE", Bytes: der}) |
| + putBucket(t, s, importHost+"+rsa", buf.Bytes()) |
| + get, _, _ := importLayer(t, s, deployedOnly(importHost)) |
| + if _, err := get(rsaOnlyHello(importHost)); !errors.Is(err, errInnerProbe) { |
| + t.Fatalf("an RSA-only hello with a CARLOS +rsa entry = %v; want the inner chain", err) |
| + } |
| +} |
| + |
| +// Not served: expired, not yet valid, bound to another host, an ECDSA import |
| +// to an RSA-only hello, or a name that is not a deployment host. |
| +func TestImportNotServedWhenUnusable(t *testing.T) { |
| + ca := newE2ECA(t) |
| + now := time.Now() |
| + for _, tc := range []struct { |
| + label string |
| + body []byte |
| + hello *tls.ClientHelloInfo |
| + deployed func(string) bool |
| + }{ |
| + {"expired", importPEM(t, ca, importBinding(importHost), importHost, false, now.Add(-48*time.Hour), now.Add(-time.Hour)), modernHello(importHost), deployedOnly(importHost)}, |
| + {"not yet valid", importPEM(t, ca, importBinding(importHost), importHost, false, now.Add(time.Hour), now.Add(48*time.Hour)), modernHello(importHost), deployedOnly(importHost)}, |
| + {"binding names another host", importPEM(t, ca, importBinding("other.import.test"), importHost, false, now.Add(-time.Hour), now.Add(48*time.Hour)), modernHello(importHost), deployedOnly(importHost)}, |
| + {"hello cannot use it", goodImport(t, ca, importHost, false), rsaOnlyHello(importHost), deployedOnly(importHost)}, |
| + {"not a deployment host", goodImport(t, ca, importHost, false), modernHello(importHost), deployedOnly("elsewhere.test")}, |
| + {"no deployment predicate", goodImport(t, ca, importHost, false), modernHello(importHost), nil}, |
| + } { |
| + t.Run(tc.label, func(t *testing.T) { |
| + s := release.NewDirStore(t.TempDir()) |
| + putBucket(t, s, domains.ImportName(importHost), tc.body) |
| + get, _, _ := importLayer(t, s, tc.deployed) |
| + if _, err := get(tc.hello); !errors.Is(err, errInnerProbe) { |
| + t.Fatalf("got %v; want the inner chain", err) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// The chain the warm calls (perHostCert: the mirror over autocert, below the |
| +// import layer) never serves an import, cached on disk or mirrored. |
| +func TestImportWarmPathNeverSeesIt(t *testing.T) { |
| + ca := newE2ECA(t) |
| + s := release.NewDirStore(t.TempDir()) |
| + putBucket(t, s, domains.ImportName(importHost), goodImport(t, ca, importHost, false)) |
| + local := autocert.DirCache(t.TempDir()) |
| + m := newCertMirror(s, local) |
| + perHost, _ := gatedChain(t, m, local, importHost) |
| + refreshMirror(t, m) |
| + if c, err := perHost(modernHello(importHost)); err == nil || c != nil { |
| + t.Fatalf("the per-host chain served %v; it must never see an import", c != nil) |
| + } |
| +} |
| + |
| +// ---- the issuer's HostPolicy ------------------------------------------------ |
| + |
| +const importPrimary = "app.acct.apps.test" |
| + |
| +func ownFile(pointing bool) string { |
| + mark := "false" |
| + if pointing { |
| + mark = "true" |
| + } |
| + return `{"v":1,"box":"annie","eip":"1.1.1.1","hosts":{"` + importPrimary + `":{"role":"home","platform":true},` + |
| + `"` + importHost + `":{"role":"home","alias":true,"target_host":"` + importPrimary + `","dns_pointing":` + mark + `}}}` |
| +} |
| + |
| +// importIssuer is the issuer as the imported name's home box: its route table |
| +// holds the alias, it holds the gate, its home map reads its own file. |
| +func importIssuer(t *testing.T, s release.Store) (*Edge, *homeMap) { |
| + t.Helper() |
| + e := testIssuerEdge(importPrimary, importHost) |
| + e.staticStore = s |
| + e.issuer = func() (context.Context, bool) { return context.Background(), true } |
| + homes := newHomeMap(s, "annie") |
| + refreshHomeMap(t, homes) |
| + e.homes.Store(homes) |
| + m := newCertMirror(s, nil) |
| + refreshMirror(t, m) |
| + e.certs.Store(m) |
| + return e, homes |
| +} |
| + |
| +// The issuer as home box refuses to order an imported name before any box |
| +// publishes it pointing: for an incompatible hello that falls past the |
| +// import layer, and with an ordinary cached entry autocert would otherwise |
| +// load (arming a renewal timer). Published pointing, it is allowed. |
| +func TestHostPolicyRefusesAnImportedNameBeforePointing(t *testing.T) { |
| + ca := newE2ECA(t) |
| + s := release.NewDirStore(t.TempDir()) |
| + putJSON(t, s, "control/edges/annie.json", ownFile(false)) |
| + putBucket(t, s, domains.ImportName(importHost), goodImport(t, ca, importHost, false)) |
| + e, homes := importIssuer(t, s) |
| + if !e.Allowed(importHost) { |
| + t.Fatal("test bug: the issuer must be the name's home") |
| + } |
| + pol := e.issuerHostPolicy() |
| + if err := pol(context.Background(), importHost); !errors.Is(err, errImportNotPointing) { |
| + t.Fatalf("HostPolicy = %v; want the not-pointing refusal", err) |
| + } |
| + if err := pol(context.Background(), importPrimary); err != nil { |
| + t.Fatalf("a name with no import is unaffected: %v", err) |
| + } |
| + |
| + cache := newCountingCache(t) |
| + if err := cache.Put(context.Background(), importHost, hostCertPEM(t, importHost, time.Now().Add(20*24*time.Hour))); err != nil { |
| + t.Fatal(err) |
| + } |
| + fake := newFakeACME(t) |
| + mgr := offlineManager(t, cache, pol) |
| + mgr.Client.DirectoryURL = fake.directoryURL() |
| + for _, h := range []*tls.ClientHelloInfo{rsaOnlyHello(importHost), modernHello(importHost)} { |
| + if _, err := mgr.GetCertificate(h); err == nil { |
| + t.Fatal("autocert answered an imported name before it points") |
| + } |
| + } |
| + if n := cache.count(importHost) + cache.count(importHost+"+rsa"); n != 0 { |
| + t.Fatalf("autocert read its cache %d time(s); the refusal must come first", n) |
| + } |
| + if accounts, orders := fake.counts(); accounts+orders != 0 { |
| + t.Fatalf("the CA saw %d accounts, %d orders", accounts, orders) |
| + } |
| + |
| + putJSON(t, s, "control/edges/annie.json", ownFile(true)) |
| + refreshHomeMap(t, homes) |
| + if err := pol(context.Background(), importHost); err != nil { |
| + t.Fatalf("published pointing by this box, HostPolicy = %v; want allowed", err) |
| + } |
| +} |
| + |
| +// Another box publishing the name pointing lifts the refusal as well, and an |
| +// expired import is no reason to refuse. |
| +func TestHostPolicyImportOtherBoxPointingAndExpired(t *testing.T) { |
| + ca := newE2ECA(t) |
| + s := release.NewDirStore(t.TempDir()) |
| + putJSON(t, s, "control/edges/annie.json", ownFile(false)) |
| + putJSON(t, s, "control/edges/betty.json", `{"v":1,"box":"betty","eip":"2.2.2.2","hosts":{"`+importHost+`":{"role":"home","alias":true,"target_host":"x.acct.apps.test","dns_pointing":true}}}`) |
| + putBucket(t, s, domains.ImportName(importHost), goodImport(t, ca, importHost, false)) |
| + e, _ := importIssuer(t, s) |
| + if err := e.issuerHostPolicy()(context.Background(), importHost); err != nil { |
| + t.Fatalf("published pointing by another box, HostPolicy = %v", err) |
| + } |
| + |
| + s2 := release.NewDirStore(t.TempDir()) |
| + putJSON(t, s2, "control/edges/annie.json", ownFile(false)) |
| + now := time.Now() |
| + putBucket(t, s2, domains.ImportName(importHost), importPEM(t, ca, importBinding(importHost), importHost, false, now.Add(-48*time.Hour), now.Add(-time.Hour))) |
| + e2, _ := importIssuer(t, s2) |
| + if err := e2.issuerHostPolicy()(context.Background(), importHost); err != nil { |
| + t.Fatalf("with only an expired import, HostPolicy = %v; want today's behaviour", err) |
| + } |
| +} |
| + |
| +// ---- the issuer's reconcile ------------------------------------------------- |
| + |
| +func putClaim(t *testing.T, s release.Store, host, account, app, created string, pending bool) { |
| + t.Helper() |
| + p := "" |
| + if pending { |
| + p = `,"pending":true` |
| + } |
| + putJSON(t, s, domains.ClaimKey(host), `{"schema":1,"host":"`+host+`","account":"`+account+`","app":"`+app+`","created_at":"`+created+`"`+p+`}`) |
| +} |
| + |
| +func reconcilerFor(s release.Store, m *certMirror, issuing bool) *importReconciler { |
| + e := &Edge{staticStore: s} |
| + e.issuer = func() (context.Context, bool) { return context.Background(), issuing } |
| + return e.newImportReconciler(m) |
| +} |
| + |
| +func importPresent(t *testing.T, s release.Store, host string) bool { |
| + t.Helper() |
| + _, err := certStoreGet(t, s, certKey(domains.ImportName(host))) |
| + if err != nil && !errors.Is(err, os.ErrNotExist) { |
| + t.Fatal(err) |
| + } |
| + return err == nil |
| +} |
| + |
| +func TestImportReconcileDeletesStaleBindings(t *testing.T) { |
| + e2eQuietLogs(t) |
| + ca := newE2ECA(t) |
| + s := release.NewDirStore(t.TempDir()) |
| + cases := map[string]bool{ // host -> kept |
| + "keep.import.test": true, |
| + "gone.import.test": false, |
| + "otheracct.import.test": false, |
| + "otherapp.import.test": false, |
| + "reacq.import.test": false, |
| + "pending.import.test": false, |
| + "nobinding.import.test": false, |
| + } |
| + putClaim(t, s, "keep.import.test", importAccount, importApp, importCreated, false) |
| + putClaim(t, s, "otheracct.import.test", "zzz", importApp, importCreated, false) |
| + putClaim(t, s, "otherapp.import.test", importAccount, "other", importCreated, false) |
| + putClaim(t, s, "reacq.import.test", importAccount, importApp, "2026-11-25T11:00:00Z", false) |
| + putClaim(t, s, "pending.import.test", importAccount, importApp, importCreated, true) |
| + putClaim(t, s, "nobinding.import.test", importAccount, importApp, importCreated, false) |
| + for host := range cases { |
| + body := goodImport(t, ca, host, false) |
| + if host == "nobinding.import.test" { |
| + body = hostCertPEM(t, host, time.Now().Add(24*time.Hour)) |
| + } |
| + putBucket(t, s, domains.ImportName(host), body) |
| + } |
| + m := newCertMirror(s, nil) |
| + refreshMirror(t, m) |
| + var buf bytes.Buffer |
| + log.SetOutput(&buf) |
| + r := reconcilerFor(s, m, true) |
| + r.pass(context.Background()) // six stale: five this pass (the cap) |
| + refreshMirror(t, m) |
| + r.pass(context.Background()) // and the sixth |
| + r.pass(context.Background()) // nothing left: no second log line for any |
| + for host, kept := range cases { |
| + if got := importPresent(t, s, host); got != kept { |
| + t.Errorf("%s: present %v, want %v", host, got, kept) |
| + } |
| + } |
| + if n := strings.Count(buf.String(), "removed the imported certificate"); n != 6 { |
| + t.Errorf("logged %d removals, want 6:\n%s", n, buf.String()) |
| + } |
| + if strings.Contains(buf.String(), "BEGIN") { |
| + t.Error("a log line carries PEM bytes") |
| + } |
| +} |
| + |
| +// Nothing is deleted by a non-issuer, on a failed claims listing, for a claim |
| +// that was listed but could not be read, or when the store cannot delete |
| +// conditionally. |
| +func TestImportReconcileDeletesNothingWhenItCannotDecide(t *testing.T) { |
| + e2eQuietLogs(t) |
| + ca := newE2ECA(t) |
| + setup := func(t *testing.T) (*release.DirStore, *certMirror) { |
| + s := release.NewDirStore(t.TempDir()) |
| + putBucket(t, s, domains.ImportName(importHost), goodImport(t, ca, importHost, false)) // no claim at all |
| + m := newCertMirror(s, nil) |
| + refreshMirror(t, m) |
| + return s, m |
| + } |
| + t.Run("non-issuer", func(t *testing.T) { |
| + s, m := setup(t) |
| + reconcilerFor(s, m, false).pass(context.Background()) |
| + if !importPresent(t, s, importHost) { |
| + t.Fatal("a non-issuer deleted an import") |
| + } |
| + }) |
| + t.Run("ungated hand-run edge", func(t *testing.T) { |
| + s, m := setup(t) |
| + e := &Edge{staticStore: s} |
| + e.newImportReconciler(m).pass(context.Background()) |
| + if !importPresent(t, s, importHost) { |
| + t.Fatal("an edge with no issuer gate deleted an import") |
| + } |
| + }) |
| + t.Run("claims listing failed", func(t *testing.T) { |
| + s, m := setup(t) |
| + r := reconcilerFor(s, m, true) |
| + r.claims = func(context.Context) ([]domains.Claim, []domains.UnreadClaim, error) { |
| + return nil, nil, errors.New("bucket down") |
| + } |
| + r.pass(context.Background()) |
| + if !importPresent(t, s, importHost) { |
| + t.Fatal("a failed claims listing was read as no claims") |
| + } |
| + }) |
| + t.Run("claim listed but unreadable", func(t *testing.T) { |
| + s, m := setup(t) |
| + r := reconcilerFor(s, m, true) |
| + r.claims = func(context.Context) ([]domains.Claim, []domains.UnreadClaim, error) { |
| + return nil, []domains.UnreadClaim{{Host: importHost}}, nil |
| + } |
| + r.pass(context.Background()) |
| + if !importPresent(t, s, importHost) { |
| + t.Fatal("an unreadable claim was read as gone") |
| + } |
| + }) |
| + t.Run("store without conditional delete", func(t *testing.T) { |
| + s, m := setup(t) |
| + r := reconcilerFor(plainStore{s}, m, true) |
| + r.pass(context.Background()) |
| + if !importPresent(t, s, importHost) { |
| + t.Fatal("a store without DeleteIfMatch deleted an import") |
| + } |
| + }) |
| + t.Run("rewritten since the mirror read it", func(t *testing.T) { |
| + s, m := setup(t) |
| + fresh := goodImport(t, ca, importHost, false) |
| + putBucket(t, s, domains.ImportName(importHost), fresh) |
| + reconcilerFor(s, m, true).pass(context.Background()) |
| + got, err := certStoreGet(t, s, certKey(domains.ImportName(importHost))) |
| + if err != nil || !bytes.Equal(got, fresh) { |
| + t.Fatalf("a CAS refusal must leave the rewritten import in place (%v)", err) |
| + } |
| + }) |
| +} |
| + |
| +// plainStore hides every optional interface of the store it wraps. |
| +type plainStore struct{ release.Store } |
| + |
| +func TestImportReconcileDeletesAtMostFivePerPass(t *testing.T) { |
| + e2eQuietLogs(t) |
| + ca := newE2ECA(t) |
| + s := release.NewDirStore(t.TempDir()) |
| + var hosts []string |
| + for _, l := range "abcdefg" { |
| + h := string(l) + ".import.test" |
| + hosts = append(hosts, h) |
| + putBucket(t, s, domains.ImportName(h), goodImport(t, ca, h, false)) |
| + } |
| + m := newCertMirror(s, nil) |
| + refreshMirror(t, m) |
| + r := reconcilerFor(s, m, true) |
| + r.pass(context.Background()) |
| + left := 0 |
| + for _, h := range hosts { |
| + if importPresent(t, s, h) { |
| + left++ |
| + } |
| + } |
| + if left != 2 { |
| + t.Fatalf("%d imports left after one pass, want 2", left) |
| + } |
| + refreshMirror(t, m) |
| + r.pass(context.Background()) |
| + for _, h := range hosts { |
| + if importPresent(t, s, h) { |
| + t.Fatalf("%s still present after the second pass", h) |
| + } |
| + } |
| +} |
diff --git a/internal/edge/certsync.go b/internal/edge/certsync.go| index 9bf211b97..5bfe5bed7 100644 |
| --- a/internal/edge/certsync.go |
| +++ b/internal/edge/certsync.go |
| @@ -26,6 +26,13 @@ package edge |
| // (writer map, Part 1); the mirror side polls this prefix on its own |
| // cadence. Renewals run ~30 days before expiry, so a poll cadence measured |
| // in seconds is never on a deadline. |
| +// |
| +// Writers of control/certs/ (the writer map's line for this prefix): the |
| +// issuer (issuance artifacts, through publishingCache, and the cert sweep's |
| +// deletes); any contending box (the backfill of settled cert entries, #318); |
| +// and, for <host>+import entries ONLY, the console's import door (#1429, |
| +// certimport.go). The issuer's import reconcile deletes +import entries whose |
| +// claim binding no longer holds; nothing else writes or republishes them. |
| import ( |
| "bytes" |
| @@ -110,6 +117,24 @@ var errNotIssuer = errors.New("acme: not available here") |
| // :80 response. |
| var errAliasNotPointing = errors.New("acme: not available here") |
| +// errImportNotPointing is issuerHostPolicy's refusal for a name served from |
| +// an imported certificate that no box publishes pointing yet (#1429). |
| +// Generic text for the same reason as errNotIssuer. |
| +var errImportNotPointing = errors.New("acme: not available here") |
| + |
| +// importNotPointing reports whether the mirror holds a usable import for host |
| +// and neither this box's own published file nor any other box's publishes it |
| +// pointing (OwnServedHosts and ServedHosts, the warm set's own sources, both |
| +// filtered on the DNS mark). Nothing to check without an import, so the cost |
| +// lands only on imported names. |
| +func (e *Edge) importNotPointing(host string, now time.Time) bool { |
| + if !e.certs.Load().holdsUsableImport(host, now) { |
| + return false |
| + } |
| + hm := e.homes.Load() |
| + return !slices.Contains(hm.OwnServedHosts(), host) && !slices.Contains(hm.ServedHosts(), host) |
| +} |
| + |
| // armCertIssuance wires cert DISTRIBUTION and the issuance GATE together, |
| // because they are one decision and not two: a box may only be told "you are |
| // not the issuer" if some other box's certificates can reach it. |
| @@ -222,6 +247,16 @@ func (e *Edge) issuerHostPolicyAt(now func() time.Time) autocert.HostPolicy { |
| if !e.Allowed(host) && e.homes.Load().AliasNotPointing(host) { |
| return errAliasNotPointing |
| } |
| + // A name the mirror holds a usable imported certificate for (#1429) |
| + // is not ordered until some box, this one included, publishes it |
| + // pointing: before that HTTP-01 cannot validate, and refusing here |
| + // also keeps autocert from loading a cached entry and arming a |
| + // renewal timer. Unlike the check above this holds when this box is |
| + // the name's home (Allowed): an incompatible hello that falls past |
| + // the import layer must not order either. |
| + if e.importNotPointing(host, now()) { |
| + return errImportNotPointing |
| + } |
| if _, ok := e.issuerGate(); !ok { |
| return errNotIssuer |
| } |
| @@ -408,7 +443,8 @@ func putCAS(ctx context.Context, s release.Store, key string, body []byte) error |
| // certMirror is the serving half of the pair at the top of this file, and the |
| // reason the issuance gate above is safe to shut. It POLLS control/certs/ |
| // (its serving side never writes there; the one writer it carries is the |
| -// backfill below, bounded to cert entries this box owns — #318) and keeps |
| +// backfill below, bounded to cert entries this box owns — #318 — and never |
| +// an imported certificate, which is the console's to write) and keeps |
| // the whole prefix in memory, so any edge can answer a |
| // handshake for a name some OTHER edge issued, and can answer an HTTP-01 |
| // challenge for an order some OTHER edge is running. |
| @@ -471,10 +507,17 @@ type certSnapshot struct { |
| // certs is the parsed form of every cert-shaped entry, keyed by the same |
| // name. Parsing happens ONCE per poll per changed entry, never per |
| // handshake. A name whose body does not parse is absent, not nil. |
| + // Imported certificates (<host>+import) are never here: nothing that |
| + // reads certs may serve one (#1429). |
| certs map[string]*tls.Certificate |
| + // imports is every <host>+import entry (#1429), keyed by cache name, |
| + // parsed through domains.ParseImport with its binding and the ETag it was |
| + // read at. Only wrapImported serves from it; an entry that does not parse |
| + // is kept with a nil cert, for the issuer's reconcile to remove. |
| + imports map[string]importEntry |
| } |
| -var emptyCertSnapshot = &certSnapshot{entries: map[string][]byte{}, certs: map[string]*tls.Certificate{}} |
| +var emptyCertSnapshot = &certSnapshot{entries: map[string][]byte{}, certs: map[string]*tls.Certificate{}, imports: map[string]importEntry{}} |
| type certMirror struct { |
| s release.Store |
| @@ -724,6 +767,7 @@ func (m *certMirror) refreshFull(ctx context.Context) error { |
| // closer to the same cliff. us-east-1 at ~75ms is about a third of the |
| // way there at today's count. |
| var items []certFetch |
| + listed := make(map[string]bool, len(keys)) |
| for _, key := range keys { |
| name, ok := strings.CutPrefix(key, certPrefix) |
| // publishableCertName is the same filter the publish side applies: |
| @@ -732,6 +776,7 @@ func (m *certMirror) refreshFull(ctx context.Context) error { |
| if !ok || !publishableCertName(name) { |
| continue |
| } |
| + listed[name] = true |
| items = append(items, certFetch{key: key, name: name}) |
| } |
| tried := len(items) |
| @@ -744,7 +789,7 @@ func (m *certMirror) refreshFull(ctx context.Context) error { |
| if failed > 0 { |
| m.logPartialPoll(failed, tried, lastErr) |
| } |
| - m.publish(ctx, prev, next, etags) |
| + m.publish(ctx, prev, next, etags, listed) |
| // A partial rebuild still counts as the full rebuild: the objects it |
| // could not read carry an unknown ETag, so the next poll's changed-only |
| // read fetches exactly those again. It reflects no generation, though, |
| @@ -825,11 +870,13 @@ func (m *certMirror) refreshChanged(ctx context.Context, gen uint64) error { |
| next := make(map[string][]byte, len(listed)) |
| etags := make(map[string]string, len(listed)) |
| var items []certFetch |
| + names := make(map[string]bool, len(listed)) |
| for _, le := range listed { |
| name, ok := strings.CutPrefix(le.Key, certPrefix) |
| if !ok || !publishableCertName(name) { |
| continue |
| } |
| + names[name] = true |
| if was := m.etags[name]; was != "" && was == le.ETag { |
| if body, ok := prev.entries[name]; ok { |
| next[name], etags[name] = body, was |
| @@ -850,7 +897,7 @@ func (m *certMirror) refreshChanged(ctx context.Context, gen uint64) error { |
| if failed > 0 { |
| m.logPartialPoll(failed, tried, lastErr) |
| } |
| - m.publish(ctx, prev, next, etags) |
| + m.publish(ctx, prev, next, etags, names) |
| m.actedGen, m.actedOK = gen, failed == 0 |
| return nil |
| } |
| @@ -949,15 +996,23 @@ func applyCertFetches(items []certFetch, results []certFetchResult, prev *certSn |
| } |
| // publish swaps in the snapshot built from next, whole, and does what every |
| -// landed refresh does after it: the local cache copy-in, the health latch and |
| -// the wildcard wake. Under refreshMu. |
| -func (m *certMirror) publish(ctx context.Context, prev *certSnapshot, next map[string][]byte, etags map[string]string) { |
| +// landed refresh does after it: the local cache copy-in, the removal of disk |
| +// copies of imports the listing no longer returns (listed is every cache |
| +// name the listing returned, read or not), the health latch and the wildcard |
| +// wake. Under refreshMu. |
| +func (m *certMirror) publish(ctx context.Context, prev *certSnapshot, next map[string][]byte, etags map[string]string, listed map[string]bool) { |
| snap := buildCertSnapshot(prev, next) |
| + for name, ie := range snap.imports { |
| + // The revision the issuer's reconcile deletes on, if it must. |
| + ie.etag = etags[name] |
| + snap.imports[name] = ie |
| + } |
| m.mu.Lock() |
| m.snap = snap |
| m.mu.Unlock() |
| m.etags = etags |
| m.localPending = m.syncLocal(ctx, snap) |
| + m.pruneLocalImports(listed) |
| // The local cache the handshake reads now holds what the bucket does: |
| // the certificate condition is met for good (§6). A later failed |
| // refresh keeps serving this copy and leaves the latch set. |
| @@ -1032,8 +1087,20 @@ func (m *certMirror) logPartialPoll(failed, tried int, err error) { |
| // parse forward — a handshake never pays for x509 parsing, and a quiet |
| // deployment pays for it once. |
| func buildCertSnapshot(prev *certSnapshot, entries map[string][]byte) *certSnapshot { |
| - snap := &certSnapshot{entries: entries, certs: make(map[string]*tls.Certificate, len(entries))} |
| + snap := &certSnapshot{entries: entries, certs: make(map[string]*tls.Certificate, len(entries)), imports: map[string]importEntry{}} |
| for name, body := range entries { |
| + if importCacheName(name) { |
| + // An imported certificate (#1429): parsed with its binding into |
| + // its own map, never into certs, and never through the ordinary |
| + // parse below (which would accept it without the binding). |
| + // Unchanged bytes carry the previous result forward, as below. |
| + if old, seen := prev.imports[name]; seen && bytes.Equal(prev.entries[name], body) { |
| + snap.imports[name] = importEntry{binding: old.binding, cert: old.cert} |
| + continue |
| + } |
| + snap.imports[name] = parseImportEntry(name, body) |
| + continue |
| + } |
| if !certShapedName(name) { |
| continue |
| } |
| @@ -1276,6 +1343,12 @@ func (m *certMirror) backfill(ctx context.Context) { |
| if strings.HasSuffix(name, httpTokenSuffix) || strings.HasSuffix(name, alpnTokenSuffix) { |
| continue |
| } |
| + if importCacheName(name) { |
| + // An imported certificate is the console's to write and the |
| + // issuer's reconcile's to delete (#1429): republishing a disk |
| + // copy would resurrect a removed import. |
| + continue |
| + } |
| remote, inBucket := snap.entries[name] |
| info, err := ent.Info() |
| if err != nil { |
| @@ -1475,7 +1548,14 @@ func (m *certMirror) syncLocal(ctx context.Context, snap *certSnapshot) (failedA |
| if prev, ok := m.synced[name]; ok && bytes.Equal(prev, body) { |
| continue |
| } |
| - switch err := m.reconcileLocal(ctx, name, body, snap.certs[name]); { |
| + reconcile := func() error { return m.reconcileLocal(ctx, name, body, snap.certs[name]) } |
| + if importCacheName(name) { |
| + // By identity, not by expiry (#1429): the disk copy is what the |
| + // edges-file writer publishes early from, and a re-import with an |
| + // earlier expiry must still replace it. |
| + reconcile = func() error { return m.reconcileLocalImport(ctx, name, body) } |
| + } |
| + switch err := reconcile(); { |
| case err == nil: |
| m.synced[name] = body |
| case errors.Is(err, errUnparseableEntry): |
diff --git a/internal/edge/edge.go b/internal/edge/edge.go| index 1f57b2f01..497e8916d 100644 |
| --- a/internal/edge/edge.go |
| +++ b/internal/edge/edge.go |
| @@ -5165,6 +5165,13 @@ func RunWithActivatorReady(args []string, act Activator, cache *Cache, ready fun |
| // this is what the cert warm below calls. Calling the WRAPPED chain would |
| // let the wildcard answer for a covered name and order nothing. |
| perHostCert := getCert |
| + // Imported certificates (#1429, certimport.go): above the mirror, below |
| + // the wildcard, and after perHostCert is captured, so the warm never |
| + // sees an import and still orders CARLOS's own certificate. Served only |
| + // to a hello no usable CARLOS certificate suits, for a deployment host. |
| + if mirror != nil { |
| + getCert = mirror.wrapImported(getCert, e.deploymentHost) |
| + } |
| // Wildcard certs (wildcard.go, ACME DNS-01): covered names — one label |
| // under a per-account or configured parent — are served the wildcard; |
| // everything else (custom domains, canary hosts, parents not yet |
| @@ -5219,6 +5226,11 @@ func RunWithActivatorReady(args []string, act Activator, cache *Cache, ready fun |
| go p.run() |
| log.Printf("edge: certificates before DNS moves on for %v (DNS-01, %s pass, issuer only)", p.scope.Zones, preIssueInterval) |
| } |
| + // Imported certificates (#1429, certimport.go): the issuer removes |
| + // every import whose claim binding no longer holds. |
| + if r := e.newImportReconciler(mirror); r != nil { |
| + go r.run() |
| + } |
| } |
| tlsCfg.GetCertificate = getCert |
| if mirror != nil { |