Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
82 changes: 82 additions & 0 deletions .surface

Large diffs are not rendered by default.

45 changes: 45 additions & 0 deletions docs/body-conflict-guard.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# 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)
Comment thread
robzolkos marked this conversation as resolved.
Resolved
- `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 `files update` and `files replace` guards also apply through the file-group aliases: `file`, `docs`, `documents`, `vaults`, `vault`, and `folders`.

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.
43 changes: 43 additions & 0 deletions e2e/smoke/smoke_comments.bats
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,49 @@ setup_file() {
assert_json_value '.ok' 'true'
}

@test "comments guarded replacement refuses stale versions before writing" {
local todo_out todo_id comment_out comment_id baseline unchanged
todo_out=$(basecamp todos create "Guard target $(date +%s)" --list "$QA_TODOLIST" -p "$QA_PROJECT" --json)
todo_id=$(echo "$todo_out" | jq -r '.data.id // empty')
[[ -n "$todo_id" ]] || fail "No synthetic target returned"
comment_out=$(basecamp comments create "$todo_id" "Original synthetic comment" -p "$QA_PROJECT" --json)
comment_id=$(echo "$comment_out" | jq -r '.data.id // empty')
baseline=$(echo "$comment_out" | jq -r '.data.updated_at // empty')
[[ -n "$comment_id" && -n "$baseline" ]] || fail "Missing comment/version"

run_smoke basecamp comments update "$comment_id" "Matching version writes" \
--if-unmodified-since "$baseline" -p "$QA_PROJECT" --json
assert_success
assert_json_value '.ok' 'true'
run_smoke basecamp comments show "$comment_id" -p "$QA_PROJECT" --json
assert_success
assert_json_value '.ok' 'true'
assert_json_not_null '.data.content'
assert_json_not_null '.data.updated_at'
unchanged=$(echo "$output" | jq -c '.data | {content,updated_at}')

run_smoke basecamp comments update "$comment_id" "Must not replace human text" \
--if-unmodified-since '2000-01-01T00:00:00Z' -p "$QA_PROJECT" --json
assert_failure
assert_json_value '.ok' 'false'
assert_json_value '.error | contains("update conflict")' 'true'
run_smoke basecamp comments show "$comment_id" -p "$QA_PROJECT" --json
assert_success
assert_json_value '.ok' 'true'
assert_json_not_null '.data.content'
assert_json_not_null '.data.updated_at'
[[ "$(echo "$output" | jq -c '.data | {content,updated_at}')" == "$unchanged" ]] || fail "Refusal changed the comment"

run_smoke basecamp comments update "$comment_id" "Explicit override writes" \
--if-unmodified-since '2000-01-01T00:00:00Z' --force -p "$QA_PROJECT" --json
assert_success
assert_json_value '.ok' 'true'
run_smoke basecamp comments show "$comment_id" -p "$QA_PROJECT" --json
assert_success
assert_json_value '.ok' 'true'
assert_json_value '.data.content | contains("Explicit override writes")' 'true'
}

@test "comments trash trashes a comment" {
local id_file="$BATS_FILE_TMPDIR/direct_comment_id"
[[ -f "$id_file" ]] || mark_unverifiable "No comment created in prior test"
Expand Down
54 changes: 54 additions & 0 deletions internal/commands/body_guard.go
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
}
246 changes: 246 additions & 0 deletions internal/commands/body_guard_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,246 @@
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
emptyRecord bool
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)
if r.Method == http.MethodGet && tr.emptyRecord {
body = "null"
}
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 ![image](./does-not-exist.png)"}},
{"messages", newMessagesUpdateCmd, []string{"789", "--body", "replacement ![image](./does-not-exist.png)"}},
{"todos", newTodosUpdateCmd, []string{"789", "--description", "replacement ![image](./does-not-exist.png)"}},
{"cards", newCardsUpdateCmd, []string{"789", "--body", "replacement ![image](./does-not-exist.png)"}},
{"todolists", func() *cobra.Command { return newTodolistsUpdateCmd(&project) }, []string{"789", "--description", "replacement"}},
{"schedule", func() *cobra.Command { return newScheduleUpdateCmd(&project) }, []string{"789", "--description", "replacement ![image](./does-not-exist.png)"}},
{"answers", func() *cobra.Command { return newCheckinsAnswerUpdateCmd(&project) }, []string{"789", "replacement ![image](./does-not-exist.png)"}},
{"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 ![image](./does-not-exist.png)"}},
{"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 ![image](./does-not-exist.png)"}},
{"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 TestBodyGuardEmptyLiveRecordRefuses(t *testing.T) {
for _, tc := range bodyGuardCommands() {
for _, status := range []int{http.StatusOK, http.StatusNoContent} {
t.Run(fmt.Sprintf("%s/%d", tc.name, status), func(t *testing.T) {
tr := &bodyGuardTransport{live: `null`, emptyRecord: true, getStatus: status}
app, _ := newTestAppWithTransport(t, tr)
args := append(append([]string{}, tc.args...), "--if-unmodified-since", "2026-11-08T18:00:00Z", "--force")
require.NotPanics(t, func() {
require.Error(t, executeCommand(tc.newCmd(), app, args...))
})
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)
})
}
}
Loading
Loading