| index 1683ce6e3..5dfd0b871 100644 |
| --- a/internal/console/apicli_ha_test.go |
| +++ b/internal/console/apicli_ha_test.go |
| @@ -2,11 +2,18 @@ package console |
| |
| import ( |
| "context" |
| + "crypto/sha256" |
| + "errors" |
| "fmt" |
| + "maps" |
| "net/http" |
| + "os" |
| "slices" |
| + "strings" |
| + "sync" |
| "testing" |
| |
| + "github.com/carlosframework/platform/internal/apppolicy" |
| "github.com/carlosframework/platform/internal/registry" |
| "github.com/carlosframework/platform/internal/svcrole" |
| ) |
| @@ -107,26 +114,154 @@ func haRegionFixture(t *testing.T, o haRegionOpts) *haRegionWorld { |
| return w |
| } |
| |
| -// assertNotCreated: a refused create left no row and no object under the |
| -// name's account prefix beyond the ones listed in before. |
| -func (w *haRegionWorld) assertNotCreated(t *testing.T, name string, before []string) { |
| +// refused runs req, a create of name the test expects refused, and proves |
| +// it changed nothing: before it, name gets an earlier app's policy object |
| +// (the object createClaimAppRow clears before its insert), and after it |
| +// the request must have made no bucket mutation (put or delete, whether or |
| +// not it succeeded) and, unless lists, no bucket listing; every bucket |
| +// object's bytes and every console database table must be as they were; |
| +// and name has no row. lists is for a refusal that by design follows the |
| +// claim's prefix checks (an adoption). |
| +func (w *haRegionWorld) refused(t *testing.T, name string, lists bool, req func() (int, map[string]any)) (int, map[string]any) { |
| t.Helper() |
| + w.seedPolicy(t, name) |
| + bucket, db := w.bucketSnap(t), w.dbSnap(t) |
| + var mu sync.Mutex |
| + var muts, listed []string |
| + ds := w.rel.(*deletableStore) |
| + ds.setOpWitness(func(op, key string) { |
| + mu.Lock() |
| + defer mu.Unlock() |
| + if op == "put" || op == "delete" { |
| + muts = append(muts, op+" "+key) |
| + } else { |
| + listed = append(listed, op+" "+key) |
| + } |
| + }) |
| + status, res := req() |
| + ds.setOpWitness(nil) |
| + mu.Lock() |
| + defer mu.Unlock() |
| + if len(muts) > 0 { |
| + t.Errorf("%s: the refused request mutated the bucket: %v", name, muts) |
| + } |
| + if len(listed) > 0 && !lists { |
| + t.Errorf("%s: the refused request listed the bucket: %v", name, listed) |
| + } |
| + if got := w.bucketSnap(t); !maps.Equal(got, bucket) { |
| + t.Errorf("%s: the bucket changed: %v", name, mapDiff(bucket, got)) |
| + } |
| + if got := w.dbSnap(t); !maps.Equal(got, db) { |
| + t.Errorf("%s: the console database changed: %v", name, mapDiff(db, got)) |
| + } |
| if has, err := w.st.HasAppIn(OpsAccountID, name); err != nil || has { |
| t.Errorf("%s: HasAppIn = %v %v, want no row", name, has, err) |
| } |
| - if got := w.keysUnder(t, name); !slices.Equal(got, before) { |
| - t.Errorf("%s: keys under apps/bab/%s/ = %v, want %v", name, name, got, before) |
| + return status, res |
| +} |
| + |
| +// seedPolicy puts an earlier app's policy object at name's policy key, |
| +// as a purged app of that name leaves one. |
| +func (w *haRegionWorld) seedPolicy(t *testing.T, name string) { |
| + t.Helper() |
| + under, key := w.rel.(*deletableStore).Store, apppolicy.Key("bab", name) |
| + etag := "" |
| + if _, cur, err := under.Get(context.Background(), key); err == nil { |
| + etag = cur |
| + } else if !errors.Is(err, os.ErrNotExist) { |
| + t.Fatal(err) |
| + } |
| + if _, err := under.Put(context.Background(), key, []byte(`{"seeded":"`+name+`"}`), etag); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +func (w *haRegionWorld) policyPresent(t *testing.T, name string) bool { |
| + t.Helper() |
| + _, _, err := w.rel.(*deletableStore).Store.Get(context.Background(), apppolicy.Key("bab", name)) |
| + if err != nil && !errors.Is(err, os.ErrNotExist) { |
| + t.Fatal(err) |
| } |
| + return err == nil |
| } |
| |
| -func (w *haRegionWorld) keysUnder(t *testing.T, name string) []string { |
| +// bucketSnap is every bucket object's key and a hash of its bytes, read |
| +// beneath the op witness. |
| +func (w *haRegionWorld) bucketSnap(t *testing.T) map[string]string { |
| t.Helper() |
| - keys, err := w.rel.List(context.Background(), "apps/bab/"+name+"/") |
| + under := w.rel.(*deletableStore).Store |
| + keys, err := under.List(context.Background(), "") |
| if err != nil { |
| t.Fatal(err) |
| } |
| - slices.Sort(keys) |
| - return keys |
| + out := make(map[string]string, len(keys)) |
| + for _, k := range keys { |
| + b, _, err := under.Get(context.Background(), k) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + out[k] = fmt.Sprintf("%x", sha256.Sum256(b)) |
| + } |
| + return out |
| +} |
| + |
| +// dbSnap is every console database table's rows, one hash per table. |
| +func (w *haRegionWorld) dbSnap(t *testing.T) map[string]string { |
| + t.Helper() |
| + tables, err := w.st.db.Query(`SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name`) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var names []string |
| + for tables.Next() { |
| + var n string |
| + if err := tables.Scan(&n); err != nil { |
| + t.Fatal(err) |
| + } |
| + names = append(names, n) |
| + } |
| + tables.Close() |
| + out := make(map[string]string, len(names)) |
| + for _, n := range names { |
| + rows, err := w.st.db.Query(`SELECT * FROM "` + n + `"`) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + cols, _ := rows.Columns() |
| + var lines []string |
| + for rows.Next() { |
| + vals := make([]any, len(cols)) |
| + ptrs := make([]any, len(cols)) |
| + for i := range vals { |
| + ptrs[i] = &vals[i] |
| + } |
| + if err := rows.Scan(ptrs...); err != nil { |
| + t.Fatal(err) |
| + } |
| + lines = append(lines, fmt.Sprintf("%q", vals)) |
| + } |
| + rows.Close() |
| + slices.Sort(lines) |
| + out[n] = fmt.Sprintf("%x", sha256.Sum256([]byte(strings.Join(lines, "\n")))) |
| + } |
| + return out |
| +} |
| + |
| +// mapDiff names the keys whose values differ between a and b. |
| +func mapDiff(a, b map[string]string) []string { |
| + var d []string |
| + for k, v := range a { |
| + if b[k] != v { |
| + d = append(d, k) |
| + } |
| + } |
| + for k := range b { |
| + if _, ok := a[k]; !ok { |
| + d = append(d, k) |
| + } |
| + } |
| + slices.Sort(d) |
| + return d |
| } |
| |
| // wantHARefusal asserts a JSON refusal: status, message and (when not "") |
| @@ -140,7 +275,7 @@ func wantHARefusal(t *testing.T, what string, status int, res map[string]any, wa |
| } |
| |
| // TestAPICreateAppHA: "ha": true at the API create door (G6 Task 2). Every |
| -// refusal leaves no row and no object; each has a passing control in the |
| +// refusal changes nothing (refused); each has a passing control in the |
| // same world. |
| func TestAPICreateAppHA(t *testing.T) { |
| w := haRegionFixture(t, haRegionOpts{Accounts: []string{"bab"}}) |
| @@ -162,14 +297,26 @@ func TestAPICreateAppHA(t *testing.T) { |
| |
| t.Run("a service credential", func(t *testing.T) { |
| svc := serviceToken(t, w.st, OpsAccountID, "hub", "", svcrole.Publish) |
| - status, res := post(svc, map[string]any{"name": "svcha", "region": "us", "ha": true}) |
| + // A credential's first use stamps cli_tokens (authentication's |
| + // bookkeeping, before any door runs); a read uses it first, so the |
| + // refusal below is measured alone, as the person's token is after |
| + // the world's control. |
| + if code, _, out := rawReq(t, http.MethodGet, w.ts.URL+"/api/cli/apps", svc, ""); code != http.StatusOK { |
| + t.Fatalf("service warm-up = %d %s", code, out) |
| + } |
| + status, res := w.refused(t, "svcha", false, func() (int, map[string]any) { |
| + return post(svc, map[string]any{"name": "svcha", "region": "us", "ha": true}) |
| + }) |
| wantHARefusal(t, "service ha", status, res, http.StatusForbidden, haCopyNotAllowed, haPoolNotAllowedCode) |
| - w.assertNotCreated(t, "svcha", nil) |
| - // Control: the same credential without ha creates a plain app. |
| + // Control: the same credential without ha creates a plain app, and |
| + // clears the seeded policy a late refusal would have cleared too. |
| status, res = post(svc, map[string]any{"name": "svcha", "region": "us"}) |
| if status != http.StatusOK { |
| t.Fatalf("service plain = %d %v, want 200", status, res) |
| } |
| + if w.policyPresent(t, "svcha") { |
| + t.Fatal("control: the create left the earlier policy; the seed is not one the claim clears") |
| + } |
| if _, ok := res["ha_pool"]; ok { |
| t.Fatalf("service plain answered ha_pool: %v", res) |
| } |
| @@ -181,18 +328,18 @@ func TestAPICreateAppHA(t *testing.T) { |
| {"name": "noregion", "region": " ", "ha": true}, |
| {"name": "noregion", "region": autoRegion, "ha": true}, |
| } { |
| - status, res := post(w.token, body) |
| + status, res := w.refused(t, "noregion", false, func() (int, map[string]any) { return post(w.token, body) }) |
| wantHARefusal(t, fmt.Sprintf("ha %v", body), status, res, http.StatusBadRequest, haCopyNeedsRegion, "") |
| - w.assertNotCreated(t, "noregion", nil) |
| } |
| // Control: the same create naming us is (a). |
| }) |
| |
| t.Run("a region that is not HA", func(t *testing.T) { |
| for _, c := range []struct{ region, code string }{{"ie", ""}, {"uk", "uk"}} { |
| - status, res := post(w.token, map[string]any{"name": "notha", "region": c.region, "ha": true}) |
| + status, res := w.refused(t, "notha", false, func() (int, map[string]any) { |
| + return post(w.token, map[string]any{"name": "notha", "region": c.region, "ha": true}) |
| + }) |
| wantHARefusal(t, "ha in "+c.region, status, res, http.StatusBadRequest, fmt.Sprintf(haCopyRegion, srv.offlinePlace(c.code)), "") |
| - w.assertNotCreated(t, "notha", nil) |
| } |
| // Control: the same create in us is (a); a plain create in ie or |
| // uk is the world's control's shape. |
| @@ -200,16 +347,19 @@ func TestAPICreateAppHA(t *testing.T) { |
| |
| t.Run("a placement", func(t *testing.T) { |
| place := "fleet/" + w.ownFleet |
| - status, res := post(w.token, map[string]any{"name": "placed", "region": "us", "place": place, "ha": true}) |
| + status, res := w.refused(t, "placed", false, func() (int, map[string]any) { |
| + return post(w.token, map[string]any{"name": "placed", "region": "us", "place": place, "ha": true}) |
| + }) |
| wantHARefusal(t, "ha with place", status, res, http.StatusBadRequest, fmt.Sprintf(haCopyRegion, place), "") |
| - w.assertNotCreated(t, "placed", nil) |
| // A foreign fleet keeps its byte-identical 404, first. |
| - code, _, body := rawReq(t, http.MethodPost, newAppURL(w.consoleFixture), w.token, |
| - `{"name":"placed","region":"us","place":"fleet/`+w.foreignFleet+`","ha":true}`) |
| - if code != http.StatusNotFound { |
| - t.Errorf("ha with a foreign fleet = %d %s, want 404", code, body) |
| - } |
| - w.assertNotCreated(t, "placed", nil) |
| + w.refused(t, "placed", false, func() (int, map[string]any) { |
| + code, _, body := rawReq(t, http.MethodPost, newAppURL(w.consoleFixture), w.token, |
| + `{"name":"placed","region":"us","place":"fleet/`+w.foreignFleet+`","ha":true}`) |
| + if code != http.StatusNotFound { |
| + t.Errorf("ha with a foreign fleet = %d %s, want 404", code, body) |
| + } |
| + return code, nil |
| + }) |
| // Control: the same placed create without ha. |
| status, res = post(w.token, map[string]any{"name": "placed", "region": "us", "place": place}) |
| if status != http.StatusOK || res["placement"] != place { |
| @@ -221,12 +371,14 @@ func TestAPICreateAppHA(t *testing.T) { |
| if _, err := w.rel.Put(context.Background(), "apps/bab/adopted/releases/v1.json", []byte(`{}`), ""); err != nil { |
| t.Fatal(err) |
| } |
| - before := w.keysUnder(t, "adopted") |
| - status, res := post(w.token, map[string]any{"name": "adopted", "region": "us", "ha": true}) |
| + // This refusal follows the claim's prefix checks by design (it |
| + // needs their answer), so it may list; it may not write. |
| + status, res := w.refused(t, "adopted", true, func() (int, map[string]any) { |
| + return post(w.token, map[string]any{"name": "adopted", "region": "us", "ha": true}) |
| + }) |
| if status != http.StatusConflict || errOf(res) != "that name is taken" { |
| t.Errorf("ha adoption = %d %v, want 409 that name is taken", status, res) |
| } |
| - w.assertNotCreated(t, "adopted", before) |
| // Control: the owner's adoption without ha is unchanged. |
| status, res = post(w.token, map[string]any{"name": "adopted", "region": "us"}) |
| if status != http.StatusOK { |
| @@ -242,9 +394,10 @@ func TestAPICreateAppHA(t *testing.T) { |
| // is refused with the machine code, and its plain creates are untouched. |
| func TestAPICreateAppHAUnlisted(t *testing.T) { |
| w := haRegionFixture(t, haRegionOpts{Accounts: []string{"cdef"}}) |
| - status, res := postJSON(t, newAppURL(w.consoleFixture), map[string]any{"name": "shop", "region": "us", "ha": true}, w.token) |
| + status, res := w.refused(t, "shop", false, func() (int, map[string]any) { |
| + return postJSON(t, newAppURL(w.consoleFixture), map[string]any{"name": "shop", "region": "us", "ha": true}, w.token) |
| + }) |
| wantHARefusal(t, "unlisted ha", status, res, http.StatusForbidden, haCopyNotAllowed, haPoolNotAllowedCode) |
| - w.assertNotCreated(t, "shop", nil) |
| // Control: the same person's plain create, with no ha_pool in the body. |
| status, res = postJSON(t, newAppURL(w.consoleFixture), map[string]any{"name": "shop", "region": "us"}, w.token) |
| if status != http.StatusOK { |
| @@ -266,9 +419,10 @@ func TestAPICreateAppHABrokenConfig(t *testing.T) { |
| if !w.srv.haPoolsBroken { |
| t.Fatal("fixture: the HA config is not broken") |
| } |
| - status, res := postJSON(t, newAppURL(w.consoleFixture), map[string]any{"name": "shop", "region": "us", "ha": true}, w.token) |
| + status, res := w.refused(t, "shop", false, func() (int, map[string]any) { |
| + return postJSON(t, newAppURL(w.consoleFixture), map[string]any{"name": "shop", "region": "us", "ha": true}, w.token) |
| + }) |
| wantHARefusal(t, "broken ha", status, res, http.StatusBadRequest, fmt.Sprintf(haCopyRegion, w.srv.offlinePlace("us")), "") |
| - w.assertNotCreated(t, "shop", nil) |
| } |
| |
| // TestAPICreateAppHASwitchOff: with the region switch off every create |
| @@ -277,9 +431,10 @@ func TestAPICreateAppHABrokenConfig(t *testing.T) { |
| // home. The world's control (a plain create naming us) lands on ie. |
| func TestAPICreateAppHASwitchOff(t *testing.T) { |
| w := haRegionFixture(t, haRegionOpts{Accounts: []string{"bab"}, HistoryInactive: true}) |
| - status, res := postJSON(t, newAppURL(w.consoleFixture), map[string]any{"name": "shop", "region": "us", "ha": true}, w.token) |
| + status, res := w.refused(t, "shop", false, func() (int, map[string]any) { |
| + return postJSON(t, newAppURL(w.consoleFixture), map[string]any{"name": "shop", "region": "us", "ha": true}, w.token) |
| + }) |
| wantHARefusal(t, "ha in us, switch off", status, res, http.StatusBadRequest, fmt.Sprintf(haCopyRegion, w.srv.offlinePlace("us")), "") |
| - w.assertNotCreated(t, "shop", nil) |
| } |
| |
| // TestAPICreateAppHAHomeRegion (Review Focus 1, dev's shape): the home is |
| @@ -299,3 +454,39 @@ func TestAPICreateAppHAHomeRegion(t *testing.T) { |
| } |
| } |
| } |
| + |
| +// TestAPICreateAppHARegionBinding: the pool is written only at the region |
| +// the HA checks admitted. The hostname history invalidated after the door's |
| +// checks turns the region switch off before the claim resolves the region, |
| +// which would land the app on the home: the create fails and writes no row. |
| +// Control: the same create with no invalidation is (a); a retry after it |
| +// meets the door's own switch-off refusal. |
| +func TestAPICreateAppHARegionBinding(t *testing.T) { |
| + w := haRegionFixture(t, haRegionOpts{Accounts: []string{"bab"}}) |
| + fired := false |
| + w.srv.beforeClaimRegion = func() { |
| + if fired { |
| + return |
| + } |
| + fired = true |
| + if err := w.srv.invalidateHosts(context.Background(), "test: a breach between the HA checks and the region"); err != nil { |
| + t.Error(err) |
| + } |
| + if w.srv.appRegionsOn() { |
| + t.Error("fixture: the region switch is still on after the invalidation") |
| + } |
| + } |
| + status, res := postJSON(t, newAppURL(w.consoleFixture), map[string]any{"name": "shop", "region": "us", "ha": true}, w.token) |
| + if !fired { |
| + t.Fatal("the seam did not run") |
| + } |
| + if status != http.StatusInternalServerError || errOf(res) != appCreateFailedMsg { |
| + t.Errorf("HA create across an invalidation = %d %v, want 500 %q", status, res, appCreateFailedMsg) |
| + } |
| + if has, err := w.st.HasAppIn(OpsAccountID, "shop"); err != nil || has { |
| + pool, region, _ := w.st.AppHAPool(context.Background(), OpsAccountID, "shop") |
| + t.Fatalf("HasAppIn = %v %v (pool %q region %q), want no row", has, err, pool, region) |
| + } |
| + status, res = postJSON(t, newAppURL(w.consoleFixture), map[string]any{"name": "shop", "region": "us", "ha": true}, w.token) |
| + wantHARefusal(t, "retry, switch off", status, res, http.StatusBadRequest, fmt.Sprintf(haCopyRegion, w.srv.offlinePlace("us")), "") |
| +} |