From d4f09f596bf834fe6d5d2a7b5911ce987c160558 Mon Sep 17 00:00:00 2001 From: James Tucker Date: Sat, 5 Dec 2026 02:40:50 +0000 Subject: [PATCH] feature/acme: rotate existing P-256 ACME account keys to P-384 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Upgrade persisted ECDSA P-256 ACME account keys to ECDSA P-384 on the next certificate issuance or renewal using RFC 8555 §7.3.5 account key rollover via (*tempfork/acme.Client).AccountKeyRollover. Pre-commit rollover failures (such as a CA without keyChange support or a transient CA error) are logged and treated as non-fatal so certificate issuance proceeds with the existing key and retries rotation later. Concurrent issuances that loaded the old P-256 key before rotation re-read the persisted key under accountMu so rollover happens once. Updates #22893 Signed-off-by: James Tucker Change-Id: I5685c5e247804f305926fa6b56bb7f19a02c0212 --- feature/acme/cert.go | 83 +++++- feature/acme/certstore.go | 20 +- feature/acme/issue_test.go | 535 +++++++++++++++++++++++++++++++++++++ 3 files changed, 627 insertions(+), 11 deletions(-) diff --git a/feature/acme/cert.go b/feature/acme/cert.go index 2effdbc51..4234a0e54 100644 --- a/feature/acme/cert.go +++ b/feature/acme/cert.go @@ -6,6 +6,7 @@ package acme import ( "bytes" "context" + "crypto" "crypto/ecdsa" "crypto/elliptic" "crypto/rand" @@ -384,7 +385,7 @@ var getCertPEM = func(ctx context.Context, e *extension, b *ipnlocal.LocalBacken logf("acme: using Directory URL %q", ac.DirectoryURL) } - a, err := e.ensureAccount(ctx, ac, logf, traceACME) + a, err := e.ensureAccount(ctx, cs, ac, logf, traceACME) if err != nil { return nil, err } @@ -449,15 +450,26 @@ var getCertPEM = func(ctx context.Context, e *extension, b *ipnlocal.LocalBacken } // ensureAccount returns a valid ACME account, registering one if -// needed. Locked so two first-time issuances don't both create one. -func (e *extension) ensureAccount(ctx context.Context, ac *xacme.Client, logf logger.Logf, traceACME func(any)) (*xacme.Account, error) { +// needed, and upgrades an existing P-256 account key to P-384 via +// RFC 8555 §7.3.5 account key rollover. Locked so concurrent issuances +// do not race on registration or key rotation. +func (e *extension) ensureAccount(ctx context.Context, cs certStore, ac *xacme.Client, logf logger.Logf, traceACME func(any)) (*xacme.Account, error) { e.accountMu.Lock() defer e.accountMu.Unlock() + + // Re-check the stored key in case another goroutine rotated it while we + // waited for accountMu. + if shouldRotateACMEKey(ac.Key) { + if stored, err := readACMEKey(cs); err == nil && !shouldRotateACMEKey(stored) { + ac.Key = stored + ac.KID = "" + } + } + a, err := ac.GetReg(ctx, "" /* pre-RFC param */) switch { case err == nil: logf("already had ACME account.") - return a, nil case err == xacme.ErrNoAccount: a, err = ac.Register(ctx, new(xacme.Account), xacme.AcceptTOS) if err == xacme.ErrAccountAlreadyExists { @@ -468,10 +480,71 @@ func (e *extension) ensureAccount(ctx context.Context, ac *xacme.Client, logf lo } logf("registered ACME account.") traceACME(a) - return a, nil default: return nil, fmt.Errorf("acme.GetReg: %w", err) } + + if a.Status == xacme.StatusValid && shouldRotateACMEKey(ac.Key) { + if err := e.rotateACMEAccountKeyLocked(ctx, cs, ac, a, logf); err != nil { + return nil, err + } + } + return a, nil +} + +// shouldRotateACMEKey reports whether key is an ECDSA P-256 account key +// that should be rotated to ECDSA P-384. +func shouldRotateACMEKey(key crypto.Signer) bool { + ec, ok := key.(*ecdsa.PrivateKey) + return ok && ec.Curve == elliptic.P256() +} + +// rotateACMEAccountKeyLocked rotates ac's P-256 account key to a fresh +// P-384 key via RFC 8555 §7.3.5 key rollover and persists the new key to cs. +// +// Pre-commit failures (such as a CA without keyChange support or a rejected +// rollover request) are logged and ignored so issuance proceeds with the +// existing key; persistence failures after a successful rollover are returned. +// +// Caller must hold e.accountMu. +func (e *extension) rotateACMEAccountKeyLocked(ctx context.Context, cs certStore, ac *xacme.Client, a *xacme.Account, logf logger.Logf) error { + dir, err := ac.Discover(ctx) + if err != nil { + if ctx.Err() != nil { + return ctx.Err() + } + logf("acme: skipping P-384 account key rotation: Discover: %v", err) + return nil + } + if dir.KeyChangeURL == "" { + logf("acme: CA does not advertise keyChange; skipping P-384 account key rotation") + return nil + } + if ac.KID == "" && a.URI != "" { + ac.KID = xacme.KeyID(a.URI) + } + + newKey, err := ecdsa.GenerateKey(elliptic.P384(), rand.Reader) + if err != nil { + return fmt.Errorf("generating P-384 ACME account key: %w", err) + } + var pemBuf bytes.Buffer + if err := encodeECDSAKey(&pemBuf, newKey); err != nil { + return fmt.Errorf("encoding P-384 ACME account key: %w", err) + } + + if err := ac.AccountKeyRollover(ctx, newKey); err != nil { + if ctx.Err() != nil { + return ctx.Err() + } + logf("acme: account key rollover to P-384 failed; continuing with existing key: %v", err) + return nil + } + if err := cs.WriteACMEKey(pemBuf.Bytes()); err != nil { + return fmt.Errorf("persisting rotated ACME account key: %w", err) + } + logf("rotated ACME account key to ECDSA P-384.") + return nil } type acmeCertIssueArgs struct { diff --git a/feature/acme/certstore.go b/feature/acme/certstore.go index b2db19832..32d2cb341 100644 --- a/feature/acme/certstore.go +++ b/feature/acme/certstore.go @@ -364,18 +364,26 @@ func parsePrivateKey(der []byte) (crypto.Signer, error) { return nil, errors.New("acme/autocert: failed to parse private key") } +func readACMEKey(cs certStore) (crypto.Signer, error) { + v, err := cs.ACMEKey() + if err != nil { + return nil, err + } + priv, _ := pem.Decode(v) + if priv == nil || !strings.Contains(priv.Type, "PRIVATE") { + return nil, errors.New("acme/autocert: invalid account key found in cache") + } + return parsePrivateKey(priv.Bytes) +} + func (e *extension) acmeKey(cs certStore) (crypto.Signer, error) { // Lock so two callers don't both generate a key and race on the // write. e.accountMu.Lock() defer e.accountMu.Unlock() - if v, err := cs.ACMEKey(); err == nil { - priv, _ := pem.Decode(v) - if priv == nil || !strings.Contains(priv.Type, "PRIVATE") { - return nil, errors.New("acme/autocert: invalid account key found in cache") - } - return parsePrivateKey(priv.Bytes) + if key, err := readACMEKey(cs); err == nil { + return key, nil } else if !errors.Is(err, ipn.ErrStateNotExist) { return nil, err } diff --git a/feature/acme/issue_test.go b/feature/acme/issue_test.go index b6dfb5989..82aaa6a06 100644 --- a/feature/acme/issue_test.go +++ b/feature/acme/issue_test.go @@ -9,6 +9,8 @@ import ( "crypto/ecdsa" "crypto/elliptic" "crypto/rand" + "crypto/sha256" + "crypto/sha512" "crypto/tls" "crypto/x509" "encoding/base64" @@ -30,6 +32,7 @@ import ( xacme "tailscale.com/tempfork/acme" "tailscale.com/tstest/acmetest" "tailscale.com/types/logger" + "tailscale.com/util/httpm" ) func newTestACMEClient(t *testing.T, s *acmetest.Server) *xacme.Client { @@ -288,3 +291,535 @@ func TestIssueACMECertRetriesWithoutReplaces(t *testing.T) { }) } } + +type failingWriteACMEKeyStore struct { + certStore + writeErr error +} + +func (s failingWriteACMEKeyStore) WriteACMEKey([]byte) error { + return s.writeErr +} + +// testRolloverACMEServer is a minimal ACME server that tracks the single +// registered account key and validates RFC 8555 §7.3.5 key-change requests. +type testRolloverACMEServer struct { + t *testing.T + ts *httptest.Server + advertiseKC bool + keyChangeErr int // if non-zero, HTTP status returned by /key-change + + mu sync.Mutex + accountKey *ecdsa.PublicKey // currently registered key + keyChangeCalls int + newAccountCalls int +} + +func newTestRolloverACMEServer(t *testing.T, initialKey *ecdsa.PublicKey, advertiseKC bool) *testRolloverACMEServer { + t.Helper() + srv := &testRolloverACMEServer{ + t: t, + advertiseKC: advertiseKC, + accountKey: initialKey, + } + srv.ts = httptest.NewServer(http.HandlerFunc(srv.serveHTTP)) + t.Cleanup(srv.ts.Close) + return srv +} + +func (s *testRolloverACMEServer) directoryURL() string { return s.ts.URL + "/directory" } + +func (s *testRolloverACMEServer) serveHTTP(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Replay-Nonce", "test-nonce") + switch { + case r.Method == httpm.GET && r.URL.Path == "/directory": + dir := map[string]string{ + "newNonce": s.ts.URL + "/new-nonce", + "newAccount": s.ts.URL + "/new-account", + "newOrder": s.ts.URL + "/new-order", + } + if s.advertiseKC { + dir["keyChange"] = s.ts.URL + "/key-change" + } + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(dir) + case (r.Method == httpm.HEAD || r.Method == httpm.GET) && r.URL.Path == "/new-nonce": + w.WriteHeader(http.StatusOK) + case r.Method == httpm.POST && r.URL.Path == "/new-account": + s.serveNewAccount(w, r) + case r.Method == httpm.POST && r.URL.Path == "/key-change": + s.serveKeyChange(w, r) + default: + http.NotFound(w, r) + } +} + +type rawJWS struct { + Protected string `json:"protected"` + Payload string `json:"payload"` + Signature string `json:"signature"` +} + +type jwsProtectedHeader struct { + Alg string `json:"alg"` + KID string `json:"kid"` + JWK json.RawMessage `json:"jwk"` + Nonce string `json:"nonce"` + URL string `json:"url"` +} + +func parseECJWK(raw []byte) (*ecdsa.PublicKey, error) { + var jwk struct { + Kty string `json:"kty"` + Crv string `json:"crv"` + X string `json:"x"` + Y string `json:"y"` + } + if err := json.Unmarshal(raw, &jwk); err != nil { + return nil, err + } + if jwk.Kty != "EC" { + return nil, fmt.Errorf("unexpected kty %q", jwk.Kty) + } + var curve elliptic.Curve + switch jwk.Crv { + case "P-256": + curve = elliptic.P256() + case "P-384": + curve = elliptic.P384() + default: + return nil, fmt.Errorf("unsupported curve %q", jwk.Crv) + } + xb, err := base64.RawURLEncoding.DecodeString(jwk.X) + if err != nil { + return nil, err + } + yb, err := base64.RawURLEncoding.DecodeString(jwk.Y) + if err != nil { + return nil, err + } + return &ecdsa.PublicKey{ + Curve: curve, + X: new(big.Int).SetBytes(xb), + Y: new(big.Int).SetBytes(yb), + }, nil +} + +func verifyECJWS(msg rawJWS, pub *ecdsa.PublicKey, alg string) error { + var digest []byte + var coordLen int + switch alg { + case "ES256": + if pub.Curve != elliptic.P256() { + return fmt.Errorf("ES256 with curve %s", pub.Curve.Params().Name) + } + sum := sha256.Sum256([]byte(msg.Protected + "." + msg.Payload)) + digest = sum[:] + coordLen = 32 + case "ES384": + if pub.Curve != elliptic.P384() { + return fmt.Errorf("ES384 with curve %s", pub.Curve.Params().Name) + } + sum := sha512.Sum384([]byte(msg.Protected + "." + msg.Payload)) + digest = sum[:] + coordLen = 48 + default: + return fmt.Errorf("unsupported alg %q", alg) + } + sig, err := base64.RawURLEncoding.DecodeString(msg.Signature) + if err != nil { + return err + } + if len(sig) != coordLen*2 { + return fmt.Errorf("signature length = %d, want %d", len(sig), coordLen*2) + } + r := new(big.Int).SetBytes(sig[:coordLen]) + s := new(big.Int).SetBytes(sig[coordLen:]) + if !ecdsa.Verify(pub, digest, r, s) { + return errors.New("ECDSA signature verification failed") + } + return nil +} + +func (s *testRolloverACMEServer) serveNewAccount(w http.ResponseWriter, r *http.Request) { + body, err := io.ReadAll(r.Body) + if err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + var msg rawJWS + if err := json.Unmarshal(body, &msg); err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + phBytes, err := base64.RawURLEncoding.DecodeString(msg.Protected) + if err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + var ph jwsProtectedHeader + if err := json.Unmarshal(phBytes, &ph); err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + pub, err := parseECJWK(ph.JWK) + if err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + if err := verifyECJWS(msg, pub, ph.Alg); err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + payloadBytes, err := base64.RawURLEncoding.DecodeString(msg.Payload) + if err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + var req struct { + OnlyReturnExisting bool `json:"onlyReturnExisting"` + } + if err := json.Unmarshal(payloadBytes, &req); err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + + s.mu.Lock() + defer s.mu.Unlock() + s.newAccountCalls++ + if s.accountKey == nil || !s.accountKey.Equal(pub) { + if req.OnlyReturnExisting { + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(http.StatusBadRequest) + w.Write([]byte(`{"type":"urn:ietf:params:acme:error:accountDoesNotExist","detail":"no account for key"}`)) + return + } + s.accountKey = pub + w.Header().Set("Location", s.ts.URL+"/account/1") + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusCreated) + w.Write([]byte(`{"status":"valid"}`)) + return + } + w.Header().Set("Location", s.ts.URL+"/account/1") + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) + w.Write([]byte(`{"status":"valid"}`)) +} + +func (s *testRolloverACMEServer) serveKeyChange(w http.ResponseWriter, r *http.Request) { + s.mu.Lock() + defer s.mu.Unlock() + s.keyChangeCalls++ + if s.keyChangeErr != 0 { + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(s.keyChangeErr) + w.Write([]byte(`{"type":"urn:ietf:params:acme:error:serverInternal","detail":"keyChange failed"}`)) + return + } + body, err := io.ReadAll(r.Body) + if err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + var outer rawJWS + if err := json.Unmarshal(body, &outer); err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + outerPHBytes, err := base64.RawURLEncoding.DecodeString(outer.Protected) + if err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + var outerPH jwsProtectedHeader + if err := json.Unmarshal(outerPHBytes, &outerPH); err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + wantURL := s.ts.URL + "/key-change" + wantAcct := s.ts.URL + "/account/1" + if outerPH.URL != wantURL || outerPH.KID != wantAcct || outerPH.Nonce == "" { + http.Error(w, fmt.Sprintf("invalid outer protected header: %+v", outerPH), http.StatusBadRequest) + return + } + if err := verifyECJWS(outer, s.accountKey, outerPH.Alg); err != nil { + http.Error(w, fmt.Sprintf("outer JWS verify: %v", err), http.StatusBadRequest) + return + } + + innerBytes, err := base64.RawURLEncoding.DecodeString(outer.Payload) + if err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + var inner rawJWS + if err := json.Unmarshal(innerBytes, &inner); err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + innerPHBytes, err := base64.RawURLEncoding.DecodeString(inner.Protected) + if err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + var innerPH jwsProtectedHeader + if err := json.Unmarshal(innerPHBytes, &innerPH); err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + if innerPH.URL != wantURL || innerPH.Nonce != "" || innerPH.KID != "" { + http.Error(w, fmt.Sprintf("invalid inner protected header: %+v", innerPH), http.StatusBadRequest) + return + } + newPub, err := parseECJWK(innerPH.JWK) + if err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + if err := verifyECJWS(inner, newPub, innerPH.Alg); err != nil { + http.Error(w, fmt.Sprintf("inner JWS verify: %v", err), http.StatusBadRequest) + return + } + + innerPayloadBytes, err := base64.RawURLEncoding.DecodeString(inner.Payload) + if err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + var rollover struct { + Account string `json:"account"` + OldKey json.RawMessage `json:"oldKey"` + } + if err := json.Unmarshal(innerPayloadBytes, &rollover); err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + if rollover.Account != wantAcct { + http.Error(w, fmt.Sprintf("rollover account = %q, want %q", rollover.Account, wantAcct), http.StatusBadRequest) + return + } + oldPub, err := parseECJWK(rollover.OldKey) + if err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + if !oldPub.Equal(s.accountKey) { + http.Error(w, "rollover oldKey does not match registered account key", http.StatusBadRequest) + return + } + + s.accountKey = newPub + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) + w.Write([]byte(`{"status":"valid"}`)) +} + +func writeTestAccountKey(t *testing.T, cs certStore, key *ecdsa.PrivateKey) { + t.Helper() + var buf bytes.Buffer + if err := encodeECDSAKey(&buf, key); err != nil { + t.Fatalf("encodeECDSAKey: %v", err) + } + if err := cs.WriteACMEKey(buf.Bytes()); err != nil { + t.Fatalf("WriteACMEKey: %v", err) + } +} + +func TestEnsureAccount_RotatesP256KeyToP384(t *testing.T) { + oldKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + t.Fatal(err) + } + srv := newTestRolloverACMEServer(t, &oldKey.PublicKey, true) + cs := certStateStore{StateStore: new(mem.Store)} + writeTestAccountKey(t, cs, oldKey) + + e := &extension{logf: t.Logf} + ac := &xacme.Client{ + Key: oldKey, + DirectoryURL: srv.directoryURL(), + RetryBackoff: func(int, *http.Request, *http.Response) time.Duration { return 0 }, + } + a, err := e.ensureAccount(t.Context(), cs, ac, t.Logf, func(any) {}) + if err != nil { + t.Fatalf("ensureAccount: %v", err) + } + if a.Status != xacme.StatusValid { + t.Fatalf("account status = %q, want valid", a.Status) + } + + gotClientKey, ok := ac.Key.(*ecdsa.PrivateKey) + if !ok || gotClientKey.Curve != elliptic.P384() { + t.Fatalf("ac.Key = %T (curve=%v), want ECDSA P-384", ac.Key, gotClientKey) + } + stored, err := readACMEKey(cs) + if err != nil { + t.Fatalf("readACMEKey: %v", err) + } + storedEC, ok := stored.(*ecdsa.PrivateKey) + if !ok || !storedEC.Equal(gotClientKey) { + t.Fatalf("persisted key does not match rotated client key") + } + srv.mu.Lock() + kcCalls := srv.keyChangeCalls + srvKey := srv.accountKey + srv.mu.Unlock() + if kcCalls != 1 { + t.Errorf("keyChange calls = %d, want 1", kcCalls) + } + if !srvKey.Equal(&gotClientKey.PublicKey) { + t.Errorf("server account key does not match rotated P-384 key") + } + + // A subsequent ensureAccount with the persisted P-384 key must not rotate again. + ac2 := &xacme.Client{Key: stored, DirectoryURL: srv.directoryURL()} + if _, err := e.ensureAccount(t.Context(), cs, ac2, t.Logf, func(any) {}); err != nil { + t.Fatalf("second ensureAccount: %v", err) + } + srv.mu.Lock() + kcCalls = srv.keyChangeCalls + srv.mu.Unlock() + if kcCalls != 1 { + t.Errorf("keyChange calls after second ensureAccount = %d, want 1", kcCalls) + } +} + +func TestEnsureAccount_SkipsRotationWithoutKeyChangeURL(t *testing.T) { + oldKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + t.Fatal(err) + } + srv := newTestRolloverACMEServer(t, &oldKey.PublicKey, false) + cs := certStateStore{StateStore: new(mem.Store)} + writeTestAccountKey(t, cs, oldKey) + + e := &extension{logf: t.Logf} + ac := &xacme.Client{Key: oldKey, DirectoryURL: srv.directoryURL()} + if _, err := e.ensureAccount(t.Context(), cs, ac, t.Logf, func(any) {}); err != nil { + t.Fatalf("ensureAccount: %v", err) + } + if gotEC, ok := ac.Key.(*ecdsa.PrivateKey); !ok || !gotEC.Equal(oldKey) { + t.Errorf("ac.Key changed despite CA not advertising keyChange") + } + stored, err := readACMEKey(cs) + if err != nil { + t.Fatalf("readACMEKey: %v", err) + } + if storedEC, ok := stored.(*ecdsa.PrivateKey); !ok || !storedEC.Equal(oldKey) { + t.Errorf("stored key changed despite CA not advertising keyChange") + } +} + +func TestEnsureAccount_RolloverFailureIsNonFatal(t *testing.T) { + oldKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + t.Fatal(err) + } + srv := newTestRolloverACMEServer(t, &oldKey.PublicKey, true) + srv.keyChangeErr = http.StatusInternalServerError + cs := certStateStore{StateStore: new(mem.Store)} + writeTestAccountKey(t, cs, oldKey) + + e := &extension{logf: t.Logf} + ac := &xacme.Client{ + Key: oldKey, + DirectoryURL: srv.directoryURL(), + RetryBackoff: func(int, *http.Request, *http.Response) time.Duration { return 0 }, + } + if _, err := e.ensureAccount(t.Context(), cs, ac, t.Logf, func(any) {}); err != nil { + t.Fatalf("ensureAccount failed on rollover error: %v", err) + } + if gotEC, ok := ac.Key.(*ecdsa.PrivateKey); !ok || !gotEC.Equal(oldKey) { + t.Errorf("ac.Key changed after failed rollover") + } + stored, err := readACMEKey(cs) + if err != nil { + t.Fatalf("readACMEKey: %v", err) + } + if storedEC, ok := stored.(*ecdsa.PrivateKey); !ok || !storedEC.Equal(oldKey) { + t.Errorf("stored key changed after failed rollover") + } +} + +func TestEnsureAccount_RolloverPersistFailureReturnsError(t *testing.T) { + oldKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + t.Fatal(err) + } + srv := newTestRolloverACMEServer(t, &oldKey.PublicKey, true) + baseCS := certStateStore{StateStore: new(mem.Store)} + writeTestAccountKey(t, baseCS, oldKey) + cs := failingWriteACMEKeyStore{certStore: baseCS, writeErr: errors.New("disk full")} + + e := &extension{logf: t.Logf} + ac := &xacme.Client{Key: oldKey, DirectoryURL: srv.directoryURL()} + _, err = e.ensureAccount(t.Context(), cs, ac, t.Logf, func(any) {}) + if err == nil || !strings.Contains(err.Error(), "disk full") { + t.Fatalf("ensureAccount err = %v, want error containing %q", err, "disk full") + } +} + +func TestEnsureAccount_ConcurrentP256RolloverRotatesOnce(t *testing.T) { + oldKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + t.Fatal(err) + } + srv := newTestRolloverACMEServer(t, &oldKey.PublicKey, true) + cs := certStateStore{StateStore: new(mem.Store)} + writeTestAccountKey(t, cs, oldKey) + + e := &extension{logf: t.Logf} + const n = 4 + clients := make([]*xacme.Client, n) + for i := range clients { + clients[i] = &xacme.Client{ + Key: oldKey, + DirectoryURL: srv.directoryURL(), + RetryBackoff: func(int, *http.Request, *http.Response) time.Duration { return 0 }, + } + } + + var start sync.WaitGroup + start.Add(1) + errs := make(chan error, n) + for _, ac := range clients { + go func() { + start.Wait() + _, err := e.ensureAccount(t.Context(), cs, ac, t.Logf, func(any) {}) + errs <- err + }() + } + start.Done() + + for range n { + if err := <-errs; err != nil { + t.Fatalf("concurrent ensureAccount: %v", err) + } + } + + srv.mu.Lock() + kcCalls := srv.keyChangeCalls + srvKey := srv.accountKey + srv.mu.Unlock() + if kcCalls != 1 { + t.Errorf("keyChange calls = %d, want 1", kcCalls) + } + stored, err := readACMEKey(cs) + if err != nil { + t.Fatalf("readACMEKey: %v", err) + } + storedEC, ok := stored.(*ecdsa.PrivateKey) + if !ok || storedEC.Curve != elliptic.P384() { + t.Fatalf("stored key = %T, want ECDSA P-384", stored) + } + if !srvKey.Equal(&storedEC.PublicKey) { + t.Errorf("server key does not match stored rotated key") + } + for i, ac := range clients { + gotEC, ok := ac.Key.(*ecdsa.PrivateKey) + if !ok || !gotEC.Equal(storedEC) { + t.Errorf("client %d key does not match stored rotated key", i) + } + } +}