| new file mode 100644 |
| index 000000000..3a1de6bad |
| --- /dev/null |
| +++ b/internal/console/hacreate_test.go |
| @@ -0,0 +1,656 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "fmt" |
| + "io" |
| + "net/http" |
| + "net/http/httptest" |
| + "os" |
| + "reflect" |
| + "strings" |
| + "sync" |
| + "testing" |
| + |
| + lsfile "github.com/benbjohnson/litestream/file" |
| + "path/filepath" |
| + |
| + "github.com/carlosframework/platform/internal/activator" |
| + "github.com/carlosframework/platform/internal/objstore" |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +// Count attempts, including failed mutations and bounded LISTs. Embedding |
| +// Store deliberately hides optional listing interfaces unless supplied below. |
| +type haCreateStore struct { |
| + release.Store |
| + mu sync.Mutex |
| + writes int |
| + pages []string |
| + pageErr error |
| + failKey string |
| +} |
| + |
| +func (s *haCreateStore) Put(ctx context.Context, k string, b []byte, match string) (string, error) { |
| + s.mu.Lock() |
| + s.writes++ |
| + s.mu.Unlock() |
| + return s.Store.Put(ctx, k, b, match) |
| +} |
| +func (s *haCreateStore) Delete(ctx context.Context, k string) error { |
| + s.mu.Lock() |
| + s.writes++ |
| + s.mu.Unlock() |
| + return s.Store.Delete(ctx, k) |
| +} |
| +func (s *haCreateStore) Get(ctx context.Context, k string) ([]byte, string, error) { |
| + if k == s.failKey { |
| + return nil, "", errors.New("secret-bucket record read") |
| + } |
| + return s.Store.Get(ctx, k) |
| +} |
| +func (s *haCreateStore) ListPage(ctx context.Context, p, after string, n int) ([]string, error) { |
| + s.mu.Lock() |
| + s.pages = append(s.pages, fmt.Sprintf("%s|%s|%d", p, after, n)) |
| + s.mu.Unlock() |
| + if s.pageErr != nil { |
| + return nil, s.pageErr |
| + } |
| + return s.Store.(release.PageLister).ListPage(ctx, p, after, n) |
| +} |
| +func (s *haCreateStore) counts() (int, []string) { |
| + s.mu.Lock() |
| + defer s.mu.Unlock() |
| + return s.writes, append([]string(nil), s.pages...) |
| +} |
| + |
| +func haCreateHome(t *testing.T) *leftoverFx { |
| + t.Helper() |
| + fx := leftoverFixture(t, "code-ha-create") |
| + fx.srv.cfg.HomeRegion = "ie" |
| + fx.srv.cfg.Region = "" |
| + fx.srv.cfg.HARegions = []string{"ie"} |
| + fx.srv.cfg.SeedData = release.NewDirStore(t.TempDir()) |
| + m := titoManifest() |
| + m.Pool = "" |
| + m.Regions = nil |
| + enableInstances(t, fx.consoleFixture, "titogo", m) |
| + return fx |
| +} |
| +func haCreateTrack(fx *leftoverFx) (*haCreateStore, *haCreateStore) { |
| + control := &haCreateStore{Store: fx.srv.cfg.Releases} |
| + data := &haCreateStore{Store: fx.srv.cfg.SeedData} |
| + fx.srv.cfg.Releases = control |
| + fx.srv.cfg.SeedData = data |
| + return control, data |
| +} |
| +func haCreateNoWrites(t *testing.T, control, data *haCreateStore) { |
| + t.Helper() |
| + cw, _ := control.counts() |
| + dw, _ := data.counts() |
| + if cw != 0 || dw != 0 { |
| + t.Fatalf("refusal mutation attempts: control=%d data=%d", cw, dw) |
| + } |
| +} |
| +func haCreatePost(t *testing.T, fx *leftoverFx, body string) (int, http.Header, string) { |
| + t.Helper() |
| + return rawReq(t, http.MethodPost, instancesURL(fx.consoleFixture, "bab", "titogo"), fx.token, body) |
| +} |
| + |
| +func TestHACreatePrefixObjects(t *testing.T) { |
| + objects := []struct{ key, body, class string }{ |
| + {"lock.json", `{"release":{"lifetime":"old-secret-lifetime"}}`, "lock"}, |
| + {"lock.json", "corrupt-secret-body", "lock"}, |
| + {"lock.json", `{"owner":"legacy-secret-owner"}`, "lock"}, |
| + {"files/0/manifest", "secret-body", "files"}, |
| + {"files/0/objects/secret-sha", "secret-sealed-body", "files"}, |
| + {"unknown-secret-key", "secret-body", "other"}, |
| + } |
| + for level := 0; level < 10; level++ { |
| + objects = append(objects, struct{ key, body, class string }{strings.TrimPrefix(ltxKey("x", level), "x/"), "secret-body", "replica"}) |
| + } |
| + for i, obj := range objects { |
| + t.Run(fmt.Sprintf("%d-%s", i, obj.class), func(t *testing.T) { |
| + fx := haCreateHome(t) |
| + const host = "acme.go.tito.io" |
| + prefix := activator.HibernatePrefix(fx.srv.cfg.HibernatePrefix, host) + "/" |
| + if _, err := fx.srv.cfg.SeedData.Put(context.Background(), prefix+obj.key, []byte(obj.body), ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + control, data := haCreateTrack(fx) |
| + code, _, out := haCreatePost(t, fx, leftoverDoors[0].body) |
| + want := fmt.Sprintf("%s still holds %s from a deleted instance. choose another address, or ask an operator to purge it.", host, obj.class) |
| + if code != 409 || errorText(out) != want { |
| + t.Fatalf("create = %d %s, want F2 %q", code, out, want) |
| + } |
| + for _, private := range []string{prefix, obj.key, obj.body, "secret-sha", "data-test"} { |
| + // The fixed class 'lock' is allowed; a complete key never is. |
| + if strings.Contains(out, private) { |
| + t.Errorf("private data %q in %s", private, out) |
| + } |
| + } |
| + haCreateNoWrites(t, control, data) |
| + _, pages := data.counts() |
| + if !reflect.DeepEqual(pages, []string{prefix + "||1"}) { |
| + t.Fatalf("bounded LISTs = %v", pages) |
| + } |
| + if fx.opens.Load() != 0 { |
| + t.Fatal("predecessor proof opened LTX reader") |
| + } |
| + }) |
| + } |
| + for _, sibling := range []string{"", "instances/acme.go.tito.io.extra/files/0/manifest"} { |
| + t.Run("empty-"+sibling, func(t *testing.T) { |
| + fx := haCreateHome(t) |
| + if sibling != "" { |
| + if _, err := fx.srv.cfg.SeedData.Put(context.Background(), sibling, []byte("secret"), ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + _, data := haCreateTrack(fx) |
| + code, _, out := haCreatePost(t, fx, leftoverDoors[0].body) |
| + if code != 201 { |
| + t.Fatalf("empty create = %d %s", code, out) |
| + } |
| + _, pages := data.counts() |
| + if len(pages) != 1 || fx.opens.Load() != 1 { |
| + t.Fatalf("pages=%v LTX opens=%d", pages, fx.opens.Load()) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestHACreateUninspectableRefusesBeforeWrites(t *testing.T) { |
| + for _, private := range []bool{false, true} { |
| + for _, mode := range []string{"remote", "pool", "missing-store", "missing-bucket", "mismatched-region", "no-bounded-list", "list-error"} { |
| + t.Run(fmt.Sprintf("private=%v/%s", private, mode), func(t *testing.T) { |
| + fx := haCreateHome(t) |
| + m := titoManifest() |
| + m.Pool = "" |
| + m.Regions = nil |
| + m.PrivateStorage = private |
| + if private { |
| + pub, _, _ := sealedFor(t, "irrelevant") |
| + fx.srv.cfg.SecretsPub = pub |
| + fx.srv.cfg.StoreProvisioner = objstore.NewMemProvisioner("eu-west-1") |
| + fx.srv.cfg.StoreDeployment = objstore.Deployment{Backend: "mem", Region: "eu-west-1", BucketPrefix: "carlos-"} |
| + approveStoreAccount(t, fx.consoleFixture, "operator@keymail.dev") |
| + } |
| + body := leftoverDoors[0].body |
| + switch mode { |
| + case "remote": |
| + fx.srv.cfg.HARegions = append(fx.srv.cfg.HARegions, "uk") |
| + body = `{"host":"acme.go.tito.io","region":"uk"}` |
| + case "pool": |
| + m.Pool = "tito" |
| + case "missing-store": |
| + fx.srv.cfg.SeedData = nil |
| + case "missing-bucket": |
| + fx.srv.cfg.HibernateBucket = "" |
| + case "mismatched-region": |
| + fx.srv.cfg.Region = "uk" |
| + case "no-bounded-list": |
| + fx.srv.cfg.SeedData = struct{ release.Store }{fx.srv.cfg.SeedData} |
| + } |
| + enableInstances(t, fx.consoleFixture, "titogo", m) |
| + control := &haCreateStore{Store: fx.srv.cfg.Releases} |
| + fx.srv.cfg.Releases = control |
| + data := &haCreateStore{Store: release.NewDirStore(t.TempDir())} |
| + if mode == "list-error" { |
| + data.pageErr = errors.New("secret-bucket/secret-key/secret-sha") |
| + fx.srv.cfg.SeedData = data |
| + } |
| + code, headers, out := haCreatePost(t, fx, body) |
| + status := 503 |
| + want := "could not check this instance's data in ie. nothing was created. try again. persistent failures may require an operator to check home data access." |
| + if mode == "remote" || mode == "pool" { |
| + status = 409 |
| + region := "ie" |
| + if mode == "remote" { |
| + region = "uk" |
| + } |
| + want = fmt.Sprintf("high availability data creation is not available yet in %s. use the console's home region without a pool.", region) |
| + } |
| + if code != status || errorText(out) != want { |
| + t.Fatalf("create = %d %s, want %d %q", code, out, status, want) |
| + } |
| + if headers.Get("Retry-After") != "" { |
| + t.Fatal("unexpected Retry-After") |
| + } |
| + haCreateNoWrites(t, control, data) |
| + if strings.Contains(out, "secret-") { |
| + t.Fatal("private error leaked") |
| + } |
| + if fx.opens.Load() != 0 { |
| + t.Fatal("uninspectable create opened replica") |
| + } |
| + }) |
| + } |
| + } |
| +} |
| + |
| +func TestHACreateDuplicatePrecedesReplica(t *testing.T) { |
| + for _, d := range leftoverDoors { |
| + for _, mode := range []string{"home", "remote", "pool", "read-error"} { |
| + t.Run(d.name+"/"+mode, func(t *testing.T) { |
| + fx := leftoverFixture(t, "code-ha-duplicate") |
| + if c, _, out := rawReq(t, http.MethodPost, d.url(fx.consoleFixture), fx.token, d.body); c != 201 { |
| + t.Fatalf("setup %d %s", c, out) |
| + } |
| + fx.srv.cfg.HomeRegion = "ie" |
| + fx.srv.cfg.HARegions = []string{"ie"} |
| + fx.srv.cfg.Region = "" |
| + im := titoManifest() |
| + im.Pool = "" |
| + im.Regions = nil |
| + enableInstances(t, fx.consoleFixture, "titogo", im) |
| + sm := titoSidecarManifest() |
| + sm.Pool = "" |
| + sm.Regions = nil |
| + enableSidecars(t, fx.consoleFixture, "titogo", sm) |
| + if mode == "remote" { |
| + fx.srv.cfg.HomeRegion = "uk" |
| + fx.srv.cfg.Region = "ie" |
| + } |
| + if mode == "pool" { |
| + m := titoManifest() |
| + m.Regions = nil |
| + enableInstances(t, fx.consoleFixture, "titogo", m) |
| + } |
| + control := &haCreateStore{Store: fx.srv.cfg.Releases} |
| + fx.srv.cfg.Releases = control |
| + if mode == "read-error" { |
| + control.failKey = d.recordKey() |
| + } |
| + data := &haCreateStore{Store: release.NewDirStore(t.TempDir()), pageErr: errors.New("must not list")} |
| + fx.srv.cfg.SeedData = data |
| + fx.opens.Store(0) |
| + c, _, out := rawReq(t, http.MethodPost, d.url(fx.consoleFixture), fx.token, d.body) |
| + want := "instance acme.go.tito.io already exists" |
| + if d.name == "sidecar" { |
| + want = "sidecar bot already exists" |
| + } |
| + status := 409 |
| + if mode == "read-error" { |
| + status = 502 |
| + want = "" |
| + } |
| + if c != status || (want != "" && errorText(out) != want) { |
| + t.Fatalf("retry = %d %s, want %d %q", c, out, status, want) |
| + } |
| + haCreateNoWrites(t, control, data) |
| + _, pages := data.counts() |
| + if len(pages) != 0 || fx.opens.Load() != 0 { |
| + t.Fatalf("retry inspected data: %v / %d", pages, fx.opens.Load()) |
| + } |
| + }) |
| + } |
| + } |
| +} |
| + |
| +func TestHACreateAddressBackedSkipsHADataProof(t *testing.T) { |
| + for _, mode := range []string{"home", "remote", "pool"} { |
| + t.Run(mode, func(t *testing.T) { |
| + fx := haCreateHome(t) |
| + if err := fx.st.SetOperator("alice@keymail.dev", true); err != nil { |
| + t.Fatal(err) |
| + } |
| + fx.srv.cfg.HARegions = append(fx.srv.cfg.HARegions, "uk") |
| + m := titoManifest() |
| + m.Pool = "" |
| + m.Regions = nil |
| + if mode == "pool" { |
| + m.Pool = "tito" |
| + } |
| + enableInstances(t, fx.consoleFixture, "titogo", m) |
| + region := "ie" |
| + if mode == "remote" { |
| + region = "uk" |
| + } |
| + data := &haCreateStore{Store: fx.srv.cfg.SeedData, pageErr: errors.New("must not inspect HA prefix")} |
| + fx.srv.cfg.SeedData = data |
| + code, _, out := haCreatePost(t, fx, fmt.Sprintf(`{"host":"acme.go.tito.io","region":%q,"addrs":["127.0.0.1:8401"]}`, region)) |
| + if code != 201 { |
| + t.Fatalf("addr create = %d %s", code, out) |
| + } |
| + rec, err := provision.GetRecord(context.Background(), fx.rel, "bab", "titogo", "acme.go.tito.io") |
| + if err != nil || !rec.HA { |
| + t.Fatalf("address stamp = %+v, %v", rec, err) |
| + } |
| + _, pages := data.counts() |
| + if len(pages) != 0 { |
| + t.Fatalf("address HA proof=%v", pages) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestHACreateShapeBeforeWrites(t *testing.T) { |
| + no := false |
| + for _, tc := range []struct { |
| + name string |
| + rec provision.Record |
| + blocked bool |
| + }{ |
| + {"binary", provision.Record{Region: "ie", Hibernate: &no}, true}, |
| + {"home-binary", provision.Record{Hibernate: &no}, true}, |
| + {"hibernating", provision.Record{Region: "ie"}, false}, |
| + {"legacy", provision.Record{Region: "uk", Hibernate: &no}, false}, |
| + {"static", provision.Record{Region: "ie", Kind: "static", Hibernate: &no}, false}, |
| + {"rootfs", provision.Record{Region: "ie", Runtime: provision.RuntimeRootfsV1, Hibernate: &no}, false}, |
| + {"addr", provision.Record{Region: "ie", Addr: "127.0.0.1:8401"}, false}, |
| + {"addrs", provision.Record{Region: "ie", Addrs: []string{"127.0.0.1:8401"}}, false}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + s := &Server{cfg: Config{HomeRegion: "ie", HARegions: []string{"ie"}}} |
| + ref := s.haCreateShapeRefusal(tc.rec) |
| + if !tc.blocked { |
| + if ref != nil { |
| + t.Fatalf("unexpected refusal: %+v", ref) |
| + } |
| + return |
| + } |
| + want := "ie has high availability turned on. binary socket instances must allow hibernation. resident rootfs instances are still allowed." |
| + if ref == nil || ref.Status != 400 || ref.Msg != want { |
| + t.Fatalf("shape refusal = %+v", ref) |
| + } |
| + }) |
| + } |
| + // The HTTP body has no Hibernate column. Pin the production call order |
| + // without introducing a member-writable operator column just for a test. |
| + raw, err := os.ReadFile("apiinstances.go") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + source := string(raw) |
| + start := strings.Index(source, "func (s *Server) handleAPIInstanceCreate(") |
| + source = source[start:] |
| + shape := strings.Index(source, "s.haCreateShapeRefusal(rec)") |
| + if shape < strings.Index(source, "provision.ValidateShape(rec)") { |
| + t.Fatal("F1 precedes validation or is absent") |
| + } |
| + for _, call := range []string{"s.environmentBindingRefusal(", "s.createFrom(", "s.createImport(", "s.bindEnvironmentCreate(", "s.beginClaimCreate(", "s.instanceStoreProvision("} { |
| + if next := strings.Index(source, call); next < 0 || shape > next { |
| + t.Fatalf("F1 absent or after %s", call) |
| + } |
| + } |
| +} |
| + |
| +func TestHACreateImportDispatch(t *testing.T) { |
| + f := newImportFixture(t) |
| + f.fx.srv.cfg.HomeRegion = "ie" |
| + f.fx.srv.cfg.HARegions = []string{"ie"} |
| + control := &haCreateStore{Store: f.fx.srv.cfg.Releases} |
| + f.fx.srv.cfg.Releases = control |
| + data := &haCreateStore{Store: f.fx.srv.cfg.SeedData, pageErr: errors.New("must not inspect seed data")} |
| + f.fx.srv.cfg.SeedData = data |
| + code, out := beginImport(t, f, importHost, importSHA, 10) |
| + if code != 409 || str(t, out, "error") != haImportC2 { |
| + t.Fatalf("hibernating import = %d %v", code, out) |
| + } |
| + haCreateNoWrites(t, control, data) |
| + _, pages := data.counts() |
| + if len(pages) != 0 { |
| + t.Fatalf("import inspected HA data %v", pages) |
| + } |
| + no := false |
| + ref := f.fx.srv.haCreateShapeRefusal(provision.Record{Hibernate: &no}) |
| + if ref == nil || ref.Status != 400 { |
| + t.Fatalf("non-hibernating import precedence = %+v", ref) |
| + } |
| +} |
| + |
| +func TestHACreateMoveStagingBudget(t *testing.T) { |
| + for level := -1; level < 10; level++ { |
| + t.Run(fmt.Sprint(level), func(t *testing.T) { |
| + fx := haCreateHome(t) |
| + var keys []string |
| + if level >= 0 { |
| + keys = []string{ltxKey("moves/acme.go.tito.io", level)} |
| + } |
| + bucket := useFakeDataBucket(t, fx.srv, keys...) |
| + control, data := haCreateTrack(fx) |
| + code, _, out := haCreatePost(t, fx, leftoverDoors[0].body) |
| + wantStatus := 201 |
| + if level >= 0 { |
| + wantStatus = 409 |
| + haCreateNoWrites(t, control, data) |
| + if errorText(out) != "acme.go.tito.io still holds replica from a deleted instance. choose another address, or ask an operator to purge it." { |
| + t.Fatal(out) |
| + } |
| + } |
| + if code != wantStatus { |
| + t.Fatalf("create = %d %s", code, out) |
| + } |
| + n := 10 |
| + if level >= 0 { |
| + n = level + 1 |
| + } |
| + var want []string |
| + for i := 0; i < n; i++ { |
| + want = append(want, fmt.Sprintf("moves/acme.go.tito.io/%04x/", i)) |
| + } |
| + if got := bucket.listed(); !reflect.DeepEqual(got, want) { |
| + t.Fatalf("LTX LISTs=%v want %v", got, want) |
| + } |
| + _, pages := data.counts() |
| + if !reflect.DeepEqual(pages, []string{"instances/acme.go.tito.io/||1"}) { |
| + t.Fatalf("prefix proof=%v", pages) |
| + } |
| + }) |
| + } |
| + for _, seam := range []string{"client", "list", "iterator"} { |
| + t.Run(seam, func(t *testing.T) { |
| + fx := haCreateHome(t) |
| + fx.srv.dbReplica = func(_ context.Context, p string) (replicaReader, error) { |
| + if p != "moves/acme.go.tito.io" { |
| + t.Errorf("unexpected replica prefix %q", p) |
| + } |
| + switch seam { |
| + case "client": |
| + return nil, errors.New("secret-bucket") |
| + case "list": |
| + return failingReplica{}, nil |
| + default: |
| + return pagingFailReplica{}, nil |
| + } |
| + } |
| + control, data := haCreateTrack(fx) |
| + code, _, out := haCreatePost(t, fx, leftoverDoors[0].body) |
| + if code != 503 || errorText(out) != "could not check this instance's data in ie. nothing was created. try again. persistent failures may require an operator to check home data access." { |
| + t.Fatalf("staging error=%d %s", code, out) |
| + } |
| + haCreateNoWrites(t, control, data) |
| + }) |
| + } |
| +} |
| + |
| +func TestHACreateLifetimesPrivateStorageRefusal(t *testing.T) { |
| + for _, on := range []bool{false, true} { |
| + for _, mode := range []string{"object", "remote", "pool", "missing-store", "list-error"} { |
| + t.Run(fmt.Sprintf("on=%v/%s", on, mode), func(t *testing.T) { |
| + clock := useLifetimesClock(t) |
| + f := newFromFixture(t, 0) |
| + if on { |
| + turnLifetimesOn(t, f.fx.srv, clock) |
| + } |
| + f.fx.srv.cfg.HomeRegion = "ie" |
| + f.fx.srv.cfg.HARegions = []string{"ie", "uk"} |
| + m := fromManifest(true) |
| + body := `{"host":"canary.shop.example.com"}` |
| + if mode == "pool" { |
| + m.Pool = "gold" |
| + } |
| + enableInstances(t, f.fx, "shop", m) |
| + if mode == "object" { |
| + if _, err := f.data.Put(context.Background(), "instances/"+fromHost+"/lock.json", []byte("secret-lock-body"), ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + if mode == "remote" { |
| + body = `{"host":"canary.shop.example.com","region":"uk"}` |
| + } |
| + control := &haCreateStore{Store: f.fx.srv.cfg.Releases} |
| + f.fx.srv.cfg.Releases = control |
| + data := &haCreateStore{Store: f.data} |
| + f.fx.srv.cfg.SeedData = data |
| + if mode == "missing-store" { |
| + f.fx.srv.cfg.SeedData = nil |
| + } |
| + if mode == "list-error" { |
| + data.pageErr = errors.New("secret-bucket") |
| + } |
| + buckets, users := len(f.fake.Buckets), len(f.fake.Users) |
| + before := bucketState(t, f.fx.rel) |
| + code, _, out := rawReq(t, http.MethodPost, f.url, f.token, body) |
| + status := 409 |
| + if mode == "missing-store" || mode == "list-error" { |
| + status = 503 |
| + } |
| + if code != status { |
| + t.Fatalf("private lifetime refusal=%d %s", code, out) |
| + } |
| + haCreateNoWrites(t, control, data) |
| + if !reflect.DeepEqual(bucketState(t, f.fx.rel), before) { |
| + t.Fatal("refused request changed control bucket") |
| + } |
| + if len(f.fake.Buckets) != buckets || len(f.fake.Users) != users { |
| + t.Fatal("refusal provisioned private storage") |
| + } |
| + }) |
| + } |
| + } |
| +} |
| + |
| +// haEmptyHomeData provides coherent home-bucket authority for plain creates. |
| +func haEmptyHomeData(t *testing.T, s *Server) { |
| + t.Helper() |
| + s.cfg.HomeRegion = "ie" |
| + s.cfg.Region = "" |
| + s.cfg.HibernateBucket = "data-test" |
| + s.cfg.SeedData = release.NewDirStore(t.TempDir()) |
| + root := t.TempDir() |
| + s.dbReplica = func(_ context.Context, p string) (replicaReader, error) { |
| + return lsfile.NewReplicaClient(filepath.Join(root, p)), nil |
| + } |
| +} |
| + |
| +// Exercise the real PageLister, including a truncated result: there is no |
| +// paginator, body GET or unbounded fallback behind this proof. |
| +func TestHACreateBoundedS3Proof(t *testing.T) { |
| + for _, mode := range []string{"empty", "object", "error"} { |
| + t.Run(mode, func(t *testing.T) { |
| + var mu sync.Mutex |
| + attempts := 0 |
| + endpoint := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + mu.Lock() |
| + attempts++ |
| + mu.Unlock() |
| + q := r.URL.Query() |
| + if r.Method != "GET" || q.Get("list-type") != "2" || q.Get("prefix") != "custom/shop.example.com/" || q.Get("max-keys") != "1" || q.Get("start-after") != "" || q.Get("continuation-token") != "" { |
| + t.Errorf("unexpected data request: %s %s", r.Method, r.URL.String()) |
| + } |
| + w.Header().Set("Content-Type", "application/xml") |
| + if mode == "error" { |
| + w.WriteHeader(400) |
| + fmt.Fprint(w, "<Error><Code>AccessDenied</Code><Message>secret-bucket</Message></Error>") |
| + return |
| + } |
| + if mode == "empty" { |
| + fmt.Fprint(w, "<ListBucketResult><KeyCount>0</KeyCount><IsTruncated>false</IsTruncated></ListBucketResult>") |
| + return |
| + } |
| + fmt.Fprint(w, "<ListBucketResult><KeyCount>1</KeyCount><IsTruncated>true</IsTruncated><NextContinuationToken>secret-token</NextContinuationToken><Contents><Key>custom/shop.example.com/lock.json</Key></Contents></ListBucketResult>") |
| + })) |
| + defer endpoint.Close() |
| + t.Setenv("CARLOS_S3_ENDPOINT", endpoint.URL) |
| + t.Setenv("AWS_ACCESS_KEY_ID", "test-key") |
| + t.Setenv("AWS_SECRET_ACCESS_KEY", "test-secret") |
| + t.Setenv("AWS_SESSION_TOKEN", "") |
| + t.Setenv("AWS_EC2_METADATA_DISABLED", "true") |
| + st, err := release.NewS3StoreIn(context.Background(), "secret-bucket", "us-east-1") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + class, err := firstHALeftover(context.Background(), st, "custom/shop.example.com/") |
| + want := "" |
| + if mode == "object" { |
| + want = "lock" |
| + } |
| + if (err != nil) != (mode == "error") || class != want { |
| + t.Fatalf("proof = %q, %v", class, err) |
| + } |
| + mu.Lock() |
| + n := attempts |
| + mu.Unlock() |
| + if n != 1 { |
| + t.Fatalf("proof made %d attempts, want 1", n) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// A browser asking the API for HTML still receives only the safe JSON |
| +// refusal; no object names or contents can enter a browser error page. |
| +func TestHACreateHTMLPrivacy(t *testing.T) { |
| + fx := haCreateHome(t) |
| + if _, err := fx.srv.cfg.SeedData.Put(context.Background(), "instances/acme.go.tito.io/files/0/secret-sha", []byte("secret-body"), ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + req, err := http.NewRequest("POST", instancesURL(fx.consoleFixture, "bab", "titogo"), strings.NewReader(leftoverDoors[0].body)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + req.Header.Set("Authorization", "Bearer "+fx.token) |
| + req.Header.Set("Accept", "text/html") |
| + req.Header.Set("Content-Type", "application/json") |
| + resp, err := http.DefaultClient.Do(req) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer resp.Body.Close() |
| + raw, err := io.ReadAll(resp.Body) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if resp.StatusCode != 409 || !strings.Contains(string(raw), "still holds files") { |
| + t.Fatalf("HTML accept = %d %s", resp.StatusCode, raw) |
| + } |
| + for _, secret := range []string{"secret-sha", "secret-body", "instances/", "data-test"} { |
| + if strings.Contains(string(raw), secret) { |
| + t.Fatalf("browser response leaked %q", secret) |
| + } |
| + } |
| +} |
| + |
| +// The rail's one existence read must precede both the F5 cut and data access. |
| +func TestHACreateExistenceReadBudget(t *testing.T) { |
| + for _, region := range []string{"", "uk"} { |
| + for _, result := range []string{"duplicate", "read-error"} { |
| + t.Run(region+"/"+result, func(t *testing.T) { |
| + s := &Server{cfg: Config{HomeRegion: "ie"}} |
| + reads := 0 |
| + c := leftoverCreate{HAData: true, host: "shop.example.com", region: region, |
| + duplicate: doorRefusal{409, "duplicate"}, readFailed: doorRefusal{502, "read failure"}, |
| + exists: func(context.Context) (bool, error) { |
| + reads++ |
| + if result == "read-error" { |
| + return false, errors.New("secret-bucket") |
| + } |
| + return true, nil |
| + }, |
| + } |
| + ref := s.leftoverReplicaRefusal(context.Background(), c) |
| + want := c.duplicate |
| + if result == "read-error" { |
| + want = c.readFailed |
| + } |
| + if reads != 1 || ref == nil || *ref != want { |
| + t.Fatalf("existence reads=%d refusal=%+v want %+v", reads, ref, want) |
| + } |
| + }) |
| + } |
| + } |
| +} |