diff --git a/feature/acme/acme.go b/feature/acme/acme.go index 3c2316fff..6181dfad2 100644 --- a/feature/acme/acme.go +++ b/feature/acme/acme.go @@ -3,10 +3,10 @@ // Package acme registers the ACME/TLS-cert feature and implements its // associated [ipnext.Extension]. The extension owns the per-LocalBackend -// 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. +// in-flight certificate issuances, the dns-01 propagation settle, the +// refresh loop's cancel func, and the test-only hooks; together with the +// cert acquisition logic in this package, it is everything tailscaled +// needs to obtain and renew TLS certificates via ACME. // // In builds without ACME support (js or ts_omit_acme), this package is // not linked in; [ipn/ipnlocal] then exposes only stub wrappers that @@ -22,6 +22,7 @@ import ( "sync/atomic" "time" + "tailscale.com/envknob" "tailscale.com/feature" "tailscale.com/feature/buildfeatures" "tailscale.com/health" @@ -128,6 +129,17 @@ type extension struct { // Tests use it to assert whether an operation kicked off async work. goroutinesStarted atomic.Int64 + // dnsSettle is how long a dns-01 issuance waits after publishing + // its TXT record before asking the CA to validate. Zero means no + // wait. Set once by newExtension; tests set it directly. + dnsSettle time.Duration + + // setDNS and lookupTXT, if non-nil, replace [LocalBackend.SetDNS] + // and the system resolver's TXT lookup in the dns-01 flow. Tests + // set them; production leaves them nil. + setDNS func(ctx context.Context, b *ipnlocal.LocalBackend, name, value string) error + lookupTXT func(ctx context.Context, name string) ([]string, error) + // mu guards the test/lifecycle fields below. mu sync.Mutex @@ -166,9 +178,37 @@ func newExtension(logf logger.Logf, _ ipnext.SafeBackend) (ipnext.Extension, err logf: logger.WithPrefix(logf, featureName+": "), baseCtx: baseCtx, baseCancel: baseCancel, + dnsSettle: dnsSettleFromEnv(logf), }, nil } +// defaultDNSSettle is how long a dns-01 issuance waits after control +// has published the TXT record before asking the CA to validate it. +// Control answers set-dns after a fixed wait of its own, but the record +// reaches the DNS provider's anycast servers some time later, and the CA +// validates from several vantage points that must all see it. +const defaultDNSSettle = 30 * time.Second + +// dnsSettleFromEnv returns the dns-01 settle to use: defaultDNSSettle, +// or the duration in TS_DEBUG_ACME_DNS_SETTLE when it is set. "0" +// disables the settle. +func dnsSettleFromEnv(logf logger.Logf) time.Duration { + s := envknob.String("TS_DEBUG_ACME_DNS_SETTLE") + if s == "" { + return defaultDNSSettle + } + d, err := time.ParseDuration(s) + if err != nil { + logf("acme: ignoring TS_DEBUG_ACME_DNS_SETTLE=%q: %v", s, err) + return defaultDNSSettle + } + if d < 0 { + logf("acme: ignoring TS_DEBUG_ACME_DNS_SETTLE=%q: negative", s) + return defaultDNSSettle + } + return d +} + // Name implements [ipnext.Extension]. func (e *extension) Name() string { return featureName } diff --git a/feature/acme/cert.go b/feature/acme/cert.go index 79078f845..fd7c6f811 100644 --- a/feature/acme/cert.go +++ b/feature/acme/cert.go @@ -29,6 +29,7 @@ import ( "tailscale.com/ipn/ipnlocal" "tailscale.com/tailcfg/nodecap" xacme "tailscale.com/tempfork/acme" + "tailscale.com/tstime" "tailscale.com/types/logger" "tailscale.com/util/mak" "tailscale.com/util/set" @@ -232,8 +233,8 @@ type issuance struct { } // 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. +// for DNS propagation, twice for a wildcard order, the dns-01 settle, +// the CA's validation, and finalization. const issuanceTimeout = 10 * time.Minute // startIssuance returns the issuance in flight for domain, starting one @@ -577,6 +578,13 @@ func (e *extension) issueACMECert(ctx context.Context, b *ipnlocal.LocalBackend, } args.traceACME(order) + // dns-01 challenges are accepted after every record is published and + // the settle has passed, so a wildcard order (two authorizations on + // one record name) waits once. Control adds a TXT value per set-dns + // call and keeps the earlier ones, so both of a wildcard's values are + // served together. + var dnsChallenges []*xacme.Challenge + published := false for _, aurl := range order.AuthzURLs { az, err := ac.GetAuthorization(ctx, aurl) if err != nil { @@ -601,13 +609,29 @@ func (e *extension) issueACMECert(ctx context.Context, b *ipnlocal.LocalBackend, } args.traceACME(chal) case acmeChallengeDNS01: - if err := fulfillACMEDNS01Challenge(ctx, b, ac, az, args.logf, args.traceACME); err != nil { + ch, didPublish, err := e.publishDNS01Challenge(ctx, b, ac, az, args.logf) + if err != nil { return nil, err } + dnsChallenges = append(dnsChallenges, ch) + published = published || didPublish default: return nil, fmt.Errorf("unknown ACME challenge type %q", args.challengeType) } } + if published && e.dnsSettle > 0 { + args.logf("waiting %v for the DNS record to propagate before accepting the challenge", e.dnsSettle) + if !tstime.Sleep(ctx, e.dnsSettle) { + return nil, ctx.Err() + } + } + for _, ch := range dnsChallenges { + chal, err := ac.Accept(ctx, ch) + if err != nil { + return nil, fmt.Errorf("Accept: %v", err) + } + args.traceACME(chal) + } // Wait for each authorization to settle before waiting on the order. // When validation fails, the order reports only "invalid". The CA's @@ -706,45 +730,50 @@ func isOrderRejected(err error) bool { return ae.StatusCode >= 400 && ae.StatusCode < 500 && ae.StatusCode != http.StatusTooManyRequests } -func fulfillACMEDNS01Challenge(ctx context.Context, b *ipnlocal.LocalBackend, ac *xacme.Client, az *xacme.Authorization, logf logger.Logf, traceACME func(any)) error { - for _, ch := range az.Challenges { - if ch.Type != string(acmeChallengeDNS01) { - continue - } - rec, err := ac.DNS01ChallengeRecord(ch.Token) - if err != nil { - return err - } - // For wildcards, the challenge is on the base domain. - // e.g., "*.node.ts.net" -> "_acme-challenge.node.ts.net" - key := "_acme-challenge." + strings.TrimPrefix(az.Identifier.Value, "*.") - - // Do a best-effort lookup to see if we've already created this DNS name - // in a previous attempt. Don't burn too much time on it, though. Worst - // case we ask the server to create something that already exists. - var resolver net.Resolver - lookupCtx, lookupCancel := context.WithTimeout(ctx, 500*time.Millisecond) - txts, _ := resolver.LookupTXT(lookupCtx, key) - lookupCancel() - if slices.Contains(txts, rec) { - logf("TXT record already existed for %s", key) - } else { - logf("starting SetDNS call for %s...", key) - err = b.SetDNS(ctx, key, rec) - if err != nil { - return fmt.Errorf("SetDNS %q => %q: %w", key, rec, err) - } - logf("did SetDNS for %s", key) - } - - chal, err := ac.Accept(ctx, ch) - if err != nil { - return fmt.Errorf("Accept: %v", err) - } - traceACME(chal) - return nil +// publishDNS01Challenge makes the TXT record for az's dns-01 challenge +// available through control, unless a lookup shows it is already +// published. It returns the challenge for the caller to accept and +// whether this call published the record. +func (e *extension) publishDNS01Challenge(ctx context.Context, b *ipnlocal.LocalBackend, ac *xacme.Client, az *xacme.Authorization, logf logger.Logf) (ch *xacme.Challenge, published bool, err error) { + ch = challengeByType(az.Challenges, string(acmeChallengeDNS01)) + if ch == nil { + return nil, false, errors.New("dns-01 challenge not offered") } - return errors.New("dns-01 challenge not offered") + rec, err := ac.DNS01ChallengeRecord(ch.Token) + if err != nil { + return nil, false, err + } + // For wildcards, the challenge is on the base domain. + // e.g., "*.node.ts.net" -> "_acme-challenge.node.ts.net" + key := "_acme-challenge." + strings.TrimPrefix(az.Identifier.Value, "*.") + + // Do a best-effort lookup to see if we've already created this DNS name + // in a previous attempt. Don't burn too much time on it, though. Worst + // case we ask the server to create something that already exists. + lookupTXT := e.lookupTXT + if lookupTXT == nil { + lookupTXT = new(net.Resolver).LookupTXT + } + lookupCtx, lookupCancel := context.WithTimeout(ctx, 500*time.Millisecond) + txts, _ := lookupTXT(lookupCtx, key) + lookupCancel() + if slices.Contains(txts, rec) { + logf("TXT record already existed for %s", key) + return ch, false, nil + } + + setDNS := e.setDNS + if setDNS == nil { + setDNS = func(ctx context.Context, b *ipnlocal.LocalBackend, name, value string) error { + return b.SetDNS(ctx, name, value) + } + } + logf("starting SetDNS call for %s...", key) + if err := setDNS(ctx, b, key, rec); err != nil { + return nil, false, fmt.Errorf("SetDNS %q => %q: %w", key, rec, err) + } + logf("did SetDNS for %s", key) + return ch, true, nil } // validLookingCertDomain reports whether name looks like a valid domain diff --git a/feature/acme/issue_test.go b/feature/acme/issue_test.go index 101b7bb97..b7ff0965d 100644 --- a/feature/acme/issue_test.go +++ b/feature/acme/issue_test.go @@ -25,6 +25,7 @@ import ( "testing" "time" + "tailscale.com/ipn/ipnlocal" "tailscale.com/ipn/store/mem" xacme "tailscale.com/tempfork/acme" "tailscale.com/tstest/acmetest" @@ -264,3 +265,198 @@ func TestIssueACMECertRetriesWithoutReplaces(t *testing.T) { }) } } + +// dns01TestEnv wires an extension and an acmetest server for a dns-01 +// issuance: SetDNS writes into a map the server validates against, and +// both the publish and the Accept are timestamped. +type dns01TestEnv struct { + e *extension + s *acmetest.Server + logs []string + logsMu sync.Mutex + + mu sync.Mutex + records map[string][]string + published []time.Time + accepted []time.Time +} + +func newDNS01TestEnv(t *testing.T, settle time.Duration) *dns01TestEnv { + t.Helper() + env := &dns01TestEnv{records: map[string][]string{}} + env.s = acmetest.Start(t) + env.s.LookupTXT = func(name string) []string { + env.mu.Lock() + defer env.mu.Unlock() + return env.records[strings.TrimSuffix(name, ".")] + } + env.s.Validate = func(identifier, challengeType string) error { + env.mu.Lock() + defer env.mu.Unlock() + env.accepted = append(env.accepted, time.Now()) + name := "_acme-challenge." + strings.TrimPrefix(identifier, "*.") + if len(env.records[name]) == 0 { + return errors.New("No TXT record found at " + name) + } + return nil + } + env.e = &extension{ + logf: t.Logf, + dnsSettle: settle, + setDNS: func(ctx context.Context, b *ipnlocal.LocalBackend, name, value string) error { + env.mu.Lock() + defer env.mu.Unlock() + env.records[name] = append(env.records[name], value) + env.published = append(env.published, time.Now()) + return nil + }, + lookupTXT: func(ctx context.Context, name string) ([]string, error) { return nil, nil }, + } + return env +} + +func (env *dns01TestEnv) logf(format string, args ...any) { + env.logsMu.Lock() + env.logs = append(env.logs, fmt.Sprintf(format, args...)) + env.logsMu.Unlock() +} + +func (env *dns01TestEnv) settleLogs() int { + env.logsMu.Lock() + defer env.logsMu.Unlock() + n := 0 + for _, line := range env.logs { + if strings.Contains(line, "for the DNS record to propagate") { + n++ + } + } + return n +} + +func (env *dns01TestEnv) issue(ctx context.Context, t *testing.T, domain string) (*ipnlocal.TLSCertKeyPair, error) { + t.Helper() + roots := x509.NewCertPool() + roots.AddCert(env.s.Root()) + return env.e.issueACMECert(ctx, nil, newTestACMEClient(t, env.s), acmeCertIssueArgs{ + cs: certStateStore{StateStore: new(mem.Store), testRoots: roots}, + logf: env.logf, + domain: domain, + challengeType: acmeChallengeDNS01, + }) +} + +// TestIssueACMECertDNS01SettlesBeforeAccept checks that a dns-01 +// issuance waits dnsSettle between publishing the TXT record and asking +// the CA to validate it. +func TestIssueACMECertDNS01SettlesBeforeAccept(t *testing.T) { + const settle = 100 * time.Millisecond + env := newDNS01TestEnv(t, settle) + pair, err := env.issue(context.Background(), t, "example.com") + if err != nil { + t.Fatalf("issueACMECert: %v", err) + } + if pair == nil || len(pair.CertPEM) == 0 { + t.Fatal("no certificate issued") + } + env.mu.Lock() + defer env.mu.Unlock() + if len(env.published) != 1 || len(env.accepted) != 1 { + t.Fatalf("published %d, accepted %d; want 1 and 1", len(env.published), len(env.accepted)) + } + if gap := env.accepted[0].Sub(env.published[0]); gap < settle { + t.Errorf("Accept came %v after SetDNS; want at least %v", gap, settle) + } + if n := env.settleLogs(); n != 1 { + t.Errorf("settle logged %d times, want 1", n) + } +} + +// TestIssueACMECertDNS01WildcardSettlesOnce checks that a wildcard order, +// whose two authorizations share one TXT record name, publishes both +// values and waits once. +func TestIssueACMECertDNS01WildcardSettlesOnce(t *testing.T) { + env := newDNS01TestEnv(t, 50*time.Millisecond) + if _, err := env.issue(context.Background(), t, "*.example.com"); err != nil { + t.Fatalf("issueACMECert: %v", err) + } + env.mu.Lock() + defer env.mu.Unlock() + if got := env.records["_acme-challenge.example.com"]; len(got) != 2 { + t.Errorf("TXT values at _acme-challenge.example.com = %d, want 2", len(got)) + } + if len(env.accepted) != 2 { + t.Errorf("accepted %d challenges, want 2", len(env.accepted)) + } + if n := env.settleLogs(); n != 1 { + t.Errorf("settle logged %d times, want 1", n) + } +} + +// TestIssueACMECertDNS01SkipsSettleForExistingRecord checks that when the +// pre-check finds the TXT record already published, neither SetDNS nor +// the settle runs. +func TestIssueACMECertDNS01SkipsSettleForExistingRecord(t *testing.T) { + env := newDNS01TestEnv(t, time.Hour) + ac := newTestACMEClient(t, env.s) + // The pre-check skips SetDNS only for the exact value the CA wants. + // The token is fixed by acmetest's ID sequence, so compute that value + // the way the client will. + rec, err := ac.DNS01ChallengeRecord("token-3") + if err != nil { + t.Fatal(err) + } + env.e.lookupTXT = func(ctx context.Context, name string) ([]string, error) { + return []string{rec}, nil + } + env.e.setDNS = func(ctx context.Context, b *ipnlocal.LocalBackend, name, value string) error { + t.Errorf("SetDNS(%q) called; the pre-check should have found the record", name) + return nil + } + env.s.Validate = nil + env.s.LookupTXT = func(name string) []string { return []string{rec} } + + roots := x509.NewCertPool() + roots.AddCert(env.s.Root()) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + if _, err := env.e.issueACMECert(ctx, nil, ac, acmeCertIssueArgs{ + cs: certStateStore{StateStore: new(mem.Store), testRoots: roots}, + logf: env.logf, + domain: "example.com", + challengeType: acmeChallengeDNS01, + }); err != nil { + t.Fatalf("issueACMECert: %v", err) + } + if n := env.settleLogs(); n != 0 { + t.Errorf("settle logged %d times, want 0", n) + } +} + +// TestIssueACMECertDNS01SettleHonorsContext checks that cancelling the +// issuance during the settle returns promptly without accepting. +func TestIssueACMECertDNS01SettleHonorsContext(t *testing.T) { + env := newDNS01TestEnv(t, time.Hour) + ctx, cancel := context.WithCancel(context.Background()) + orig := env.e.setDNS + env.e.setDNS = func(ctx2 context.Context, b *ipnlocal.LocalBackend, name, value string) error { + err := orig(ctx2, b, name, value) + cancel() // the settle starts right after publishing + return err + } + done := make(chan error, 1) + go func() { + _, err := env.issue(ctx, t, "example.com") + done <- err + }() + select { + case err := <-done: + if !errors.Is(err, context.Canceled) { + t.Fatalf("got %v, want context.Canceled", err) + } + case <-time.After(5 * time.Second): + t.Fatal("issuance did not return after cancellation during the settle") + } + if n := env.s.Requests("/challenge/3"); n != 0 { + t.Errorf("challenge was accepted %d times; want 0", n) + } +}