domains: imported-certificate entry format with claim binding (#1429)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2 files changed,
+272
−0
internal/domains/certimport.go+150 −0internal/domains/certimport_test.go+122 −0
diff --git a/internal/domains/certimport.go b/internal/domains/certimport.go| new file mode 100644 |
| index 000000000..3ed62f5c2 |
| --- /dev/null |
| +++ b/internal/domains/certimport.go |
| @@ -0,0 +1,150 @@ |
| +package domains |
| + |
| +import ( |
| + "bytes" |
| + "crypto/tls" |
| + "crypto/x509" |
| + "encoding/pem" |
| + "errors" |
| + "io" |
| + "os" |
| + "path/filepath" |
| + "strings" |
| + "time" |
| +) |
| + |
| +// Imported certificates (#1429). An operator imports a certificate and key |
| +// for an attached custom domain so every edge can serve it before the |
| +// name's DNS points at the deployment. The entry lives at |
| +// control/certs/<host>+import, beside the issuer's own entries, under a |
| +// name autocert never reads and the backfill never republishes. |
| +// |
| +// The entry is the console's re-encoding of what it verified, in this |
| +// order: one binding block, the private key as PKCS#8, then the leaf and |
| +// the intermediates. tls.X509KeyPair skips the binding block, so the |
| +// entry parses like any autocert entry. |
| + |
| +// ImportSuffix is the cache-name suffix of an imported certificate. |
| +const ImportSuffix = "+import" |
| + |
| +// importBindingType is the PEM type of the binding block. It must not end |
| +// in " PRIVATE KEY", or tls.X509KeyPair would take it for the key. |
| +const importBindingType = "CARLOS IMPORT BINDING" |
| + |
| +// ImportName is host's imported-certificate cache name. |
| +func ImportName(host string) string { return host + ImportSuffix } |
| + |
| +// ImportHost returns the host an imported-certificate cache name is for. |
| +func ImportHost(name string) (string, bool) { |
| + host, ok := strings.CutSuffix(name, ImportSuffix) |
| + if !ok || !validHostShape(host) { |
| + return "", false |
| + } |
| + return host, true |
| +} |
| + |
| +// ImportBinding ties an import to the claim acquisition that authorized |
| +// it: the claim's host, account, app and created_at. A detach and |
| +// re-attach changes ClaimCreated, so an import never outlives the claim it |
| +// was made for. |
| +type ImportBinding struct { |
| + Host string |
| + Account string |
| + App string |
| + ClaimCreated string |
| +} |
| + |
| +// Matches reports whether c is the claim acquisition b was made for, and |
| +// still a live exact claim: not pending, not an instance catch-all. |
| +func (b ImportBinding) Matches(c Claim) bool { |
| + return c.Host == b.Host && c.Account == b.Account && c.App == b.App && |
| + c.CreatedAt == b.ClaimCreated && b.ClaimCreated != "" && |
| + !c.Pending && !c.Instances && !strings.HasPrefix(c.Host, "*.") |
| +} |
| + |
| +// EncodeImport builds an import entry from a binding, a PKCS#8 key DER and |
| +// the chain's DERs (leaf first). |
| +func EncodeImport(b ImportBinding, pkcs8 []byte, chain [][]byte) []byte { |
| + var buf bytes.Buffer |
| + _ = pem.Encode(&buf, &pem.Block{Type: importBindingType, Headers: map[string]string{ |
| + "Host": b.Host, "Account": b.Account, "App": b.App, "Claim-Created": b.ClaimCreated, |
| + }}) |
| + _ = pem.Encode(&buf, &pem.Block{Type: "PRIVATE KEY", Bytes: pkcs8}) |
| + for _, der := range chain { |
| + _ = pem.Encode(&buf, &pem.Block{Type: "CERTIFICATE", Bytes: der}) |
| + } |
| + return buf.Bytes() |
| +} |
| + |
| +// ErrImportEntry is ParseImport's one error. It never carries entry bytes. |
| +var ErrImportEntry = errors.New("imported certificate entry does not parse") |
| + |
| +// ParseImport reads an import entry: the binding (the first block, which |
| +// must be the binding block, with every header present) and the key pair. |
| +// The leaf is parsed into cert.Leaf. |
| +func ParseImport(raw []byte) (ImportBinding, *tls.Certificate, error) { |
| + block, _ := pem.Decode(raw) |
| + if block == nil || block.Type != importBindingType { |
| + return ImportBinding{}, nil, ErrImportEntry |
| + } |
| + b := ImportBinding{ |
| + Host: block.Headers["Host"], Account: block.Headers["Account"], |
| + App: block.Headers["App"], ClaimCreated: block.Headers["Claim-Created"], |
| + } |
| + if b.Host == "" || b.Account == "" || b.App == "" || b.ClaimCreated == "" { |
| + return ImportBinding{}, nil, ErrImportEntry |
| + } |
| + pair, err := tls.X509KeyPair(raw, raw) |
| + if err != nil || len(pair.Certificate) == 0 { |
| + return ImportBinding{}, nil, ErrImportEntry |
| + } |
| + if pair.Leaf == nil { |
| + leaf, err := x509.ParseCertificate(pair.Certificate[0]) |
| + if err != nil { |
| + return ImportBinding{}, nil, ErrImportEntry |
| + } |
| + pair.Leaf = leaf |
| + } |
| + return b, &pair, nil |
| +} |
| + |
| +// ImportUsable reports whether an import entry would serve host right now: |
| +// its binding names host, its key matches, its leaf names host and is in |
| +// date. |
| +func ImportUsable(b ImportBinding, cert *tls.Certificate, host string, now time.Time) bool { |
| + if cert == nil || cert.Leaf == nil || b.Host != host { |
| + return false |
| + } |
| + leaf := cert.Leaf |
| + return !now.Before(leaf.NotBefore) && now.Before(leaf.NotAfter) && leaf.VerifyHostname(host) == nil |
| +} |
| + |
| +// UsableImportedCert reports whether acmeDir holds an imported certificate |
| +// for host, bound to account, that would serve right now: a regular file |
| +// (a symlink is not followed) named host+ImportSuffix. It is the edges-file |
| +// writer's readiness test for publishing an alias before its DNS points |
| +// here (#1429), the import counterpart of UsablePerHostCert. |
| +func UsableImportedCert(acmeDir, host, account string, now time.Time) bool { |
| + if acmeDir == "" || account == "" || !validHostShape(host) { |
| + return false |
| + } |
| + p := filepath.Join(acmeDir, ImportName(host)) |
| + fi, err := os.Lstat(p) |
| + if err != nil || !fi.Mode().IsRegular() || fi.Size() > maxCertEntry { |
| + return false |
| + } |
| + f, err := os.Open(p) |
| + if err != nil { |
| + return false |
| + } |
| + defer f.Close() |
| + raw, err := io.ReadAll(io.LimitReader(f, maxCertEntry)) |
| + if err != nil { |
| + return false |
| + } |
| + b, cert, err := ParseImport(raw) |
| + if err != nil || b.Account != account { |
| + return false |
| + } |
| + return ImportUsable(b, cert, host, now) |
| +} |
diff --git a/internal/domains/certimport_test.go b/internal/domains/certimport_test.go| new file mode 100644 |
| index 000000000..b34fcc3e4 |
| --- /dev/null |
| +++ b/internal/domains/certimport_test.go |
| @@ -0,0 +1,122 @@ |
| +package domains |
| + |
| +import ( |
| + "crypto/ecdsa" |
| + "crypto/elliptic" |
| + "crypto/rand" |
| + "crypto/x509" |
| + "crypto/x509/pkix" |
| + "math/big" |
| + "os" |
| + "path/filepath" |
| + "testing" |
| + "time" |
| +) |
| + |
| +func importFixture(t *testing.T, host string, notAfter time.Time, b ImportBinding) []byte { |
| + t.Helper() |
| + key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + tmpl := &x509.Certificate{SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: host}, DNSNames: []string{host}, |
| + NotBefore: time.Now().Add(-time.Hour), NotAfter: notAfter} |
| + der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + pkcs8, err := x509.MarshalPKCS8PrivateKey(key) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return EncodeImport(b, pkcs8, [][]byte{der}) |
| +} |
| + |
| +func TestImportEntryRoundTrips(t *testing.T) { |
| + b := ImportBinding{Host: "shop.example.com", Account: "bes", App: "web", ClaimCreated: "2026-11-25T10:00:00Z"} |
| + raw := importFixture(t, "shop.example.com", time.Now().Add(30*24*time.Hour), b) |
| + got, cert, err := ParseImport(raw) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if got != b { |
| + t.Fatalf("binding = %+v, want %+v", got, b) |
| + } |
| + if !ImportUsable(got, cert, "shop.example.com", time.Now()) { |
| + t.Fatal("fresh import not usable") |
| + } |
| + if ImportUsable(got, cert, "other.example.com", time.Now()) { |
| + t.Fatal("import usable for another host") |
| + } |
| + if ImportUsable(got, cert, "shop.example.com", time.Now().Add(31*24*time.Hour)) { |
| + t.Fatal("expired import usable") |
| + } |
| +} |
| + |
| +func TestParseImportRefusesAnEntryWithoutItsBinding(t *testing.T) { |
| + b := ImportBinding{Host: "shop.example.com", Account: "bes", App: "web", ClaimCreated: "x"} |
| + raw := importFixture(t, "shop.example.com", time.Now().Add(time.Hour), b) |
| + // Drop the binding block: what is left is an ordinary autocert entry. |
| + if _, _, err := ParseImport(raw[len("-----BEGIN CARLOS IMPORT BINDING-----"):]); err == nil { |
| + t.Fatal("entry without a binding parsed") |
| + } |
| + if _, _, err := ParseImport(importFixture(t, "shop.example.com", time.Now().Add(time.Hour), ImportBinding{Host: "shop.example.com", Account: "bes"})); err == nil { |
| + t.Fatal("binding with missing headers parsed") |
| + } |
| +} |
| + |
| +func TestImportBindingMatchesOneClaimAcquisition(t *testing.T) { |
| + b := ImportBinding{Host: "shop.example.com", Account: "bes", App: "web", ClaimCreated: "t1"} |
| + live := Claim{Host: "shop.example.com", Account: "bes", App: "web", CreatedAt: "t1"} |
| + if !b.Matches(live) { |
| + t.Fatal("matching claim refused") |
| + } |
| + for name, c := range map[string]Claim{ |
| + "other account": {Host: "shop.example.com", Account: "zzz", App: "web", CreatedAt: "t1"}, |
| + "other app": {Host: "shop.example.com", Account: "bes", App: "api", CreatedAt: "t1"}, |
| + "re-attached": {Host: "shop.example.com", Account: "bes", App: "web", CreatedAt: "t2"}, |
| + "pending": {Host: "shop.example.com", Account: "bes", App: "web", CreatedAt: "t1", Pending: true}, |
| + "catch-all": {Host: "shop.example.com", Account: "bes", App: "web", CreatedAt: "t1", Instances: true}, |
| + } { |
| + if b.Matches(c) { |
| + t.Errorf("%s: matched", name) |
| + } |
| + } |
| +} |
| + |
| +func TestUsableImportedCertChecksFileAccountAndName(t *testing.T) { |
| + dir := t.TempDir() |
| + host := "shop.example.com" |
| + b := ImportBinding{Host: host, Account: "bes", App: "web", ClaimCreated: "t1"} |
| + if err := os.WriteFile(filepath.Join(dir, ImportName(host)), importFixture(t, host, time.Now().Add(48*time.Hour), b), 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| + now := time.Now() |
| + if !UsableImportedCert(dir, host, "bes", now) { |
| + t.Fatal("usable import refused") |
| + } |
| + if UsableImportedCert(dir, host, "zzz", now) { |
| + t.Fatal("import bound to another account accepted") |
| + } |
| + if UsableImportedCert(dir, "other.example.com", "bes", now) { |
| + t.Fatal("missing file accepted") |
| + } |
| + link := filepath.Join(dir, ImportName("link.example.com")) |
| + if err := os.Symlink(filepath.Join(dir, ImportName(host)), link); err != nil { |
| + t.Fatal(err) |
| + } |
| + if UsableImportedCert(dir, "link.example.com", "bes", now) { |
| + t.Fatal("symlink followed") |
| + } |
| +} |
| + |
| +func TestImportHost(t *testing.T) { |
| + if h, ok := ImportHost("shop.example.com+import"); !ok || h != "shop.example.com" { |
| + t.Fatalf("ImportHost = %q, %v", h, ok) |
| + } |
| + for _, n := range []string{"shop.example.com", "shop.example.com+rsa", "+import", "../x+import"} { |
| + if _, ok := ImportHost(n); ok { |
| + t.Errorf("%q accepted", n) |
| + } |
| + } |
| +} |