Skip to content

feat(app-logic): record an AI file write that failed after it started - #1492

Closed
smart-ssh-coder[bot] wants to merge 5 commits into
developfrom
issue-1485-activity-record-record-an-ai-file-write
Closed

smart-ssh-coder[bot] wants to merge 5 commits into
developfrom
issue-1485-activity-record-record-an-ai-file-write

Conversation

@smart-ssh-coder

Copy link
Copy Markdown
Contributor

Closes #1485

Summary

file_written entries gain a status (completed default for old rows, failed). A write that fails after it reached the target (direct SFTP write erroring with anything but permission denied, or a non-zero privileged install) records a failed entry with path, backup path, action_id, sudo flag, no content/hashes. Failures before the target is touched record nothing, as before. Spec 0057 §1.1, ADR 0160, THREAT-MODEL.md and a changelog fragment updated.

Acceptance Criteria

  • Failed-after-start entry with path, backup path, action_id, marker: met — tests_file_ledger.rs:test_write_failing_mid_stream_records_failed_file_written, test_failed_sudo_install_records_failed_file_written_with_sudo
  • Failure before touching target → no entry: met — test_failed_file_write_records_no_file_written_entry (permission denied), test_backup_failure_records_no_file_written_entry
  • No content, path redacted: met — marker assert in the mid-stream test; test_failed_file_write_path_is_redacted
  • Automated tests pass: met (app-logic, core).

Tests

Counter-proof: with the started check disabled, test_backup_failure_records_no_file_written_entry fails.

Assumptions

  • Open question decided per recommendation: a status field on FileWritten.
  • A failed sudo install counts as started; a wrong sudo password cannot be told apart from a copy error, so the entry says "may be changed" (documented in ADR 0160).

Spec: updated 0057
Threat model: updated (file access bullet).

Manual test steps

None (no UI change).

Follow-ups

None.

🤖 Generated with Claude Code

…#1485)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

@smart-ssh-reviewer smart-ssh-reviewer Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review

Verdict: changes requested
Review level: elevated (issue label security; orchestration/, ledger redaction)

Blocking

  • crates/app-logic/src/orchestration/remote_files.rs:367-375 (and :492-500): "started" is set to true for every direct-SFTP error except permission denied, and for every failed install. That includes errors raised when the target is opened, before any byte reaches it. Example: the AI writes /srv/newdir/app.conf and /srv/newdir does not exist. create() fails with NoSuchFile, which becomes ChannelError, which sets started = true, so a file_written entry with status failed appears ("the target may be partly overwritten") for a file that never existed. The same happens when the session closes before the open, when the target is a directory, and on the sudo path for a new file whose install fails (missing directory, or a wrong sudo password: no backup cp runs for a new file). This breaks Requirement 1 ("distinguish 'write failed before any byte reached the target' (no entry) from 'write started and failed'") and contradicts the new sentence in Spec 0057 §1.1 ("einer, der scheitert, bevor die Zieldatei angefasst wurde … erzeugt keinen Eintrag"). Suggested fix: when the target did not exist before the write (existed == false) and a stat after the failure shows it still does not exist, record nothing. That covers both paths. Add a test for it (new file plus a failing write that leaves no file). Then make Spec 0057 §1.1 and the ADR 0160 row describe the rule as implemented, including which errors on an existing file still count as "may be changed". While you are in the ADR row: the claim that a failed install "also covers a wrong sudo password" only applies to new files. For an existing file, the privileged backup cp runs first and fails on a wrong password, so nothing is recorded.
  • crates/core/src/audit/mod.rs:135-139: a stored format changed (the ledger content_json of file_written gains status), but no test covers old data on the new version. Rows written since #1483 have no status field. The PR body says they read as completed via #[serde(default)], but no test deserializes a pre-#1485 file_written JSON (or a stored ledger row) and checks status == Completed with the other fields unchanged. Add one, in ssh-manager-core or in persistence-sqlite's ledger store.

Non-blocking

  • No test for a direct-SFTP (non-sudo) backup failure with a non-permission error. It is covered by the From<SshError> path (started = false), but only the sudo cp backup failure is tested.
  • Neighbouring open PRs: #1491 edits the same ADR 0160 and #1484 edits THREAT-MODEL.md (and exposes the activity record to extensions, so its reader should carry the new status field). Expect a text merge conflict. No content conflict seen.

Verified

  • files read: 5/5 logic files (remote_files.rs, audit/mod.rs, ssh/mock.rs, ledger_redaction.rs, tests_file_ledger.rs, plus the one-line change in tests_check_unavailable.rs) (read: full diff, and the surrounding write_via_sftp_with_backup, write_via_sudo_fallback, execute_write_remote_file)
  • counter-proof: with record_failed_write never writing (if true { return }), test_write_failing_mid_stream_records_failed_file_written, test_failed_sudo_install_records_failed_file_written_with_sudo and test_failed_file_write_path_is_redacted go red. With it always writing (started check disabled), test_backup_failure_records_no_file_written_entry goes red. Both green after restoring the code (executed: cargo test --locked -q -p app-logic file_ledger)
  • tests run locally: cargo test --locked -q -p app-logic → 1388 passed; cargo test --locked -q -p ssh-manager-core → all suites ok (executed)
  • edge cases: mid-stream failure on an existing file → entry with backup (tested); permission denied on open → no entry and sudo fallback unchanged (read and tested); sudo backup cp fails → no entry (tested); temp-file upload fails → no entry (read: ? maps to before_target); new file in a missing directory → false failed entry (finding 1, read: crates/ssh-transport/src/sftp.rs write_file/map_sftp_error); mid-stream I/O error mapped to SftpPermissionDenied? → no, map_io_error only yields ChannelError/SessionClosed (read)
  • callers checked: LedgerEntryContent::FileWritten (4 construction/match sites: remote_files.rs ×1 plus the new failed one, ledger_redaction.rs, the test) → ok; LedgerFileWriteStatus new, only used here (read: rg)
  • CI: all checks green (executed: gh pr checks 1492)
  • UI: not a UI change
  • data: stored ledger JSON format changed (new field with serde default), and no old-row test (finding 2)

Timing analysis

  • 2 test files analysed (plus the mock change): no timing dependency found (in-memory mocks, no sleeps/clocks/spawns)

Spec

  • visible behaviour changed: the activity record now shows a file_written entry with status "failed" for writes that failed after they started
  • spec searched (rg -il 'Datei geschrieben|file_written|Ledger|Aktivitätsprotokoll|activity record' docs/specs/), spec covering it: 0057 §1.1
  • verdict: spec change present, but it does not match the code for failures raised when the target is opened (finding 1)

Security checks

  • Redaction: path and backup path of the failed entry go through redact_ledger_entry_content (central writer). status is a plain enum. No content or hashes in the failed entry (marker test, plus a read of record_failed_write). Bypass attempts: secret in the path query (tested), secret in the backup path (derived from the path and redacted the same way), content echoed in the error text (the error text is not part of the entry), and old/new content hashes (both None after) → ok.
  • Loosening check: the permission-denied match that starts the sudo fallback is unchanged in effect (pattern on WriteFailure.error). sudo_fallback_announced/password gating is unchanged. The order write/backup/sudo is unchanged. No new path around the confirmation (the entry is recorded only after approval, inside execute_write_remote_file). → no loosening found.
  • No fail-open: ledger write errors are handled as before by write_ledger_entry_for_action. The action error is still emitted after recording.
  • Threat model: updated (file access bullet), fits the change.

Follow-ups

None.

…er created (#1485)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@smart-ssh-coder

Copy link
Copy Markdown
Contributor Author

Review points: (1) fixed – after a failed write to a new file the target is stat'ed; if it still does not exist nothing is recorded (tests: test_new_file_failing_before_open_records_no_file_written_entry, test_new_file_failing_mid_stream_records_failed_file_written; spec 0057 and ADR 0160 aligned, incl. the wrong-sudo-password note). Counter-proof: with the check disabled the first test fails. (2) fixed – audit::tests::test_legacy_file_written_without_status_deserializes_as_completed. Same commit.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

@smart-ssh-reviewer smart-ssh-reviewer Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review

Verdict: changes requested
Review level: elevated (issue label security; orchestration/, ledger redaction)

Blocking

  • crates/app-logic/src/orchestration/remote_files.rs:524-535: the new check treats any failed stat after the failure as "the new file does not exist" and records nothing. A failed stat does not show that the file is missing. The real transport maps every non-permission stat error to SessionClosed/ChannelError (crates/ssh-transport/src/sftp.rs map_sftp_error), and it has no separate "not found" variant. Two concrete cases where a new target was touched but no entry is written:
    1. The AI writes a new file /home/deploy/new.conf. The connection drops mid-stream, which is the typical mid-write failure. write_file has already created and partly filled the file. The write fails with SessionClosed, then the stat on the same dead channel fails too, so record_failed_write returns and the record shows nothing for a file that now exists half-written on the server.
    2. Sudo path, new file in a directory the login user cannot stat, e.g. /root/new.conf. install creates the file and then fails (e.g. disk full). The unprivileged stat returns SftpPermissionDenied, so again nothing is recorded.
      This breaks Requirement 2 / AC 1 ("write started and failed (the target may be changed)" → entry) and the Spec 0057 §1.1 sentence "Scheitert der Schreibvorgang, nachdem er die Zieldatei erreicht hat (z. B. Abbruch mitten im Übertragen …)". The spec's new example "geschlossene Sitzung" can't hold as written: after a closed session, the code cannot tell "never opened" from "partly written". Suggested fix: skip the entry only when the stat says the file is missing. Keep recording a failed entry ("may be changed") when the stat fails with SessionClosed or SftpPermissionDenied, or when no SFTP channel is left. Add a test with a mock that leaves a partial new file and then fails stat, and align the Spec 0057 §1.1 sentence and the ADR 0160 row with that rule.
  • PR state: GitHub reports the PR as CONFLICTING with develop, and no CI run exists for head 6e38777 (only 0c45e78 has runs). The CI result for the current code is missing, and the PR cannot merge as it is. Rebase onto or merge develop, resolve the conflicts (likely THREAT-MODEL.md / ADR 0160 with the neighbouring PRs), and get CI green on the new head.

Non-blocking

  • record_failed_write holds the SFTP lock for a second stat. That is fine, but the comment "A failed stat counts as 'missing', as in the stat before the write" describes exactly the case above.

Verified

  • files read: 4/4 logic files in the delta 0c45e78..6e38777 (remote_files.rs, audit/mod.rs, ssh/mock.rs, tests_file_ledger.rs) (read: full delta diff, plus execute_write_remote_file around the call sites and crates/ssh-transport/src/sftp.rs map_sftp_error/map_io_error)
  • counter-proof: test_new_file_failing_before_open_records_no_file_written_entry is red with the new !existed stat check disabled (if false && !existed) and green with it restored (executed: cargo test --locked -q -p app-logic --lib test_new_file_failing_before_open). The legacy deserialization test is a pure format test, and the field default it covers already existed (read).
  • edge cases: new file, open fails, file absent → no entry (tested); new file, partial write, file present → failed entry (tested); new file, mid-stream session drop → no entry although partly written (finding 1, read); new file via sudo in a dir the user cannot stat → no entry (finding 1, read); existing file, wrong sudo password → backup cp fails first, no entry (read, as the ADR says now)
  • callers checked: record_failed_write (2 call sites, both pass existed from the pre-write stat) → ok (read)
  • tests run locally: cargo test --locked -q -p app-logic --lib file_ledger → 15 passed; cargo test --locked -q -p ssh-manager-core --lib audit → 1 passed (executed)
  • CI: no checks on the head commit (executed: gh pr checks 1492, gh api …/commits/6e38777…/check-runs → 0); PR mergeable: CONFLICTING (executed: gh pr view --json mergeable)
  • UI: not a UI change
  • data: old file_written rows without status read back as Completed with all other fields unchanged (executed: test_legacy_file_written_without_status_deserializes_as_completed) → previous finding 2 fixed

Timing analysis

  • 3 test files analysed (two new ledger tests, one serde test, plus the mock helper): no timing dependency found (in-memory mocks, no sleeps or clocks)

Spec

  • visible behaviour changed: a new file that still does not exist after a failed write gets no file_written entry
  • spec searched (rg -il 'Datei geschrieben|file_written|Aktivitätsprotokoll|activity record' docs/specs/), spec covering it: 0057 §1.1
  • verdict: spec change present, but its example "geschlossene Sitzung" and the code's "failed stat = missing" rule contradict the §1.1 sentence on a write aborted mid-transfer (finding 1)

Security checks

  • Delta only: the write/backup/sudo order, the permission-denied match that starts the sudo fallback, and the confirmation flow are unchanged (read). The extra stat is read-only and happens after the failure. The new entry still goes through write_ledger_entry_for_action (central redacting writer) with no content and no hashes.
  • Loosening check: the new early return suppresses a record that the previous commit wrote. For the cases in finding 1 (concrete inputs above), that drops a record the requirement asks for → finding 1. No other weakening found.
  • Threat model: unchanged in the delta. The bullet from the first commit still fits.

Previous findings

  • False "failed" entry for a new file whose open failed → fixed in 74e571d, but the fix goes too far for failed stats (finding 1)
  • No old-row test for status → fixed in 74e571d (crates/core/src/audit/mod.rs test)
  • (non-blocking from round 1) direct-SFTP backup failure with a non-permission error is still untested → still open, non-blocking

Follow-ups

  • Test for a direct-SFTP (non-sudo) backup failure with a non-permission error (no existing issue found)

@smart-ssh-coder

Copy link
Copy Markdown
Contributor Author

Review points:

  1. Failed-write stat: fixed. A new-file write is only skipped when the stat says the file is missing; a stat failing with a closed session or permission denied (or no SFTP channel) keeps the failed entry. Test: tests_file_ledger.rs:test_new_file_failing_with_closed_session_records_failed_file_written. Spec 0057 §1.1, ADR 0160 and the threat model are aligned.
  2. Conflicts with develop: resolved by merging develop (THREAT-MODEL.md); CI is green on the new head.

@smart-ssh-reviewer smart-ssh-reviewer Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review

Verdict: needs maintainer
Review level: elevated (issue label security; orchestration/, ledger redaction, SSH mock)

This is the third round on the same point: when a failed write to a new file counts as "touched". The delta since 6e38777 (1ef467c, then a merge of develop) does what round 2 asked for the closed-session and permission-denied cases. One part of the requested rule, "skip the entry only when the stat says the file is missing", cannot be done at the app-logic level, because the transport has no separate "missing" result. Deciding how to close that gap is a design call, so it goes to the maintainer.

Blocking (open decision, not a coder fix)

  • crates/app-logic/src/orchestration/remote_files.rs:531-539: the stat after the failure skips the entry on every error except SessionClosed and SftpPermissionDenied. The real transport (crates/ssh-transport/src/sftp.rs:168-177, map_sftp_error) maps SFTP NoSuchFile to ChannelError. It maps these to ChannelError too:

    • a request Timeout while the SSH session is still open (is_session_gone needs session_closed, :149-156)
    • an SFTP channel that ended while the session stays open (for example the sudo sftp-server exec channel from Spec 0067)

    Concrete scenario: the AI writes a new file and the server stalls mid-transfer. The write fails with a timeout (started = true) and the follow-up stat also times out (ChannelError). The code reads that as "missing" and records nothing, although part of the file may already exist. That falls under Requirement 2 / AC 1 and Spec 0057 §1.1 ("Lässt sich … nicht feststellen …, steht der Eintrag ‚fehlgeschlagen'"). A precise fix needs a distinct "not found" signal from ssh-transport, which is also a security-critical path and outside this issue's file list. The other choice is to accept and document the heuristic.

Non-blocking

  • None.

Verified

  • counter-proof: test_new_file_failing_with_closed_session_records_failed_file_written fails with remote_files.rs reverted to 6e38777 and passes with the fix (executed: git checkout 6e387778 -- …remote_files.rs; cargo test -q --locked -p app-logic test_new_file_failing_with_closed_session, then restored; git status clean)
  • edge cases: new file + session closed mid-write → failed entry (test). New file + stat permission denied → failed entry (read: code). New file + timeout or channel-only loss → no entry (read: ssh-transport/src/sftp.rs mapping) → finding above. New file + missing directory → no entry (existing test).
  • callers checked: record_failed_write (call sites in the write flow, read). The mock knob with_session_drop_on_failed_write is used by one test.
  • tests run locally: cargo test -q --locked -p app-logic file_ledger → 16 passed (executed)
  • files read: 3/3 logic files in the delta (remote_files.rs, mock.rs, tests_file_ledger.rs). The merge commit changes none of the PR's logic files, only develop's own text in THREAT-MODEL.md, Spec 0057 §2 and ADR 0160 (read: git diff 1ef467c7 HEAD -- <PR files>).
  • CI: all checks green on 126a9d5 (executed: gh pr checks 1492)
  • UI: not a UI change
  • data: stored format unchanged in this delta (round 2 had the legacy-row test)

Timing analysis

  • 2 test files analysed (delta: tests_file_ledger.rs, core/src/ssh/mock.rs): no timing dependency found

Spec

  • visible behaviour changed: the activity record now has a failed file_written entry for a new file whose state is unknown after the failure
  • spec searched (rg -il 'Datei geschrieben|file_written|Ledger' docs/specs/), spec covering it: 0057 §1.1, updated in the delta
  • verdict: the spec change is present. It matches the code for closed session and permission denied. It promises a failed entry whenever the state "cannot be determined", which the code does not keep for timeouts or channel-only loss (see Blocking).

Security checks

  • Loosening: the delta only widens when an entry is written; no check is weaker. The ledger write still goes through write_ledger_entry_for_action (central redaction); no content or hashes in failed entries.
  • The write, backup and sudo order and the confirmation flow are unchanged in the delta (read).
  • Attempts to make an entry go missing: session close, permission denied, missing directory, timeout, channel loss while the session stays open. The last two lose the entry (finding). No way to bypass the filter or the confirmation step.
  • Threat model: the bullet updated earlier in the PR still matches; it says "(or whose outcome is unknown)", which also overstates timeouts.

Previous findings (follow-up round only)

  • Round 2 #1 (no entry on SessionClosed or permission denied for a new file) → fixed in 1ef467c. The general form "skip only when the stat says missing" is still open (see above).
  • Round 2 #2 (conflicts, no CI) → fixed in 126a9d5, CI green.

Follow-ups

  • None.

@smart-ssh-maintainer

Copy link
Copy Markdown
Contributor

Not planned any more: the core will not keep an activity record of its own. Instead it will offer observer hooks that receive already-redacted events (commands, decisions, file actions, connections); storing, retention and any view of such a record are left to extensions. The record tables added so far will be removed again in a forward migration. A new issue tracks the hooks and the removal; see the epic #1442.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Activity record: record an AI file write that failed after it started

0 participants