| new file mode 100644 |
| index 000000000..0293cdd00 |
| --- /dev/null |
| +++ b/internal/edge/demo_api_test.go |
| @@ -0,0 +1,733 @@ |
| +package edge |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "io" |
| + "net" |
| + "net/http" |
| + "net/http/httptest" |
| + "net/http/httptrace" |
| + "net/textproto" |
| + "os" |
| + "path/filepath" |
| + "reflect" |
| + "strings" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/assetcache" |
| + "github.com/carlosframework/platform/internal/edgeproof" |
| + "github.com/carlosframework/platform/internal/ratelimit" |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +const demoAPISite = "example.com" |
| +const demoAPIConsole = "console.example.com" |
| + |
| +func demoAPISettings(t *testing.T) { |
| + t.Helper() |
| + t.Setenv("CARLOS_DEMO_API_ORIGIN", "https://"+demoAPISite) |
| + t.Setenv("CARLOS_DEMO_API_CONSOLE_ORIGIN", "https://"+demoAPIConsole) |
| +} |
| + |
| +func demoAPIArm(t *testing.T, e *Edge) []byte { |
| + t.Helper() |
| + s := meshTestStore(t) |
| + if err := mintMeshKey(context.Background(), s); err != nil { |
| + t.Fatal(err) |
| + } |
| + m := newHomeMap(s, "local") |
| + refreshHomeMap(t, m) |
| + e.homes.Store(m) |
| + key, _ := m.meshKeys() |
| + return key |
| +} |
| + |
| +func demoAPIBackend(t *testing.T, e *Edge, handler http.Handler) registry.Route { |
| + t.Helper() |
| + srv := httptest.NewServer(handler) |
| + t.Cleanup(srv.Close) |
| + rt := registry.Route{Host: demoAPIConsole, Kind: "instance", App: "console", Unit: "console.service", Addr: srv.Listener.Addr().String(), Status: "ready", Version: "v1"} |
| + if err := e.reg.Upsert(rt); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := e.Reload(); err != nil { |
| + t.Fatal(err) |
| + } |
| + return rt |
| +} |
| + |
| +func demoAPIRequest(e *Edge, host, method, target string, h http.Header) *httptest.ResponseRecorder { |
| + r := httptest.NewRequest(method, "https://"+host+target, nil) |
| + r.RemoteAddr = "192.0.2.1:40000" |
| + if h != nil { |
| + r.Header = h.Clone() |
| + } |
| + w := httptest.NewRecorder() |
| + e.ServeHTTP(w, r) |
| + return w |
| +} |
| + |
| +func demoAPINoStore(t *testing.T, h http.Header) { |
| + t.Helper() |
| + for k, want := range map[string]string{"Cache-Control": "no-store, private", "CDN-Cache-Control": "no-store", "Surrogate-Control": "no-store"} { |
| + if h.Get(k) != want { |
| + t.Errorf("%s = %q, want %q", k, h.Get(k), want) |
| + } |
| + } |
| + for _, k := range []string{"Set-Cookie", "Etag", "Last-Modified", "Expires", "Age"} { |
| + if len(h.Values(k)) != 0 { |
| + t.Errorf("response retained %s", k) |
| + } |
| + } |
| +} |
| + |
| +func TestDemoAPIAliasBoundary(t *testing.T) { |
| + t.Run("configuration", func(t *testing.T) { |
| + for _, c := range []struct { |
| + site, console string |
| + valid bool |
| + }{ |
| + {"", "", true}, {"https://example.com", "https://console.example.com", true}, |
| + {"https://example.com", "", false}, {"", "https://console.example.com", false}, |
| + {"https://example.com", "https://example.com", false}, |
| + } { |
| + t.Setenv("CARLOS_DEMO_API_ORIGIN", c.site) |
| + t.Setenv("CARLOS_DEMO_API_CONSOLE_ORIGIN", c.console) |
| + e, err := New(openReg(t), nil) |
| + if e != nil { |
| + e.probers.Stop() |
| + } |
| + if (err == nil) != c.valid { |
| + t.Errorf("config accepted=%v, want %v", err == nil, c.valid) |
| + } |
| + } |
| + for _, bad := range []string{"http://example.com", "https://Example.com", "https://example.com:443", "https://example.com/", "https://example.com?", "https://example.com#", "https://user@example.com", "https://127.0.0.1", "https://[::1]", "https://*.example.com", "https://example.com."} { |
| + for _, name := range []string{"CARLOS_DEMO_API_ORIGIN", "CARLOS_DEMO_API_CONSOLE_ORIGIN"} { |
| + demoAPISettings(t) |
| + t.Setenv(name, bad) |
| + e, err := New(openReg(t), nil) |
| + if e != nil { |
| + e.probers.Stop() |
| + } |
| + if err == nil { |
| + t.Errorf("accepted invalid %s", name) |
| + } |
| + } |
| + } |
| + }) |
| + t.Run("disabled", func(t *testing.T) { |
| + t.Setenv("CARLOS_DEMO_API_ORIGIN", "") |
| + t.Setenv("CARLOS_DEMO_API_CONSOLE_ORIGIN", "") |
| + e, err := New(openReg(t), nil) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(e.probers.Stop) |
| + demoAPIBackend(t, e, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + w.Header().Set("Set-Cookie", "ordinary=1") |
| + io.WriteString(w, "ordinary") |
| + })) |
| + w := demoAPIRequest(e, demoAPIConsole, "POST", "/api/demo/apps", nil) |
| + if w.Body.String() != "ordinary" || w.Header().Get("Set-Cookie") == "" { |
| + t.Fatal("disabled configuration changed console behavior") |
| + } |
| + }) |
| + t.Run("paths and hosts", func(t *testing.T) { |
| + demoAPISettings(t) |
| + e, promote := markdownEdge(t) |
| + t.Cleanup(e.probers.Stop) |
| + if e.staticLock != nil { |
| + t.Cleanup(func() { e.staticLock.Close() }) |
| + } |
| + promote(t, "v1", map[string]string{"index.html": "page"}) |
| + key := demoAPIArm(t, e) |
| + var calls atomic.Int32 |
| + demoAPIBackend(t, e, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + calls.Add(1) |
| + if r.Host != demoAPIConsole { |
| + t.Error("client selected target Host") |
| + } |
| + w.WriteHeader(202) |
| + })) |
| + for _, c := range []struct { |
| + method, path string |
| + status int |
| + }{ |
| + {"POST", "/api/demo/apps", 202}, {"GET", "/api/demo/jobs/a-Z_09", 202}, |
| + {"GET", "/api/demo", 404}, {"GET", "/api/demo/", 404}, {"GET", "/api/demo/apps", 404}, {"PUT", "/api/demo/apps", 404}, |
| + {"HEAD", "/api/demo/jobs/a", 404}, {"OPTIONS", "/api/demo/apps", 404}, {"DELETE", "/api/demo/jobs/a", 404}, {"POST", "/api/demo/jobs/a", 404}, |
| + {"GET", "/api/demo/jobs/", 404}, {"GET", "/api/demo/jobs/a/b", 404}, {"GET", "/api/demo/jobs/a.b", 404}, {"GET", "/api/demo/jobs/a/", 404}, |
| + {"POST", "/api/demo/claims", 404}, {"POST", "/api/demo/claims/verify", 404}, {"POST", "/api/demo/claims/select", 404}, {"GET", "/api/demo/claims/status", 404}, {"POST", "/api/demo/reports", 404}, |
| + {"POST", "/api/demo/apps?", 404}, {"POST", "/api/demo/apps?a=b", 404}, |
| + {"POST", "/api/%64emo/apps", 404}, {"POST", "/api/demo%2fapps", 404}, {"POST", "/api/demo/%2e%2e/demo/apps", 404}, |
| + {"POST", "/x/../api/demo/apps", 404}, {"POST", "//api//demo/apps", 404}, {"POST", "/api/demo/../apps", 404}, {"POST", "/api/demo/apps/", 404}, {"GET", "/api/demo/jobs/a%5cb", 404}, {"GET", "/api/demo/jobs/a%2fb", 404}, |
| + } { |
| + before := calls.Load() |
| + w := demoAPIRequest(e, demoAPISite, c.method, c.path, nil) |
| + if w.Code != c.status { |
| + t.Errorf("%s %s = %d, want %d", c.method, c.path, w.Code, c.status) |
| + } |
| + demoAPINoStore(t, w.Result().Header) |
| + if c.status == 404 && (w.Body.Len() != 0 || calls.Load() != before) { |
| + t.Errorf("refused path dispatched or got body: %s", c.path) |
| + } |
| + } |
| + for _, target := range []string{"/demo/report", "/demo/claim", "/demo/claim/intent", "/demo/claim/prove", "/demo/claim/select", "/api/box/demo/build", "/api/box/demo/claim", "/api/box/demo/retirement", "/api/accounts", "/api/operator", "/api/demolition"} { |
| + for _, method := range []string{"GET", "POST"} { |
| + before := calls.Load() |
| + demoAPIRequest(e, demoAPISite, method, target, nil) |
| + if calls.Load() != before { |
| + t.Errorf("excluded path dispatched: %s", target) |
| + } |
| + } |
| + } |
| + for _, h := range []http.Header{{"Connection": {"upgrade"}, "Upgrade": {"websocket"}}, {"Upgrade": {"websocket"}}} { |
| + w := demoAPIRequest(e, demoAPISite, "POST", "/api/demo/apps", h) |
| + if w.Code != 404 { |
| + t.Errorf("upgrade = %d", w.Code) |
| + } |
| + demoAPINoStore(t, w.Header()) |
| + } |
| + for _, host := range []string{"other.example.com", "www.example.com", "example.com.attacker.com", "EXAMPLE.COM"} { |
| + before := calls.Load() |
| + demoAPIRequest(e, host, "POST", "/api/demo/apps", http.Header{"Host": {demoAPIConsole}, "X-Forwarded-Host": {demoAPIConsole}}) |
| + if calls.Load() != before { |
| + t.Errorf("unconfigured host reached console: %s", host) |
| + } |
| + } |
| + // An unrelated tenant keeps its own namespace, even with the same paths. |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { io.WriteString(w, "tenant") })) |
| + t.Cleanup(srv.Close) |
| + if err := e.reg.Upsert(registry.Route{Host: "shop.example.com", Kind: "instance", App: "shop", Addr: srv.Listener.Addr().String(), Status: "ready"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := e.Reload(); err != nil { |
| + t.Fatal(err) |
| + } |
| + if w := demoAPIRequest(e, "shop.example.com", "POST", "/api/demo/apps", nil); w.Body.String() != "tenant" { |
| + t.Fatal("tenant namespace intercepted") |
| + } |
| + // Platform-attached sites enter before alias or placement dispatch. |
| + upsertAlias(t, e.reg, "attached.example.com", demoAPISite) |
| + if err := e.Reload(); err != nil { |
| + t.Fatal(err) |
| + } |
| + before := calls.Load() |
| + demoAPIRequest(e, "attached.example.com", "POST", "/api/demo/apps", nil) |
| + if calls.Load() != before { |
| + t.Fatal("ordinary alias gained API authority") |
| + } |
| + t.Setenv("CARLOS_DEMO_API_ORIGIN", "https://attached.example.com") |
| + attached, err := New(e.reg, nil) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(attached.probers.Stop) |
| + demoAPIArm(t, attached) |
| + if w := demoAPIRequest(attached, "attached.example.com", "POST", "/api/demo/apps", nil); w.Code != 202 { |
| + t.Fatal("configured attached source did not dispatch") |
| + } |
| + before = calls.Load() |
| + r := httptest.NewRequest("POST", "https://example.com/api/demo/apps", nil) |
| + r = r.WithContext(context.WithValue(r.Context(), doorCallerKey{}, doorCaller{Account: "shop", App: "shop"})) |
| + w := httptest.NewRecorder() |
| + e.ServeHTTP(w, r) |
| + if w.Code != 503 || calls.Load() != before { |
| + t.Fatal("door request admitted") |
| + } |
| + for _, h := range []http.Header{ |
| + {hopHeader: {""}}, {hopAuthHeader: {"invalid"}}, |
| + {hopHeader: {"1", "1"}, hopAuthHeader: {signHop(key, demoAPISite, time.Now())}}, |
| + {hopHeader: {"1"}, hopAuthHeader: {signHop(key, demoAPISite, time.Now()), "invalid"}}, |
| + } { |
| + w := demoAPIRequest(e, demoAPISite, "POST", "/api/demo/apps", h) |
| + if w.Code != 503 { |
| + t.Errorf("malformed hop = %d, want 503", w.Code) |
| + } |
| + } |
| + for _, host := range []string{demoAPISite, demoAPIConsole} { |
| + w := demoAPIRequest(e, host, "POST", "/api/demo/apps", http.Header{hopHeader: {"1"}, hopAuthHeader: {"invalid"}}) |
| + if w.Code != 503 { |
| + t.Errorf("invalid hop = %d", w.Code) |
| + } |
| + demoAPINoStore(t, w.Header()) |
| + w = demoAPIRequest(e, host, "POST", "/api/demo/apps", http.Header{hopHeader: {"1"}, hopAuthHeader: {signHop(key, host, time.Now())}, "X-Forwarded-For": {"192.0.2.1"}}) |
| + if w.Code != 202 { |
| + t.Errorf("verified hop = %d", w.Code) |
| + } |
| + } |
| + }) |
| + t.Run("local transports", func(t *testing.T) { |
| + demoAPISettings(t) |
| + for _, socket := range []bool{true, false} { |
| + e, err := New(openReg(t), nil) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(e.probers.Stop) |
| + demoAPIArm(t, e) |
| + rt := registry.Route{Host: demoAPIConsole, Kind: "instance", App: "console", Unit: "console.service", Status: "ready", Version: "v2"} |
| + if socket { |
| + dir, err := os.MkdirTemp(os.Getenv("TMPDIR"), "api-") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { os.RemoveAll(dir) }) |
| + rt.Socket = filepath.Join(dir, "api.sock") |
| + ln, err := net.Listen("unix", rt.Socket) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + srv := &httptest.Server{Listener: ln, Config: &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { io.WriteString(w, "socket") })}} |
| + srv.Start() |
| + t.Cleanup(srv.Close) |
| + } else { |
| + a, _ := countingBackend(t, "probed") |
| + b, _ := countingBackend(t, "probed") |
| + rt.Addrs = a + "," + b |
| + rt.Health = healthJSON(t, frozenHealth()) |
| + } |
| + if err := e.reg.Upsert(rt); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := e.Reload(); err != nil { |
| + t.Fatal(err) |
| + } |
| + w := demoAPIRequest(e, demoAPISite, "POST", "/api/demo/apps", nil) |
| + if w.Code != 200 || w.Header().Get("X-Carlos-Version") != "v2" { |
| + t.Errorf("socket=%v: %d", socket, w.Code) |
| + } |
| + } |
| + }) |
| + t.Run("exact home and one hop containment", func(t *testing.T) { |
| + demoAPISettings(t) |
| + e, err := New(openReg(t), nil) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(e.probers.Stop) |
| + store := meshTestStore(t) |
| + if err := mintMeshKey(t.Context(), store); err != nil { |
| + t.Fatal(err) |
| + } |
| + m := newHomeMap(store, "local") |
| + refreshHomeMap(t, m) |
| + e.homes.Store(m) |
| + key, _ := m.meshKeys() |
| + var dials atomic.Int32 |
| + tr := &http.Transport{DialContext: func(context.Context, string, string) (net.Conn, error) { |
| + dials.Add(1) |
| + return nil, errors.New("unavailable") |
| + }} |
| + t.Cleanup(tr.CloseIdleConnections) |
| + e.backhaulTransports.Store("127.0.0.1", tr) |
| + for _, hosts := range []string{`{"*.example.com":{"role":"home"}}`, `{"console.example.com":{"role":"home"}}`} { |
| + putJSON(t, store, "control/edges/remote.json", `{"v":1,"box":"remote","eip":"127.0.0.1","hosts":`+hosts+`}`) |
| + refreshHomeMap(t, m) |
| + before := dials.Load() |
| + w := demoAPIRequest(e, demoAPISite, "POST", "/api/demo/apps", nil) |
| + if w.Code != 503 || w.Body.Len() != 0 || w.Header().Get("Retry-After") != "2" { |
| + t.Fatal("home failure response changed") |
| + } |
| + demoAPINoStore(t, w.Header()) |
| + want := before |
| + if strings.Contains(hosts, "console.example.com") { |
| + want++ |
| + } |
| + if dials.Load() != want { |
| + t.Fatal("exact home not respected") |
| + } |
| + } |
| + before := dials.Load() |
| + w := demoAPIRequest(e, demoAPISite, "POST", "/api/demo/apps", http.Header{hopHeader: {"1"}, hopAuthHeader: {signHop(key, demoAPISite, time.Now())}, "X-Forwarded-For": {"192.0.2.1"}}) |
| + if w.Code != 503 || dials.Load() != before { |
| + t.Fatal("second hop attempted") |
| + } |
| + old := backhaulMaxInflight.Load() |
| + backhaulMaxInflight.Store(0) |
| + t.Cleanup(func() { backhaulMaxInflight.Store(old) }) |
| + w = demoAPIRequest(e, demoAPISite, "POST", "/api/demo/apps", nil) |
| + if w.Code != 503 || w.Body.String() != "temporarily busy\n" || dials.Load() != before { |
| + t.Fatal("hop admission response overwritten") |
| + } |
| + demoAPINoStore(t, w.Header()) |
| + backhaulMaxInflight.Store(old) |
| + putJSON(t, store, "control/edges/conflict.json", `{"v":1,"box":"conflict","eip":"127.0.0.2","hosts":{"console.example.com":{"role":"home"}}}`) |
| + refreshHomeMap(t, m) |
| + w = demoAPIRequest(e, demoAPISite, "POST", "/api/demo/apps", nil) |
| + if w.Code != 503 || dials.Load() != before { |
| + t.Fatal("held home admitted") |
| + } |
| + }) |
| + t.Run("destination authority and reload", func(t *testing.T) { |
| + demoAPISettings(t) |
| + e, err := New(openReg(t), nil) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(e.probers.Stop) |
| + demoAPIArm(t, e) |
| + var calls atomic.Int32 |
| + rt := demoAPIBackend(t, e, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { calls.Add(1); io.WriteString(w, "first") })) |
| + for name, change := range map[string]func(*registry.Route){ |
| + "account": func(r *registry.Route) { r.Account = "shop" }, "app": func(r *registry.Route) { r.App = "shop" }, "unit": func(r *registry.Route) { r.Unit = "shop.service" }, |
| + "tunnel": func(r *registry.Route) { r.Tunnel = "shop" }, "not ready": func(r *registry.Route) { r.Status = "creating" }, |
| + "activator": func(r *registry.Route) { r.Hibernate = true }, "remote": func(r *registry.Route) { r.Addr = "192.0.2.8:80" }, |
| + } { |
| + t.Run(name, func(t *testing.T) { |
| + bad := rt |
| + change(&bad) |
| + if err := e.reg.Delete(demoAPIConsole); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := e.reg.Upsert(bad); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := e.Reload(); err != nil { |
| + t.Fatal(err) |
| + } |
| + before := calls.Load() |
| + w := demoAPIRequest(e, demoAPISite, "POST", "/api/demo/apps", nil) |
| + if w.Code != 503 || w.Body.Len() != 0 || calls.Load() != before { |
| + t.Errorf("ineligible target: %d", w.Code) |
| + } |
| + demoAPINoStore(t, w.Header()) |
| + }) |
| + } |
| + if err := e.reg.Delete(demoAPIConsole); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := e.reg.PutForward(registry.Route{Host: demoAPIConsole, Kind: registry.KindForward, App: "console", Region: "fleet/shop"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := e.Reload(); err != nil { |
| + t.Fatal(err) |
| + } |
| + if w := demoAPIRequest(e, demoAPISite, "POST", "/api/demo/apps", nil); w.Code != 503 { |
| + t.Fatal("forward target accepted") |
| + } |
| + if _, err := e.reg.DeleteForward(demoAPIConsole); err != nil { |
| + t.Fatal(err) |
| + } |
| + other := rt |
| + other.Host = "other-console.example.com" |
| + if err := e.reg.Upsert(other); err != nil { |
| + t.Fatal(err) |
| + } |
| + upsertAlias(t, e.reg, demoAPIConsole, other.Host) |
| + if err := e.Reload(); err != nil { |
| + t.Fatal(err) |
| + } |
| + if w := demoAPIRequest(e, demoAPISite, "POST", "/api/demo/apps", nil); w.Code != 503 { |
| + t.Fatal("console alias accepted") |
| + } |
| + if err := e.reg.DeleteAlias(demoAPIConsole); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := e.Reload(); err != nil { |
| + t.Fatal(err) |
| + } |
| + if w := demoAPIRequest(e, demoAPISite, "POST", "/api/demo/apps", nil); w.Code != 503 { |
| + t.Fatal("missing target accepted") |
| + } |
| + demoAPIBackend(t, e, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { io.WriteString(w, "second") })) |
| + if w := demoAPIRequest(e, demoAPISite, "POST", "/api/demo/apps", nil); w.Body.String() != "second" { |
| + t.Fatal("reload did not select replacement") |
| + } |
| + e.homes.Store(nil) |
| + if w := demoAPIRequest(e, demoAPISite, "POST", "/api/demo/apps", nil); w.Code != 503 { |
| + t.Fatal("unsigned local request admitted") |
| + } |
| + }) |
| +} |
| + |
| +func TestDemoAPIAliasIsolation(t *testing.T) { |
| + t.Run("static cache gzip burst and usage", func(t *testing.T) { |
| + demoAPISettings(t) |
| + e, promote := markdownEdge(t) |
| + t.Cleanup(e.probers.Stop) |
| + if e.staticLock != nil { |
| + t.Cleanup(func() { e.staticLock.Close() }) |
| + } |
| + demoAPIArm(t, e) |
| + promote(t, "v1", map[string]string{"start/index.html": "page", "start/index.md": "# page", "api/demo/apps/index.html": "static API", "_headers": "/*\n Cache-Control: public, max-age=300\n"}) |
| + if w := demoAPIRequest(e, demoAPISite, "GET", "/start/", http.Header{"Accept": {"text/markdown"}}); w.Body.String() != "# page" { |
| + t.Fatal("ordinary Markdown page changed") |
| + } |
| + if w := demoAPIRequest(e, demoAPISite, "GET", "/start", nil); w.Code != 301 && w.Code != 308 { |
| + t.Fatal("ordinary slash redirect changed") |
| + } |
| + if _, err := parseHeaders([]byte("/*\n Set-Cookie: site=1\n")); err == nil { |
| + t.Fatal("static cookie rules unexpectedly supported") |
| + } |
| + assets := openLAStore(t) |
| + local := &fakeLocalAssets{hosts: map[string]HostAssets{}, builds: map[string]bool{"v1": true}} |
| + site, ok := e.current()[demoAPISite] |
| + if !ok { |
| + t.Fatal("site route missing") |
| + } |
| + site.route.AssetGen = "g1" |
| + if err := e.reg.Upsert(site.route); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := e.Reload(); err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, host := range []string{demoAPISite, demoAPIConsole} { |
| + a := HostAssets{Account: release.RouteAccount(site.route), App: "shop", Gen: "g1", Paths: []string{"/api/demo/"}, Primary: demoAPISite, At: time.Now()} |
| + local.set(host, a) |
| + k := assetcache.Key{Account: a.Account, App: a.App, Gen: a.Gen, Host: host, Path: "/api/demo/jobs/a"} |
| + fill, err := assets.Reserve(k, 6) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := fill.Write([]byte("cached")); err != nil { |
| + fill.Abort() |
| + t.Fatal(err) |
| + } |
| + if err := fill.Commit(assetcache.Meta{Key: k, Header: http.Header{"Content-Type": {"text/plain"}}, Lifetime: time.Hour, StoredAt: time.Now(), Expires: time.Now().Add(time.Hour)}, false); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, ok := assets.Get(k); !ok { |
| + t.Fatal("asset cache seed missing") |
| + } |
| + } |
| + e.assets.Store(&assetState{store: assets, local: local, now: time.Now}) |
| + meter := NewUsageMeter() |
| + e.EnableUsage(meter) |
| + e.burst.apply(burstScanner, time.Now().Add(time.Hour)) |
| + var calls atomic.Int32 |
| + body := strings.Repeat("response", 200) |
| + demoAPIBackend(t, e, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + calls.Add(1) |
| + w.Header().Set("Cache-Control", "public, max-age=300") |
| + w.Header().Set("Set-Cookie", "console=1") |
| + w.Header().Set("Content-Type", "text/plain") |
| + io.WriteString(w, body) |
| + })) |
| + for _, host := range []string{demoAPISite, demoAPIConsole} { |
| + e.cache.Put(CacheKey{Host: host, Method: "GET", Path: "/api/demo/jobs/a"}, "", &CachedResponse{StatusCode: 200, Header: http.Header{"Cache-Control": {"public"}}, Body: []byte("cached"), StoredAt: time.Now(), TTL: time.Hour}) |
| + for i := 0; i < 2; i++ { |
| + w := demoAPIRequest(e, host, "GET", "/api/demo/jobs/a", http.Header{"Accept": {"text/markdown"}, "Accept-Encoding": {"gzip"}}) |
| + if w.Code != 200 || w.Body.String() != body || w.Header().Get("Content-Encoding") != "" { |
| + t.Errorf("API intercepted: %d", w.Code) |
| + } |
| + demoAPINoStore(t, w.Result().Header) |
| + } |
| + } |
| + if calls.Load() != 4 { |
| + t.Errorf("calls=%d, want 4", calls.Load()) |
| + } |
| + if f := meter.Drain(); len(f.Rows) != 0 || len(f.Guard) != 0 { |
| + t.Fatal("API debited tenant usage") |
| + } |
| + }) |
| + t.Run("empty authorization and local failure", func(t *testing.T) { |
| + demoAPISettings(t) |
| + e, err := newEdge(openReg(t), nil, localHold{}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(e.probers.Stop) |
| + demoAPIArm(t, e) |
| + var wanted []string |
| + rt := demoAPIBackend(t, e, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + if !reflect.DeepEqual(r.Header.Values("Authorization"), wanted) { |
| + t.Error("authorization presence or values changed") |
| + } |
| + if r.Host != demoAPIConsole { |
| + t.Error("forged Host reached target") |
| + } |
| + io.Copy(io.Discard, r.Body) |
| + if len(r.Trailer) != 0 { |
| + t.Error("request trailers reached target") |
| + } |
| + w.WriteHeader(202) |
| + })) |
| + for _, values := range [][]string{nil, {""}, {"Bearer example"}, {"", "Bearer example"}} { |
| + wanted = values |
| + r := httptest.NewRequest("POST", "https://example.com/api/demo/apps", strings.NewReader("body")) |
| + if values != nil { |
| + r.Header["Authorization"] = values |
| + } |
| + r.Header.Set("X-Forwarded-Host", "other.example.com") |
| + r.Trailer = http.Header{"X-Test-Trailer": {"not forwarded"}} |
| + w := httptest.NewRecorder() |
| + e.ServeHTTP(w, r) |
| + if w.Code != 202 { |
| + t.Errorf("request = %d", w.Code) |
| + } |
| + } |
| + // Nothing listens on this fixture's closed loopback listener. |
| + ln, err := net.Listen("tcp", "127.0.0.1:0") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + rt.Addr = ln.Addr().String() |
| + ln.Close() |
| + if err := e.reg.Upsert(rt); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := e.Reload(); err != nil { |
| + t.Fatal(err) |
| + } |
| + w := demoAPIRequest(e, demoAPISite, "POST", "/api/demo/apps", nil) |
| + if w.Code != 503 || w.Body.Len() != 0 || w.Header().Get("Retry-After") != "2" { |
| + t.Fatal("local transport error response changed") |
| + } |
| + demoAPINoStore(t, w.Header()) |
| + }) |
| + t.Run("request headers and response informational trailers", func(t *testing.T) { |
| + demoAPISettings(t) |
| + e, err := New(openReg(t), nil) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(e.probers.Stop) |
| + key := demoAPIArm(t, e) |
| + auth := []string{"", "Bearer example"} |
| + demoAPIBackend(t, e, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + if !reflect.DeepEqual(r.Header.Values("Authorization"), auth) { |
| + t.Error("Authorization values changed") |
| + } |
| + for k, values := range map[string][]string{"X-Carlos-Client": {"first", "second"}, "Content-Type": {"application/octet-stream"}, "Content-Encoding": {"identity"}, "Accept": {"application/json", "text/plain"}, "User-Agent": {"example"}} { |
| + if !reflect.DeepEqual(r.Header.Values(k), values) { |
| + t.Errorf("preserved field changed: %s", k) |
| + } |
| + } |
| + if r.Header.Get("Origin") != "https://other.example.com" || r.Header.Get("Accept-Encoding") != "identity" { |
| + t.Error("origin or encoding changed") |
| + } |
| + for _, k := range []string{"Cookie", "Forwarded", "If-None-Match", "Range", "X-Target-Host", "Idempotency-Key"} { |
| + if len(r.Header.Values(k)) != 0 { |
| + t.Errorf("request retained %s", k) |
| + } |
| + } |
| + if len(r.Trailer) != 0 { |
| + t.Error("request trailers retained") |
| + } |
| + if !edgeproof.Verify(key, nil, r.Host, r.Header.Get("X-Forwarded-For"), r.Header.Get(edgeproof.Header), time.Now()) { |
| + t.Error("missing forwarding proof") |
| + } |
| + w.Header().Set("Set-Cookie", "early=1") |
| + w.Header().Set("Cache-Control", "public") |
| + w.WriteHeader(103) |
| + w.Header().Set("Trailer", "Set-Cookie, Cache-Control, X-Result") |
| + w.Header().Set("Set-Cookie", "final=1") |
| + w.Header().Set("Etag", "validator") |
| + w.Header().Set("Age", "10") |
| + w.Header().Set("Retry-After", "7") |
| + w.Header().Set("Location", "https://other.example.com/") |
| + w.WriteHeader(202) |
| + io.WriteString(w, "answer") |
| + w.Header().Set("Set-Cookie", "trailer=1") |
| + w.Header().Set("Cache-Control", "public") |
| + w.Header().Set("X-Result", "done") |
| + w.Header().Set(http.TrailerPrefix+"Set-Cookie", "late=1") |
| + w.Header().Set(http.TrailerPrefix+"Surrogate-Control", "public") |
| + })) |
| + srv := httptest.NewServer(e) |
| + t.Cleanup(srv.Close) |
| + req, err := http.NewRequest("POST", srv.URL+"/api/demo/apps", strings.NewReader("body")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + req.Host = demoAPISite |
| + req.Header = http.Header{"Authorization": auth, "Origin": {"https://other.example.com"}, "Accept-Encoding": {"gzip"}, "Cookie": {"site=1"}, "Forwarded": {"for=spoof"}, "If-None-Match": {"*"}, "Range": {"bytes=0-1"}, "X-Target-Host": {"other.example.com"}, "Idempotency-Key": {"example"}} |
| + for k, values := range map[string][]string{"X-Carlos-Client": {"first", "second"}, "Content-Type": {"application/octet-stream"}, "Content-Encoding": {"identity"}, "Accept": {"application/json", "text/plain"}, "User-Agent": {"example"}} { |
| + req.Header[k] = values |
| + } |
| + var informational atomic.Int32 |
| + req = req.WithContext(httptrace.WithClientTrace(req.Context(), &httptrace.ClientTrace{Got1xxResponse: func(code int, h textproto.MIMEHeader) error { |
| + if code == 103 { |
| + informational.Add(1) |
| + demoAPINoStore(t, http.Header(h)) |
| + } |
| + return nil |
| + }})) |
| + resp, err := srv.Client().Do(req) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer resp.Body.Close() |
| + b, err := io.ReadAll(resp.Body) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if resp.StatusCode != 202 || string(b) != "answer" || informational.Load() != 1 { |
| + t.Fatal("response status, bytes or 103 changed") |
| + } |
| + demoAPINoStore(t, resp.Header) |
| + if resp.Header.Get("Retry-After") != "7" || resp.Header.Get("Location") != "https://other.example.com/" || resp.Header.Get("X-Carlos-Version") != "v1" { |
| + t.Fatal("end-to-end headers changed") |
| + } |
| + for _, k := range []string{"Set-Cookie", "Cache-Control", "Surrogate-Control"} { |
| + if len(resp.Trailer.Values(k)) != 0 { |
| + t.Errorf("retained trailer %s", k) |
| + } |
| + } |
| + if resp.Trailer.Get("X-Result") != "done" { |
| + t.Fatal("ordinary trailer lost") |
| + } |
| + }) |
| + t.Run("console rate admission across hosts and hops", func(t *testing.T) { |
| + demoAPISettings(t) |
| + t.Setenv("CARLOS_RATE_LIMIT", "enforce") |
| + e, err := New(openReg(t), nil) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(e.probers.Stop) |
| + key := demoAPIArm(t, e) |
| + var calls atomic.Int32 |
| + rt := demoAPIBackend(t, e, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + calls.Add(1) |
| + if e.rateLimiter.InFlight(demoAPIConsole) != 1 { |
| + t.Error("no console slot during handler") |
| + } |
| + w.WriteHeader(202) |
| + })) |
| + rt.RateLimit = `{"rate":1,"burst":1}` |
| + if err := e.reg.Upsert(rt); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := e.Reload(); err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, firstHost := range []string{demoAPISite, demoAPIConsole} { |
| + for _, firstHop := range []bool{false, true} { |
| + e.rateLimiter = ratelimit.NewLimiter(func() time.Time { return time.Unix(1000, 0) }, 100) |
| + before := calls.Load() |
| + for i, host := range []string{firstHost, demoAPISite, demoAPIConsole} { |
| + for _, hop := range []bool{firstHop, !firstHop} { |
| + h := http.Header{} |
| + if hop { |
| + h.Set(hopHeader, "1") |
| + h.Set(hopAuthHeader, signHop(key, host, time.Now())) |
| + h.Set("X-Forwarded-For", "192.0.2.1") |
| + } |
| + w := demoAPIRequest(e, host, "POST", "/api/demo/apps", h) |
| + want := 429 |
| + if i == 0 && hop == firstHop { |
| + want = 202 |
| + } |
| + if w.Code != want { |
| + t.Errorf("host=%s hop=%v: %d, want %d", host, hop, w.Code, want) |
| + } |
| + demoAPINoStore(t, w.Header()) |
| + if e.rateLimiter.InFlight(demoAPIConsole) != 0 { |
| + t.Fatal("slot not released") |
| + } |
| + } |
| + } |
| + if calls.Load() != before+1 { |
| + t.Fatal("refusal reached handler or admitted request replayed") |
| + } |
| + } |
| + } |
| + }) |
| +} |