Skip to content

fix(deploy): quote the copyable remediation command in the TTL 409 - #19784

Merged
iamwhatever merged 1 commit into
mainfrom
fix/quote-deploy-ttl-409-remediation-17789
Oct 21, 2026
Merged

iamwhatever merged 1 commit into
mainfrom
fix/quote-deploy-ttl-409-remediation-17789

Conversation

@CrysisDeu

@CrysisDeu CrysisDeu commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

Problem / Motivation

Goal: The fix command in the deploy "auto-cleanup missing" error is safe to copy and paste, whatever the stored profile name or region contains.

A deploy with a time limit answers 409 when the account has no auto-cleanup. The payload carries a remediation command, and the dashboard shows it with a copy button. That command was built with " ".join(parts), no shell quoting. The --profile and --region words come from the deploy profile registry (profiles.json), a file agents may write and that load_registry did not validate. A stored region such as us-west-2;touch${IFS}/tmp/pwned makes describe-stacks fail, so this exact 409 is reached every time, and the pasted command runs touch /tmp/pwned on the user's machine, outside any sandbox.

Why it matters

The copy button invites the user to run the string as-is. A hostile or merely odd registry value becomes a command the user executes with their own credentials.

Not a goal

  • Changing what the 409 says or when it fires.
  • Validating registry fields other than name and region.
  • Changing the setup guide's command line in ArtifactDeployPage.tsx; its profile now comes from a validated registry, and the script path it receives is already a quoted shell word.

What changed (motivation → approach → change)

The pasted command broke because two layers were missing: the renderer trusted its words, and the registry trusted its file.

layer before after
renderers _reaper_remediation / _base_remediation (deploy/handlers.py) " ".join(parts) shlex.join(parts); paths spelled with as_posix()
registry loader load_registry (deploy/profiles.py) any entry with a name entry kept only when name and region pass STORED_PROFILE_SPEC / REGION_SPEC; a dropped default clears

Quoting: every word of both commands goes through shlex.join. Plain words stay bare, so --profile dev --region us-west-2 reads exactly as before. A value with spaces, quotes or ;/$ is single-quoted and reaches install-reaper.sh or aws as one literal argument. The command is a POSIX shell line on every host (the script is bash and the base step chains with &&), so the script and template paths are spelled POSIX-style: on Windows str(Path) carries backslashes that shlex.join would single-quote, while C:/Users/... stays bare and runs as-is in Git Bash.

Registry: _well_formed_entry checks a stored name against STORED_PROFILE_SPEC, the union of every writer's charset (the deploy routes' PROFILE_SPEC plus the @ and = the AWS control app's register route admits), and region against REGION_SPEC. An entry is kept only when the validator returns the stored value unchanged (validate_field strips NUL and padding before matching, so a cleaned copy passing is not enough). A malformed entry is dropped on load with one warning log naming it. When the dropped entry was the default, default becomes "" so a deploy naming no profile gets 400 "not configured" instead of silently going to another account; a default that never named an entry still falls back to the first profile as before. This is a load-time guarantee: a later profile edit may pick a new default under that route's own rules (the AWS control app's unregister fills an empty default with the first kept profile), which is unchanged behavior. The legacy single-profile config.json goes through the same check. An empty region is still fine; make_entry fills in the default. docs/deploy-web.md says so, including that the next write erases the entry.

Backwards compatibility

Breaking: a profiles.json entry whose name fails STORED_PROFILE_SPEC or whose region fails REGION_SPEC is no longer served; the registry reads as if it were absent, a default pointing at it clears, and the next registry write (profile POST/PUT/DELETE, aws_control register/unregister, any locked_registry() block) saves the filtered list, erasing the malformed entry from disk for good. Writer sweep on origin/main @ b6a7b33: deploy/handlers.py:_save_config (PUT /config, both fields validated with PROFILE_SPEC/REGION_SPEC), deploy/handlers.py:_handle_profiles_post and _handle_profiles_put (same), deploy/profiles.py:create_aws_profile (same), apps/builtins/aws_control/backend/routes.py register route (name via aws_consent._PROFILE_RE, which also admits @ and =; region via accounts.configured_region, validated against the region pattern). STORED_PROFILE_SPEC is the union of those two name charsets, so every shipped writer's output survives the loader; only a hand- or agent-edited file is affected.

Reader: deploy/handlers.py:_resolve_profile -- chat|app|crew page -- a dropped default answers 400 "not configured" instead of a 409 carrying the hostile command; test_registry_drops_an_entry_the_request_path_would_refuse
Reader: deploy/handlers.py:_load_config / _handle_profiles_list -- crew page -- lists only well-formed entries
Reader: publish/personal_drive.py:_resolve_profile -- chat|app -- same registry contract, unknown or dropped names resolve to its existing "not registered" path
Reader: apps/builtins/aws_control/backend/routes.py register/unregister -- app -- re-adding a dropped name writes a validated entry

Tests

test/test_deploy_remediation_quoting.py, platform independent:

  • hostile name and region (separator, ${IFS}, space, both quote styles, $(id)) survive as single shell words after their flag, for both renderers; no touch word escapes. Removing shlex.join turns these red.
  • the base command has exactly one &&, both steps quoted.
  • a skills root with a space renders the template and script paths as one word each.
  • safe values render with no quotes at all.
  • load_registry drops an entry with a hostile region, a hostile name, an option-shaped name, a non-string region, a NUL inside the name, a space-padded region, or a bare-number name, logging one warning per dropped entry; the default that named it clears and resolve_profile("") is None. The NUL and padding cases pin that the RAW stored value must pass, not the validator's cleaned copy.
  • names with @ and = (what the AWS control app registers) are kept, resolve as default, render as one quoted word, and survive a no-op locked write on disk.
  • a dropped default clears instead of switching to another profile; a default that never existed still falls back to the first profile.
  • an empty region is kept and defaulted; the legacy config.json path is validated too.

Existing remediation tests keep passing: plain profile/region words are unchanged by shlex.join.

Intended? / Repro

Intended? No. Checked the introducing commits (#102 added _reaper_remediation, #17744 added _base_remediation), their docstrings, docs/ and the deploy skill: none says the command is meant to be unquoted; #17744's own review raised this issue. The registry module's docstring says "All values are schema-validated before reaching argv", which the load path did not honor.

Repro, without the test suite: a standalone script seeded profiles.json with {"name": "p", "region": "us-west-2;touch${IFS}<tmp>/pwned"}, called profiles.resolve_profile("") and handlers._reaper_remediation exactly as _do_deploy does, then ran the string with bash -c against a stub install-reaper.sh. On main: the stub received --region us-west-2 and the marker file was created. With this change: the entry is dropped (resolve_profile returns None), and the renderers called directly with the same values print --region 'us-west-2;touch${IFS}...', the stub receives the literal, and no marker is created.

Manual verification

Covered by the standalone repro above. N/A beyond that — unit coverage sufficient; the 409 path itself is unchanged.

Screenshots / video

N/A — no frontend change.

Related Issues

Fixes #17789

Pattern harvest

Rule candidate: semgrep
Pattern: a string built with " ".join(...) or an f-string that is returned as a remediation/command/hint field, or passed to shlex.split/subprocess with shell=True, without shlex.join/shlex.quote.

Checklist

  • At most two commits (one is the norm), with a Conventional Commits title (feat|fix|docs|style|refactor|perf|test|chore|ci|build|revert: ...)
  • Existing tests pass and new tests added for new functionality
  • Self-review completed; code follows project style guidelines
  • Documentation updated (if applicable)
  • No secrets, credentials, or internal references in the diff

@CrysisDeu
CrysisDeu requested review from a team and KiroCrewCaptain as code owners October 13, 2026 09:49
@CrysisDeu
CrysisDeu requested a review from mbriones98 October 13, 2026 09:49
@github-actions github-actions Bot added the readiness: checking Automated validation is still running label Oct 13, 2026
@github-actions

github-actions Bot commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

First Principles Review (Opus 5.5) — ✅ PASS

Premise-level review of 5c2f9cd3845c3068abe9d09487c1366f3118c764 — why this exists and whether the shipped surface is the smallest honest version. Updated in place on each push. A BLOCK verdict blocks PR readiness; PASS/CONCERNS are advisory.

First-Principles-Verdict: PASS

Check before merge: after this change, the next registry write permanently erases a hand- or agent-edited profiles.json entry that fails the new checks.

What this change ships

Inventory (6 items) — 6 justified

Intent: make the deploy 409's copyable fix command safe to paste whatever the stored profile or region holds. This is a FIX.

  1. The pasted remediation command now quotes every word, so a hostile profile or region stays one literal argument — justified
  2. Script and template paths in that command are now spelled with forward slashes (matters on Windows) — justified
  3. A registry entry whose name or region is malformed is ignored on load, with a warning log — justified
  4. A default that pointed at a dropped entry now clears to a 400 "not configured" instead of switching to another account — justified
  5. The legacy single-profile config.json gets the same check — justified
  6. The packaged deploy doc describes the drop, the cleared default and the erase-on-next-write — justified

[FIRST-PRINCIPLES-REVIEWED] 5c2f9cd

Description read

[DESCRIPTION-READ] b71ce1097dc189f425d987184fac11af417ff39699abab515bd63b6d61238dfa

That sha256 names the PR description this verdict read. Recompute it with .github/scripts/pr-description-capture.sh; if it differs, the description changed after this verdict was formed and any finding drawn from the description is unproven.

@github-actions

github-actions Bot commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

Design Review (Opus 5.5) — ✅ PASS

Design-level review of 5c2f9cd3845c3068abe9d09487c1366f3118c764 — updated in place on each push. A BLOCK verdict blocks PR readiness; PASS/CONCERNS are advisory.

Design-Verdict: PASS

Check that dashboard/handlers/aws_project_profile.py:_registry_names stays correct. It reads load_registry too, though it isn't in the description's list of readers.

[DESIGN-REVIEWED] 5c2f9cd

Description read

[DESCRIPTION-READ] abfc7e5b0f6d396b9a99a07522c75660378a82f624d39913787cda5c7169510b

That sha256 names everything this verdict read: the PR description, plus the 1 evidence file(s) the workflow collected from it and handed this review. It covers that evidence because the media strip replaces every attachment URL with the same placeholder, so an edit swapping one attachment for another would leave the description's captured text identical while what this review judged changed. Recompute it with .github/scripts/pr-description-capture.sh over the same inputs; if it differs, the description or that evidence changed after this verdict was formed and any finding drawn from either is unproven.

@github-actions

github-actions Bot commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

UX Review (Opus 5.5) — ⏭️ skipped

Revision 5c2f9cd3845c3068abe9d09487c1366f3118c764 touches no user-facing surface (no changes under website/ or committed screenshots), so the UX review was skipped. Advisory — does not block merge.

@github-actions

github-actions Bot commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

Opus 5.5 Review — ✅ no blocking findings

Reviewed 5c2f9cd3845c3068abe9d09487c1366f3118c764 — this comment is updated in place on each push.

Review details

No findings.

[OPUS-REVIEWED] 5c2f9cd

Verdict parsed from the review's SHA-scoped output markers for commit 5c2f9cd3845c3068abe9d09487c1366f3118c764.

False positive or not applicable? A repository writer can comment:
/ai-review override fable 5c2f9cd3845c3068abe9d09487c1366f3118c764: <one-sentence reason>

@github-actions

github-actions Bot commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

GPT 6.1 Review — ✅ no blocking findings

GPT 6.1 completed its review of 5c2f9cd3845c3068abe9d09487c1366f3118c764 and found no blocking issues.

This comment is updated in place on each push.

Review details

No findings.
[GPT-REVIEWED] 5c2f9cd

False positive or not applicable? A repository writer can comment:
/ai-review override gpt 5c2f9cd3845c3068abe9d09487c1366f3118c764: <one-sentence reason>

@github-actions github-actions Bot added readiness: passed Eligible automated validation passed for the current revision and removed readiness: checking Automated validation is still running labels Oct 13, 2026

@buluoray buluoray left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Verdict: REQUEST CHANGES (head 608344be26)

What it fixes

The reaper_required 409 hands the dashboard a copyable fix command built with " ".join. A stored region such as us-west-2;touch${IFS}... therefore ran a second command when the user pasted it. The fix has two layers: shlex.join in the renderers, and validating registry entries when they are loaded.

What I verified

  • deploy/handlers.py:176-189 _shell_line = shlex.join. Both renderers use it (:225, :255), and paths are spelled with as_posix(). The && is still emitted unquoted between the two steps, as intended. Plain --profile dev --region us-west-2 output is byte-identical.
  • deploy/profiles.py:158-192 _well_formed_entry requires the RAW stored value to equal what validate_field returns. It is applied at :220, :236 and the legacy config.json path.
  • Mutations, each run on its own: shlex.join → " ".join turns 4 tests red (incl. test_template_and_script_paths_are_quoted_words); loader filter disabled turns 7 red; raw-vs-cleaned comparison weakened turns test_registry_drops_an_entry_the_request_path_would_refuse[padded-region] red.
  • New tests plus the deploy/aws_control suites I ran pass at this head.

Blocking

1. The loader drops names a shipped writer registers, and then silently switches the default to a different account. The PR's writer sweep says every writer already refuses what the loader now drops. That is not true for the AWS control app. apps/builtins/aws_control/backend/routes.py:808 gates registration with aws_consent._PROFILE_RE (aws_consent.py:151), which deliberately admits @ and =. The loader checks against PROFILE_SPEC (constants.AWS_PROFILE_NAME_RE), which admits neither. I seeded a registry with default dev@corp (eu-central-1) and a second entry other. At this head:

  • load_registry() returns only other, and default becomes other (profiles.py:223-224, picking the first surviving entry).
  • resolve_profile("") returns ('other', 'us-east-1'). A deploy that names no profile now goes to a different AWS account and region with no error.
  • A no-op locked_registry() write then rewrites the file without dev@corp, so the entry is permanently erased from disk.

Fix:

  • Have the loader accept the union of what every writer can store. @ and = are inert once shlex.join quotes them, and the AWS CLI accepts them.
  • When the stored default is the entry that was dropped, set default to "" (so the user gets 400 "not configured"). Do not fall back to another profile.
  • Add a test that loads a registry whose default is an @ name, and assert both the default and the on-disk file after a write.

Non-blocking follow-ups

  • src/kiro_crew/docs/deploy-web.md (around :212) could say that malformed registry entries are ignored, and that the warning log names them.

Not verified

  • I did not run the frontend, and I did not do a live paste into bash/Git Bash. I checked quoting only through shlex.split in the tests and by reading the code.
  • I did not trace publish/personal_drive.py's registry reader beyond the PR's description.

@github-actions github-actions Bot added readiness: action required A blocking check or review needs attention and removed readiness: passed Eligible automated validation passed for the current revision labels Oct 13, 2026
@CrysisDeu
CrysisDeu force-pushed the fix/quote-deploy-ttl-409-remediation-17789 branch from 608344b to 307ad8c Compare October 13, 2026 16:45
@CrysisDeu

Copy link
Copy Markdown
Contributor Author

@buluoray thanks, the dev@corp case was a real data-loss shape. Addressed at 307ad8cb3f:

  • Loader now checks stored names against STORED_PROFILE_SPEC (deploy/profiles.py): the union of PROFILE_SPEC and aws_consent._PROFILE_RE, so @ and = are kept. Composed from AWS_PROFILE_FIRST_CHARS per the contract in constants.py.
  • A default whose entry was dropped becomes "" (400 "not configured"); a default that never named an entry still falls back to the first profile, as before (_parse_registry).
  • Tests: test_registry_keeps_names_the_aws_control_app_registers seeds dev@corp as default plus role=admin, asserts load, resolve_profile(""), the quoted remediation word, and the on-disk file after a no-op locked_registry() write. test_a_dropped_default_clears_instead_of_switching_accounts pins both default rules.
  • docs/deploy-web.md 6.1 gains the one line on ignored malformed entries.

PR body's writer sweep re-run on b6a7b33f and corrected.

@github-actions github-actions Bot added readiness: checking Automated validation is still running and removed readiness: action required A blocking check or review needs attention labels Oct 13, 2026
@CrysisDeu
CrysisDeu requested a review from buluoray October 13, 2026 17:18
@github-actions github-actions Bot added readiness: passed Eligible automated validation passed for the current revision and removed readiness: checking Automated validation is still running labels Oct 13, 2026
@iamwhatever

Copy link
Copy Markdown
Contributor

This PR fixes the TTL 409's copy-paste fix command at the root, in two layers: both renderers now use shlex.join with POSIX paths (src/kiro_crew/deploy/handlers.py:176-255), and load_registry keeps only entries whose raw name/region pass STORED_PROFILE_SPEC/REGION_SPEC, clearing a default whose entry was dropped (src/kiro_crew/deploy/profiles.py:168-229). I tried to break it: a region like us-west-2;touch${IFS}/tmp/pwned, a name with quotes and $(id), an option-shaped name, NUL and padded values all stay one literal word or get dropped. _STORED_PROFILE_RE is built from AWS_PROFILE_FIRST_CHARS with @=- at the end, so there is no accidental range admitting ; or /. The legacy config.json path goes through the same check. buluoray's blocking points at 608344b (dropping @/= names, switching the default to another account, a test for an @ default on disk) are all addressed at 307ad8c; buluoray still needs to re-review or dismiss that review. Two AI findings on the current head have no ai-review-disposition reply, so I cannot approve yet. (1) Design Review Watch: locked_registry writes back load_registry()'s filtered result, so the next profile POST/PUT or aws_control register/unregister permanently deletes a malformed entry from disk. I confirmed this in profiles.py:119-152, and neither the Breaking: line nor deploy-web.md:213 says "removed on next write". (2) First Principles item 5: _shell_line is only shlex.join under a second name (handlers.py:176). @CrysisDeu, please post a disposition for each one (fix it or rebut it), and either reword the Breaking line and the docs line to say the entry is erased on the next write or keep the dropped entries on write-back. — crew-pr-reviewer (deep re-check)

@CrysisDeu
CrysisDeu force-pushed the fix/quote-deploy-ttl-409-remediation-17789 branch from 307ad8c to b4a22dd Compare October 13, 2026 23:41
@CrysisDeu

Copy link
Copy Markdown
Contributor Author
  • Load-time filtering turns into deletion on the next write span=adcffe31a745

Outcome: fixed (documented), at b4a22dd.
The erase-on-next-write behavior is intended: a malformed entry can never be served, so keeping it on disk only preserves a value no code path will read. The PR body's Breaking line now says the next registry write (profile POST/PUT/DELETE, aws_control register/unregister, any locked_registry() block) saves the filtered list and erases the entry for good, and src/kiro_crew/docs/deploy-web.md 6.1 says the same. The warning log at load names the dropped entry so an operator can see what went. test_registry_keeps_names_the_aws_control_app_registers already asserts the on-disk file after a no-op locked_registry() write for the kept entries.

@CrysisDeu

Copy link
Copy Markdown
Contributor Author
  • Item 5 — duplicate of shlex.join span=b5f0dd951686

Outcome: fixed (removed), at b4a22dd.
_shell_line is deleted; both renderers call shlex.join(parts) directly. The rationale that lived in its docstring (POSIX shell line on every host, bare words stay bare, as_posix paths) is now a comment above _reaper_remediation. Rendered output is byte-identical; the quoting tests are unchanged.

@CrysisDeu

Copy link
Copy Markdown
Contributor Author

@iamwhatever both addressed at b4a22dd2b0, dispositions posted above. (1) Breaking line and deploy-web.md 6.1 now say the next registry write erases the malformed entry from disk. (2) _shell_line removed; renderers call shlex.join directly, rationale kept as a comment. @buluoray your three points stand fixed from 307ad8cb3f; this head only drops the alias and adds the doc sentence.

@github-actions github-actions Bot added readiness: checking Automated validation is still running and removed readiness: passed Eligible automated validation passed for the current revision readiness: checking Automated validation is still running labels Oct 13, 2026
@github-actions github-actions Bot added the readiness: action required A blocking check or review needs attention label Oct 14, 2026
@github-actions github-actions Bot added readiness: checking Automated validation is still running readiness: passed Eligible automated validation passed for the current revision and removed readiness: action required A blocking check or review needs attention readiness: checking Automated validation is still running labels Oct 14, 2026
@iamwhatever

Copy link
Copy Markdown
Contributor

HOLD at 6e2cb91. This changes command-injection protection and the AWS profile registry. Dropped registry entries can later be erased on a write. Security, credentials and data-removal changes require a human maintainer here. @buluoray's change request is also still active. Please obtain that re-review rather than treating a claimed fix as clearance. Answer the current Design review about valid CLI names excluded by the stored-name rules. Also settle the current First Principles items with source-backed replies. I have not executed the copied command, accessed AWS, or run tests. — crew-pr-reviewer (r99)

@CrysisDeu

Copy link
Copy Markdown
Contributor Author

Answers for the current (PASS) lane notes on 6e2cb91b86, with sources:

Design — a hand-edited entry with a valid AWS CLI name holding : or / is erased for good. Yes, by design, and documented in the Breaking line and docs/deploy-web.md 6.1. No writer in this repo can create such a name: the deploy routes validate with constants.AWS_PROFILE_NAME_RE ([A-Za-z0-9_.+][A-Za-z0-9_.+-]*, src/kiro_crew/constants.py:1543-1546) and the AWS control app with aws_consent._PROFILE_RE (src/kiro_crew/aws_consent.py:151, adds @=). STORED_PROFILE_SPEC is exactly the union of those two. A name with : or / can only come from a hand or agent edit of profiles.json; on main such an entry flows unvalidated into aws argv and the pasted command (issue #17789). The drop is logged once by name (profiles.py _well_formed_entry) so the operator sees what went; re-adding it goes through the same validated routes that refuse it today.

First Principles item 2 — as_posix() rides along. It is load-bearing: CI run 38490552349 on b96da5063c (the head without it) failed three Windows shards (jobs 115615302122, 115615302127, 115615302179) because str(Path) carries backslashes there and shlex.join single-quotes them, breaking test_renders_exact_operator_command, test_omits_empty_parts, test_reaper_remediation_omits_empty_flags, test_get_config_returns_registry_default and the new test_safe_values_render_without_quotes. Restored at 6e2cb91b86; the handlers.py comment records why.

First Principles item 6 — STORED_PROFILE_SPEC has one consumer. Kept public next to PROFILE_SPEC / REGION_SPEC / ACCOUNT_SPEC / ROLE_SPEC, the module's existing convention (handlers.py aliases profiles_mod.PROFILE_SPEC and REGION_SPEC from here). A rename-only push buys nothing for the Goal.

First Principles item 8 — test/conftest.py LEAK_SENTINELS hunks. Not on this branch: git diff main...HEAD --stat at merge-base 7b09ea8c43 lists only deploy/handlers.py, deploy/profiles.py, docs/deploy-web.md and test/test_deploy_remediation_quoting.py. The lane saw main's #19964 through a stale base.

@buluoray — your three blocking points from 608344be26 are fixed from 307ad8cb3f on (union charset, cleared default, @-default-on-disk test); the later heads only add the numeric-default str() fix, the drop warning, and the docs sentences. CI and all seven lanes are green on 6e2cb91b86. A re-review when you have a moment would unblock this.

mbriones98
mbriones98 previously approved these changes Oct 14, 2026

@mbriones98 mbriones98 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Checks green and PR Readiness passed at 6e2cb91; non-feature change.

@github-actions github-actions Bot added the merge conflict Branch has merge conflicts with its base — author must resolve before merge label Oct 20, 2026
buluoray
buluoray previously approved these changes Oct 20, 2026

@buluoray buluoray left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Re-review at 6e2cb91. Approve on the code; it needs a rebase before it can merge.

Both points from my change request at 608344b are fixed:

  1. Names the AWS control app registers are kept. Stored names are checked against STORED_PROFILE_SPEC (deploy/profiles.py), whose pattern admits @ and = and whose first-character set is a superset of aws_consent._PROFILE_RE, so every name that writer can store loads. test_registry_keeps_names_the_aws_control_app_registers loads dev@corp as the default, resolves it, quotes it in the remediation command, and checks the on-disk file still has both names after a write.
  2. A dropped default no longer moves to another account. _parse_registry clears the default to "" when its own entry was present but malformed, and still falls back to the first profile only for a stale pointer that names no entry. str() on the raw names keeps a bare-number account-style name from being mistaken for a missing one. test_a_dropped_default_clears_instead_of_switching_accounts pins both branches. The deploy-web.md line now says malformed entries are ignored with a warning and what the next write does.

The two v2 loaders now share _parse_registry, and the v1 config.json path is validated too. test/test_deploy_remediation_quoting.py passes on this head (16).

Before merge: src/kiro_crew/deploy/handlers.py conflicts with main. #22145 split that file into guards, content and sites owners, so _shell_line and the two renderers need to move with the code they belong to rather than a line-level merge. The approval will be dismissed by the rebase push; I will re-check the moved code then.

Follow-up question, not blocking: REGION_SPEC is narrower than aws_consent._REGION_RE. If the AWS control app can store a region REGION_SPEC refuses, the loader would now drop that entry too. Worth one line confirming no shipped writer stores such a region.

@CrysisDeu
CrysisDeu dismissed stale reviews from buluoray and mbriones98 via 41e5373 October 20, 2026 22:24
@CrysisDeu
CrysisDeu force-pushed the fix/quote-deploy-ttl-409-remediation-17789 branch from 6e2cb91 to 41e5373 Compare October 20, 2026 22:24
@github-actions github-actions Bot added readiness: checking Automated validation is still running and removed readiness: passed Eligible automated validation passed for the current revision labels Oct 20, 2026
@CrysisDeu

Copy link
Copy Markdown
Contributor Author

Rebased onto main after #22145 split handlers.py. The same two shlex.join quoting changes (plus as_posix() on the script/template paths) now live in src/kiro_crew/deploy/handlers_guards.py, where _reaper_remediation / _base_remediation moved; test/test_deploy_remediation_quoting.py imports from handlers_guards accordingly. No behavior change; profiles.py, the doc line and the test bodies are unchanged. Head 6e2cb91 → 41e5373.

@buluoray @mbriones98 GitHub dismissed your approvals on the force-push; could you re-approve once CI is green?

@github-actions

Copy link
Copy Markdown
Contributor

Security Scope Review -- 🔴 could not complete (fails closed)

No scope verdict for 41e5373a9903acc4e346413e2e19524b7fe91eb7 (the candidate stage failed). This lane fails CLOSED: an unmeasured tightening must not read as "nothing newly refused". See the job logs, then re-run -- or record /ai-review override scope 41e5373a9903acc4e346413e2e19524b7fe91eb7: <reason> if a human has judged the scope by hand.

@github-actions github-actions Bot removed the merge conflict Branch has merge conflicts with its base — author must resolve before merge label Oct 20, 2026
The finite-TTL 409 hands the dashboard a `remediation` command behind a
copy button. Its `--profile` and `--region` words come from the deploy
profile registry, an agent-writable file, so a stored value such as
`us-west-2;touch /tmp/x` ran as a second command when pasted.

Two layers now hold that line:

* `_reaper_remediation` / `_base_remediation` (now in
  `deploy/handlers_guards.py`, where #22145 moved them) render every word
  with `shlex.join`; the script and template paths are spelled POSIX-style
  (`as_posix`) so Windows backslashes are not quoted into the command.
* `load_registry` drops an entry whose name or region fails the stored
  field spec, clears a dropped default instead of switching accounts, and
  validates the legacy single-profile config the same way.

Fixes #17789
@CrysisDeu
CrysisDeu force-pushed the fix/quote-deploy-ttl-409-remediation-17789 branch from 41e5373 to 5c2f9cd Compare October 20, 2026 22:53
@github-actions github-actions Bot added readiness: passed Eligible automated validation passed for the current revision and removed readiness: checking Automated validation is still running labels Oct 20, 2026
@iamwhatever

Copy link
Copy Markdown
Contributor

HOLD at 5c2f9cd, reserved for human review.

This PR changes two things a human must review: the command-injection quoting of the copyable remediation command, and which AWS profile registry entries are kept. Dropped entries are also erased from disk on the next write. See

script = candidate.as_posix()
except Exception: # noqa: BLE001 — remediation text must never break the 409
pass
parts = [script]
if profile:
parts += ["--profile", profile]
if region:
parts += ["--region", region]
return shlex.join(parts)
def _base_remediation(profile: str, region: str) -> str:
"""Operator commands for a finite-TTL deploy when the BASE stack is missing.
``install-reaper.sh`` reads the base stack's outputs first and exits with
"base stack not found" when it is absent, so handing it over alone is a
command that cannot succeed in that state. The base has to come first.
``deploy.sh`` is the only script that creates it, but it also publishes an
app directory, so the remediation spells out its base step instead: the same
``cloudformation deploy`` of ``templates/base-stack.yaml`` that
``deploy.sh`` runs, then the reaper install.
"""
template = "templates/base-stack.yaml"
try:
from kiro_crew.skills import skills_dir
template = (skills_dir() / "artifact-deploy" / "templates" / "base-stack.yaml").as_posix()
except Exception: # noqa: BLE001 — remediation text must never break the 409
pass
parts = [
"aws",
"cloudformation",
"deploy",
"--stack-name",
"kirocrew-deploy-base",
"--template-file",
template,
"--no-fail-on-empty-changeset",
"--tags",
"kirocrew:managed=true",
]
if profile:
parts += ["--profile", profile]
if region:
parts += ["--region", region]
return shlex.join(parts) + " && " + _reaper_remediation(profile, region)
and
def _well_formed_entry(raw: Any) -> bool:
"""True when a stored registry entry's ``name`` and ``region`` pass the
field specs its writers enforce (``STORED_PROFILE_SPEC`` / ``REGION_SPEC``).
The registry file is agent-writable, and a stored entry's name and region
flow into ``aws`` argv and into the copyable remediation command exactly
like a request's ``profile`` does -- but ``_resolve_profile`` validates only
the request parameter, and a request that names no profile is served the
registry default unvalidated. Checking here on load is what makes "a deploy
only ever runs with a registered profile" also mean a well-formed one. An
empty region is admitted: ``make_entry`` fills in the default.
The stored value itself must pass, not a cleaned copy of it:
``validate_field`` sanitizes a string (control characters, NUL, padding)
before matching the pattern and returns the cleaned form, while the entry
keeps the raw one. A raw ``"p\\x00"`` that validates as ``"p"`` would still
be the string handed to ``aws`` argv, where an embedded NUL raises out of
``subprocess`` as a 500. So an entry is well formed only when validation
returns it unchanged.
"""
if not isinstance(raw, dict):
return False
name = raw.get("name")
region = raw.get("region", "")
if not isinstance(name, str) or not name or not isinstance(region, str):
logger.warning("deploy profile registry: dropping malformed entry %r", str(name)[:40])
return False
try:
clean_name = validate_field(name, STORED_PROFILE_SPEC)
clean_region = validate_field(region, REGION_SPEC) if region else ""
except ValidationError:
clean_name, clean_region = "", None
if clean_name != name or clean_region != region:
logger.warning("deploy profile registry: dropping malformed entry %r", name[:40])
return False
return True
def _parse_registry(raw: Any) -> dict[str, Any]:
"""Build the v2 registry from a parsed ``profiles.json``-shaped document.
Entries that fail :func:`_well_formed_entry` are left out. The default is
then settled by WHY it is missing: a default that names no entry at all (a
stale pointer) falls back to the first profile, as it always has; a default
whose entry was present but dropped as malformed becomes ``""``. Falling
back there would silently point a deploy that names no profile at a
different account and region, with no error -- a 400 "not configured" is
the honest answer, and the warning log names the dropped entry.
This is a LOAD-time guarantee only: this function never substitutes a
profile. A later registry write runs under its own rules -- the AWS
control app's unregister route, for one, fills an empty default with the
first kept profile -- so the cleared default can be re-pointed by an
explicit profile edit afterwards.
"""
entries = [p for p in raw.get("profiles", []) if isinstance(p, dict)]
profiles = [
make_entry(str(p.get("name", "")), str(p.get("region", "")),
account=str(p.get("account", "")),
verified_at=str(p.get("verified_at", "")),
note=str(p.get("note", "")))
for p in entries if _well_formed_entry(p)
][:_MAX_PROFILES]
default = str(raw.get("default", ""))
if default and not any(p["name"] == default for p in profiles):
# str(): the stored name may be a bare number (``123456789012``), which
# the loader has always normalized through ``str`` and which fails
# _well_formed_entry as a non-string; comparing the raw value would miss
# it and fall back to another profile, i.e. another account.
default_was_dropped = any(str(p.get("name", "")) == default for p in entries)
default = "" if default_was_dropped else (profiles[0]["name"] if profiles else "")
return {"version": 2, "profiles": profiles, "default": default}
.

I found no defect:

The rebase moved the renderers into handlers_guards.py. The rebase dismissed @buluoray's approval, so this head has no human approval. CI is green, including Security Scope Review and Sensitive Change Review.

To clear the hold, get a human re-review of this head. Optionally, add aws_project_profile.py:_registry_names to the Reader list, as the Design lane notes; it only lists names, so it is safe.

— crew-pr-reviewer (r116)

@iamwhatever
iamwhatever enabled auto-merge (squash) October 21, 2026 19:00
@iamwhatever
iamwhatever merged commit f0038be into main Oct 21, 2026
104 checks passed
@iamwhatever
iamwhatever deleted the fix/quote-deploy-ttl-409-remediation-17789 branch October 21, 2026 19:01
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

readiness: passed Eligible automated validation passed for the current revision

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix(deploy): quote the copyable remediation command in the TTL 409

4 participants