| 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) |
| + } |
| +} |