| new file mode 100644 |
| index 000000000..d4a82e44d |
| --- /dev/null |
| +++ b/internal/host/haingress_alias_test.go |
| @@ -0,0 +1,306 @@ |
| +package host |
| + |
| +import ( |
| + "context" |
| + "crypto/ed25519" |
| + "crypto/rand" |
| + "crypto/tls" |
| + "crypto/x509" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "io" |
| + "math/big" |
| + "net" |
| + "net/http" |
| + "net/http/httptest" |
| + "strings" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/activator" |
| + "github.com/carlosframework/platform/internal/domains" |
| + "github.com/carlosframework/platform/internal/edge" |
| + "github.com/carlosframework/platform/internal/hafresh" |
| + "github.com/carlosframework/platform/internal/lease/locktest" |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +func TestHAIngressNamesWithoutLocalRow(t *testing.T) { |
| + for _, indexed := range []bool{false, true} { |
| + t.Run(fmt.Sprintf("indexed=%v", indexed), func(t *testing.T) { |
| + disarmView(t) |
| + oldAliases := boxHAIngress.aliases.Load() |
| + boxHAIngress.aliases.Store(nil) |
| + oldRoutes, oldNames, oldEpoch := boxHAIngress.routes.Load(), boxHAIngress.regional.Load(), boxHAIngress.epoch |
| + boxHAIngress.routes.Store(nil) |
| + boxHAIngress.regional.Store(nil) |
| + boxHAIngress.epoch = 0 |
| + t.Cleanup(func() { |
| + boxHAIngress.aliases.Store(oldAliases) |
| + boxHAIngress.routes.Store(oldRoutes) |
| + boxHAIngress.regional.Store(oldNames) |
| + boxHAIngress.epoch = oldEpoch |
| + }) |
| + w := newCIWorld(t) |
| + t.Setenv("CARLOS_REGION", "") |
| + t.Setenv("CARLOS_REGION_HA", "1") |
| + t.Setenv("CARLOS_POOLS", "other") |
| + fx := locktest.NewLockFixture(t) |
| + rec := provision.Record{Schema: 1, Host: "example.com", Slug: "ha", Account: w.acct, App: "shop", Channel: "stable", Pool: "ha", HA: true, CreatedAt: time.Now()} |
| + if err := provision.CreateRecord(t.Context(), w.live, rec); err != nil { |
| + t.Fatal(err) |
| + } |
| + if indexed { |
| + armView(t, w.live) |
| + } |
| + reg := edgesTestRegistry(t) |
| + peerReg := edgesTestRegistry(t) |
| + if err := peerReg.Upsert(registry.Route{Host: rec.Host, Account: rec.Account, App: rec.App, Pool: rec.Pool, HA: true, Hibernate: true, Socket: "/unused"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, peer := range []struct { |
| + name, ip, pool string |
| + reg *registry.Registry |
| + }{ |
| + {"ingress", "127.0.0.1", "other", reg}, {"holder", "127.0.0.2", "ha", peerReg}, |
| + } { |
| + t.Setenv("CARLOS_POOLS", peer.pool) |
| + var last []byte |
| + yes, no := true, false |
| + ident := edgesFile{ServedPools: (provision.ReconcileConfig{Pools: []string{peer.pool}}).ServedPools(), Box: peer.name, Region: "eu-west-1", DataBucket: fx.Bucket, SecretsKeyFP: "shared", HibernationConfigured: true, Capabilities: []string{capRegionHA1}, BoxRole: "serve", Admitted: &yes, Drained: &no, Headroom: &edgeHeadroom{MemFreeMiB: 300, MemTotalMiB: 1000, DiskFreeMiB: 300, DiskTotalMiB: 1000}} |
| + if err := edgesFileWrite(t.Context(), w.live, peer.reg, ident, peer.ip, &last, true); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + t.Setenv("CARLOS_POOLS", "other") |
| + stale := registry.Route{Host: rec.Host, Account: rec.Account, App: rec.App, Pool: rec.Pool, Hibernate: true, Socket: "/unused"} |
| + if err := reg.Upsert(stale); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := w.live.Put(t.Context(), "control/edge-mesh-key", []byte(strings.Repeat("a", 64)), ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + var deliveries atomic.Int32 |
| + peer := httptest.NewUnstartedServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { |
| + if r.Header.Get("X-Carlos-Hop-Auth") == "" { |
| + t.Errorf("unsigned or wrong host: %s %v", r.Host, r.Header) |
| + } |
| + deliveries.Add(1) |
| + io.WriteString(rw, "forwarded") |
| + })) |
| + pub, key, err := ed25519.GenerateKey(rand.Reader) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + cert := &x509.Certificate{SerialNumber: big.NewInt(1), DNSNames: []string{"example.com", "*.example.net", "*.wild.example.net"}, NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(time.Hour), KeyUsage: x509.KeyUsageDigitalSignature, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}} |
| + der, err := x509.CreateCertificate(rand.Reader, cert, cert, pub, key) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + peer.TLS = &tls.Config{Certificates: []tls.Certificate{{Certificate: [][]byte{der}, PrivateKey: key}}} |
| + peer.StartTLS() |
| + defer peer.Close() |
| + oldDial, oldRoots := startupForwardDial, startupBackhaulRoots |
| + startupBackhaulRoots = x509.NewCertPool() |
| + startupBackhaulRoots.AddCert(peer.Certificate()) |
| + startupForwardDial = func(ctx context.Context, network, addr string) (net.Conn, error) { |
| + if !strings.HasPrefix(addr, "127.0.0.2:") { |
| + return nil, fmt.Errorf("unexpected target %s", addr) |
| + } |
| + return (&net.Dialer{}).DialContext(ctx, network, peer.Listener.Addr().String()) |
| + } |
| + defer func() { startupForwardDial, startupBackhaulRoots = oldDial, oldRoots }() |
| + cfg := activator.Config{Bucket: fx.Bucket, Idle: time.Hour, Self: func() hafresh.Self { return hafresh.Self{Ref: "ingress", IID: "i-ingress"} }} |
| + svc := activator.New(cfg, &activator.ExecBackend{Cfg: cfg, ServedPools: (provision.ReconcileConfig{Pools: []string{"other"}}).ServedPools}, nil) |
| + defer svc.Shutdown(context.Background()) |
| + e, err := edge.New(reg, svc) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + edge.WithBoxLabel("ingress")(e) |
| + e.EnableStatic(w.live, ed25519.NewKeyFromSeed(make([]byte, 32)).Public().(ed25519.PublicKey), t.TempDir()) |
| + e.SetHAIngressLookup(boxHAIngress.lookup) |
| + if e.ArmHomeMap() == nil { |
| + t.Fatal("peer view not armed") |
| + } |
| + snapshot := e.DutySnapshot(registry.Route{Host: rec.Host, Account: rec.Account, App: rec.App, Pool: rec.Pool, HA: true}) |
| + if !snapshot.Usable || !snapshot.LocalDenied || len(snapshot.Serving) != 1 || snapshot.Serving[0].BoxID != "holder" { |
| + t.Fatalf("startup peer view: %+v", snapshot) |
| + } |
| + if err := refreshHAIngressAtStart(t.Context(), func(context.Context) (release.Store, error) { return w.live, nil }, newBoxJudge(claimsOffEnv)); err != nil { |
| + t.Fatal(err) |
| + } |
| + claims := []domains.Claim{ |
| + {Schema: 1, Host: "alias.example.net", Route: rec.Host, Account: rec.Account, App: rec.App}, |
| + {Schema: 2, Host: "regional.example.net", Route: rec.Host, Account: rec.Account, App: rec.App, Placements: []domains.Placement{{Region: "", Host: rec.Host}}}, |
| + {Schema: 2, Host: "foreign.example.net", Route: rec.Host, Account: rec.Account, App: rec.App, Placements: []domains.Placement{{Region: "us", Host: rec.Host}}}, |
| + {Schema: 2, Host: "regional-cross.example.net", Route: rec.Host, Account: "bab", App: rec.App, Placements: []domains.Placement{{Region: "", Host: rec.Host}}}, |
| + {Schema: 1, Host: "cross-account.example.net", Route: rec.Host, Account: "bab", App: rec.App}, |
| + {Schema: 1, Host: "cross-app.example.net", Route: rec.Host, Account: rec.Account, App: "cafe"}, |
| + {Schema: 1, Host: "pending.example.net", Route: rec.Host, Account: rec.Account, App: rec.App, Pending: true}, |
| + {Schema: 1, Host: "wild.example.net", Route: rec.Host, Account: rec.Account, App: rec.App, Wildcard: true, Catchall: true}, |
| + } |
| + for _, claim := range claims { |
| + claim.CreatedAt = time.Now().UTC().Format(time.RFC3339) |
| + data, err := json.Marshal(claim) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := w.live.Put(t.Context(), domains.ClaimKey(claim.Host), data, ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + refresh := func() { |
| + t.Helper() |
| + if err := aliasPassReporting(t.Context(), w.live, reg, nil, newAssetAuthority(nil), ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := e.Reload(); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + request := func(host string, want int) { |
| + t.Helper() |
| + before, reads := deliveries.Load(), len(fx.Requests()) |
| + rw := httptest.NewRecorder() |
| + e.ServeHTTP(rw, httptest.NewRequest("POST", "https://"+host+"/", strings.NewReader("once"))) |
| + if rw.Code != want { |
| + t.Fatalf("%s: got %d %q, want %d", host, rw.Code, rw.Body.String(), want) |
| + } |
| + if want == 200 && (rw.Body.String() != "forwarded" || deliveries.Load() != before+1) { |
| + t.Fatalf("%s: wrong delivery: %q %d", host, rw.Body.String(), deliveries.Load()-before) |
| + } |
| + if want != 200 && (deliveries.Load() != before || len(fx.Requests()) != reads) { |
| + t.Fatalf("%s: refused name forwarded or read a lock", host) |
| + } |
| + } |
| + for _, phase := range []string{"stale-row", "row-absent"} { |
| + if phase == "row-absent" { |
| + if err := reg.Delete(rec.Host); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + refresh() |
| + for _, host := range []string{"alias.example.net", "regional.example.net", "child.wild.example.net"} { |
| + t.Run(phase+"/"+host, func(t *testing.T) { |
| + // Keep the assertion on this subtest so the regional case also runs when the alias fails. |
| + before := deliveries.Load() |
| + rw := httptest.NewRecorder() |
| + e.ServeHTTP(rw, httptest.NewRequest("POST", "https://"+host+"/", strings.NewReader("once"))) |
| + if rw.Code != 200 || rw.Body.String() != "forwarded" || deliveries.Load() != before+1 { |
| + t.Fatalf("got %d %q deliveries=%d, want one forward", rw.Code, rw.Body.String(), deliveries.Load()-before) |
| + } |
| + }) |
| + } |
| + request("foreign.example.net", 503) |
| + request("regional-cross.example.net", 503) |
| + for _, host := range []string{"cross-account.example.net", "cross-app.example.net", "pending.example.net", "attacker.invalid", "deep.child.wild.example.net"} { |
| + request(host, 404) |
| + } |
| + } |
| + if err := reg.UpsertAlias(registry.RouteAlias{Alias: "spoof.example.net", Host: rec.Host, Account: "bab", App: rec.App}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := e.Reload(); err != nil { |
| + t.Fatal(err) |
| + } |
| + request("spoof.example.net", 404) |
| + if rows, err := reg.List(); err != nil || len(rows) != 0 { |
| + t.Fatalf("projection minted local routes: %+v %v", rows, err) |
| + } |
| + exact := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { io.WriteString(w, "exact") })) |
| + defer exact.Close() |
| + for _, name := range []string{"child.wild.example.net", "*.example.net"} { |
| + if err := reg.Upsert(registry.Route{Host: name, Account: rec.Account, App: rec.App, Pool: "other", Addr: strings.TrimPrefix(exact.URL, "http://"), Status: "ready"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := e.Reload(); err != nil { |
| + t.Fatal(err) |
| + } |
| + if name == "*.example.net" { |
| + request("alias.example.net", 200) |
| + } else { |
| + before, reads := deliveries.Load(), len(fx.Requests()) |
| + rw := httptest.NewRecorder() |
| + e.ServeHTTP(rw, httptest.NewRequest("GET", "https://"+name+"/", nil)) |
| + if rw.Code != 200 || rw.Body.String() != "exact" || deliveries.Load() != before || len(fx.Requests()) != reads { |
| + t.Fatalf("exact route lost to projected catch-all: %d %q", rw.Code, rw.Body.String()) |
| + } |
| + } |
| + if err := reg.Delete(name); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := e.Reload(); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + current := boxHAIngress.routes.Load() |
| + boxHAIngress.publish(nil, errors.New("record refresh failed")) |
| + refresh() |
| + request("alias.example.net", 503) |
| + request("child.wild.example.net", 503) |
| + boxHAIngress.routes.Store(current) |
| + refresh() |
| + w.live.setFailList(domains.ClaimsPrefix) |
| + if err := aliasPassReporting(t.Context(), w.live, reg, nil, newAssetAuthority(nil), ""); err == nil { |
| + t.Fatal("failed claim listing was accepted") |
| + } |
| + request("alias.example.net", 503) |
| + request("child.wild.example.net", 503) |
| + request("regional.example.net", 503) |
| + request("attacker.invalid", 404) |
| + w.live.setFailList("") |
| + refresh() |
| + request("alias.example.net", 200) |
| + for _, host := range []string{"alias.example.net", "wild.example.net"} { |
| + if err := w.live.Delete(t.Context(), domains.ClaimKey(host)); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + refresh() |
| + request("alias.example.net", 404) |
| + request("child.wild.example.net", 404) |
| + for _, req := range fx.Requests() { |
| + if strings.HasPrefix(req, "PUT ") { |
| + t.Fatalf("ingress acquired: %s", req) |
| + } |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestHAIngressAliasBinding(t *testing.T) { |
| + base := registry.Route{Host: "primary.example.com", Account: "bab", App: "shop", Pool: "ha", Region: "ie", HA: true, Incarnation: 7, ServingSeq: 3} |
| + for _, change := range []struct { |
| + name string |
| + apply func(*registry.Route) |
| + }{ |
| + {"account", func(r *registry.Route) { r.Account = "bac" }}, |
| + {"app", func(r *registry.Route) { r.App = "other" }}, |
| + {"target", func(r *registry.Route) { r.Host = "other.example.com" }}, |
| + {"region", func(r *registry.Route) { r.Region = "us" }}, |
| + {"pool", func(r *registry.Route) { r.Pool = "other" }}, |
| + {"incarnation", func(r *registry.Route) { r.Incarnation++ }}, |
| + {"serving sequence", func(r *registry.Route) { r.ServingSeq++ }}, |
| + {"HA", func(r *registry.Route) { r.HA = false }}, |
| + } { |
| + t.Run(change.name, func(t *testing.T) { |
| + var p haIngressProjection |
| + p.publish(map[string]registry.Route{base.Host: base}, nil) |
| + p.publishAliases(map[string]registry.Route{"alias.example.com": base}, true) |
| + if rt, ok := p.lookup("alias.example.com"); !ok || rt.Host != base.Host { |
| + t.Fatalf("accepted alias lost: %+v %v", rt, ok) |
| + } |
| + next := base |
| + change.apply(&next) |
| + p.publish(map[string]registry.Route{base.Host: next}, nil) |
| + if rt, ok := p.lookup("alias.example.com"); !ok || rt.HA { |
| + t.Fatalf("old alias authorized changed target: %+v %v", rt, ok) |
| + } |
| + }) |
| + } |
| +} |