cmd/k8s-operator/e2e: cascade stress test with Pebble + rate-limit proxy

Exercises L7 HA Ingress cert issuance against a calendar-bucket
rate-limit proxy in front of Pebble that mirrors LE's
Certificates-per-Registered-Domain shape. Subtests cover:

  - concurrent_issuance: 20 ingresses against a permissive bucket
  - cascade_failure: 15 ingresses with 20s injected ACME latency,
    surfacing the global-mutex bottleneck
  - rate_limit_recovery: tight bucket + Retry-After honouring
  - saturation: bucket-rate efficiency vs theoretical maximum;
    extrapolates a sustainable weekly issuance ceiling
  - renewal_cycle: locks the bucket, waits for organic renewal,
    asserts ARI "replaces" bypasses the limit

Uses TS_DEBUG_CERT_LOOP_INTERVAL to shrink the cert loop's 24h
re-check to 30s so the renewal subtest can observe a renewal in
about 2 minutes.
This commit is contained in:
chaosinthecrd committed 2026-06-26 18:08:50 +00:00
1 parent 4fae4b13d6
commit cf48b0f8eb
10 files changed
+961 -49

No files matched your search

+3
View File
@@ -133,6 +133,9 @@ publishdevtsidp: check-image-repo ## Build and publish tsidp image to location s
publishdevproxy: check-image-repo ## Build and publish k8s-proxy image to location specified by ${REPO}
TAGS="${TAGS}" REPOS=${REPO} PLATFORM=${PLATFORM} PUSH=true TARGET=k8s-proxy ./build_docker.sh
publishdevacmeratelimitproxy: check-image-repo ## Build and publish acmeratelimitproxy (e2e cascade test only) image to location specified by ${REPO}
TAGS="${TAGS}" REPOS=${REPO} PLATFORM=${PLATFORM} PUSH=true TARGET=acmeratelimitproxy ./build_docker.sh
.PHONY: sshintegrationtest
sshintegrationtest: ## Run the SSH integration tests in various Docker containers
@GOOS=linux GOARCH=amd64 CGO_ENABLED=0 ./tool/go test -tags integrationtest -c ./ssh/tailssh -o ssh/tailssh/testcontainers/tailssh.test && \
+15
View File
@@ -148,6 +148,21 @@ case "$TARGET" in
--files="${FILES}" \
/usr/local/bin/k8s-proxy
;;
acmeratelimitproxy)
DEFAULT_REPOS="tailscale/acmeratelimitproxy"
REPOS="${REPOS:-${DEFAULT_REPOS}}"
go run github.com/tailscale/mkctr \
--gopaths="tailscale.com/cmd/k8s-operator/e2e/acmeratelimitproxy:/usr/local/bin/acmeratelimitproxy" \
--base="${BASE}" \
--tags="${TAGS}" \
--repos="${REPOS}" \
--push="${PUSH}" \
--target="${PLATFORM}" \
--goarch="${GOARCH}" \
--annotations="${ANNOTATIONS}" \
--files="${FILES}" \
/usr/local/bin/acmeratelimitproxy
;;
*)
echo "unknown target: $TARGET"
exit 1
@@ -0,0 +1,87 @@
// Copyright (c) Tailscale Inc & contributors
// SPDX-License-Identifier: BSD-3-Clause
package e2e
import (
"context"
"fmt"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/intstr"
"sigs.k8s.io/controller-runtime/pkg/client"
)
// applyACMERatelimitProxyResources deploys the rate-limit proxy.
// Called after the image is built and loaded so the pod can come up
// without an ImagePullBackOff stall.
func applyACMERatelimitProxyResources(ctx context.Context, cl client.Client, tag string) error {
owner := client.FieldOwner("k8s-test")
for _, r := range []client.Object{
acmeRateLimitProxyDeployment(tag),
acmeRateLimitProxyService(),
} {
if err := cl.Patch(ctx, r, client.Apply, owner); err != nil {
return fmt.Errorf("apply %T %s/%s: %w", r, r.GetNamespace(), r.GetName(), err)
}
}
return nil
}
func acmeRateLimitProxyDeployment(tag string) *appsv1.Deployment {
return &appsv1.Deployment{
TypeMeta: metav1.TypeMeta{
Kind: "Deployment",
APIVersion: "apps/v1",
},
ObjectMeta: metav1.ObjectMeta{
Name: "acme-ratelimit",
Namespace: ns,
},
Spec: appsv1.DeploymentSpec{
Replicas: new(int32(1)),
Selector: &metav1.LabelSelector{
MatchLabels: map[string]string{"app": "acme-ratelimit"},
},
Template: corev1.PodTemplateSpec{
ObjectMeta: metav1.ObjectMeta{
Labels: map[string]string{"app": "acme-ratelimit"},
},
Spec: corev1.PodSpec{
Containers: []corev1.Container{{
Name: "proxy",
Image: "local/acmeratelimitproxy:" + tag,
ImagePullPolicy: corev1.PullIfNotPresent,
Ports: []corev1.ContainerPort{
{Name: "acme", ContainerPort: 14000},
{Name: "admin", ContainerPort: 14999},
},
}},
},
},
},
}
}
func acmeRateLimitProxyService() *corev1.Service {
return &corev1.Service{
TypeMeta: metav1.TypeMeta{
Kind: "Service",
APIVersion: "v1",
},
ObjectMeta: metav1.ObjectMeta{
Name: "acme-ratelimit",
Namespace: ns,
},
Spec: corev1.ServiceSpec{
Type: corev1.ServiceTypeClusterIP,
Selector: map[string]string{"app": "acme-ratelimit"},
Ports: []corev1.ServicePort{
{Name: "acme", Port: 14000, TargetPort: intstr.FromInt(14000)},
{Name: "admin", Port: 14999, TargetPort: intstr.FromInt(14999)},
},
},
}
}
@@ -0,0 +1,211 @@
// Copyright (c) Tailscale Inc & contributors
// SPDX-License-Identifier: BSD-3-Clause
// Command acmeratelimitproxy is the reverse proxy used by the cascade
// e2e test. It fronts Pebble, applies a calendar-bucket rate limit to
// new-order POSTs (matching LE's "Certificates per Registered Domain"
// shape), and exempts orders carrying the ARI "replaces" claim.
//
// All knobs are tunable at runtime via POST /set on :14999.
package main
import (
"bytes"
"crypto/tls"
_ "embed"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"net/http/httputil"
"net/url"
"os"
"strconv"
"strings"
"sync"
"time"
)
// Pebble's static localhost TLS material (MIT-licensed, from
// github.com/letsencrypt/pebble v2.8.0 test/certs/localhost/). Signed by
// Pebble's minica root (24e2db), which tailscaled's proxy image trusts.
// Lets this proxy transparently serve "pebble:14000" in front of Pebble.
var (
//go:embed pebble.crt
certPEM []byte
//go:embed pebble.key
keyPEM []byte
)
// state is a calendar-bucket rate limiter: a fixed cap that refills on a
// wall-clock interval, like LE's per-registered-domain weekly cap.
type state struct {
mu sync.Mutex
threshold int
window time.Duration
delay time.Duration
windowStart time.Time
consumed int
total429 int
totalNew int
totalRenew int
}
// check admits a request, or returns the time until the next refill on 429.
func (s *state) check() (allow bool, retryAfter time.Duration) {
s.mu.Lock()
defer s.mu.Unlock()
now := time.Now()
if s.windowStart.IsZero() {
s.windowStart = now
}
if elapsed := now.Sub(s.windowStart); s.window > 0 && elapsed >= s.window {
s.windowStart = s.windowStart.Add(s.window * (elapsed / s.window))
s.consumed = 0
}
if s.consumed >= s.threshold {
s.total429++
ra := s.window - now.Sub(s.windowStart)
if ra < time.Second {
ra = time.Second
}
return false, ra
}
s.consumed++
s.totalNew++
return true, 0
}
// isRenewal reports whether a JWS body's payload carries an ARI "replaces".
func isRenewal(body []byte) bool {
var jws struct{ Payload string }
if json.Unmarshal(body, &jws) != nil || jws.Payload == "" {
return false
}
payload, err := base64.RawURLEncoding.DecodeString(jws.Payload)
if err != nil {
return false
}
var ord struct{ Replaces string }
return json.Unmarshal(payload, &ord) == nil && ord.Replaces != ""
}
func isNewOrder(r *http.Request) bool {
return r.Method == http.MethodPost &&
(strings.Contains(r.URL.Path, "order-plz") || strings.Contains(r.URL.Path, "new-order"))
}
func main() {
upstream := "https://pebble:14000"
if v := os.Getenv("UPSTREAM"); v != "" {
upstream = v
}
u, err := url.Parse(upstream)
if err != nil {
log.Fatalf("UPSTREAM: %v", err)
}
st := &state{threshold: 1000, window: 5 * time.Minute}
go adminServer(":14999", st)
rp := httputil.NewSingleHostReverseProxy(u)
rp.Transport = &http.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: true}}
origDir := rp.Director
rp.Director = func(req *http.Request) {
host := req.Host
origDir(req)
req.Host = host
req.Header.Set("X-Forwarded-Host", host)
}
cert, err := tls.X509KeyPair(certPEM, keyPEM)
if err != nil {
log.Fatalf("X509KeyPair: %v", err)
}
srv := &http.Server{
Addr: ":14000",
Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !isNewOrder(r) {
rp.ServeHTTP(w, r)
return
}
body, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
r.Body = io.NopCloser(bytes.NewReader(body))
r.ContentLength = int64(len(body))
if isRenewal(body) {
st.mu.Lock()
st.totalRenew++
st.mu.Unlock()
} else if allow, ra := st.check(); !allow {
w.Header().Set("Retry-After", strconv.Itoa(max(1, int(ra.Seconds()))))
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(http.StatusTooManyRequests)
io.WriteString(w, `{"type":"urn:ietf:params:acme:error:rateLimited","detail":"too many new-order requests"}`)
return
}
st.mu.Lock()
d := st.delay
st.mu.Unlock()
if d > 0 {
time.Sleep(d)
}
rp.ServeHTTP(w, r)
}),
TLSConfig: &tls.Config{Certificates: []tls.Certificate{cert}},
}
log.Fatal(srv.ListenAndServeTLS("", ""))
}
func adminServer(addr string, st *state) {
mux := http.NewServeMux()
mux.HandleFunc("/set", func(w http.ResponseWriter, r *http.Request) {
var cfg struct {
Threshold *int `json:"threshold,omitempty"`
WindowSec *int `json:"windowSec,omitempty"`
DelayMs *int `json:"delayMs,omitempty"`
Reset bool `json:"reset,omitempty"`
}
if err := json.NewDecoder(r.Body).Decode(&cfg); err != nil {
http.Error(w, err.Error(), 400)
return
}
st.mu.Lock()
defer st.mu.Unlock()
if cfg.Reset {
st.windowStart, st.consumed = time.Time{}, 0
st.total429, st.totalNew, st.totalRenew = 0, 0, 0
st.delay = 0
}
if cfg.Threshold != nil {
st.threshold = *cfg.Threshold
}
if cfg.WindowSec != nil {
st.window = time.Duration(*cfg.WindowSec) * time.Second
}
if cfg.DelayMs != nil {
st.delay = time.Duration(*cfg.DelayMs) * time.Millisecond
}
fmt.Fprintln(w, "ok")
})
mux.HandleFunc("/state", func(w http.ResponseWriter, r *http.Request) {
st.mu.Lock()
defer st.mu.Unlock()
json.NewEncoder(w).Encode(map[string]any{
"threshold": st.threshold,
"windowSec": int(st.window.Seconds()),
"delayMs": int(st.delay.Milliseconds()),
"consumed": st.consumed,
"total429": st.total429,
"totalNew": st.totalNew,
"totalRenew": st.totalRenew,
})
})
log.Fatal(http.ListenAndServe(addr, mux))
}
@@ -0,0 +1,25 @@
# Pebble's static localhost test cert (MIT-licensed, copied from
# github.com/letsencrypt/pebble at v2.8.0, test/certs/localhost/cert.pem).
# Signed by Pebble's minica root (24e2db), which tailscaled's proxy image
# trust store recognises. SAN: localhost, pebble, 127.0.0.1.
# Tied to the pebbleTag constant in pebble.go — if that's bumped to a
# Pebble release that regenerates this material, replace this file too.
-----BEGIN CERTIFICATE-----
MIIDGzCCAgOgAwIBAgIIbEfayDFsBtwwDQYJKoZIhvcNAQELBQAwIDEeMBwGA1UE
AxMVbWluaWNhIHJvb3QgY2EgMjRlMmRiMCAXDTE3MTIwNjE5NDIxMFoYDzIxMDcx
MjA2MTk0MjEwWjAUMRIwEAYDVQQDEwlsb2NhbGhvc3QwggEiMA0GCSqGSIb3DQEB
AQUAA4IBDwAwggEKAoIBAQCbFMW3DXXdErvQf2lCZ0qz0DGEWadDoF0O2neM5mVa
VQ7QGW0xc5Qwvn3Tl62C0JtwLpF0pG2BICIN+DHdVaIUwkf77iBS2doH1I3waE1I
8GkV9JrYmFY+j0dA1SwBmqUZNXhLNwZGq1a91nFSI59DZNy/JciqxoPX2K++ojU2
FPpuXe2t51NmXMsszpa+TDqF/IeskA9A/ws6UIh4Mzhghx7oay2/qqj2IIPjAmJj
i73kdUvtEry3wmlkBvtVH50+FscS9WmPC5h3lDTk5nbzSAXKuFusotuqy3XTgY5B
PiRAwkZbEY43JNfqenQPHo7mNTt29i+NVVrBsnAa5ovrAgMBAAGjYzBhMA4GA1Ud
DwEB/wQEAwIFoDAdBgNVHSUEFjAUBggrBgEFBQcDAQYIKwYBBQUHAwIwDAYDVR0T
AQH/BAIwADAiBgNVHREEGzAZgglsb2NhbGhvc3SCBnBlYmJsZYcEfwAAATANBgkq
hkiG9w0BAQsFAAOCAQEAYIkXff8H28KS0KyLHtbbSOGU4sujHHVwiVXSATACsNAE
D0Qa8hdtTQ6AUqA6/n8/u1tk0O4rPE/cTpsM3IJFX9S3rZMRsguBP7BSr1Lq/XAB
7JP/CNHt+Z9aKCKcg11wIX9/B9F7pyKM3TdKgOpqXGV6TMuLjg5PlYWI/07lVGFW
/mSJDRs8bSCFmbRtEqc4lpwlrpz+kTTnX6G7JDLfLWYw/xXVqwFfdengcDTHCc8K
wtgGq/Gu6vcoBxIO3jaca+OIkMfxxXmGrcNdseuUCa3RMZ8Qy03DqGu6Y6XQyK4B
W8zIG6H9SVKkAznM2yfYhW8v2ktcaZ95/OBHY97ZIw==
-----END CERTIFICATE-----
@@ -0,0 +1,30 @@
# Private key for pebble.crt (MIT-licensed, copied from
# github.com/letsencrypt/pebble at v2.8.0, test/certs/localhost/key.pem).
# Public test material — do not reuse outside this e2e harness.
-----BEGIN RSA PRIVATE KEY-----
MIIEowIBAAKCAQEAmxTFtw113RK70H9pQmdKs9AxhFmnQ6BdDtp3jOZlWlUO0Blt
MXOUML5905etgtCbcC6RdKRtgSAiDfgx3VWiFMJH++4gUtnaB9SN8GhNSPBpFfSa
2JhWPo9HQNUsAZqlGTV4SzcGRqtWvdZxUiOfQ2TcvyXIqsaD19ivvqI1NhT6bl3t
redTZlzLLM6Wvkw6hfyHrJAPQP8LOlCIeDM4YIce6Gstv6qo9iCD4wJiY4u95HVL
7RK8t8JpZAb7VR+dPhbHEvVpjwuYd5Q05OZ280gFyrhbrKLbqst104GOQT4kQMJG
WxGONyTX6np0Dx6O5jU7dvYvjVVawbJwGuaL6wIDAQABAoIBAGW9W/S6lO+DIcoo
PHL+9sg+tq2gb5ZzN3nOI45BfI6lrMEjXTqLG9ZasovFP2TJ3J/dPTnrwZdr8Et/
357YViwORVFnKLeSCnMGpFPq6YEHj7mCrq+YSURjlRhYgbVPsi52oMOfhrOIJrEG
ZXPAwPRi0Ftqu1omQEqz8qA7JHOkjB2p0i2Xc/uOSJccCmUDMlksRYz8zFe8wHuD
XvUL2k23n2pBZ6wiez6Xjr0wUQ4ESI02x7PmYgA3aqF2Q6ECDwHhjVeQmAuypMF6
IaTjIJkWdZCW96pPaK1t+5nTNZ+Mg7tpJ/PRE4BkJvqcfHEOOl6wAE8gSk5uVApY
ZRKGmGkCgYEAzF9iRXYo7A/UphL11bR0gqxB6qnQl54iLhqS/E6CVNcmwJ2d9pF8
5HTfSo1/lOXT3hGV8gizN2S5RmWBrc9HBZ+dNrVo7FYeeBiHu+opbX1X/C1HC0m1
wJNsyoXeqD1OFc1WbDpHz5iv4IOXzYdOdKiYEcTv5JkqE7jomqBLQk8CgYEAwkG/
rnwr4ThUo/DG5oH+l0LVnHkrJY+BUSI33g3eQ3eM0MSbfJXGT7snh5puJW0oXP7Z
Gw88nK3Vnz2nTPesiwtO2OkUVgrIgWryIvKHaqrYnapZHuM+io30jbZOVaVTMR9c
X/7/d5/evwXuP7p2DIdZKQKKFgROm1XnhNqVgaUCgYBD/ogHbCR5RVsOVciMbRlG
UGEt3YmUp/vfMuAsKUKbT2mJM+dWHVlb+LZBa4pC06QFgfxNJi/aAhzSGvtmBEww
xsXbaceauZwxgJfIIUPfNZCMSdQVIVTi2Smcx6UofBz6i/Jw14MEwlvhamaa7qVf
kqflYYwelga1wRNCPopLaQKBgQCWsZqZKQqBNMm0Q9yIhN+TR+2d7QFjqeePoRPl
1qxNejhq25ojE607vNv1ff9kWUGuoqSZMUC76r6FQba/JoNbefI4otd7x/GzM9uS
8MHMJazU4okwROkHYwgLxxkNp6rZuJJYheB4VDTfyyH/ng5lubmY7rdgTQcNyZ5I
majRYQKBgAMKJ3RlII0qvAfNFZr4Y2bNIq+60Z+Qu2W5xokIHCFNly3W1XDDKGFe
CCPHSvQljinke3P9gPt2HVdXxcnku9VkTti+JygxuLkVg7E0/SWwrWfGsaMJs+84
fK+mTZay2d3v24r9WKEKwLykngYPyZw5+BdWU0E+xx5lGUd3U4gG
-----END RSA PRIVATE KEY-----
@@ -0,0 +1,364 @@
// Copyright (c) Tailscale Inc & contributors
// SPDX-License-Identifier: BSD-3-Clause
package e2e
import (
"context"
"crypto/x509"
"encoding/pem"
"fmt"
"sync"
"testing"
"time"
corev1 "k8s.io/api/core/v1"
networkingv1 "k8s.io/api/networking/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/rest"
"sigs.k8s.io/controller-runtime/pkg/client"
tsapi "tailscale.com/k8s-operator/apis/v1alpha1"
)
// TestL7HAIngressCascade exercises L7 HA Ingress cert issuance against
// Pebble fronted by a rate-limit proxy that mimics LE's calendar-bucket
// behaviour. Requires -devcontrol.
func TestL7HAIngressCascade(t *testing.T) {
if !*fDevcontrol {
t.Skip("requires -devcontrol")
}
if tnClient == nil {
t.Skip("requires tnClient")
}
nginx := nginxDeployment(ns)
createAndCleanup(t, kubeClient, nginx)
createAndCleanup(t, kubeClient, &corev1.Service{
ObjectMeta: metav1.ObjectMeta{Name: nginx.Name, Namespace: ns},
Spec: corev1.ServiceSpec{
Selector: map[string]string{"app.kubernetes.io/name": nginx.Name},
Ports: []corev1.ServicePort{{Name: "http", Port: 80}},
},
})
// ProxyClass shortens the cert loop's normal interval so the
// renewal subtest can observe a renewal organically.
pc := cascadeProxyClass()
createAndCleanup(t, kubeClient, pc)
// Shared ProxyGroup so cert loops persist across subtests.
pg := &tsapi.ProxyGroup{
ObjectMeta: metav1.ObjectMeta{Name: generateName("cascade")},
Spec: tsapi.ProxyGroupSpec{
Type: tsapi.ProxyGroupTypeIngress,
Replicas: new(int32(2)),
ProxyClass: pc.Name,
},
}
createAndCleanup(t, kubeClient, pg)
if err := waitForProxyGroupReady(t, pg.Name, 5*time.Minute); err != nil {
t.Fatalf("ProxyGroup never became ready: %v", err)
}
fastCfg := rest.CopyConfig(restCfg)
fastCfg.QPS = 100
fastCfg.Burst = 200
fastClient, err := client.New(fastCfg, client.Options{Scheme: tsapi.GlobalScheme})
if err != nil {
t.Fatalf("fast client: %v", err)
}
rl := newRateLimitClient(t)
if err := rl.waitReady(5 * time.Minute); err != nil {
t.Fatalf("rate-limit proxy not ready: %v", err)
}
t.Run("concurrent_issuance", func(t *testing.T) {
rl.reset(t)
runCascade(t, fastClient, pg.Name, nginx.Name, 20, 6*time.Minute, "concurrent")
})
t.Run("cascade_failure", func(t *testing.T) {
// 20s per-order delay + 15 ingresses = 5m of serial work on main
// (one mutex). The back of the queue blows past the per-call
// deadline, the loop calls it a failure, and the backoff piles on.
// Per-domain locking lets them issue concurrently.
rl.reset(t)
rl.setDelay(t, 20*time.Second)
defer rl.setDelay(t, 0)
runCascade(t, fastClient, pg.Name, nginx.Name, 15, 6*time.Minute, "cascade")
})
t.Run("rate_limit_recovery", func(t *testing.T) {
// 3 per 90s. With Retry-After honoured the second batch lands on
// the refill cleanly. With a fixed 1m backoff it overshoots,
// gets another 429, escalates, and lands a window later.
rl.set(t, 3, 90*time.Second, true)
defer rl.reset(t)
runCascade(t, fastClient, pg.Name, nginx.Name, 6, 8*time.Minute, "ratelimit")
})
t.Run("saturation", func(t *testing.T) {
runSaturation(t, fastClient, pg.Name, nginx.Name, rl)
})
t.Run("renewal_cycle", func(t *testing.T) {
runRenewal(t, fastClient, pg.Name, nginx.Name, rl)
})
}
// runCascade creates n Ingresses against pgName, waits for all to land
// hostnames in parallel, and reports timings.
func runCascade(t *testing.T, cl client.Client, pgName, backendSvc string, n int, timeout time.Duration, tag string) {
t.Helper()
names := make([]string, n)
for i := range n {
ing := l7Ingress(ns, backendSvc, map[string]string{
"tailscale.com/proxy-group": pgName,
})
ing.Name = generateName(fmt.Sprintf("%s-%02d", tag, i))
names[i] = ing.Name
createAndCleanup(t, kubeClient, ing)
}
errs := make(chan error, n)
start := time.Now()
var wg sync.WaitGroup
for _, name := range names {
wg.Add(1)
go func() {
defer wg.Done()
ctx, cancel := context.WithTimeout(t.Context(), timeout)
defer cancel()
_, err := waitForHostname(ctx, cl, ns, name)
if err != nil {
errs <- fmt.Errorf("%s: %w", name, err)
}
}()
}
wg.Wait()
close(errs)
var failed int
for err := range errs {
failed++
t.Error(err)
}
t.Logf("%s: %d/%d issued in %v", tag, n-failed, n, time.Since(start).Round(time.Second))
}
// runSaturation requests more ingresses than the bucket allows and asks
// what fraction of the bucket's max rate the operator achieved. Measuring
// rate (not 429 count) catches both common failure modes: too cautious
// (e.g. global mutex serialising) and too aggressive (Retry-After misses).
const (
saturationCap = 10 // scaled LE: 50/week ≈ 10/min in test
saturationRefill = 60 * time.Second
saturationIngresses = 30
leWeeklyCap = 50 // LE certs/week per registered domain
)
func runSaturation(t *testing.T, cl client.Client, pgName, backendSvc string, rl *rateLimitClient) {
t.Helper()
rl.set(t, saturationCap, saturationRefill, true)
defer rl.reset(t)
windows := (saturationIngresses + saturationCap - 1) / saturationCap
optimalWall := time.Duration(windows-1)*saturationRefill + 30*time.Second
runWall := 3 * optimalWall
if runWall < 6*time.Minute {
runWall = 6 * time.Minute
}
start := time.Now()
runCascade(t, cl, pgName, backendSvc, saturationIngresses, runWall, "sat")
wall := time.Since(start)
s := rl.state(t)
rate := float64(s.TotalNew) / wall.Seconds()
maxRate := float64(saturationCap) / saturationRefill.Seconds()
eff := rate / maxRate
t.Logf("saturation: %d/%d issued in %v, %d 429s; rate=%.0f%% of bucket max → ~%.0f/week",
s.TotalNew, saturationIngresses, wall.Round(time.Second), s.Total429,
eff*100, float64(leWeeklyCap)*eff)
if s.TotalNew < saturationIngresses {
t.Errorf("issued %d, want >=%d", s.TotalNew, saturationIngresses)
}
if eff < 0.75 {
t.Errorf("rate %.0f%% of bucket max (want >=75%%)", eff*100)
}
}
// runRenewal issues 3 certs, locks the bucket so any new (non-replaces)
// order would 429, and waits long enough for the cert loop to fire a
// renewal organically. With ARI "replaces" wired up, renewals bypass the
// locked budget and NotAfter advances; without it (e.g. when
// TS_DEBUG_ACME_FORCE_RENEWAL strips the field), they 429 and NotAfter
// stays put.
//
// Timing: Pebble issues 180s certs, the proxy pods run with
// TS_DEBUG_CERT_LOOP_INTERVAL=30s, so the loop fires after the cert
// reaches 2/3 lifetime (~120s) and triggers a renewal.
func runRenewal(t *testing.T, cl client.Client, pgName, backendSvc string, rl *rateLimitClient) {
t.Helper()
const n = 3
rl.reset(t)
names := make([]string, n)
hosts := make(map[string]string, n)
for i := range n {
ing := l7Ingress(ns, backendSvc, map[string]string{
"tailscale.com/proxy-group": pgName,
})
ing.Name = generateName(fmt.Sprintf("renewal-%02d", i))
names[i] = ing.Name
createAndCleanup(t, kubeClient, ing)
}
for _, name := range names {
ctx, cancel := context.WithTimeout(t.Context(), 5*time.Minute)
host, err := waitForHostname(ctx, cl, ns, name)
cancel()
if err != nil {
t.Fatalf("initial issuance of %s: %v", name, err)
}
hosts[name] = host
}
initial := make(map[string]time.Time, n)
for _, name := range names {
na, err := certNotAfter(t, hosts[name])
if err != nil {
t.Fatalf("NotAfter %s: %v", name, err)
}
initial[name] = na
}
baseline := rl.state(t)
// Lock the bucket at the in-window count: any further non-replaces
// order 429s. Don't reset — keep the existing orders saturating us.
rl.set(t, baseline.TotalNew, 30*time.Minute, false)
// Cert lifetime is 180s and the cert loop fires every 30s; renewal
// becomes due at 2/3 lifetime (120s). Sleep long enough that the
// loop has fired at least once past that mark.
time.Sleep(150 * time.Second)
final := rl.state(t)
renewals := final.TotalRenew - baseline.TotalRenew
new429 := final.Total429 - baseline.Total429
var renewed int
for _, name := range names {
na, err := certNotAfter(t, hosts[name])
if err != nil {
t.Errorf("NotAfter %s: %v", name, err)
continue
}
if na.After(initial[name]) {
renewed++
} else {
t.Errorf("%s NotAfter did not advance (%v)", name, na.UTC())
}
}
if renewals == 0 {
t.Errorf("no orders carried ARI replaces")
}
if new429 > 0 {
t.Errorf("renewals 429ed %d times; should be zero with ARI replaces", new429)
}
t.Logf("renewal: %d/%d renewed, %d ARI-replaces, %d 429s",
renewed, n, renewals, new429)
}
// certNotAfter reads NotAfter from the per-domain TLS Secret (named after
// the operator-assigned hostname in cert-share rw mode).
func certNotAfter(t *testing.T, hostname string) (time.Time, error) {
t.Helper()
sec := &corev1.Secret{}
if err := kubeClient.Get(t.Context(), types.NamespacedName{
Namespace: "tailscale",
Name: hostname,
}, sec); err != nil {
return time.Time{}, err
}
pemBytes := sec.Data["tls.crt"]
if len(pemBytes) == 0 {
return time.Time{}, fmt.Errorf("empty tls.crt in Secret %s", hostname)
}
block, _ := pem.Decode(pemBytes)
if block == nil {
return time.Time{}, fmt.Errorf("no PEM block in tls.crt")
}
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
return time.Time{}, err
}
return cert.NotAfter, nil
}
func waitForHostname(ctx context.Context, cl client.Client, ns, name string) (string, error) {
t := time.NewTicker(2 * time.Second)
defer t.Stop()
for {
var ing networkingv1.Ingress
if err := cl.Get(ctx, types.NamespacedName{Namespace: ns, Name: name}, &ing); err != nil {
if !apierrors.IsNotFound(err) {
return "", err
}
} else if len(ing.Status.LoadBalancer.Ingress) > 0 && ing.Status.LoadBalancer.Ingress[0].Hostname != "" {
return ing.Status.LoadBalancer.Ingress[0].Hostname, nil
}
select {
case <-ctx.Done():
return "", ctx.Err()
case <-t.C:
}
}
}
func waitForProxyGroupReady(t *testing.T, name string, timeout time.Duration) error {
t.Helper()
deadline := time.Now().Add(timeout)
for {
var pg tsapi.ProxyGroup
if err := kubeClient.Get(t.Context(), types.NamespacedName{Name: name}, &pg); err != nil {
return err
}
for _, c := range pg.Status.Conditions {
if c.Type == "ProxyGroupAvailable" && c.Status == "True" {
return nil
}
}
if time.Now().After(deadline) {
return fmt.Errorf("timed out waiting for ProxyGroup %s", name)
}
time.Sleep(2 * time.Second)
}
}
// cascadeProxyClass shortens runCertLoop's normal interval to 30s so the
// renewal subtest can observe an organic renewal in ~2 minutes.
func cascadeProxyClass() *tsapi.ProxyClass {
return &tsapi.ProxyClass{
ObjectMeta: metav1.ObjectMeta{Name: generateName("cascade")},
Spec: tsapi.ProxyClassSpec{
StatefulSet: &tsapi.StatefulSet{
Pod: &tsapi.Pod{
TailscaleContainer: &tsapi.Container{
Env: []tsapi.Env{
{Name: "TS_DEBUG_CERT_LOOP_INTERVAL", Value: "30s"},
},
},
},
},
},
}
}
+102 -46
View File
@@ -16,23 +16,58 @@ import (
func applyPebbleResources(ctx context.Context, cl client.Client) error {
owner := client.FieldOwner("k8s-test")
if err := cl.Patch(ctx, pebbleDeployment(pebbleTag), client.Apply, owner); err != nil {
return fmt.Errorf("failed to apply pebble Deployment: %w", err)
resources := []client.Object{
pebbleConfigMap(),
pebbleDeployment(pebbleTag),
pebbleService(),
tailscaleNamespace(),
pebbleExternalNameService(),
}
if err := cl.Patch(ctx, pebbleService(), client.Apply, owner); err != nil {
return fmt.Errorf("failed to apply pebble Service: %w", err)
for _, r := range resources {
if err := cl.Patch(ctx, r, client.Apply, owner); err != nil {
return fmt.Errorf("apply %T %s/%s: %w", r, r.GetNamespace(), r.GetName(), err)
}
}
if err := cl.Patch(ctx, tailscaleNamespace(), client.Apply, owner); err != nil {
return fmt.Errorf("failed to apply tailscale Namespace: %w", err)
}
if err := cl.Patch(ctx, pebbleExternalNameService(), client.Apply, owner); err != nil {
return fmt.Errorf("failed to apply pebble ExternalName Service: %w", err)
}
return nil
}
// pebbleConfigJSON tells Pebble to issue short-lived certs so the cascade
// renewal subtest can observe a renewal cycle within ~2 minutes (cert
// hits 2/3 lifetime at 120s). v2.8+ ignores the deprecated
// certificateValidityPeriod field; validity goes on the profile.
const pebbleConfigJSON = `{
"pebble": {
"listenAddress": "0.0.0.0:14000",
"managementListenAddress": "0.0.0.0:15000",
"certificate": "test/certs/localhost/cert.pem",
"privateKey": "test/certs/localhost/key.pem",
"httpPort": 5002,
"tlsPort": 5001,
"ocspResponderURL": "",
"externalAccountBindingRequired": false,
"profiles": {
"default": {
"description": "Short-lived for cascade e2e",
"validityPeriod": 180
}
}
}
}`
func pebbleConfigMap() *corev1.ConfigMap {
return &corev1.ConfigMap{
TypeMeta: metav1.TypeMeta{
Kind: "ConfigMap",
APIVersion: "v1",
},
ObjectMeta: metav1.ObjectMeta{
Name: "pebble-config",
Namespace: ns,
},
Data: map[string]string{"pebble-config.json": pebbleConfigJSON},
}
}
func pebbleDeployment(tag string) *appsv1.Deployment {
return &appsv1.Deployment{
TypeMeta: metav1.TypeMeta{
@@ -57,6 +92,16 @@ func pebbleDeployment(tag string) *appsv1.Deployment {
},
},
Spec: corev1.PodSpec{
Volumes: []corev1.Volume{{
Name: "pebble-config",
VolumeSource: corev1.VolumeSource{
ConfigMap: &corev1.ConfigMapVolumeSource{
LocalObjectReference: corev1.LocalObjectReference{
Name: "pebble-config",
},
},
},
}},
Containers: []corev1.Container{
{
Name: "pebble",
@@ -64,8 +109,14 @@ func pebbleDeployment(tag string) *appsv1.Deployment {
ImagePullPolicy: corev1.PullIfNotPresent,
Args: []string{
"-dnsserver=localhost:8053",
"-config=/etc/pebble/pebble-config.json",
"-strict",
},
VolumeMounts: []corev1.VolumeMount{{
Name: "pebble-config",
MountPath: "/etc/pebble",
ReadOnly: true,
}},
Ports: []corev1.ContainerPort{
{
Name: "acme",
@@ -81,6 +132,12 @@ func pebbleDeployment(tag string) *appsv1.Deployment {
Name: "PEBBLE_VA_NOSLEEP",
Value: "1",
},
{
// Don't reuse authz; renewal subtest
// reissues immediately after issuance.
Name: "PEBBLE_AUTHZREUSE",
Value: "0",
},
},
},
{
@@ -102,6 +159,39 @@ func pebbleDeployment(tag string) *appsv1.Deployment {
}
}
func tailscaleNamespace() *corev1.Namespace {
return &corev1.Namespace{
TypeMeta: metav1.TypeMeta{
Kind: "Namespace",
APIVersion: "v1",
},
ObjectMeta: metav1.ObjectMeta{
Name: "tailscale",
},
}
}
// pebbleExternalNameService gives tailscaled in the tailscale namespace a
// "pebble" hostname that matches Pebble's TLS cert SAN. The cascade test
// points the alias at the acme-ratelimit proxy in the default namespace so
// new-order POSTs can be intercepted before they reach Pebble.
func pebbleExternalNameService() *corev1.Service {
return &corev1.Service{
TypeMeta: metav1.TypeMeta{
Kind: "Service",
APIVersion: "v1",
},
ObjectMeta: metav1.ObjectMeta{
Name: "pebble",
Namespace: "tailscale",
},
Spec: corev1.ServiceSpec{
Type: corev1.ServiceTypeExternalName,
ExternalName: "acme-ratelimit.default.svc.cluster.local",
},
}
}
func pebbleService() *corev1.Service {
return &corev1.Service{
TypeMeta: metav1.TypeMeta{
@@ -137,37 +227,3 @@ func pebbleService() *corev1.Service {
},
}
}
func tailscaleNamespace() *corev1.Namespace {
return &corev1.Namespace{
TypeMeta: metav1.TypeMeta{
Kind: "Namespace",
APIVersion: "v1",
},
ObjectMeta: metav1.ObjectMeta{
Name: "tailscale",
},
}
}
// pebbleExternalNameService ensures the operator in the tailscale namespace
// can reach pebble on a DNS name (pebble) that matches its TLS cert.
func pebbleExternalNameService() *corev1.Service {
return &corev1.Service{
TypeMeta: metav1.TypeMeta{
Kind: "Service",
APIVersion: "v1",
},
ObjectMeta: metav1.ObjectMeta{
Name: "pebble",
Namespace: "tailscale",
},
Spec: corev1.ServiceSpec{
Type: corev1.ServiceTypeExternalName,
Selector: map[string]string{
"app": "pebble",
},
ExternalName: "pebble.default.svc.cluster.local",
},
}
}
+113
View File
@@ -0,0 +1,113 @@
// Copyright (c) Tailscale Inc & contributors
// SPDX-License-Identifier: BSD-3-Clause
package e2e
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"testing"
"time"
"k8s.io/client-go/rest"
)
// rateLimitClient talks to the acme-ratelimit-proxy admin endpoint via
// the kube API server proxy (no port-forward needed).
type rateLimitClient struct {
hc *http.Client
base string
}
func newRateLimitClient(t *testing.T) *rateLimitClient {
t.Helper()
hc, err := rest.HTTPClientFor(restCfg)
if err != nil {
t.Fatalf("rest HTTPClientFor: %v", err)
}
return &rateLimitClient{
hc: hc,
base: strings.TrimRight(restCfg.Host, "/") +
"/api/v1/namespaces/" + ns + "/services/acme-ratelimit:admin/proxy",
}
}
type rateLimitState struct {
Total429 int `json:"total429"`
TotalNew int `json:"totalNew"`
TotalRenew int `json:"totalRenew"`
}
// waitReady polls /state until the proxy returns 200 or timeout elapses.
func (c *rateLimitClient) waitReady(timeout time.Duration) error {
deadline := time.Now().Add(timeout)
for {
resp, err := c.hc.Get(c.base + "/state")
if err == nil {
resp.Body.Close()
if resp.StatusCode == 200 {
return nil
}
}
if time.Now().After(deadline) {
return fmt.Errorf("acme-ratelimit proxy not ready after %v", timeout)
}
time.Sleep(3 * time.Second)
}
}
func (c *rateLimitClient) state(t *testing.T) rateLimitState {
t.Helper()
resp, err := c.hc.Get(c.base + "/state")
if err != nil {
t.Fatalf("rate-limit state: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
out, _ := io.ReadAll(resp.Body)
t.Fatalf("rate-limit state: %v: %s", resp.Status, out)
}
var s rateLimitState
if err := json.NewDecoder(resp.Body).Decode(&s); err != nil {
t.Fatalf("rate-limit state decode: %v", err)
}
return s
}
// set configures the bucket: at most threshold requests per window.
// Retry-After on 429 is the time until the window refills.
func (c *rateLimitClient) set(t *testing.T, threshold int, window time.Duration, reset bool) {
c.post(t, fmt.Sprintf(`{"threshold":%d,"windowSec":%d,"reset":%t}`,
threshold, int(window.Seconds()), reset))
}
// reset sets a permissive bucket (10000 per 5min) and clears counters.
func (c *rateLimitClient) reset(t *testing.T) { c.set(t, 10000, 5*time.Minute, true) }
// setDelay holds each forwarded new-order for d before sending it to
// Pebble, simulating ACME latency.
func (c *rateLimitClient) setDelay(t *testing.T, d time.Duration) {
c.post(t, fmt.Sprintf(`{"delayMs":%d}`, d.Milliseconds()))
}
func (c *rateLimitClient) post(t *testing.T, body string) {
t.Helper()
req, err := http.NewRequest(http.MethodPost, c.base+"/set", bytes.NewBufferString(body))
if err != nil {
t.Fatalf("rate-limit POST: %v", err)
}
req.Header.Set("Content-Type", "application/json")
resp, err := c.hc.Do(req)
if err != nil {
t.Fatalf("rate-limit POST: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
out, _ := io.ReadAll(resp.Body)
t.Fatalf("rate-limit POST %s: %v: %s", body, resp.Status, out)
}
}
+11 -3
View File
@@ -379,9 +379,10 @@ func runTests(m *testing.M) (int, error) {
}
logger.Infof("using OSS image tag: %q", ossTag)
ossImageToTarget := map[string]string{
"local/k8s-operator": "publishdevoperator",
"local/tailscale": "publishdevimage",
"local/k8s-proxy": "publishdevproxy",
"local/k8s-operator": "publishdevoperator",
"local/tailscale": "publishdevimage",
"local/k8s-proxy": "publishdevproxy",
"local/acmeratelimitproxy": "publishdevacmeratelimitproxy",
}
for img, target := range ossImageToTarget {
if err := buildImage(ctx, ossDir, img, target, ossTag, caPaths); err != nil {
@@ -416,6 +417,13 @@ func runTests(m *testing.M) (int, error) {
}
}
}
// Deploy the rate-limit proxy now that its image is loaded.
if *fDevcontrol {
if err := applyACMERatelimitProxyResources(ctx, kubeClient, ossTag); err != nil {
return 0, fmt.Errorf("apply acme-ratelimit resources: %w", err)
}
}
}
// Generate CRDs for the helm chart.