| index 928385686..1cfb10fac 100644 |
| --- a/internal/console/regionoff_test.go |
| +++ b/internal/console/regionoff_test.go |
| @@ -2,15 +2,20 @@ package console |
| |
| import ( |
| "bytes" |
| + "context" |
| + "encoding/hex" |
| "encoding/json" |
| "io" |
| "net/http" |
| + "net/http/httptest" |
| "net/url" |
| "regexp" |
| "sort" |
| "strings" |
| "testing" |
| + "time" |
| |
| + "github.com/carlosframework/platform/internal/edgeproof" |
| "github.com/carlosframework/platform/internal/geo" |
| ) |
| |
| @@ -30,9 +35,45 @@ func switchOffFixture(t *testing.T) (*consoleFixture, string) { |
| return fx, cliToken(t, fx, "paul@keymail.dev", "code-region-off") |
| } |
| |
| -// rawPost sends body as JSON and returns the status, the response headers |
| -// without Date, and the body with the test server's address as ORIGIN. |
| -func rawPost(t *testing.T, fx *consoleFixture, u string, body any, bearer, xff string) (int, string, string) { |
| +var ( |
| + switchOffHome = geo.PlaceName("eu-west-1", "ie") |
| + contentLengthRE = regexp.MustCompile(`^Content-Length: \d+$`) |
| + expiresAtRE = regexp.MustCompile(`"expires_at":"[^"]*"`) |
| + expiringDetailRE = regexp.MustCompile(`expiring \d{4}-\d\d-\d\d \d\d:\d\d UTC`) |
| +) |
| + |
| +// normHeaders is the response's headers, one "Key: value" line each, |
| +// sorted, without Date, with Content-Length blanked. |
| +func normHeaders(h http.Header) string { |
| + var hs []string |
| + for k, vs := range h { |
| + if k == "Date" { |
| + continue |
| + } |
| + for _, v := range vs { |
| + line := k + ": " + v |
| + line = contentLengthRE.ReplaceAllString(line, "Content-Length: LEN") |
| + hs = append(hs, line) |
| + } |
| + } |
| + sort.Strings(hs) |
| + return strings.Join(hs, "\n") |
| +} |
| + |
| +// sendRaw sends req and returns the status, the normalized headers and the |
| +// body with the test server's address as ORIGIN. |
| +func sendRaw(t *testing.T, fx *consoleFixture, c *http.Client, req *http.Request) (int, string, string) { |
| + t.Helper() |
| + res, err := c.Do(req) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer res.Body.Close() |
| + b, _ := io.ReadAll(res.Body) |
| + return res.StatusCode, strings.ReplaceAll(normHeaders(res.Header), fx.ts.URL, "ORIGIN"), strings.ReplaceAll(string(b), fx.ts.URL, "ORIGIN") |
| +} |
| + |
| +func jsonReq(t *testing.T, u string, body any, bearer string) *http.Request { |
| t.Helper() |
| raw, _ := json.Marshal(body) |
| req, err := http.NewRequest(http.MethodPost, u, bytes.NewReader(raw)) |
| @@ -41,35 +82,50 @@ func rawPost(t *testing.T, fx *consoleFixture, u string, body any, bearer, xff s |
| } |
| req.Header.Set("Content-Type", "application/json") |
| req.Header.Set("Authorization", "Bearer "+bearer) |
| - if xff != "" { |
| - req.Header.Set("X-Forwarded-For", xff) |
| - } |
| - res, err := http.DefaultClient.Do(req) |
| + return req |
| +} |
| + |
| +func formReq(t *testing.T, u string, form url.Values) *http.Request { |
| + t.Helper() |
| + req, err := http.NewRequest(http.MethodPost, u, strings.NewReader(form.Encode())) |
| if err != nil { |
| t.Fatal(err) |
| } |
| - defer res.Body.Close() |
| - b, _ := io.ReadAll(res.Body) |
| - var hs []string |
| - for k, v := range res.Header { |
| - if k != "Date" { |
| - hs = append(hs, k+": "+strings.Join(v, ",")) |
| - } |
| + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| + return req |
| +} |
| + |
| +// rawPost is a JSON POST with an optional X-Forwarded-For. |
| +func rawPost(t *testing.T, fx *consoleFixture, u string, body any, bearer, xff string) (int, string, string) { |
| + t.Helper() |
| + req := jsonReq(t, u, body, bearer) |
| + if xff != "" { |
| + req.Header.Set("X-Forwarded-For", xff) |
| } |
| - sort.Strings(hs) |
| - return res.StatusCode, strings.Join(hs, "\n"), strings.ReplaceAll(string(b), fx.ts.URL, "ORIGIN") |
| + return sendRaw(t, fx, http.DefaultClient, req) |
| +} |
| + |
| +// oneAudit is the app's audit trail, which must be exactly one entry. |
| +func oneAudit(t *testing.T, fx *consoleFixture, app string) string { |
| + t.Helper() |
| + events, err := fx.st.Events(OpsAccountID, app, 10) |
| + if err != nil || len(events) != 1 { |
| + t.Fatalf("%s: audit = %+v %v, want exactly one entry", app, events, err) |
| + } |
| + e := events[0] |
| + return e.Action + " " + e.Address + " " + expiringDetailRE.ReplaceAllString(e.Detail, "expiring WHEN") |
| } |
| |
| const switchOffJSONHeaders = "Cache-Control: no-store\nContent-Length: LEN\nContent-Type: application/json" |
| |
| -func headersSansLength(h string) string { |
| - return regexp.MustCompile(`Content-Length: \d+`).ReplaceAllString(h, "Content-Length: LEN") |
| +func switchOffCreated(name string) string { |
| + return `{"account":"bab","app":"` + name + `","build_probe":"","control_plane":false,"placement":"","region":"ie","region_name":"` + |
| + switchOffHome + `","region_source":"default","regions_available":1,"url":"ORIGIN/a/bab/apps/` + name + `"}` + "\n" |
| } |
| |
| func TestSwitchOffAPICreateDoorAnswers(t *testing.T) { |
| fx, token := switchOffFixture(t) |
| fx.srv.cfg.GeoIP = fakeLocator{"81.2.69.142": geo.Point{Lat: 51.5, Lon: -0.12}} |
| - home := geo.PlaceName("eu-west-1", "ie") |
| for _, c := range []struct { |
| name string |
| body map[string]string |
| @@ -83,24 +139,24 @@ func TestSwitchOffAPICreateDoorAnswers(t *testing.T) { |
| {"person", map[string]string{"name": "person"}, "81.2.69.142"}, |
| } { |
| status, hdr, body := rawPost(t, fx, newAppURL(fx), c.body, token, c.xff) |
| - want := `{"account":"bab","app":"` + c.name + `","build_probe":"","control_plane":false,"placement":"","region":"ie","region_name":"` + |
| - home + `","region_source":"default","regions_available":1,"url":"ORIGIN/a/bab/apps/` + c.name + `"}` + "\n" |
| - if status != http.StatusOK || body != want { |
| + if want := switchOffCreated(c.name); status != http.StatusOK || body != want { |
| t.Errorf("%s: %d %s\nwant 200 %s", c.name, status, body, want) |
| } |
| - if got := headersSansLength(hdr); got != switchOffJSONHeaders { |
| - t.Errorf("%s: headers\n%s\nwant\n%s", c.name, got, switchOffJSONHeaders) |
| + if hdr != switchOffJSONHeaders { |
| + t.Errorf("%s: headers\n%s\nwant\n%s", c.name, hdr, switchOffJSONHeaders) |
| } |
| if r, src, err := fx.st.AppRegion(OpsAccountID, c.name); err != nil || r != "" || src != "default" { |
| t.Errorf("%s: stored %q %q %v, want the home as default", c.name, r, src, err) |
| } |
| + if got, want := oneAudit(t, fx, c.name), "create paul@keymail.dev created app "+c.name+" (cli)"; got != want { |
| + t.Errorf("%s: audit %q, want %q", c.name, got, want) |
| + } |
| } |
| } |
| |
| func TestSwitchOffTemporaryCreateDoorAnswers(t *testing.T) { |
| fx, token := switchOffFixture(t) |
| fx.srv.cfg.TemporaryApps = true |
| - home := geo.PlaceName("eu-west-1", "ie") |
| for _, c := range []struct { |
| name string |
| body map[string]any |
| @@ -110,39 +166,44 @@ func TestSwitchOffTemporaryCreateDoorAnswers(t *testing.T) { |
| {"tmp-bad", map[string]any{"name": "tmp-bad", "region": "Bad/Code"}}, |
| } { |
| status, hdr, body := rawPost(t, fx, newTemporaryURL(fx), c.body, token, "") |
| - var res map[string]any |
| - if err := json.Unmarshal([]byte(body), &res); err != nil { |
| - t.Fatalf("%s: %d %s: %v", c.name, status, body, err) |
| - } |
| - if status != http.StatusOK || res["region"] != "ie" || res["region_name"] != home || |
| - res["region_source"] != "default" || res["regions_available"] != 1.0 { |
| - t.Errorf("%s: %d %s, want 200 with the home as default and one region", c.name, status, body) |
| + body = expiresAtRE.ReplaceAllString(body, `"expires_at":"WHEN"`) |
| + want := `{"account":"bab","app":"` + c.name + `","expires_at":"WHEN","region":"ie","region_name":"` + switchOffHome + |
| + `","region_source":"default","regions_available":1,"url":"ORIGIN/a/bab/apps/` + c.name + `"}` + "\n" |
| + if status != http.StatusOK || body != want { |
| + t.Errorf("%s: %d %s\nwant 200 %s", c.name, status, body, want) |
| } |
| - if got := headersSansLength(hdr); got != switchOffJSONHeaders { |
| - t.Errorf("%s: headers\n%s\nwant\n%s", c.name, got, switchOffJSONHeaders) |
| + if hdr != switchOffJSONHeaders { |
| + t.Errorf("%s: headers\n%s\nwant\n%s", c.name, hdr, switchOffJSONHeaders) |
| } |
| if r, src, err := fx.st.AppRegion(OpsAccountID, c.name); err != nil || r != "" || src != "default" { |
| t.Errorf("%s: stored %q %q %v", c.name, r, src, err) |
| } |
| + if got, want := oneAudit(t, fx, c.name), "create paul@keymail.dev created temporary app "+c.name+", expiring WHEN (cli)"; got != want { |
| + t.Errorf("%s: audit %q, want %q", c.name, got, want) |
| + } |
| } |
| } |
| |
| +// The flash cookie carries "ok|Created app APP — it's yours.", query-escaped. |
| +const switchOffBrowserCreatedHeaders = "Content-Length: LEN\nLocation: /a/bab/apps/APP\nSet-Cookie: carlos_console_flash=ok%7CCreated+app+APP+%E2%80%94+it%27s+yours.; Path=/; Max-Age=300; HttpOnly; SameSite=Lax" |
| + |
| func TestSwitchOffBrowserCreateDoor(t *testing.T) { |
| fx, _ := switchOffFixture(t) |
| c, csrf := signInAs(t, fx, "paul@keymail.dev", "code-region-off-form") |
| for _, c2 := range []struct{ name, region string }{ |
| {"form-uk", "uk"}, {"form-auto", "@auto"}, {"form-mars", "mars!"}, {"form-none", ""}, |
| } { |
| - status, loc, _ := postForm(t, c, fx.u("/apps/new"), url.Values{"csrf": {csrf}, "name": {c2.name}, "region": {c2.region}, "tz": {"Europe/London"}}) |
| - if status != http.StatusSeeOther || loc != fx.path("/apps/"+c2.name) { |
| - t.Errorf("%s: %d %q, want 303 to the app", c2.name, status, loc) |
| + status, hdr, body := sendRaw(t, fx, c, formReq(t, fx.u("/apps/new"), url.Values{"csrf": {csrf}, "name": {c2.name}, "region": {c2.region}, "tz": {"Europe/London"}})) |
| + wantHdr := strings.ReplaceAll(switchOffBrowserCreatedHeaders, "APP", c2.name) |
| + wantBody := "" |
| + if status != http.StatusSeeOther || hdr != wantHdr || body != wantBody { |
| + t.Errorf("%s: %d\n%s\n%q\nwant 303\n%s\n%q", c2.name, status, hdr, body, wantHdr, wantBody) |
| } |
| if r, src, err := fx.st.AppRegion(OpsAccountID, c2.name); err != nil || r != "" || src != "default" { |
| t.Errorf("%s: stored %q %q %v", c2.name, r, src, err) |
| } |
| - events, err := fx.st.Events(OpsAccountID, c2.name, 10) |
| - if err != nil || len(events) != 1 || events[0].Action != "create" || events[0].Detail != "created app "+c2.name { |
| - t.Errorf("%s: audit = %+v %v, want one create %q", c2.name, events, err, "created app "+c2.name) |
| + if got, want := oneAudit(t, fx, c2.name), "create paul@keymail.dev created app "+c2.name; got != want { |
| + t.Errorf("%s: audit %q, want %q", c2.name, got, want) |
| } |
| } |
| } |
| @@ -184,18 +245,22 @@ func TestSwitchOffNewAppPage(t *testing.T) { |
| func TestSwitchOffGuessDoorAnswers(t *testing.T) { |
| fx, _ := switchOffFixture(t) |
| c, csrf := signInAs(t, fx, "paul@keymail.dev", "code-region-off-guess") |
| - status, _, body := postForm(t, c, fx.u("/apps/new/region"), url.Values{"csrf": {csrf}, "tz": {"Europe/London"}}) |
| - want := `{"code":"uk","name":"` + ukPlace + `","source":"timezone"}` + "\n" |
| - if status != http.StatusOK || body != want { |
| - t.Errorf("guess = %d %q, want 200 %q", status, body, want) |
| - } |
| - status, _, body = postForm(t, c, fx.u("/apps/new/region"), url.Values{"csrf": {csrf}}) |
| - want = `{"code":"ie","name":"` + geo.PlaceName("eu-west-1", "ie") + `","source":"default"}` + "\n" |
| - if status != http.StatusOK || body != want { |
| - t.Errorf("no hint = %d %q, want 200 %q", status, body, want) |
| + for _, g := range []struct { |
| + name string |
| + form url.Values |
| + want string |
| + }{ |
| + {"timezone", url.Values{"csrf": {csrf}, "tz": {"Europe/London"}}, `{"code":"uk","name":"` + ukPlace + `","source":"timezone"}` + "\n"}, |
| + {"no hint", url.Values{"csrf": {csrf}}, `{"code":"ie","name":"` + switchOffHome + `","source":"default"}` + "\n"}, |
| + } { |
| + status, hdr, body := sendRaw(t, fx, c, formReq(t, fx.u("/apps/new/region"), g.form)) |
| + if status != http.StatusOK || body != g.want || hdr != switchOffJSONHeaders { |
| + t.Errorf("%s: %d\n%s\n%q\nwant 200\n%s\n%q", g.name, status, hdr, body, switchOffJSONHeaders, g.want) |
| + } |
| } |
| - if status, _, _ := postForm(t, c, fx.u("/apps/new/region"), url.Values{"csrf": {"wrong"}, "tz": {"Europe/London"}}); status != http.StatusForbidden { |
| - t.Errorf("bad csrf = %d, want 403", status) |
| + status, hdr, body := sendRaw(t, fx, c, formReq(t, fx.u("/apps/new/region"), url.Values{"csrf": {"wrong"}, "tz": {"Europe/London"}})) |
| + if want := `{"error":"Cross-site request blocked."}` + "\n"; status != http.StatusForbidden || body != want || hdr != switchOffJSONHeaders { |
| + t.Errorf("bad csrf = %d\n%s\n%q, want 403 %q", status, hdr, body, want) |
| } |
| } |
| |
| @@ -218,12 +283,16 @@ func TestSwitchOffCreateLogsOneRegionLine(t *testing.T) { |
| func TestSwitchOffAdoptionStoresTheHome(t *testing.T) { |
| fx, token := switchOffFixture(t) |
| seedBucketApp(t, fx, "bab", "oldsite") |
| - if status, _, body := rawPost(t, fx, newAppURL(fx), map[string]string{"name": "oldsite", "region": "uk", "timezone": "Europe/London"}, token, ""); status != http.StatusOK { |
| - t.Fatalf("adoption = %d %s", status, body) |
| + status, hdr, body := rawPost(t, fx, newAppURL(fx), map[string]string{"name": "oldsite", "region": "uk", "timezone": "Europe/London"}, token, "") |
| + if want := switchOffCreated("oldsite"); status != http.StatusOK || body != want || hdr != switchOffJSONHeaders { |
| + t.Fatalf("adoption = %d\n%s\n%s\nwant 200\n%s\n%s", status, hdr, body, switchOffJSONHeaders, want) |
| } |
| if r, src, err := fx.st.AppRegion(OpsAccountID, "oldsite"); err != nil || r != "" || src != "default" { |
| t.Fatalf("adoption stored %q %q %v", r, src, err) |
| } |
| + if got, want := oneAudit(t, fx, "oldsite"), "create paul@keymail.dev created app oldsite (cli)"; got != want { |
| + t.Errorf("audit %q, want %q", got, want) |
| + } |
| } |
| |
| // The regions door for an app the switch-off create door made: the |
| @@ -235,14 +304,78 @@ func TestSwitchOffRegionsDoorAnswers(t *testing.T) { |
| } |
| req, _ := http.NewRequest(http.MethodGet, fx.ts.URL+"/api/cli/apps/bab/regdoor/regions", nil) |
| req.Header.Set("Authorization", "Bearer "+token) |
| - res, err := http.DefaultClient.Do(req) |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - defer res.Body.Close() |
| - b, _ := io.ReadAll(res.Body) |
| + status, hdr, body := sendRaw(t, fx, http.DefaultClient, req) |
| const want = `{"app_default":{"region":"ie","name":"Ireland · Dublin","source":"default","effective":"ie","available":true,"region_known":true,"placement_known":true},"default":"ie","regions":[{"code":"ie","armed":true,"aws_region":"eu-west-1","name":"Ireland · Dublin"},{"code":"nz","armed":false,"name":"nz"},{"code":"uk","armed":true,"aws_region":"eu-west-2","name":"UK · London"}]}` + "\n" |
| - if res.StatusCode != http.StatusOK || string(b) != want { |
| - t.Errorf("regions = %d %q\nwant 200 %q", res.StatusCode, b, want) |
| + if status != http.StatusOK || body != want || hdr != switchOffJSONHeaders { |
| + t.Errorf("regions = %d\n%s\n%q\nwant 200\n%s\n%q", status, hdr, body, switchOffJSONHeaders, want) |
| + } |
| +} |
| + |
| +// Every create door read a person's client address (personIP) before its |
| +// switch-off return, and reading it is what closes the edge-proof latch |
| +// (edgeproof.go): the first edge-signed X-Forwarded-For stores |
| +// edge_proof_seen, and from then on an unsigned loopback chain counts |
| +// against the peer. So a signed request to each door records the marker, |
| +// and a later unsigned loopback request, even in a fresh process, is |
| +// counted against 127.0.0.1. |
| +func TestSwitchOffCreateDoorsRecordTheEdgeProof(t *testing.T) { |
| + key := []byte("0123456789abcdef0123456789abcdef") |
| + const chain = "1.2.3.4" |
| + signed := func(req *http.Request) *http.Request { |
| + req.Header.Set("X-Forwarded-For", chain) |
| + req.Header.Set(edgeproof.Header, edgeproof.Sign(key, "127.0.0.1", chain, time.Now())) |
| + return req |
| + } |
| + for _, d := range []struct { |
| + name string |
| + status int |
| + send func(t *testing.T, fx *consoleFixture, token string) int |
| + }{ |
| + {"api create", http.StatusOK, func(t *testing.T, fx *consoleFixture, token string) int { |
| + status, _, _ := sendRaw(t, fx, http.DefaultClient, signed(jsonReq(t, newAppURL(fx), map[string]string{"name": "proofapi", "region": "uk"}, token))) |
| + return status |
| + }}, |
| + {"temporary create", http.StatusOK, func(t *testing.T, fx *consoleFixture, token string) int { |
| + fx.srv.cfg.TemporaryApps = true |
| + status, _, _ := sendRaw(t, fx, http.DefaultClient, signed(jsonReq(t, newTemporaryURL(fx), map[string]any{"name": "tmp-proof", "timezone": "Europe/London"}, token))) |
| + return status |
| + }}, |
| + {"browser create", http.StatusSeeOther, func(t *testing.T, fx *consoleFixture, _ string) int { |
| + c, csrf := signInAs(t, fx, "paul@keymail.dev", "code-proof-create") |
| + status, _, _ := sendRaw(t, fx, c, signed(formReq(t, fx.u("/apps/new"), url.Values{"csrf": {csrf}, "name": {"proofform"}, "region": {"uk"}}))) |
| + return status |
| + }}, |
| + {"create form", http.StatusOK, func(t *testing.T, fx *consoleFixture, _ string) int { |
| + c, _ := signInAs(t, fx, "paul@keymail.dev", "code-proof-page") |
| + req, _ := http.NewRequest(http.MethodGet, fx.u("/apps/new"), nil) |
| + status, _, _ := sendRaw(t, fx, c, signed(req)) |
| + return status |
| + }}, |
| + } { |
| + t.Run(d.name, func(t *testing.T) { |
| + fx, token := switchOffFixture(t) |
| + if _, err := fx.rel.Put(context.Background(), edgeproof.MeshKeyObject, []byte(hex.EncodeToString(key)), ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + if seen, err := fx.st.EdgeProofSeen(); err != nil || seen { |
| + t.Fatalf("before the door: seen = %v %v, want no marker", seen, err) |
| + } |
| + if status := d.send(t, fx, token); status != d.status { |
| + t.Fatalf("signed request = %d, want %d", status, d.status) |
| + } |
| + if seen, err := fx.st.EdgeProofSeen(); err != nil || !seen { |
| + t.Fatalf("after the door: seen = %v %v, want the marker stored", seen, err) |
| + } |
| + unsigned := httptest.NewRequest(http.MethodPost, "/api/cli/auth/start", nil) |
| + unsigned.RemoteAddr = "127.0.0.1:50000" |
| + unsigned.Header.Set("X-Forwarded-For", "5.6.7.8") |
| + if got := fx.srv.clientIP(unsigned); got != "127.0.0.1" { |
| + t.Errorf("unsigned loopback after the door = %q, want the peer", got) |
| + } |
| + again := &Server{cfg: fx.srv.cfg, store: fx.st} |
| + if got := again.clientIP(unsigned); got != "127.0.0.1" { |
| + t.Errorf("unsigned loopback in a fresh process = %q, want the peer", got) |
| + } |
| + }) |
| } |
| } |