Repository navigation
Add opt-in conflict checks before body replacements #1020
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
robzolkos
wants to merge
2
commits into
main
Choose a base branch
from
cli-cleanup/body-guard-10292437212
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 1 commit
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,43 @@ | ||
| # Opt-in conflict checks for replacements | ||
|
|
||
| Fetch the record before preparing an edit. Keep the `updated_at` from the representation actually used, then pass it unchanged as `--if-unmodified-since <updated_at>` to the typed command. Do not fetch a new timestamp merely to make an old replacement pass. | ||
|
|
||
| ```sh | ||
| basecamp comments show 789 --json | ||
| basecamp comments update 789 - --if-unmodified-since '2026-11-08T18:10:58.123Z' --json < revised.md | ||
| ``` | ||
|
|
||
| The baseline is optional. **Without it, including the first write from this CLI, current unprotected behavior is unchanged.** There is no automatic first-use protection, remembered read version, or local ledger. | ||
|
|
||
| With a baseline the CLI performs a server-revalidated GET and requires equal parsed timestamp instants, not equal text spellings. Equivalent UTC offsets compare equal; different fractional seconds or a future baseline do not. Equality is deliberately conservative: an unrelated field change can also refuse a body edit. Invalid/zero input, missing/zero/unparseable live timestamps, and failed reads refuse without uploading attachments or mutating the target. `--force` overrides only a version mismatch; it does not waive invalid input or unavailable live state. `--force` requires a baseline. | ||
|
|
||
| Re-fetch and reconcile on conflict. Only deliberately use `--force` with the supplied baseline when you intend to overwrite intervening changes. A creator is not necessarily the latest editor; the CLI does not invent an editor identity. | ||
|
|
||
| ## Exact command coverage | ||
|
|
||
| These commands accept the opt-in, **whole-record** version check, including their non-body edits. Guard flags on a title-only edit therefore check that record's version rather than being ignored: | ||
|
|
||
| - `comments update` | ||
| - `messages update` | ||
| - `todos update` (description changes/clears and every other update through this command) | ||
| - `cards update` (including attachment-only replacements) | ||
| - `todolists update` | ||
| - `schedule update` (including attachment-only updates) | ||
| - `checkins answer update` | ||
| - `chat update` (including a Ping line addressed through this command) | ||
| - `files update` (document/upload/vault, explicit type or autodetection, including title-only document writes and explicit clears) | ||
| - `files replace` (including description replacements/clears and file-only replacements) | ||
| - `doors update` (including description replacements/clears) | ||
| - `projects update` | ||
| - `templates update` | ||
| - `notes set` (an unwritten note has no version and refuses a supplied baseline) | ||
| - `gauges update` | ||
| - `timesheet entry update` | ||
|
|
||
| The guard is **not global middleware**. Raw `api put`, MCP/TUI and SDK callers, creation commands, other commands that carry a preserved body (for example to-do assignment operations), and other update verbs do not gain protection. **Boost editing is explicitly excluded from this first opt-in safeguard.** `boost update` continues to replace content without this protection and does not accept these guard flags. SDK go/v0.35.0 exposes only `created_at`, not `updated_at`, on Boost; the API representation likewise omits `updated_at`. An ETag is a different baseline contract and is not substituted here. Do not substitute creation time or a parent recording's timestamp. Boost editing is unchanged; adding its version support is separate work. Never treat unguarded paths as protected merely because a guarded typed command exists. Use guarded typed commands for body edits rather than bypassing them with raw API writes. | ||
|
|
||
| ## Limits | ||
|
|
||
| The timestamp is an API-supplied record version signal, not a cryptographic or necessarily unique per-edit token. SDK HTTP cache hits still contact the server for validation; they do not supply an acknowledged caller baseline. | ||
|
|
||
| **GET then PUT is not atomic.** An edit after the guard's GET can still be overwritten. Some SDK composite updates (notably to-dos and documents) perform another GET and send the full writable representation; this neither removes the race nor protects other command paths automatically. No conditional-write support or server changes are implied by the flag name. Ledger, append mode, default protection and server atomicity are separate features, not part of this change. | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,54 @@ | ||
| package commands | ||
|
|
||
| import ( | ||
| "fmt" | ||
| "time" | ||
|
|
||
| "github.com/spf13/cobra" | ||
|
|
||
| "github.com/basecamp/basecamp-cli/internal/output" | ||
| ) | ||
|
|
||
| // The timestamp belongs to the record the caller used to prepare the replacement, | ||
| // not a fresh read performed merely to make an old body pass. | ||
| func addBodyGuardFlags(cmd *cobra.Command) { | ||
| cmd.Flags().String("if-unmodified-since", "", "Require the record's last-seen updated_at (RFC3339); no baseline means no conflict protection") | ||
| cmd.Flags().Bool("force", false, "Override a version conflict with --if-unmodified-since (not invalid or missing timestamps)") | ||
| cmd.Long += "\n\nOptional conflict guard: pass the updated_at from the record used to prepare your edit\nwith --if-unmodified-since. This checks the whole record, including non-body edits\nthrough this command. A different live timestamp refuses before uploads or writes;\n--force explicitly overrides a conflict. Invalid or missing timestamps still refuse.\nWithout a baseline, including first use, writes remain unprotected. The live GET is\nserver-revalidated, but GET then PUT is not atomic: edits in between can still be lost." | ||
| run := cmd.RunE | ||
| cmd.RunE = func(cmd *cobra.Command, args []string) error { | ||
| if cmd.Flags().Changed("if-unmodified-since") { | ||
| value, _ := cmd.Flags().GetString("if-unmodified-since") | ||
| baseline, err := time.Parse(time.RFC3339Nano, value) | ||
| if err != nil || baseline.IsZero() { | ||
| return output.ErrUsage("--if-unmodified-since requires a nonzero RFC3339 updated_at timestamp") | ||
| } | ||
| } else if cmd.Flags().Changed("force") { | ||
| return output.ErrUsage("--force requires --if-unmodified-since; without a baseline updates are already unprotected") | ||
| } | ||
| return run(cmd, args) | ||
| } | ||
| } | ||
|
|
||
| func checkBodyUpdate(cmd *cobra.Command, fetch func() (time.Time, error)) error { | ||
| if !cmd.Flags().Changed("if-unmodified-since") { | ||
| return nil | ||
| } | ||
| value, _ := cmd.Flags().GetString("if-unmodified-since") | ||
| baseline, err := time.Parse(time.RFC3339Nano, value) | ||
| if err != nil || baseline.IsZero() { | ||
| return output.ErrUsage("--if-unmodified-since requires a nonzero RFC3339 updated_at timestamp") | ||
| } | ||
| live, err := fetch() | ||
| if err != nil { | ||
| return convertSDKError(err) | ||
| } | ||
| if live.IsZero() { | ||
| return fmt.Errorf("cannot verify updated_at: live timestamp is missing; refusing update") | ||
| } | ||
| force, _ := cmd.Flags().GetBool("force") | ||
| if !live.Equal(baseline) && !force { | ||
| return fmt.Errorf("update conflict: live updated_at %s differs from your last read %s; re-fetch and reconcile, or pass --force to overwrite (GET then PUT is not atomic)", live.Format(time.RFC3339Nano), baseline.Format(time.RFC3339Nano)) | ||
| } | ||
| return nil | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,226 @@ | ||
| package commands | ||
|
|
||
| import ( | ||
| "fmt" | ||
| "io" | ||
| "net/http" | ||
| "strings" | ||
| "testing" | ||
|
|
||
| "github.com/spf13/cobra" | ||
| "github.com/stretchr/testify/require" | ||
| ) | ||
|
|
||
| type bodyGuardTransport struct { | ||
| live string | ||
| writes int | ||
| gets int | ||
| getStatus int | ||
| detectedType string | ||
| paths []string | ||
| } | ||
|
|
||
| func (tr *bodyGuardTransport) RoundTrip(r *http.Request) (*http.Response, error) { | ||
| if r.Method != http.MethodGet { | ||
| tr.writes++ | ||
| } else { | ||
| tr.gets++ | ||
| } | ||
| status := http.StatusOK | ||
| if r.Method == http.MethodGet { | ||
| tr.paths = append(tr.paths, r.URL.Path) | ||
| if tr.getStatus != 0 { | ||
| status = tr.getStatus | ||
| } else if tr.detectedType != "" { | ||
| if strings.Contains(r.URL.Path, "/documents/") || (tr.detectedType == "upload" && strings.Contains(r.URL.Path, "/vaults/")) { | ||
| status = http.StatusNotFound | ||
| } | ||
| } | ||
| } | ||
| body := fmt.Sprintf(`{"id":789,"name":"Synthetic","title":"Synthetic","subject":"Synthetic","content":"preserved human body","description":"preserved human body","updated_at":%s,"completion_subscribers":[],"assignees":[]}`, tr.live) | ||
| return &http.Response{StatusCode: status, Header: http.Header{"Content-Type": []string{"application/json"}}, Body: io.NopCloser(strings.NewReader(body)), Request: r}, nil | ||
| } | ||
|
|
||
| func bodyGuardCommands() []struct { | ||
| name string | ||
| newCmd func() *cobra.Command | ||
| args []string | ||
| } { | ||
| project, room, contentType := "123", "456", "text/plain" | ||
| return []struct { | ||
| name string | ||
| newCmd func() *cobra.Command | ||
| args []string | ||
| }{ | ||
| {"comments", newCommentsUpdateCmd, []string{"789", "replacement "}}, | ||
| {"messages", newMessagesUpdateCmd, []string{"789", "--body", "replacement "}}, | ||
| {"todos", newTodosUpdateCmd, []string{"789", "--description", "replacement "}}, | ||
| {"cards", newCardsUpdateCmd, []string{"789", "--body", "replacement "}}, | ||
| {"todolists", func() *cobra.Command { return newTodolistsUpdateCmd(&project) }, []string{"789", "--description", "replacement"}}, | ||
| {"schedule", func() *cobra.Command { return newScheduleUpdateCmd(&project) }, []string{"789", "--description", "replacement "}}, | ||
| {"answers", func() *cobra.Command { return newCheckinsAnswerUpdateCmd(&project) }, []string{"789", "replacement "}}, | ||
| {"chat", func() *cobra.Command { return newChatLineUpdateCmd(&project, &room, &contentType) }, []string{"789", "replacement"}}, | ||
| {"files", func() *cobra.Command { return newFilesUpdateCmd(&project) }, []string{"789", "--type", "document", "--content", "replacement "}}, | ||
| {"projects", newProjectsUpdateCmd, []string{"789", "--description", "replacement"}}, | ||
| {"templates", newTemplatesUpdateCmd, []string{"789", "--description", "replacement"}}, | ||
| {"gauges", newGaugesUpdateCmd, []string{"789", "--description", "replacement"}}, | ||
| {"timesheet", newTimesheetEntryUpdateCmd, []string{"789", "--description", "replacement"}}, | ||
| {"notes", newNotesSetCmd, []string{"replacement"}}, | ||
| {"files autodetect", func() *cobra.Command { return newFilesUpdateCmd(&project) }, []string{"789", "--content", "replacement"}}, | ||
| {"files upload", func() *cobra.Command { return newFilesUpdateCmd(&project) }, []string{"789", "--type", "upload", "--content", "replacement"}}, | ||
| {"files vault nonbody", func() *cobra.Command { return newFilesUpdateCmd(&project) }, []string{"789", "--type", "vault", "--title", "replacement"}}, | ||
| {"doors", func() *cobra.Command { return newDoorsUpdateCmd(&project) }, []string{"789", "--description", "replacement"}}, | ||
| {"doors clear", func() *cobra.Command { return newDoorsUpdateCmd(&project) }, []string{"789", "--description", ""}}, | ||
| {"files replace", func() *cobra.Command { return newFilesReplaceCmd(&project) }, []string{"789", "../../go.mod", "--description", "replacement "}}, | ||
| {"files replace clear", func() *cobra.Command { return newFilesReplaceCmd(&project) }, []string{"789", "../../go.mod", "--description", ""}}, | ||
| {"files replace attachment only", func() *cobra.Command { return newFilesReplaceCmd(&project) }, []string{"789", "../../go.mod"}}, | ||
| {"cards attachment only", newCardsUpdateCmd, []string{"789", "--attach", "../../go.mod"}}, | ||
| {"schedule attachment only", func() *cobra.Command { return newScheduleUpdateCmd(&project) }, []string{"789", "--attach", "../../go.mod"}}, | ||
| {"todos clear", newTodosUpdateCmd, []string{"789", "--description", ""}}, | ||
| {"files document clear", func() *cobra.Command { return newFilesUpdateCmd(&project) }, []string{"789", "--type", "document", "--content", ""}}, | ||
| {"todo nonbody full record", newTodosUpdateCmd, []string{"789", "--title", "replacement"}}, | ||
| } | ||
| } | ||
|
|
||
| func TestBodyGuardRefusesBeforeUploadsAndMutations(t *testing.T) { | ||
| for _, tc := range bodyGuardCommands() { | ||
| t.Run(tc.name, func(t *testing.T) { | ||
| tr := &bodyGuardTransport{live: `"2026-11-08T18:10:58Z"`} | ||
| app, _ := newTestAppWithTransport(t, tr) | ||
| err := executeCommand(tc.newCmd(), app, append(tc.args, "--if-unmodified-since", "2026-11-08T18:00:00Z")...) | ||
| require.Error(t, err) | ||
| require.Contains(t, err.Error(), "conflict") | ||
| require.Zero(t, tr.writes) | ||
| require.Positive(t, tr.gets) | ||
| }) | ||
| } | ||
| } | ||
|
|
||
| func TestBodyGuardTimestampFailures(t *testing.T) { | ||
| for _, live := range []string{`null`, `"0001-01-01T00:00:00Z"`, `"invalid"`} { | ||
| t.Run(live, func(t *testing.T) { | ||
| tr := &bodyGuardTransport{live: live} | ||
| app, _ := newTestAppWithTransport(t, tr) | ||
| err := executeCommand(newCommentsUpdateCmd(), app, "789", "replacement", "--if-unmodified-since", "2026-11-08T18:00:00Z") | ||
| require.Error(t, err) | ||
| require.Zero(t, tr.writes) | ||
| }) | ||
| } | ||
| for _, tc := range []struct { | ||
| name string | ||
| value string | ||
| flags []string | ||
| }{ | ||
| {"missing even with force", `null`, []string{"--force"}}, | ||
| {"future is not equality", `"2026-11-08T18:00:00Z"`, nil}, | ||
| {"different nanoseconds", `"2026-11-08T18:10:58.000000001Z"`, nil}, | ||
| } { | ||
| t.Run(tc.name, func(t *testing.T) { | ||
| tr := &bodyGuardTransport{live: tc.value} | ||
| app, _ := newTestAppWithTransport(t, tr) | ||
| args := append([]string{"789", "replacement", "--if-unmodified-since", "2026-11-08T18:10:58Z"}, tc.flags...) | ||
| err := executeCommand(newCommentsUpdateCmd(), app, args...) | ||
| require.Error(t, err) | ||
| require.Zero(t, tr.writes) | ||
| }) | ||
| } | ||
| for _, tc := range bodyGuardCommands() { | ||
| t.Run(tc.name, func(t *testing.T) { | ||
| tr := &bodyGuardTransport{live: `"2026-11-08T18:00:00Z"`} | ||
| app, _ := newTestAppWithTransport(t, tr) | ||
| err := executeCommand(tc.newCmd(), app, append(tc.args, "--if-unmodified-since", "invalid", "--force")...) | ||
| require.Error(t, err) | ||
| require.Contains(t, err.Error(), "RFC3339") | ||
| require.Zero(t, tr.writes) | ||
| require.Zero(t, tr.gets) | ||
| }) | ||
| } | ||
| } | ||
|
|
||
| func TestBodyGuardUnavailableLiveState(t *testing.T) { | ||
| for _, tc := range bodyGuardCommands() { | ||
| for _, state := range []struct { | ||
| name, live string | ||
| status int | ||
| }{ | ||
| {"missing", `null`, 0}, | ||
| {"zero", `"0001-01-01T00:00:00Z"`, 0}, | ||
| {"malformed", `"invalid"`, 0}, | ||
| {"failed GET", `"2026-11-08T18:00:00Z"`, http.StatusForbidden}, | ||
| } { | ||
| for _, force := range []bool{false, true} { | ||
| t.Run(fmt.Sprintf("%s/%s/force=%t", tc.name, state.name, force), func(t *testing.T) { | ||
| tr := &bodyGuardTransport{live: state.live, getStatus: state.status} | ||
| app, _ := newTestAppWithTransport(t, tr) | ||
| args := append(append([]string{}, tc.args...), "--if-unmodified-since", "2026-11-08T18:00:00Z") | ||
| if force { | ||
| args = append(args, "--force") | ||
| } | ||
| err := executeCommand(tc.newCmd(), app, args...) | ||
| require.Error(t, err) | ||
| require.Zero(t, tr.writes) | ||
| require.Positive(t, tr.gets) | ||
| }) | ||
| } | ||
| } | ||
| } | ||
| } | ||
|
|
||
| func TestBodyGuardFilesAutodetection(t *testing.T) { | ||
| project := "123" | ||
| for _, kind := range []string{"vault", "upload"} { | ||
| for _, force := range []bool{false, true} { | ||
| t.Run(fmt.Sprintf("%s/force=%t", kind, force), func(t *testing.T) { | ||
| tr := &bodyGuardTransport{live: `"2026-11-08T18:10:58Z"`, detectedType: kind} | ||
| app, _ := newTestAppWithTransport(t, tr) | ||
| args := []string{"789", "--title", "replacement", "--if-unmodified-since", "2026-11-08T18:00:00Z"} | ||
| if force { | ||
| args = append(args, "--force") | ||
| } | ||
| err := executeCommand(newFilesUpdateCmd(&project), app, args...) | ||
| require.Contains(t, strings.Join(tr.paths, " "), "/"+kind+"s/789") | ||
| if force { | ||
| require.NoError(t, err) | ||
| require.Equal(t, 1, tr.writes) | ||
| } else { | ||
| require.ErrorContains(t, err, "conflict") | ||
| require.Zero(t, tr.writes) | ||
| } | ||
| }) | ||
| } | ||
| } | ||
| } | ||
|
|
||
| func TestBodyGuardBoostExplicitlyExcluded(t *testing.T) { | ||
| project := "123" | ||
| cmd := newBoostUpdateCmd(&project) | ||
| require.Nil(t, cmd.Flags().Lookup("if-unmodified-since")) | ||
| require.Nil(t, cmd.Flags().Lookup("force")) | ||
| tr := &bodyGuardTransport{live: `null`} | ||
| app, _ := newTestAppWithTransport(t, tr) | ||
| err := executeCommand(cmd, app, "789", "replacement") | ||
| require.NoError(t, err) | ||
| require.Equal(t, 1, tr.writes) | ||
| require.Zero(t, tr.gets) | ||
| } | ||
|
|
||
| func TestBodyGuardMatchingOverrideAndUnprotected(t *testing.T) { | ||
| for _, tc := range []struct { | ||
| name string | ||
| flags []string | ||
| gets int | ||
| }{ | ||
| {"same instant", []string{"--if-unmodified-since", "2026-11-08T13:10:58-05:00"}, 1}, | ||
| {"override", []string{"--if-unmodified-since", "2026-11-08T18:00:00Z", "--force"}, 1}, | ||
| {"first use no baseline", nil, 0}, | ||
| } { | ||
| t.Run(tc.name, func(t *testing.T) { | ||
| tr := &bodyGuardTransport{live: `"2026-11-08T18:10:58Z"`} | ||
| app, _ := newTestAppWithTransport(t, tr) | ||
| err := executeCommand(newCommentsUpdateCmd(), app, append([]string{"789", "replacement"}, tc.flags...)...) | ||
| require.NoError(t, err) | ||
| require.Equal(t, 1, tr.writes) | ||
| require.Equal(t, tc.gets, tr.gets) | ||
| }) | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.