| new file mode 100644 |
| index 000000000..928385686 |
| --- /dev/null |
| +++ b/internal/console/regionoff_test.go |
| @@ -0,0 +1,248 @@ |
| +package console |
| + |
| +import ( |
| + "bytes" |
| + "encoding/json" |
| + "io" |
| + "net/http" |
| + "net/url" |
| + "regexp" |
| + "sort" |
| + "strings" |
| + "testing" |
| + |
| + "github.com/carlosframework/platform/internal/geo" |
| +) |
| + |
| +// These tests pin what every app-region door answered with |
| +// CONSOLE_APP_REGIONS off, the state every deployment ran in when the |
| +// switch was deleted (claims cleanup R5). They were written and run on |
| +// the tree before the deletion and must stay green, unchanged, after it. |
| +// The fleet offers two eligible regions (the home "ie" and "uk") and the |
| +// console holds the secrets key, so a switch-on console would have |
| +// offered a choice: these answers are the switch, not the fleet. |
| + |
| +func switchOffFixture(t *testing.T) (*consoleFixture, string) { |
| + t.Helper() |
| + fx := newConsoleFixture(t) |
| + fx.srv.cfg.HomeRegion, fx.srv.cfg.SecretsPub = "ie", testKeyPub |
| + setEdges(t, fx, map[string]string{"ie-box": homeBox, "uk-box": ukEligible, "nz-box": nzNoHosting}) |
| + 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) { |
| + t.Helper() |
| + raw, _ := json.Marshal(body) |
| + req, err := http.NewRequest(http.MethodPost, u, bytes.NewReader(raw)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + 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) |
| + 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, ",")) |
| + } |
| + } |
| + sort.Strings(hs) |
| + return res.StatusCode, strings.Join(hs, "\n"), strings.ReplaceAll(string(b), fx.ts.URL, "ORIGIN") |
| +} |
| + |
| +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 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 |
| + xff string |
| + }{ |
| + {"plain", map[string]string{"name": "plain"}, ""}, |
| + {"tzuk", map[string]string{"name": "tzuk", "region": "uk", "timezone": "Europe/London"}, ""}, |
| + {"nzapp", map[string]string{"name": "nzapp", "region": "nz"}, ""}, |
| + {"badcode", map[string]string{"name": "badcode", "region": "Bad/Code"}, ""}, |
| + {"homeapp", map[string]string{"name": "homeapp", "region": "ie"}, ""}, |
| + {"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 { |
| + 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 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) |
| + } |
| + } |
| +} |
| + |
| +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 |
| + }{ |
| + {"tmp-plain", map[string]any{"name": "tmp-plain"}}, |
| + {"tmp-tz", map[string]any{"name": "tmp-tz", "region": "uk", "timezone": "Europe/London"}}, |
| + {"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) |
| + } |
| + if got := headersSansLength(hdr); got != switchOffJSONHeaders { |
| + t.Errorf("%s: headers\n%s\nwant\n%s", c.name, got, 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) |
| + } |
| + } |
| +} |
| + |
| +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) |
| + } |
| + 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) |
| + } |
| + } |
| +} |
| + |
| +// switchOffNewAppForm is the create-app form as the tree before R5 |
| +// rendered it with the switch off, CSRF value blanked. |
| +const switchOffNewAppForm = `<form class="signin" method="post" action="/a/bab/apps/new"> |
| + <input type="hidden" name="csrf" value="CSRF"> |
| + <label class="visually-hidden" for="app-name">App name</label> |
| + <input id="app-name" type="text" name="name" placeholder="my-app" autofocus |
| + required pattern="[A-Za-z][A-Za-z0-9-]{0,31}" maxlength="32"> |
| + <button type="submit">Create app</button> |
| +</form>` |
| + |
| +func TestSwitchOffNewAppPage(t *testing.T) { |
| + fx, _ := switchOffFixture(t) |
| + fx.srv.cfg.GeoIP = fakeLocator{"81.2.69.142": geo.Point{Lat: 51.5, Lon: -0.12}} |
| + status, _, body := get(t, signInPaul(t, fx), fx.u("/apps/new")) |
| + if status != http.StatusOK { |
| + t.Fatalf("form = %d", status) |
| + } |
| + i := strings.Index(body, `<form class="signin"`) |
| + if i < 0 { |
| + t.Fatalf("no create-app form in %s", body) |
| + } |
| + j := strings.Index(body[i:], "</form>") + i + len("</form>") |
| + form := regexp.MustCompile(`name="csrf" value="[^"]*"`).ReplaceAllString(body[i:j], `name="csrf" value="CSRF"`) |
| + if form != switchOffNewAppForm { |
| + t.Errorf("form =\n%q\nwant\n%q", form, switchOffNewAppForm) |
| + } |
| + for _, absent := range []string{`id="app-region"`, `name="tz"`, "/apps/new/region", "db-ip.com", "currentScript"} { |
| + if strings.Contains(body, absent) { |
| + t.Errorf("the page carries %q", absent) |
| + } |
| + } |
| +} |
| + |
| +// The page script's guess door answered with the switch off too. |
| +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) |
| + } |
| + 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) |
| + } |
| +} |
| + |
| +func TestSwitchOffCreateLogsOneRegionLine(t *testing.T) { |
| + fx, token := switchOffFixture(t) |
| + var logs bytes.Buffer |
| + restore := captureLogTo(&logs) |
| + status, _, _ := rawPost(t, fx, newAppURL(fx), map[string]string{"name": "logged", "region": "uk"}, token, "") |
| + restore() |
| + if status != http.StatusOK { |
| + t.Fatalf("create = %d", status) |
| + } |
| + if n := strings.Count(logs.String(), "console: app region bab/logged:"); n != 1 || !strings.Contains(logs.String(), "console: app region bab/logged: ie (default)\n") { |
| + t.Errorf("%d region line(s) in %q", n, logs.String()) |
| + } |
| +} |
| + |
| +// An owner adopting objects already in the bucket keeps the home even |
| +// when the request names a region. |
| +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) |
| + } |
| + if r, src, err := fx.st.AppRegion(OpsAccountID, "oldsite"); err != nil || r != "" || src != "default" { |
| + t.Fatalf("adoption stored %q %q %v", r, src, err) |
| + } |
| +} |
| + |
| +// The regions door for an app the switch-off create door made: the |
| +// app's default is the home, as stored. |
| +func TestSwitchOffRegionsDoorAnswers(t *testing.T) { |
| + fx, token := switchOffFixture(t) |
| + if status, _, body := rawPost(t, fx, newAppURL(fx), map[string]string{"name": "regdoor", "region": "uk", "timezone": "Europe/London"}, token, ""); status != http.StatusOK { |
| + t.Fatalf("create = %d %s", status, body) |
| + } |
| + 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) |
| + 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) |
| + } |
| +} |