diff --git a/feature/acme/acme.go b/feature/acme/acme.go index 3482173a5..3c2316fff 100644 --- a/feature/acme/acme.go +++ b/feature/acme/acme.go @@ -3,8 +3,8 @@ // Package acme registers the ACME/TLS-cert feature and implements its // associated [ipnext.Extension]. The extension owns the per-LocalBackend -// ACME serialization mutex, in-flight cert tracking, the refresh loop's -// cancel func, and the test-only cert override; together with the cert +// in-flight certificate issuances, the refresh loop's cancel func, and +// the test-only cert override; together with the cert // acquisition logic in this package, it is everything tailscaled needs // to obtain and renew TLS certificates via ACME. // @@ -34,7 +34,6 @@ import ( "tailscale.com/tsconst" "tailscale.com/types/logger" "tailscale.com/util/clientmetric" - "tailscale.com/util/mak" "tailscale.com/util/set" ) @@ -77,28 +76,34 @@ var errNoExt = errors.New("acme extension not registered on this LocalBackend") type extension struct { logf logger.Logf - // domainsMu guards domainLocks. - domainsMu syncs.Mutex - // domainLocks holds a per-domain mutex serialising ACME operations - // for that domain. Different domains run concurrently; the same - // domain still queues so the first goroutine fills the on-disk - // cache and the rest reuse it. Entries are never removed; a node - // only ever has a handful of domains so the map stays small. - domainLocks map[string]*syncs.Mutex - // accountMu serialises ACME account setup (key generation, LE // registration) so two first-time issuances don't create separate // accounts. accountMu syncs.Mutex - // renewMu guards renewCertAt and renewingCertDomains. - // Lock order: per-domain lock before renewMu. + // renewMu guards renewCertAt. It is held across the ARI fetch that + // decides a domain's renewal time, so nothing that must stay prompt + // waits on it. renewMu syncs.Mutex renewCertAt map[string]time.Time // lazily initialized under renewMu - // renewingCertDomains tracks domains for which an async renewal is - // currently in flight. - renewingCertDomains set.Set[string] + // inflightMu guards inflight. + inflightMu syncs.Mutex + // inflight holds the issuance running for each domain, so a domain + // has at most one getCertPEM running at a time. Entries are removed + // when the issuance finishes. + inflight map[string]*issuance + + // baseCtx is the parent context of every issuance and of the cert + // refresh loop, independent of any caller's context. + // [extension.Shutdown] cancels it via baseCancel. Both are set by + // newExtension and never nil in production. + baseCtx context.Context + baseCancel context.CancelFunc + + // goMu serialises [extension.Go] against [extension.Shutdown]. It + // is never held while taking another mutex. + goMu sync.Mutex // pendingACMETLSALPNCerts maps SNI names to short-lived ACME // tls-alpn-01 challenge certificates while an ACME order is @@ -130,40 +135,37 @@ type extension struct { // See [LocalBackend.ConfigureCertsForTest]. getCertForTest func(hostname string) (*ipnlocal.TLSCertKeyPair, error) - // certRefreshCancel cancels the background TLS cert refresh loop - // that periodically pokes [LocalBackend.GetCertPEM] so renewals - // happen on idle nodes. Non-nil while the loop is running. + // certRefreshCancel stops the background TLS cert refresh loop. + // Non-nil from when updateCertRefreshLoop starts the loop until it + // stops it. Shutdown stops the loop through baseCtx instead. certRefreshCancel context.CancelFunc } -// lockDomain returns the mutex for domain, creating it on first use. -func (e *extension) lockDomain(domain string) *syncs.Mutex { - e.domainsMu.Lock() - defer e.domainsMu.Unlock() - if m, ok := e.domainLocks[domain]; ok { - return m +// Go runs f in a new goroutine tracked by e.wg and reports whether it +// did. It does nothing once [extension.Shutdown] has begun. +func (e *extension) Go(f func()) bool { + e.goMu.Lock() + defer e.goMu.Unlock() + if e.baseCtx.Err() != nil { + return false } - m := new(syncs.Mutex) - mak.Set(&e.domainLocks, domain, m) - return m -} - -// Go runs f in a new goroutine tracked by e.wg. [extension.Shutdown] -// waits for all such goroutines to finish. -func (e *extension) Go(f func()) { e.wg.Add(1) e.goroutinesStarted.Add(1) go func() { defer e.wg.Done() f() }() + return true } // newExtension is the [ipnext.NewExtensionFn] registered for this // feature. It is called once per [*ipnlocal.LocalBackend]. func newExtension(logf logger.Logf, _ ipnext.SafeBackend) (ipnext.Extension, error) { + baseCtx, baseCancel := context.WithCancel(context.Background()) return &extension{ - logf: logger.WithPrefix(logf, featureName+": "), + logf: logger.WithPrefix(logf, featureName+": "), + baseCtx: baseCtx, + baseCancel: baseCancel, }, nil } @@ -173,16 +175,12 @@ func (e *extension) Name() string { return featureName } // Init implements [ipnext.Extension]. func (e *extension) Init(ipnext.Host) error { return nil } -// Shutdown implements [ipnext.Extension]. It cancels the cert refresh -// loop if it's running, then waits for all in-flight goroutines -// (async renewals, refresh loop workers) to finish. +// Shutdown implements [ipnext.Extension]. It cancels baseCtx and waits +// for all goroutines to finish. func (e *extension) Shutdown() error { - e.mu.Lock() - if e.certRefreshCancel != nil { - e.certRefreshCancel() - e.certRefreshCancel = nil - } - e.mu.Unlock() + e.goMu.Lock() + e.baseCancel() + e.goMu.Unlock() e.wg.Wait() return nil } diff --git a/feature/acme/cert.go b/feature/acme/cert.go index 61503c94c..79078f845 100644 --- a/feature/acme/cert.go +++ b/feature/acme/cert.go @@ -137,17 +137,12 @@ func (e *extension) getCertPEMWithValidity(ctx context.Context, b *ipnlocal.Loca return pair, nil } if minValidity == 0 { - // Start renewal in the background if there isn't one already in progress, - // return current valid cert. - if e.beginAsyncRenewal(certDomain) { + // Renew in the background and return the current valid + // cert. If a renewal is already running, this joins it. + if _, started, err := e.startIssuance(b, cs, logf, traceACME, certDomain, now, minValidity); err != nil { + logf("async renewal not started: %v", err) + } else if started { logf("starting async renewal") - - e.Go(func() { - defer e.endAsyncRenewal(certDomain) - if _, err := getCertPEM(context.Background(), e, b, cs, logf, traceACME, certDomain, now, minValidity); err != nil { - logf("async renewal failed: getCertPem: %v", err) - } - }) } return pair, nil } @@ -160,12 +155,34 @@ func (e *extension) getCertPEMWithValidity(ctx context.Context, b *ipnlocal.Loca return nil, fmt.Errorf("retrieving cached TLS certificate failed and cert store is configured in read-only mode, not attempting to issue a new certificate: %w", cacheErr) } - pair, err = getCertPEM(ctx, e, b, cs, logf, traceACME, certDomain, now, minValidity) - if err != nil { - logf("getCertPEM: %v", err) - return nil, err + return e.awaitIssuance(ctx, b, cs, logf, traceACME, certDomain, now, minValidity) +} + +// awaitIssuance returns the result of an issuance for domain with at +// least minValidity, starting one if none is in flight. An in-flight +// issuance with a smaller minValidity is waited for and then followed +// by a new one. If ctx is done first, awaitIssuance returns and the +// issuance keeps running. +func (e *extension) awaitIssuance(ctx context.Context, b *ipnlocal.LocalBackend, cs certStore, logf logger.Logf, traceACME func(any), domain string, now time.Time, minValidity time.Duration) (*ipnlocal.TLSCertKeyPair, error) { + const maxJoins = 3 + for joins := 0; ; joins++ { + iss, _, err := e.startIssuance(b, cs, logf, traceACME, domain, now, minValidity) + if err != nil { + return nil, err + } + select { + case <-iss.done: + case <-ctx.Done(): + logf("caller stopped waiting for the in-flight issuance, which keeps running: %v", ctx.Err()) + return nil, fmt.Errorf("waiting for in-flight ACME issuance for %q: %w", domain, ctx.Err()) + } + if iss.err != nil || iss.minValidity >= minValidity { + return iss.pair, iss.err + } + if joins == maxJoins { + return nil, fmt.Errorf("acme: could not start an issuance for %q with validity %v after joining %d with less", domain, minValidity, joins+1) + } } - return pair, nil } // shouldStartDomainRenewal reports whether the domain's cert should be @@ -205,30 +222,64 @@ func (e *extension) domainRenewed(domain string) { delete(e.renewCertAt, domain) } -// beginAsyncRenewal marks a domain as having an async renewal in flight, -// and reports whether this caller started it. -// -// The caller must arrange for endAsyncRenewal(domain) when the renewal -// finishes, regardless of result. -func (e *extension) beginAsyncRenewal(domain string) bool { - e.renewMu.Lock() - defer e.renewMu.Unlock() - if e.renewingCertDomains.Contains(domain) { - return false - } - e.renewingCertDomains.Make() - e.renewingCertDomains.Add(domain) - return true +// issuance is one run of getCertPEM for a domain. Every caller that +// needs the domain's cert while it runs waits on the same issuance. +type issuance struct { + minValidity time.Duration // the requirement getCertPEM was run with + done chan struct{} // closed once pair and err are set + pair *ipnlocal.TLSCertKeyPair + err error } -// endAsyncRenewal clears the in-flight marker for domain, allowing -// a subsequent renewal to begin. -// -// It should only be called by the caller that began the renewal. -func (e *extension) endAsyncRenewal(domain string) { - e.renewMu.Lock() - defer e.renewMu.Unlock() - e.renewingCertDomains.Delete(domain) +// issuanceTimeout bounds one issuance. It has to cover control's wait +// for DNS propagation, twice for a wildcard order, the CA's validation, +// and finalization. +const issuanceTimeout = 10 * time.Minute + +// startIssuance returns the issuance in flight for domain, starting one +// if there is none. started reports whether this call started it. The +// issuance runs in its own goroutine with a context derived from +// baseCtx. +func (e *extension) startIssuance(b *ipnlocal.LocalBackend, cs certStore, logf logger.Logf, traceACME func(any), domain string, now time.Time, minValidity time.Duration) (iss *issuance, started bool, err error) { + e.inflightMu.Lock() + defer e.inflightMu.Unlock() + if iss, ok := e.inflight[domain]; ok { + return iss, false, nil + } + iss = &issuance{minValidity: minValidity, done: make(chan struct{})} + mak.Set(&e.inflight, domain, iss) + started = e.Go(func() { + ctx, cancel := context.WithTimeout(e.baseCtx, issuanceTimeout) + defer cancel() + pair, err := getCertPEM(ctx, e, b, cs, logf, traceACME, domain, now, minValidity) + if err != nil { + // Say whose deadline it was. The caller's own context is + // reported by awaitIssuance. + switch { + case errors.Is(err, context.DeadlineExceeded): + err = fmt.Errorf("acme: issuance for %q did not finish within %v: %w", domain, issuanceTimeout, err) + case errors.Is(err, context.Canceled): + err = fmt.Errorf("acme: issuance for %q stopped by shutdown: %w", domain, err) + } + logf("getCertPEM: %v", err) + } + e.finishIssuance(domain, iss, pair, err) + }) + if !started { + delete(e.inflight, domain) + return nil, false, fmt.Errorf("acme: not starting issuance for %q: shutting down", domain) + } + return iss, true, nil +} + +// finishIssuance records the result of iss, removes it from inflight, +// and closes its done channel. +func (e *extension) finishIssuance(domain string, iss *issuance, pair *ipnlocal.TLSCertKeyPair, err error) { + iss.pair, iss.err = pair, err + e.inflightMu.Lock() + delete(e.inflight, domain) + e.inflightMu.Unlock() + close(iss.done) } func domainRenewalTimeByExpiry(pair *ipnlocal.TLSCertKeyPair) (time.Time, error) { @@ -344,13 +395,9 @@ func (e *extension) domainRenewalTimeByARI(b *ipnlocal.LocalBackend, cs certStor // domain is the resolved cert domain (e.g., "*.node.ts.net" for // wildcards). It can be overridden in tests. var getCertPEM = func(ctx context.Context, e *extension, b *ipnlocal.LocalBackend, cs certStore, logf logger.Logf, traceACME func(any), domain string, now time.Time, minValidity time.Duration) (*ipnlocal.TLSCertKeyPair, error) { - dm := e.lockDomain(domain) - dm.Lock() - defer dm.Unlock() - - // In case this method was triggered multiple times in parallel (when - // serving incoming requests), check whether one of the other goroutines - // already renewed the cert before us. + // Read the cache again. The caller decided to issue from a read it + // took before calling in, and an issuance that finished in between + // may already have written a usable cert. previous, err := getCertPEMCached(cs, domain, now) if err == nil { // shouldStartDomainRenewal caches its result so it's OK to call this diff --git a/feature/acme/cert_test.go b/feature/acme/cert_test.go index 148d88efa..990faf94e 100644 --- a/feature/acme/cert_test.go +++ b/feature/acme/cert_test.go @@ -17,12 +17,15 @@ import ( "crypto/x509/pkix" "embed" "encoding/pem" + "errors" "maps" "math/big" "os" "path/filepath" "slices" + "strings" "sync" + "sync/atomic" "testing" "time" @@ -764,39 +767,34 @@ func TestGetCertPEMWithValidity(t *testing.T) { b.ForTest().SetClock(tstest.NewClock(tstest.ClockOpts{Start: tt.now})) - // Set to true if getCertPEM is called. GetCertPEM can be called in - // a goroutine for async renewal or in the main goroutine if - // issuance is required to obtain valid TLS credentials. - getCertPemWasCalled := false + // Every issuance runs in its own goroutine. The result tells + // the two cases apart. A synchronous caller gets what + // getCertPEM returned. An async renewal returns the cached + // cert right away. + issued := &ipnlocal.TLSCertKeyPair{CertPEM: []byte("issued")} + var getCertPemWasCalled atomic.Bool orig := getCertPEM getCertPEM = func(ctx context.Context, e *extension, b *ipnlocal.LocalBackend, cs certStore, logf logger.Logf, traceACME func(any), domain string, now time.Time, minValidity time.Duration) (*ipnlocal.TLSCertKeyPair, error) { - getCertPemWasCalled = true - return nil, nil + getCertPemWasCalled.Store(true) + return issued, nil } t.Cleanup(func() { getCertPEM = orig }) - prevGo := e.goroutinesStarted.Load() - _, err = b.GetCertPEMWithValidity(context.Background(), testDomain, 0) + pair, err := b.GetCertPEMWithValidity(context.Background(), testDomain, 0) if (err != nil) != tt.wantErr { t.Errorf("b.GetCertPemWithValidity got err %v, wants error: '%v'", err, tt.wantErr) } - // GetCertPEMWithValidity spawns one tracked goroutine (via - // extension.Go) iff it kicked off async renewal. - gotAsyncRenewal := e.goroutinesStarted.Load()-prevGo != 0 - if gotAsyncRenewal { - done := make(chan struct{}) - go func() { e.wg.Wait(); close(done) }() - select { - case <-time.After(5 * time.Second): - t.Fatal("timed out waiting for async renewal goroutine to finish") - case <-done: - } + done := make(chan struct{}) + go func() { e.wg.Wait(); close(done) }() + select { + case <-time.After(5 * time.Second): + t.Fatal("timed out waiting for issuance goroutines to finish") + case <-done: } - // Verify that async renewal was triggered if expected. + gotIssuance := getCertPemWasCalled.Load() && pair == issued + gotAsyncRenewal := getCertPemWasCalled.Load() && pair != nil && pair.Cached if tt.wantAsyncRenewal != gotAsyncRenewal { t.Fatalf("wants getCertPem to be called async: %v, got called %v", tt.wantAsyncRenewal, gotAsyncRenewal) } - // Verify that (non-async) issuance was started if expected. - gotIssuance := getCertPemWasCalled && !gotAsyncRenewal if tt.wantIssuance != gotIssuance { t.Errorf("wants getCertPem to be called: %v, got called %v", tt.wantIssuance, gotIssuance) } @@ -942,7 +940,10 @@ func TestAsyncRenewalDedup(t *testing.T) { getCertPEM = func(ctx context.Context, e *extension, b *ipnlocal.LocalBackend, cs certStore, logf logger.Logf, traceACME func(any), domain string, now time.Time, minValidity time.Duration) (*ipnlocal.TLSCertKeyPair, error) { t.Logf("calling getCertPEM") renewalStarted <- struct{}{} - <-renewalComplete + select { + case <-renewalComplete: + case <-ctx.Done(): + } return nil, nil } t.Cleanup(func() { getCertPEM = orig }) @@ -989,8 +990,312 @@ func TestAsyncRenewalDedup(t *testing.T) { case <-time.After(5 * time.Second): t.Fatal("timed out waiting for in-flight async renewal goroutine to finish") } - if e.renewingCertDomains.Contains(domain) { - t.Fatal("renewingCertDomains still contains domain after renewal finished") + if e.issuanceInFlight(domain) { + t.Fatal("issuance still recorded as in flight after renewal finished") + } +} + +// issuanceInFlight reports whether an issuance for domain is running. +func (e *extension) issuanceInFlight(domain string) bool { + e.inflightMu.Lock() + defer e.inflightMu.Unlock() + _, ok := e.inflight[domain] + return ok +} + +// TestIssuanceDoesNotWaitOnRenewMu checks that starting and finishing an +// issuance does not block while renewMu is held, since renewMu is held +// across a network fetch. +func TestIssuanceDoesNotWaitOnRenewMu(t *testing.T) { + tstest.AssertNotParallel(t) + + const domain = "example.com" + b := ipnlocaltest.NewBackend(t) + b.SetVarRoot(t.TempDir()) + e := extOf(t, b) + cs, err := e.getCertStore(b) + if err != nil { + t.Fatal(err) + } + issued := &ipnlocal.TLSCertKeyPair{CertPEM: []byte("issued")} + orig := getCertPEM + getCertPEM = func(ctx context.Context, e *extension, b *ipnlocal.LocalBackend, cs certStore, logf logger.Logf, traceACME func(any), domain string, now time.Time, minValidity time.Duration) (*ipnlocal.TLSCertKeyPair, error) { + return issued, nil + } + t.Cleanup(func() { getCertPEM = orig }) + + e.renewMu.Lock() + defer e.renewMu.Unlock() + iss, started, err := e.startIssuance(b, cs, logger.Logf(t.Logf), nil, domain, time.Now(), 0) + if err != nil || !started { + t.Fatalf("startIssuance = started %v, err %v; want a new issuance", started, err) + } + select { + case <-iss.done: + if iss.pair != issued { + t.Fatalf("issuance finished with %+v, want the issued pair", iss.pair) + } + case <-time.After(5 * time.Second): + t.Fatal("issuance did not finish while renewMu was held") + } +} + +// TestIssuanceDetachedFromCaller checks that an issuance keeps running +// when the caller that started it gives up, that a second caller joins +// it instead of starting another, and that the second caller gets its +// result. See tailscale/tailscale#21759. +func TestIssuanceDetachedFromCaller(t *testing.T) { + tstest.AssertNotParallel(t) + + const domain = "example.com" + b := ipnlocaltest.NewBackend(t) + b.SetVarRoot(t.TempDir()) + e := extOf(t, b) + b.ForTest().SetNetMap(&netmap.NetworkMap{ + SelfNode: (&tailcfg.Node{}).View(), + DNS: tailcfg.DNSConfig{CertDomains: []string{domain}}, + }) + + issued := &ipnlocal.TLSCertKeyPair{CertPEM: []byte("issued")} + entered := make(chan context.Context, 1) + release := make(chan struct{}) + var calls atomic.Int32 + orig := getCertPEM + getCertPEM = func(ctx context.Context, e *extension, b *ipnlocal.LocalBackend, cs certStore, logf logger.Logf, traceACME func(any), domain string, now time.Time, minValidity time.Duration) (*ipnlocal.TLSCertKeyPair, error) { + calls.Add(1) + entered <- ctx + select { + case <-release: + return issued, nil + case <-ctx.Done(): + return nil, ctx.Err() + } + } + t.Cleanup(func() { getCertPEM = orig }) + + // The first caller gives up while the issuance is running. + callerCtx, cancelCaller := context.WithCancel(context.Background()) + firstDone := make(chan error, 1) + go func() { + _, err := b.GetCertPEMWithValidity(callerCtx, domain, 0) + firstDone <- err + }() + var issuanceCtx context.Context + select { + case issuanceCtx = <-entered: + case <-time.After(5 * time.Second): + t.Fatal("timed out waiting for the issuance to start") + } + cancelCaller() + select { + case err := <-firstDone: + if !errors.Is(err, context.Canceled) { + t.Fatalf("first caller got %v, want context.Canceled", err) + } + case <-time.After(5 * time.Second): + t.Fatal("first caller did not return after its context was canceled") + } + if issuanceCtx.Err() != nil { + t.Fatal("the issuance's context was canceled along with the caller's") + } + if !e.issuanceInFlight(domain) { + t.Fatal("issuance is not in flight after the caller gave up") + } + + // A second caller joins the running issuance and gets its result. + cs, err := e.getCertStore(b) + if err != nil { + t.Fatal(err) + } + iss, started, err := e.startIssuance(b, cs, logger.Logf(t.Logf), nil, domain, time.Now(), 0) + if err != nil { + t.Fatal(err) + } + if started { + t.Fatal("second caller started a new issuance instead of joining the running one") + } + close(release) + select { + case <-iss.done: + if iss.err != nil || iss.pair == nil || string(iss.pair.CertPEM) != "issued" { + t.Fatalf("joined issuance finished with pair=%+v err=%v, want the issued pair", iss.pair, iss.err) + } + case <-time.After(5 * time.Second): + t.Fatal("joined issuance did not finish") + } + if got := calls.Load(); got != 1 { + t.Fatalf("getCertPEM ran %d times, want 1", got) + } + if e.issuanceInFlight(domain) { + t.Fatal("issuance still recorded as in flight after it finished") + } +} + +// TestAwaitIssuanceHonorsMinValidity checks that a caller with a +// validity requirement that joins an issuance started without one does +// not accept that issuance's cached cert, but runs its own issuance +// once the first finishes. +func TestAwaitIssuanceHonorsMinValidity(t *testing.T) { + tstest.AssertNotParallel(t) + + const domain = "example.com" + b := ipnlocaltest.NewBackend(t) + b.SetVarRoot(t.TempDir()) + e := extOf(t, b) + cs, err := e.getCertStore(b) + if err != nil { + t.Fatal(err) + } + + cached := &ipnlocal.TLSCertKeyPair{CertPEM: []byte("cached"), Cached: true} + issued := &ipnlocal.TLSCertKeyPair{CertPEM: []byte("issued")} + release := make(chan struct{}) + var calls atomic.Int32 + orig := getCertPEM + getCertPEM = func(ctx context.Context, e *extension, b *ipnlocal.LocalBackend, cs certStore, logf logger.Logf, traceACME func(any), domain string, now time.Time, minValidity time.Duration) (*ipnlocal.TLSCertKeyPair, error) { + calls.Add(1) + if minValidity == 0 { + // A background renewal that found the cached cert good enough. + select { + case <-release: + case <-ctx.Done(): + } + return cached, nil + } + return issued, nil + } + t.Cleanup(func() { getCertPEM = orig }) + + // A background renewal is in flight with no validity requirement. + if _, started, err := e.startIssuance(b, cs, logger.Logf(t.Logf), nil, domain, time.Now(), 0); err != nil || !started { + t.Fatalf("startIssuance = started %v, err %v; want a new issuance", started, err) + } + + // A caller that needs an hour of validity must not settle for the + // cached cert that issuance returns. + got := make(chan *ipnlocal.TLSCertKeyPair, 1) + go func() { + pair, err := e.awaitIssuance(context.Background(), b, cs, logger.Logf(t.Logf), nil, domain, time.Now(), time.Hour) + if err != nil { + t.Errorf("awaitIssuance: %v", err) + } + got <- pair + }() + close(release) + select { + case pair := <-got: + if pair != issued { + t.Fatalf("awaitIssuance returned %+v, want the pair issued with the caller's validity requirement", pair) + } + case <-time.After(5 * time.Second): + t.Fatal("awaitIssuance did not return") + } + if n := calls.Load(); n != 2 { + t.Fatalf("getCertPEM ran %d times, want 2 (the joined renewal, then the caller's own)", n) + } +} + +// TestShutdownCancelsIssuance checks that Shutdown cancels a running +// issuance and that no new one can start afterwards. +func TestShutdownCancelsIssuance(t *testing.T) { + tstest.AssertNotParallel(t) + + const domain = "example.com" + b := ipnlocaltest.NewBackend(t) + b.SetVarRoot(t.TempDir()) + e := extOf(t, b) + b.ForTest().SetNetMap(&netmap.NetworkMap{ + SelfNode: (&tailcfg.Node{}).View(), + DNS: tailcfg.DNSConfig{CertDomains: []string{domain}}, + }) + + entered := make(chan struct{}, 1) + orig := getCertPEM + getCertPEM = func(ctx context.Context, e *extension, b *ipnlocal.LocalBackend, cs certStore, logf logger.Logf, traceACME func(any), domain string, now time.Time, minValidity time.Duration) (*ipnlocal.TLSCertKeyPair, error) { + entered <- struct{}{} + <-ctx.Done() + return nil, ctx.Err() + } + t.Cleanup(func() { getCertPEM = orig }) + + done := make(chan error, 1) + go func() { + _, err := b.GetCertPEMWithValidity(context.Background(), domain, 0) + done <- err + }() + select { + case <-entered: + case <-time.After(5 * time.Second): + t.Fatal("timed out waiting for the issuance to start") + } + + shutdownDone := make(chan struct{}) + go func() { e.Shutdown(); close(shutdownDone) }() + select { + case <-shutdownDone: + case <-time.After(5 * time.Second): + t.Fatal("Shutdown did not return; the issuance was not canceled") + } + select { + case err := <-done: + if !errors.Is(err, context.Canceled) { + t.Fatalf("caller got %v, want context.Canceled from the shut-down issuance", err) + } + case <-time.After(5 * time.Second): + t.Fatal("caller did not return after Shutdown") + } + if _, _, err := e.startIssuance(b, nil, t.Logf, nil, domain, time.Now(), 0); err == nil { + t.Fatal("startIssuance succeeded after Shutdown; want an error") + } +} + +// TestIssuanceErrorNotRelabeledByShutdown checks that an issuance's own +// error is reported as is when it ends during Shutdown, and only a +// context error is attributed to the shutdown. +func TestIssuanceErrorNotRelabeledByShutdown(t *testing.T) { + tstest.AssertNotParallel(t) + + const domain = "example.com" + b := ipnlocaltest.NewBackend(t) + b.SetVarRoot(t.TempDir()) + e := extOf(t, b) + b.ForTest().SetNetMap(&netmap.NetworkMap{ + SelfNode: (&tailcfg.Node{}).View(), + DNS: tailcfg.DNSConfig{CertDomains: []string{domain}}, + }) + + caErr := errors.New("403 urn:ietf:params:acme:error:rejectedIdentifier") + entered := make(chan struct{}, 1) + orig := getCertPEM + getCertPEM = func(ctx context.Context, e *extension, b *ipnlocal.LocalBackend, cs certStore, logf logger.Logf, traceACME func(any), domain string, now time.Time, minValidity time.Duration) (*ipnlocal.TLSCertKeyPair, error) { + entered <- struct{}{} + <-ctx.Done() + // The CA's answer arrived as the context ended. + return nil, caErr + } + t.Cleanup(func() { getCertPEM = orig }) + + done := make(chan error, 1) + go func() { + _, err := b.GetCertPEMWithValidity(context.Background(), domain, 0) + done <- err + }() + select { + case <-entered: + case <-time.After(5 * time.Second): + t.Fatal("timed out waiting for the issuance to start") + } + e.Shutdown() + select { + case err := <-done: + if !errors.Is(err, caErr) { + t.Fatalf("caller got %v, want the CA's error", err) + } + if strings.Contains(err.Error(), "shutdown") { + t.Fatalf("the CA's error was attributed to shutdown: %v", err) + } + case <-time.After(5 * time.Second): + t.Fatal("caller did not return") } } @@ -1286,52 +1591,6 @@ func TestRefreshApplicableCerts(t *testing.T) { } } -// TestLockDomain_SameDomainReturnsSameMutex verifies the repeat -// calls for the same domain return the same mutex, and different -// domains get distinct mutexes. -func TestLockDomain_SameDomainReturnsSameMutex(t *testing.T) { - const domA, domB = "a.example.com", "b.example.com" - e := &extension{} - a1 := e.lockDomain(domA) - a2 := e.lockDomain(domA) - b := e.lockDomain(domB) - if a1 != a2 { - t.Errorf("lockDomain(%q) second call = %p, want %p", domA, a2, a1) - } - if a1 == b { - t.Errorf("lockDomain(%q) = lockDomain(%q) = %p, want different", domA, domB, a1) - } -} - -// TestLockDomain_PerDomainConcurrency verifies a lock on one -// domain doesn't block another, and the same domain blocks while held -// and is acquireable again after release. -func TestLockDomain_PerDomainConcurrency(t *testing.T) { - const domA, domB = "a.example.com", "b.example.com" - e := &extension{} - - aLock := e.lockDomain(domA) - aLock.Lock() - - bLock := e.lockDomain(domB) - if !bLock.TryLock() { - t.Errorf("lockDomain(%q).TryLock() = false while %q held, want true", domB, domA) - } else { - bLock.Unlock() - } - - if aLock.TryLock() { - t.Errorf("lockDomain(%q).TryLock() = true while held, want false", domA) - } - - aLock.Unlock() - - if !aLock.TryLock() { - t.Errorf("lockDomain(%q).TryLock() = false after release, want true", domA) - } - aLock.Unlock() -} - // TestAcmeKey_ConcurrentFirstCall verifies that N goroutines racing on // an empty store all return the key that ends up persisted. func TestAcmeKey_ConcurrentFirstCall(t *testing.T) { diff --git a/feature/acme/refresh.go b/feature/acme/refresh.go index f188f9b63..86b64a26c 100644 --- a/feature/acme/refresh.go +++ b/feature/acme/refresh.go @@ -42,9 +42,12 @@ func (e *extension) updateCertRefreshLoop(b *ipnlocal.LocalBackend, state ipn.St defer e.mu.Unlock() switch { case shouldRun && e.certRefreshCancel == nil: - ctx, cancel := context.WithCancel(context.Background()) - e.certRefreshCancel = cancel - e.Go(func() { e.certRefreshLoop(ctx, b) }) + ctx, cancel := context.WithCancel(e.baseCtx) + if e.Go(func() { e.certRefreshLoop(ctx, b) }) { + e.certRefreshCancel = cancel + } else { + cancel() + } case !shouldRun && e.certRefreshCancel != nil: e.certRefreshCancel() e.certRefreshCancel = nil diff --git a/ipn/ipnlocal/cert.go b/ipn/ipnlocal/cert.go index 6209956e1..b213ad0c8 100644 --- a/ipn/ipnlocal/cert.go +++ b/ipn/ipnlocal/cert.go @@ -50,7 +50,8 @@ var ( HookUpdateCertRefreshLoop feature.Hook[func(b *LocalBackend, state ipn.State, sc ipn.ServeConfigView)] // HookShutdownCertRefreshLoop is called from - // [LocalBackend.Shutdown] to cancel the cert refresh loop. + // [LocalBackend.Shutdown] to stop the cert refresh loop and any + // certificate issuance in flight. HookShutdownCertRefreshLoop feature.Hook[func(b *LocalBackend)] // HookConfigureCertsForTest implements @@ -149,9 +150,10 @@ func (b *LocalBackend) updateCertRefreshLoopLocked() { } } -// shutdownCertRefreshLoop is called from [LocalBackend.Shutdown] to cancel the -// cert refresh loop. It must be called without b.mu held because it waits for -// the loop, which can be blocked acquiring b.mu. +// shutdownCertRefreshLoop is called from [LocalBackend.Shutdown] to stop the +// cert refresh loop and any certificate issuance in flight. It must be called +// without b.mu held because it waits for the loop, which can be blocked +// acquiring b.mu. func (b *LocalBackend) shutdownCertRefreshLoop() { if f, ok := HookShutdownCertRefreshLoop.GetOk(); ok { f(b)