Accept a create conflict only for this app's own instance
Platform answers 409 both for an instance that already exists and for a host that collides with another app's reserved name. On 409 Base now reads the record at that host under the app and accepts it only when its app, host and environment match; anything else is an install failure (R27).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
3 files changed,
+104
−18
internal/platform/client.go+3 −1internal/platform/http.go+41 −16internal/platform/http_test.go+60 −1
diff --git a/internal/platform/client.go b/internal/platform/client.go| index 7071bf3..1f37f22 100644 |
| --- a/internal/platform/client.go |
| +++ b/internal/platform/client.go |
| @@ -8,7 +8,9 @@ type Client interface { |
| // SetEnv sets plain environment variables in an app's config environment. |
| SetEnv(ctx context.Context, app, environment string, vars map[string]string) error |
| // CreateInstance creates an instance of app at host, bound to the config |
| - // environment. An instance that already exists (409) counts as success. |
| + // environment. An instance of app already at host and bound to the same |
| + // environment (Platform's 409, then a matching record) counts as |
| + // success; any other conflict is an error. |
| CreateInstance(ctx context.Context, app, host, environment string) error |
| // DeleteInstance retires the instance's route. Its data is kept. |
| DeleteInstance(ctx context.Context, app, host string) error |
diff --git a/internal/platform/http.go b/internal/platform/http.go| index bead839..ce4a539 100644 |
| --- a/internal/platform/http.go |
| +++ b/internal/platform/http.go |
| @@ -32,20 +32,21 @@ func (c *httpClient) appURL(app, rest string) string { |
| return c.console + "/api/cli/apps/" + url.PathEscape(c.account) + "/" + url.PathEscape(app) + rest |
| } |
| -// do sends one request. Errors name the call and the status only: a response |
| -// body can echo secrets. |
| -func (c *httpClient) do(ctx context.Context, call, method, u, token, message string, body any, okStatus ...int) error { |
| +// do sends one request and answers its status, nil for any 2xx. Errors name |
| +// the call and the status only: a response body can echo secrets. When out |
| +// is not nil, a 2xx body (at most 1 MiB) is decoded into it. |
| +func (c *httpClient) do(ctx context.Context, call, method, u, token, message string, body, out any) (int, error) { |
| var rd io.Reader |
| if body != nil { |
| b, err := json.Marshal(body) |
| if err != nil { |
| - return fmt.Errorf("platform %s: %w", call, err) |
| + return 0, fmt.Errorf("platform %s: %w", call, err) |
| } |
| rd = bytes.NewReader(b) |
| } |
| req, err := http.NewRequestWithContext(ctx, method, u, rd) |
| if err != nil { |
| - return fmt.Errorf("platform %s: bad request", call) |
| + return 0, fmt.Errorf("platform %s: bad request", call) |
| } |
| req.Header.Set("Authorization", "Bearer "+token) |
| if body != nil { |
| @@ -60,19 +61,22 @@ func (c *httpClient) do(ctx context.Context, call, method, u, token, message str |
| if ue, ok := err.(*url.Error); ok { |
| err = ue.Err |
| } |
| - return fmt.Errorf("platform %s: %w", call, err) |
| + return 0, fmt.Errorf("platform %s: %w", call, err) |
| } |
| defer resp.Body.Close() |
| - io.Copy(io.Discard, io.LimitReader(resp.Body, 1<<20)) |
| - if resp.StatusCode/100 == 2 { |
| - return nil |
| + raw, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) |
| + if resp.StatusCode/100 != 2 { |
| + return resp.StatusCode, fmt.Errorf("platform %s: status %d", call, resp.StatusCode) |
| } |
| - for _, s := range okStatus { |
| - if resp.StatusCode == s { |
| - return nil |
| + if out != nil { |
| + if err != nil { |
| + return resp.StatusCode, fmt.Errorf("platform %s: reading the answer: %w", call, err) |
| + } |
| + if json.Unmarshal(raw, out) != nil { |
| + return resp.StatusCode, fmt.Errorf("platform %s: the answer is not the expected JSON", call) |
| } |
| } |
| - return fmt.Errorf("platform %s: status %d", call, resp.StatusCode) |
| + return resp.StatusCode, nil |
| } |
| type envVar struct { |
| @@ -90,18 +94,39 @@ func (c *httpClient) SetEnv(ctx context.Context, app, environment string, vars m |
| Message string `json:"message"` |
| Set map[string]envVar `json:"set"` |
| }{environment, "Base: install", set} |
| - return c.do(ctx, "SetEnv", http.MethodPut, c.appURL(app, "/config"), c.opToken, "", body) |
| + _, err := c.do(ctx, "SetEnv", http.MethodPut, c.appURL(app, "/config"), c.opToken, "", body, nil) |
| + return err |
| } |
| +// CreateInstance treats 409 as success only when the record already at host |
| +// is this app's, bound to environment: Platform also answers 409 when host |
| +// collides with another app's reserved name, and that is not an install. |
| func (c *httpClient) CreateInstance(ctx context.Context, app, host, environment string) error { |
| body := struct { |
| Host string `json:"host"` |
| Environment string `json:"environment"` |
| Message string `json:"message"` |
| }{host, environment, "Base: install"} |
| - return c.do(ctx, "CreateInstance", http.MethodPost, c.appURL(app, "/instances"), c.instanceToken, "", body, http.StatusConflict) |
| + status, err := c.do(ctx, "CreateInstance", http.MethodPost, c.appURL(app, "/instances"), c.instanceToken, "", body, nil) |
| + if status != http.StatusConflict { |
| + return err |
| + } |
| + var rec struct { |
| + App string `json:"app"` |
| + Host string `json:"host"` |
| + Environment string `json:"environment"` |
| + } |
| + if _, err := c.do(ctx, "CreateInstance (reading the existing instance)", http.MethodGet, |
| + c.appURL(app, "/instances/"+url.PathEscape(host)), c.instanceToken, "", nil, &rec); err != nil { |
| + return fmt.Errorf("platform CreateInstance: status 409, and %w", err) |
| + } |
| + if rec.App != app || rec.Host != host || rec.Environment != environment { |
| + return fmt.Errorf("platform CreateInstance: status 409: %s is taken by another instance", host) |
| + } |
| + return nil |
| } |
| func (c *httpClient) DeleteInstance(ctx context.Context, app, host string) error { |
| - return c.do(ctx, "DeleteInstance", http.MethodDelete, c.appURL(app, "/instances/"+url.PathEscape(host)), c.instanceToken, "Base: uninstall", nil) |
| + _, err := c.do(ctx, "DeleteInstance", http.MethodDelete, c.appURL(app, "/instances/"+url.PathEscape(host)), c.instanceToken, "Base: uninstall", nil, nil) |
| + return err |
| } |
diff --git a/internal/platform/http_test.go b/internal/platform/http_test.go| index f95d691..a889a5b 100644 |
| --- a/internal/platform/http_test.go |
| +++ b/internal/platform/http_test.go |
| @@ -53,7 +53,7 @@ func TestSetEnvShape(t *testing.T) { |
| } |
| func TestCreateInstanceShape(t *testing.T) { |
| - for _, status := range []int{201, 409} { |
| + for _, status := range []int{200, 201} { |
| ts, s := server(t, status, `{}`) |
| c := NewHTTP(ts.URL, "acct1", "inst-tok", "op-tok", ts.Client()) |
| if err := c.CreateInstance(context.Background(), "scratchpad", "b-scratchpad.example.com", "b-scratchpad"); err != nil { |
| @@ -124,3 +124,62 @@ func TestFakeRecordsAndFails(t *testing.T) { |
| t.Fatalf("args %+v", calls) |
| } |
| } |
| + |
| +// conflictServer answers the create with 409 and the record read with |
| +// status and body, and remembers the read's path and credential. |
| +func conflictServer(t *testing.T, status int, body string) (*httptest.Server, *seen) { |
| + t.Helper() |
| + read := &seen{} |
| + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + if r.Method == http.MethodPost { |
| + w.WriteHeader(http.StatusConflict) |
| + io.WriteString(w, `{"error":"instance already exists"}`) |
| + return |
| + } |
| + read.method, read.path, read.auth = r.Method, r.URL.Path, r.Header.Get("Authorization") |
| + w.WriteHeader(status) |
| + io.WriteString(w, body) |
| + })) |
| + t.Cleanup(ts.Close) |
| + return ts, read |
| +} |
| + |
| +// Finding 3 (R27): a 409 is success only when the existing record is this |
| +// app's instance at this host, bound to this environment. |
| +func TestCreateInstanceConflictMatchingRecord(t *testing.T) { |
| + ts, read := conflictServer(t, 200, `{"schema":1,"host":"b-scratchpad.example.com","app":"scratchpad","account":"acct1","environment":"b-scratchpad","gated":false}`) |
| + c := NewHTTP(ts.URL, "acct1", "inst-tok", "op-tok", ts.Client()) |
| + if err := c.CreateInstance(context.Background(), "scratchpad", "b-scratchpad.example.com", "b-scratchpad"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if read.method != "GET" || read.path != "/api/cli/apps/acct1/scratchpad/instances/b-scratchpad.example.com" || read.auth != "Bearer inst-tok" { |
| + t.Fatalf("record read %+v", read) |
| + } |
| +} |
| + |
| +func TestCreateInstanceConflictOtherRecord(t *testing.T) { |
| + for name, tc := range map[string]struct { |
| + status int |
| + body string |
| + }{ |
| + "no record for this app": {404, `404 page not found`}, |
| + "another app's record": {200, `{"host":"b-scratchpad.example.com","app":"welcome","environment":"b-scratchpad"}`}, |
| + "another environment": {200, `{"host":"b-scratchpad.example.com","app":"scratchpad","environment":"other"}`}, |
| + "no environment": {200, `{"host":"b-scratchpad.example.com","app":"scratchpad"}`}, |
| + "another host": {200, `{"host":"x.example.com","app":"scratchpad","environment":"b-scratchpad"}`}, |
| + "unreadable record": {200, `not json`}, |
| + "record read fails": {502, `{"error":"SECRET"}`}, |
| + } { |
| + t.Run(name, func(t *testing.T) { |
| + ts, _ := conflictServer(t, tc.status, tc.body) |
| + c := NewHTTP(ts.URL, "acct1", "inst-tok", "op-tok", ts.Client()) |
| + err := c.CreateInstance(context.Background(), "scratchpad", "b-scratchpad.example.com", "b-scratchpad") |
| + if err == nil { |
| + t.Fatal("a conflict with another record counted as success") |
| + } |
| + if !strings.Contains(err.Error(), "CreateInstance") || strings.Contains(err.Error(), "SECRET") { |
| + t.Errorf("error %q", err) |
| + } |
| + }) |
| + } |
| +} |