mirror of
https://github.com/tailscale/tailscale.git
synced 2026-12-05 08:02:20 -08:00
ipn/store/kubestore,feature/acme: refresh shared ACME account key on read
When kubestore is configured with a shared per-tailnet ACME accounts Secret (TS_ACME_ACCOUNT_SECRET_NAME), read through to the Secret on ReadState(acme-account.key.pem) and refresh the in-memory copy (falling back to memory if the Secret cannot be read or is empty). This lets already-running cert-share replicas observe account keys created or rotated to P-384 by another pod without restarting. In feature/acme, also re-read the stored key and adopt a concurrently rotated key if GetReg returns ErrNoAccount or AccountKeyRollover fails, closing the race window when two pods sharing an account key start rotation simultaneously. Updates #22893 Signed-off-by: James Tucker <[email protected]> Change-Id: I4d88ec69a578fff4cd47d7ab7a22e35c32322751
This commit is contained in:
1 parent
d4f09f596b
commit
057cb155df
4 files changed
+312
-8
No files matched your search
+27
-8
@@ -457,16 +457,15 @@ func (e *extension) ensureAccount(ctx context.Context, cs certStore, ac *xacme.C
|
||||
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 = ""
|
||||
}
|
||||
}
|
||||
// Re-check the stored key in case another goroutine or pod rotated it
|
||||
// while we waited for accountMu.
|
||||
adoptRotatedACMEKey(cs, ac)
|
||||
|
||||
a, err := ac.GetReg(ctx, "" /* pre-RFC param */)
|
||||
if err == xacme.ErrNoAccount && adoptRotatedACMEKey(cs, ac) {
|
||||
logf("acme: account key rotated concurrently; retrying GetReg with updated key.")
|
||||
a, err = ac.GetReg(ctx, "" /* pre-RFC param */)
|
||||
}
|
||||
switch {
|
||||
case err == nil:
|
||||
logf("already had ACME account.")
|
||||
@@ -499,6 +498,22 @@ func shouldRotateACMEKey(key crypto.Signer) bool {
|
||||
return ok && ec.Curve == elliptic.P256()
|
||||
}
|
||||
|
||||
// adoptRotatedACMEKey checks whether cs already contains a non-P-256 account
|
||||
// key (written by a concurrent goroutine or another pod sharing the store).
|
||||
// If so, it updates ac.Key, clears ac.KID, and reports true.
|
||||
func adoptRotatedACMEKey(cs certStore, ac *xacme.Client) bool {
|
||||
if !shouldRotateACMEKey(ac.Key) {
|
||||
return false
|
||||
}
|
||||
stored, err := readACMEKey(cs)
|
||||
if err != nil || shouldRotateACMEKey(stored) {
|
||||
return false
|
||||
}
|
||||
ac.Key = stored
|
||||
ac.KID = ""
|
||||
return true
|
||||
}
|
||||
|
||||
// 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.
|
||||
//
|
||||
@@ -537,6 +552,10 @@ func (e *extension) rotateACMEAccountKeyLocked(ctx context.Context, cs certStore
|
||||
if ctx.Err() != nil {
|
||||
return ctx.Err()
|
||||
}
|
||||
if adoptRotatedACMEKey(cs, ac) {
|
||||
logf("acme: account key rotated concurrently; adopted updated key from store.")
|
||||
return nil
|
||||
}
|
||||
logf("acme: account key rollover to P-384 failed; continuing with existing key: %v", err)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -823,3 +823,113 @@ func TestEnsureAccount_ConcurrentP256RolloverRotatesOnce(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// dynamicACMEKeyStore lets a test swap the stored ACME account key dynamically
|
||||
// on each read (simulating another pod updating a shared Kubernetes Secret).
|
||||
type dynamicACMEKeyStore struct {
|
||||
certStore
|
||||
onRead func()
|
||||
}
|
||||
|
||||
func (s *dynamicACMEKeyStore) ACMEKey() ([]byte, error) {
|
||||
if s.onRead != nil {
|
||||
s.onRead()
|
||||
}
|
||||
return s.certStore.ACMEKey()
|
||||
}
|
||||
|
||||
func TestEnsureAccount_AdoptsKeyRotatedByPeerOnErrNoAccount(t *testing.T) {
|
||||
oldKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
peerKey, err := ecdsa.GenerateKey(elliptic.P384(), rand.Reader)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Server already has peerKey (another pod just completed keyChange).
|
||||
srv := newTestRolloverACMEServer(t, &peerKey.PublicKey, true)
|
||||
baseCS := certStateStore{StateStore: new(mem.Store)}
|
||||
writeTestAccountKey(t, baseCS, oldKey)
|
||||
|
||||
// First read (pre-GetReg) still sees oldKey; second read (after GetReg
|
||||
// returns ErrNoAccount) sees peerKey written to the shared Secret.
|
||||
var reads atomic.Int32
|
||||
cs := &dynamicACMEKeyStore{
|
||||
certStore: baseCS,
|
||||
onRead: func() {
|
||||
if reads.Add(1) == 2 {
|
||||
writeTestAccountKey(t, baseCS, peerKey)
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
gotEC, ok := ac.Key.(*ecdsa.PrivateKey)
|
||||
if !ok || !gotEC.Equal(peerKey) {
|
||||
t.Fatalf("ac.Key did not adopt peer's rotated P-384 key")
|
||||
}
|
||||
srv.mu.Lock()
|
||||
kcCalls := srv.keyChangeCalls
|
||||
srvKey := srv.accountKey
|
||||
srv.mu.Unlock()
|
||||
if kcCalls != 0 {
|
||||
t.Errorf("keyChange calls = %d, want 0", kcCalls)
|
||||
}
|
||||
if !srvKey.Equal(&peerKey.PublicKey) {
|
||||
t.Errorf("server account key changed unexpectedly")
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnsureAccount_AdoptsKeyRotatedByPeerOnRolloverFailure(t *testing.T) {
|
||||
oldKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
peerKey, err := ecdsa.GenerateKey(elliptic.P384(), rand.Reader)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
srv := newTestRolloverACMEServer(t, &oldKey.PublicKey, true)
|
||||
srv.keyChangeErr = http.StatusBadRequest
|
||||
baseCS := certStateStore{StateStore: new(mem.Store)}
|
||||
writeTestAccountKey(t, baseCS, oldKey)
|
||||
|
||||
// First read (pre-GetReg) sees oldKey; second read (after keyChange fails)
|
||||
// sees peerKey written by the peer pod that won the rollover race.
|
||||
var reads atomic.Int32
|
||||
cs := &dynamicACMEKeyStore{
|
||||
certStore: baseCS,
|
||||
onRead: func() {
|
||||
if reads.Add(1) == 2 {
|
||||
writeTestAccountKey(t, baseCS, peerKey)
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
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: %v", err)
|
||||
}
|
||||
gotEC, ok := ac.Key.(*ecdsa.PrivateKey)
|
||||
if !ok || !gotEC.Equal(peerKey) {
|
||||
t.Fatalf("ac.Key did not adopt peer's rotated P-384 key after rollover failure")
|
||||
}
|
||||
}
|
||||
@@ -338,8 +338,40 @@ func (s *Store) SetDialer(d func(ctx context.Context, network, address string) (
|
||||
|
||||
func (s *Store) String() string { return "kube.Store" }
|
||||
|
||||
// readSharedACMEAccountKey fetches the shared per-tailnet ACME account key
|
||||
// from acmeAccountsSecretName and refreshes s.memory if present, so an
|
||||
// already-running replica observes keys written or rotated by another pod.
|
||||
// If the Secret cannot be read or the field is empty, it falls back to s.memory.
|
||||
// When a cached key is already in memory, it uses rwCertFallbackTimeout so a
|
||||
// slow API server cannot stall TLS handshakes during ARI checks.
|
||||
func (s *Store) readSharedACMEAccountKey() ([]byte, error) {
|
||||
readTimeout := timeout
|
||||
if cached, err := s.memory.ReadState(ipn.StateKey(acmeAccountStateKey)); err == nil && len(cached) > 0 {
|
||||
readTimeout = rwCertFallbackTimeout
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), readTimeout)
|
||||
defer cancel()
|
||||
shared, err := s.client.GetSecret(ctx, s.acmeAccountsSecretName)
|
||||
if err != nil {
|
||||
if !kubeclient.IsNotFoundErr(err) {
|
||||
s.logf("kubestore: reading shared ACME accounts Secret %q: %v", s.acmeAccountsSecretName, err)
|
||||
}
|
||||
return s.memory.ReadState(ipn.StateKey(acmeAccountStateKey))
|
||||
}
|
||||
if shared != nil {
|
||||
if key := shared.Data[sanitizeKey(s.acmeAccountField)]; len(key) > 0 {
|
||||
s.memory.WriteState(ipn.StateKey(acmeAccountStateKey), key)
|
||||
return bytes.Clone(key), nil
|
||||
}
|
||||
}
|
||||
return s.memory.ReadState(ipn.StateKey(acmeAccountStateKey))
|
||||
}
|
||||
|
||||
// ReadState implements the StateStore interface.
|
||||
func (s *Store) ReadState(id ipn.StateKey) ([]byte, error) {
|
||||
if s.acmeAccountsSecretName != "" && string(id) == acmeAccountStateKey {
|
||||
return s.readSharedACMEAccountKey()
|
||||
}
|
||||
return s.memory.ReadState(ipn.StateKey(sanitizeKey(id)))
|
||||
}
|
||||
|
||||
|
||||
@@ -1812,3 +1812,146 @@ func TestWriteTLSCertAndKeyStampsFingerprint(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadState_RefreshesSharedACMEAccountKey(t *testing.T) {
|
||||
const (
|
||||
sharedSecretName = "tailscale-acme-accounts"
|
||||
sharedField = "example.com.acme-account.key.pem"
|
||||
)
|
||||
oldKey := []byte("-----BEGIN EC PRIVATE KEY-----\nold-p256\n-----END EC PRIVATE KEY-----\n")
|
||||
newKey := []byte("-----BEGIN EC PRIVATE KEY-----\nnew-p384\n-----END EC PRIVATE KEY-----\n")
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
sharedSecret string
|
||||
readKey ipn.StateKey
|
||||
inMemory []byte
|
||||
remoteData map[string][]byte
|
||||
remoteErr error
|
||||
want []byte
|
||||
wantErr error
|
||||
wantMem []byte
|
||||
wantGetSecrets int
|
||||
}{
|
||||
{
|
||||
name: "refreshes_rotated_key_from_shared_secret",
|
||||
sharedSecret: sharedSecretName,
|
||||
readKey: acmeAccountStateKey,
|
||||
inMemory: oldKey,
|
||||
remoteData: map[string][]byte{sharedField: newKey},
|
||||
want: newKey,
|
||||
wantMem: newKey,
|
||||
wantGetSecrets: 1,
|
||||
},
|
||||
{
|
||||
name: "falls_back_to_memory_on_api_error",
|
||||
sharedSecret: sharedSecretName,
|
||||
readKey: acmeAccountStateKey,
|
||||
inMemory: oldKey,
|
||||
remoteErr: errors.New("apiserver unreachable"),
|
||||
want: oldKey,
|
||||
wantMem: oldKey,
|
||||
wantGetSecrets: 1,
|
||||
},
|
||||
{
|
||||
name: "falls_back_to_memory_when_field_empty",
|
||||
sharedSecret: sharedSecretName,
|
||||
readKey: acmeAccountStateKey,
|
||||
inMemory: oldKey,
|
||||
remoteData: map[string][]byte{},
|
||||
want: oldKey,
|
||||
wantMem: oldKey,
|
||||
wantGetSecrets: 1,
|
||||
},
|
||||
{
|
||||
name: "falls_back_to_not_exist_when_neither_present",
|
||||
sharedSecret: sharedSecretName,
|
||||
readKey: acmeAccountStateKey,
|
||||
remoteErr: &kubeapi.Status{Code: 404},
|
||||
wantErr: ipn.ErrStateNotExist,
|
||||
wantGetSecrets: 1,
|
||||
},
|
||||
{
|
||||
name: "skips_api_for_other_state_keys",
|
||||
sharedSecret: sharedSecretName,
|
||||
readKey: "other-key",
|
||||
inMemory: oldKey,
|
||||
remoteData: map[string][]byte{sharedField: newKey},
|
||||
wantErr: ipn.ErrStateNotExist,
|
||||
wantMem: oldKey,
|
||||
wantGetSecrets: 0,
|
||||
},
|
||||
{
|
||||
name: "skips_api_when_shared_secret_unconfigured",
|
||||
sharedSecret: "",
|
||||
readKey: acmeAccountStateKey,
|
||||
inMemory: oldKey,
|
||||
remoteData: map[string][]byte{sharedField: newKey},
|
||||
want: oldKey,
|
||||
wantMem: oldKey,
|
||||
wantGetSecrets: 0,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
var getCalls int
|
||||
var gotDeadline time.Duration
|
||||
client := &kubeclient.FakeClient{
|
||||
GetSecretImpl: func(ctx context.Context, name string) (*kubeapi.Secret, error) {
|
||||
getCalls++
|
||||
if dl, ok := ctx.Deadline(); ok {
|
||||
gotDeadline = time.Until(dl)
|
||||
}
|
||||
if name != sharedSecretName {
|
||||
t.Errorf("GetSecret(%q), want %q", name, sharedSecretName)
|
||||
}
|
||||
if tt.remoteErr != nil {
|
||||
return nil, tt.remoteErr
|
||||
}
|
||||
return &kubeapi.Secret{Data: tt.remoteData}, nil
|
||||
},
|
||||
}
|
||||
s := &Store{
|
||||
client: client,
|
||||
secretName: "ts-state",
|
||||
certShareMode: "rw",
|
||||
acmeAccountsSecretName: tt.sharedSecret,
|
||||
acmeAccountField: sharedField,
|
||||
logf: t.Logf,
|
||||
}
|
||||
if len(tt.inMemory) > 0 {
|
||||
s.memory.WriteState(ipn.StateKey(acmeAccountStateKey), tt.inMemory)
|
||||
}
|
||||
|
||||
got, err := s.ReadState(tt.readKey)
|
||||
if !errors.Is(err, tt.wantErr) {
|
||||
t.Fatalf("ReadState(%q) err = %v, want %v", tt.readKey, err, tt.wantErr)
|
||||
}
|
||||
if !bytes.Equal(got, tt.want) {
|
||||
t.Errorf("ReadState(%q) = %q, want %q", tt.readKey, got, tt.want)
|
||||
}
|
||||
if getCalls != tt.wantGetSecrets {
|
||||
t.Errorf("GetSecret calls = %d, want %d", getCalls, tt.wantGetSecrets)
|
||||
}
|
||||
if getCalls > 0 {
|
||||
if len(tt.inMemory) > 0 {
|
||||
if gotDeadline > rwCertFallbackTimeout {
|
||||
t.Errorf("GetSecret timeout with cached key = %v, want <= %v", gotDeadline, rwCertFallbackTimeout)
|
||||
}
|
||||
} else if gotDeadline <= rwCertFallbackTimeout {
|
||||
t.Errorf("GetSecret timeout without cached key = %v, want > %v", gotDeadline, rwCertFallbackTimeout)
|
||||
}
|
||||
}
|
||||
if tt.wantMem != nil {
|
||||
gotMem, err := s.memory.ReadState(ipn.StateKey(acmeAccountStateKey))
|
||||
if err != nil {
|
||||
t.Fatalf("memory ReadState: %v", err)
|
||||
}
|
||||
if !bytes.Equal(gotMem, tt.wantMem) {
|
||||
t.Errorf("memory ACME key = %q, want %q", gotMem, tt.wantMem)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user