Repository navigation
feat(cloud): a configuration home for the Fargate lane, and register it when set - #11556
Conversation
Design Review (Fable 5) — 🟡 CONCERNSDesign-level review of Design-Verdict: CONCERNS The recipient confirmation is a string the API publishes then demands back verbatim, so any client that auto-echoes it nullifies the control while appearing enforced. WatchThe server cannot distinguish an operator who read Suggestions
[DESIGN-REVIEWED] dc345aa |
GPT 5.6 Review — ✅ no blocking findingsGPT 5.6 completed its review of This comment is updated in place on each push. Review detailsNo findings. False positive or not applicable? A repository writer can comment: |
Opus 4.8 Review — ✅ no blocking findingsReviewed Verdict parsed from the review's SHA-scoped output markers for commit False positive or not applicable? A repository writer can comment: |
First Principles Review (Fable 5) — 🟡 CONCERNSPremise-level review of First-Principles-Verdict: CONCERNS The confirmation step's human half has no surface — nothing renders Not justified as shipped
What this change shipsInventory (10 items) — 7 justifiedIntent: let an operator configure the Fargate lane in
[FIRST-PRINCIPLES-REVIEWED] dc345aa |
bbb0017 to
a2faa8c
Compare
a2faa8c to
2894d49
Compare
27fe585 to
c3170d6
Compare
Security Scope Review -- 🟡 CONCERNSWhich legitimate operations does Verdict basis: the reviewer's own judgement; no confirmed regression. Security scope review -- adjudicated candidates
No candidate flipped from allowed to refused. Scope-Verdict: CONCERNS TIGHTENING: ADJUDICATED: 17 candidates, 0 confirmed newly-refused PLATFORM COVERAGE: posix — home-anchored reads under UNADJUDICATED: The bulk of this tightening lives outside the shell-command composite, so no verdict exists for it:
[SCOPE-REVIEWED] dc345aa |
c3170d6 to
2b63145
Compare
Inherited reds cleared by #11593The two backend reds this PR carried earlier were not its own. Recording the chain so
The cure is #11593 ( One earlier red on this PR was a different inherited mechanism worth separating: a The measured before/after in the description is re-run against |
82f1b4d to
bd6061e
Compare
Problem / Motivation
The Fargate launch engine landed, but nothing could reach it.
FargateLaunchEngine,its task definition, its identity model and its
RunTaskplacement all exist undersrc/kiro_crew/cloud/fargate/, and yet onmaintoday:Two things were missing. There was nowhere for an operator to write down the values
the engine refuses to guess (cluster, subnets, security groups, digest-pinned image,
the model-credential secret), and the provisioner seam still shipped exactly one
lane, so no request could name
provider_id=aws_fargateand get an engine back.Why it matters
This is the step that turns the Fargate work from code in the tree into a lane a
launch can go through. Until it lands, every earlier piece is unreachable by
construction:
cloud.jsonhas no section that mentions Fargate, and the onlyprovisioner the core offers is
aws_ec2.It also decides what an operator sees when they get the configuration half-right.
Registering the lane unconditionally would put a row in front of them that rejects
every launch made through it, at launch time, for a mistake that was visible when
they saved the file.
What changed (motivation -> approach -> change)
Goal: give the Fargate lane a configuration home, and register the lane exactly
when that home is filled in.
RFC of record:
docs/request-for-change/rfc-remote-instance-on-fargate.md(
status: in-progress, already on main).FargateConfigincloud/config.pyholds the placement, the image and thesecrets, read out of the existing
cloud.json.is_complete()demands acluster, at least one subnet, at least one security group, a digest-pinned image,
a known CPU architecture, and a secret that names the model credential. Anything
else makes
from_mappingreturnNone, and that is what leaves the laneunregistered.
taskdef._refuse_absent_credentialrefuses a task definition that delivers nosecret under
KIRO_API_KEY, and the engine derives each secret's destinationvariable from the final segment of its canonical name. So a block carrying every
placement field and no credential secret is the offered-and-refusing state in its
most likely form, and the gate this PR ships is where it is cheapest to catch.
Only the NAME is judged here; whether the ARN is that name plus one service
suffix stays the engine's verification and is not duplicated.
that starts with one variable missing is harder to diagnose than one that never
starts.
(name, ARN)pairs, not bare ARNs. An ARN alone cannotsay where the secret's name ends: Secrets Manager appends a six-character suffix
and nothing marks the boundary. These are identifiers, not credential values --
the value is fetched by the task's execution role before the container starts, so
this file's written no-credentials contract holds unchanged.
assign_public_ipaccepts only a real JSON boolean when present. Coercing itwould read the string
"false"as true, and this is the one field in the blockthat decides network exposure, so a present non-boolean voids the block rather
than being guessed. An absent key still defaults to
False.cloud.jsonnaming a movable tag reads as no Fargate configuration at all.CloudConfig.fargatecarries the raw block, and completeness is judged at thepoint of use.
CloudConfigis loaded and re-saved to recordlast_tagafter anordinary EC2 launch (
cli_cloud.py,cloud/wizard.py), andsave()writesasdict(self). A field holding only a judged value would therefore erase a block anoperator is half-way through hand-editing. So
load()stores the block exactly aswritten,
fargate_config()answers whether it is usable, and the file round-tripsuntouched. Measured below.
The conditional lane inside
DefaultRemoteProvisionerProvider(platform/defaults.py).provisioners()always returnsaws_ec2and appendsaws_fargateonly when theblock is complete.
engine_for('aws_fargate')builds aFargateLaunchEnginefromthe block, and raises the same
KeyErroran unknown id raises when the blockis absent -- a caller naming an unconfigured lane and one naming a nonexistent
lane are in the same position, and a second failure mode would ask every caller to
learn a distinction that changes nothing they can do.
cloud.jsontakeseffect on the next request and deleting the block removes the lane, with no
gateway restart.
Nonerather than raising. This runs while the selectoris being built, so raising would take the
aws_ec2lane down with it and turn onelane's misconfiguration into a Set-up tab that shows nothing.
corrected in the same commit, rather than in a subclass.
test_remote_provisioner_seam.pyasserts the core's context composes exactly thisprovider; subclassing to slip past that
isinstancecheck would satisfy the letterand dodge the intent.
cloud/fargate/*and the RFC live in this repository, so thecore plainly means to own this lane.
import raises
ImportError: cannot import name 'current_context' from partially initialized module 'kiro_crew.platform'--kiro_crew.cloudreacheskiro_crew.sandbox, which importsplatform.current_context, whileplatformisstill initializing. That circular import is the real reason for the deferral, and
a test now pins it. Weight, measured separately, agrees:
kiro_crew.cloud.configis 105 ms and 122 modules against a 126 ms init.
cloud.jsonis sealed against agent writes at both layers, and this PR is whatmakes that necessary.
The obvious framing of why that is needed is wrong, so say the real one plainly. It is
true that the block stores a secret's NAME and ARN rather than its value, and that the
execution role fetches the value before the container starts, so the file's
no-credentials contract is intact. That is beside the point. An identifier that
selects WHO RECEIVES the credential is as powerful as the credential, and the
distinction between storing a secret and naming its recipient collapses the moment the
file is writable by the thing you are defending against.
fargate.imageis thatidentifier: it names the container the launch runs, and
KIRO_API_KEYis deliveredinto whatever it names.
_DIGEST_IMAGE_REconstrains the reference's FORM, not whoowns the registry, so a prompt-injected agent could point it at a digest-pinned image
of its own and leave the owner's cluster, subnets and secret refs untouched.
Per-crew role scoping does not cover this: the attacker's image runs AS that crew's
task, so a secret read scoped to
kirocrew/crew/<crew>/*still lands in it. Scopingbounds blast radius across crews, not this.
Before the
fargateblock,cloud.jsonheld a profile name, a region and a tag --nothing that chose a recipient. So the protection ships with the change that creates
the exposure, reusing the mechanisms already in the tree rather than adding a new one
beside them:
security.paths._WRITE_PROTECTED_HOME_PATHSsandbox._CREW_READONLY_LEAVESopen(..., "w"), which never passes the tool gatesandbox._CREW_PRECREATE_READONLY_FILE_LEAVESmount(2)cannot seal a missing pathsandbox._CREW_NOFOLLOW_READONLY_FILE_LEAVEScloud.jsonis the only name this change adds to those lists, and nothing sits beside it: theadvisory lock these lists used to carry is gone with the writer that took it. Under the
option-C ruling the file's write-protection is defence in depth rather than the property the
design rests on, so the answer to a gap in a name-shaped seal is not a further name.
The whole file is sealed rather than the block alone, and nothing in the product needs
exempting from that seal: the launch path's own fields live in
cloud_launch_state.json, sothe only writer left is the operator themselves, outside both the agent's file-edit gate and
the sandbox. Sealing one sub-key would have needed
a bespoke second mechanism for a single field; sealing the file reuses the four the
tree already has. It stays READABLE at every layer, because the gateway reads it on
each request to build the provisioner list and a script cron resolves it in-sandbox --
masking it would take the Set-up tab down instead of protecting it.
Owning specs are updated in the same commit, as AGENTS.md requires.
docs/system-specs/modules/cloud.mdgains a section documenting the block's schema,the incomplete-means-absent rule and the seal, and its
config.pyandfargate_engine.pyrows no longer say the engine is unreachable or that the fileholds profile and region only.
docs/system-specs/modules/platform-context.mdnolonger describes the core as shipping a single lane.
platform/bootstrap.pyis deliberately untouched for that same circular import.It is not a weight judgement that could be revisited later; importing the config
module there does not work.
Measured before / after
Driven from a clean tree against a scratch config home, printing
provisioners()and
engine_for('aws_fargate')for each state ofcloud.json, then loading andre-saving the way an EC2 launch recording
last_tagdoes:engine_for('aws_fargate')returning an engine is the first time that has happenedin this repository. Three rows are worth reading closely:
block deletedreturns to['aws_ec2']. That is the per-call read beingvisible rather than asserted.
no credential secretandpublic ip "false"stay unregistered. Each hasevery placement field; each would otherwise be a lane that exists and refuses.
maintoo, andmaindestroys bothshapes.
mainhas nofargatefield at all, soasdict(self)writes a configwithout one and the operator's block vanishes on the first EC2 launch. This PR is
what makes that text survive, for a complete block and a half-written one alike.
What this does not do
Registering the lane makes it reachable through the API. It does not put a row in
the Set-up picker:
RemoteProvisioner.kindnames a frontend form, the dashboard skipsa kind it cannot draw, and no
registerRemoteProvisionerRendererclaimsaws_fargateanywhere today. Absent from the picker, not broken in it -- which is what that skip
exists for. No AWS resource is created by anything in this diff.
The escalated decision is resolved: option C
The open question on this PR was whether to keep defending
cloud.json's bytes. The rulingis no -- remove the file's power instead -- and this revision implements it.
Why the question existed.
cloud.jsonis only dangerous because of what it decides:fargate.imagechooses the container a launch runs, and the task's execution role deliversthe model credential into it. Every defence of the file itself is a protection over a NAME,
and a name-shaped protection has to be argued complete for each platform and each way a name
can be aliased. Eight instances of that one class were found against this single new leaf over
this PR's review rounds, the last two inside the patch written to close the previous six. That
is a signal about the shape, not about the care taken on each patch.
What C does instead. The launch path resolves the credential recipient and refuses to hand
anything over unless the operator confirmed that recipient for this launch. A rewritten
cloud.jsonthen changes what the launch resolves, which no longer matches what the operatorconfirmed, so the launch is refused with both values named. A substitution becomes something
the operator SEES rather than something that happens quietly. The confirmation does not come
from the file, is not persisted, and depends on no filesystem property.
What was deleted
The sidecar that preserved displaced bytes is gone, not guarded: the helper, its two
constants, its entries in four seal lists, and its sixteen tests. Both blocking review findings
on the previous head were defects OF that mechanism -- a preserved copy the write gate did not
cover, and a directory leaf no alias check validated -- so removing the code removes what they
are about. Answering them by adding two more names to a seal list would have been instances
nine and ten.
The write into the operator's file is gone entirely, which is the next section.
config.pyretains only a reader, so there is no longer a state in which a product write has to choose
between overwriting an operator's bytes and refusing.
What was added
fargate/taskdef.py::credential_recipientFargateConfig.credential_recipient()POST /api/cloud/launch->confirm_recipientengine_for(..., confirmed_recipient=)FargateLaunchEngine.provision, first checkThe recipient is the digest-pinned image plus the ARN of the secret that carries the
credential. Both, because both decide who receives it, and which secret that is comes from the
engine's own
secret_destinations_forrather than from a name match. It is the exact stringsand not a digest of them: a fingerprint an operator cannot read is one they cannot refuse.
One renderer, not two. The confirmation is a comparison between what an operator was shown
and what a launch resolves, so two spellings would make it a comparison of the renderings.
FargateConfig.credential_recipient()delegates to the engine's function.The comparison is against the SPEC, not against a re-read of the file. Resolving it from
cloud.jsonagain insideengine_forwould be the file confirming itself. The seam thereforecarries the operator's value through unchecked and unnormalised, and
provisioncompares it towhat it is about to launch.
Refused before
RegisterTaskDefinition, not only beforeRunTask. A revision is durablein the account and carries the secret ARNs, so a confirmation checked only at run time would
already have written the recipient down.
A resumed launch job is refused. It carries no confirmation, because persisting one would
put the operator's answer on disk beside the file it is meant to be independent of, and a
rewrite of both would be silent again. A launch resumed after a gateway restart has to be
re-requested. That is a deliberate consequence, not an oversight.
The same move again: the launch's own state leaves the operator's file
Two review findings on the previous head shared one root, and the fix is C's own shape rather
than two local patches.
What they were. A malformed
cloud.jsonlet the deploy succeed -- billed -- and then thepost-deploy write raised, so the command aborted before sign-in and dashboard setup. And
between the witness re-read and the replace, a concurrent operator save could still be
clobbered.
Both are properties of writing launch-owned state into a hand-edited file. So that write is
gone.
profile,regionandlast_taglive incloud_launch_state.json, which the launchpath owns and nothing hand-edits. There is no post-deploy write into the operator's file to
refuse on, nothing of theirs to clobber, and no cross-process lock to hold -- the advisory lock,
its bounded acquire, its unusable-lock discard and both of its sandbox seal entries are deleted
with it.
cloud resumestill re-attaches. An install that launched before the record existed has itspointer in
cloud.json, soLaunchState.load()falls back to those fields when the recordholds none. That fallback is read-only: migrating by writing would reintroduce the write being
removed, and it would write on a READ, so every
cloudsubcommand would touch the operator'sfile. Once a launch has written the record, the record wins, so a stale pointer cannot outrank
the launch that happened and a tag
destroycleared stays cleared.The record's own write is also non-fatal.
wizard._record_launchswallowsOSError, warns andprints how to reach the instance, because every caller runs after its remote work and sign-in
matters more to the operator than a pointer
kirocrew cloud listcan rediscover.The operator reads the recipient before confirming it
A confirmation the operator can only obtain by attempting a launch and reading the refusal is a
copy-paste ritual, not a decision -- they never see the recipient in time to recognise a wrong
image. So the resolved recipient rides on the DESCRIPTOR, which is the row a launch card is
drawn from and which
GET /api/cloud/provisionerspublishes asconfirm_before_launch.POST /api/cloud/launchthen requiresconfirm_recipientexactly when the resolved rowcarries a value. The requirement is DERIVED from the lane rather than hard-coded to one id, so
a client cannot reach a launch without having read what it must confirm, and the refusal echoes
the value so a stale client can correct itself. The engine still resolves and compares against
what it is about to launch, which is the check no caller can skip; the handler's exists so the
refusal arrives before a job file is persisted. The built-in EC2 lane carries no value and is
untouched: nothing in a configuration file chooses what its credential reaches.
The remaining step is the frontend renderer for the
aws_fargatekind. Until one claims thatkind the dashboard skips the row, as the seam documents, so the value is published and demanded
but not yet drawn on the panel. That renderer is its own change; every piece it needs is in
place and tested.
No launch path answers 500
Three review findings were escape paths rather than wrong decisions: the check was in the right
place, its exit was not. A
500tells an operator to file a bug; each of these has a remedythey can carry out, so each now answers a coded
400that names it.recipient_not_confirmedcloud.jsonreachable under a second nameconfig_alias_refusedlane_cannot_confirmengine_forsignatureThe alias refusal stays where it is. It is raised where a launch consumes the file, which is
the placement the exposure calls for, and only its escape changed. The message already named the
file and the remedy; now it reaches the client instead of becoming a stack trace. It is also
answered under its own code rather than folded into
unknown_provisioner, because tellingsomeone whose configuration is symlinked that the lane does not exist sends them to the wrong
thing entirely.
The seam keeps the keyword.
confirmed_recipientis keyword-only with a default, so aprovider written against the older signature is still conforming -- and calling it with the
keyword raised
TypeError, which escaped anexcept KeyErrorand became a 500. The call nowdispatches on the provider's SIGNATURE: one that accepts the value receives it, one that cannot
is called as it was before the keyword existed. Deciding by signature rather than by catching
TypeErroris deliberate: an exception-driven retry cannot tell a binding error from aTypeErrorraised inside the provider's own body, and retrying the latter would run half of ittwice.
A lane that declares a recipient while its provider cannot receive the confirmation is refused
rather than launched. Publishing a credential recipient and then being unable to accept the
operator's answer to it is the silent-substitution shape the confirmation exists to remove, and
launching would leave them believing they had confirmed something.
The launch record's read is bounded before it allocates
_read_documentreads at most_MAX_FILE_BYTES + 1and decides from that. Reading the filewhole and checking the length afterwards is not a bound -- the allocation has already happened
by the time the check can look at it, and the file does not have to be written a byte at a time
to be enormous, since
truncate -smakes a sparse one instantly.The extra byte is load-bearing and its own test initially could not prove it. Reading exactly
the ceiling makes the length check mean "the read stopped here" rather than "the file is longer
than this", so an oversized file whose first
_MAX_FILE_BYTESbytes are a COMPLETE valid recordpasses the check and is adopted -- a truncated prefix read as the whole document. A file at
exactly the limit is accepted either way, so asserting on that case was non-discriminating and
the mutation survived. The test now builds exactly that crafted prefix, and the code comment
states the real reason.
The alias refusal was only half-removed, and no test could see it
Removing the strict check from
wrap_argvleft the same behaviour reachable one function over._materialize_sealable_ceilings, whichnamespace_argvcalls on every Linux sandboxedspawn, still ran
_require_real_file_nofollowon an existingcloud.json-- so on theprimary sandbox platform a stow / chezmoi /
rsync --link-desthost still lost every chat turn,cron job and subagent, while this same commit's spec, comment and mutation row all said it
could not.
Both pinning tests were blind to it for one reason: they read source text. One AST-inspected
wrap_argv's own body; the other called the warn helper directly. Neither executes the path thatrefuses, so both pass while the host is unusable. The replacement runs
_materialize_sealable_ceilingsitself, withcloud.jsonas a symlink and as a second hardlink,and requires it to return. Restoring the refusal reddens it -- two failures, one per shape.
A third test closes the shape of the miss rather than the instance: the strict FILE check's
callers must be exactly the two CONSUME seams --
require_unaliased_cloud_configandrequire_unaliased_launch_state-- asserted over the whole module rather than per function. Aper-function check is what let a second call site survive a rename, and a spawn-path caller
appearing under any name fails this.
playwright-clikeeps main's own strict DIRECTORY rule. That is main's behaviour, not aregression here, and it is outside this change.
The launch record is sealed, and that completes C rather than counting doors
Moving the tag out of
cloud.jsonmoved a power with it: the tag is whatcloud destroyresolves when no
--tagis given, so an agent able to write the record could choose which ofthe owner's stacks a
destroy --yesdeletes. Sealing the record is what finishes that move, notone more patched bypass -- which is why it is added despite this PR otherwise adding no seal
names.
security.paths._WRITE_PROTECTED_HOME_PATHSsandbox._CREW_READONLY_LEAVESsandbox._CREW_PRECREATE_READONLY_FILE_LEAVESIt is deliberately NOT in the strict no-alias list, which is not the same as unguarded: that
list is walked where a spawn is prepared, so a leaf in it refuses every sandboxed spawn on the
host. The record's own alias refusal sits at its consume seam instead -- the next section.
Pre-creation forced one real change to the reader. The seal needs a file to bind to, so the
launcher writes
{}where none exists -- and read as a record, that stub answers "no previouslaunch" for every install whose pointer still lives in
cloud.json, breakingcloud resumethefirst time an agent spawns. The fallback is therefore keyed on the three KEYS being present
rather than on the document parsing: a
{}stub is not a record and falls through to the legacyfields, while
destroy's record carrieslast_tag: ""and does not, so a cleared pointer stayscleared. Both directions are mutation-covered.
An aliased launch record is refused where its tag is consumed
Sealing the record on three layers left one name uncovered, because every one of those layers
names a PATH: a symlink at the name, or a second hardlink to the inode, is reachable by a name
none of them matches. A write through it puts any tag in the record, and a
destroy --yesdeletes the stack that tag names, with the data on it.
launchre-attaching to a forged tag isthe same substitution one step quieter.
So the record gets what
cloud.jsonalready had, in the same kind of place -- the seam thatCONSUMES the file, never the spawn path:
cloud.jsonrequire_unaliased_cloud_configrequire_unaliased_launch_stateLaunchState.load, the read every tag-consuming verb goes throughFour parts of it are decisions rather than mechanics.
Not added to the strict no-alias list. That list is walked where a spawn is prepared, so a
leaf in it refuses every sandboxed spawn on a stow / chezmoi /
rsync --link-desthost: the wholebox for one command's exposure, and the regression Design already blocked on this PR. A test
executes
_materialize_sealable_ceilingswith the record aliased in both shapes and requires thespawn to proceed, so re-arming it reddens.
The same guard covers the LEGACY fallback. When the record holds nothing,
loadreadscloud.json's fields instead -- and that file is then the source of the tag, sorequire_unaliased_cloud_configruns before it is read. Guarding only the record left the identicalhole open through the old file, and not as an exotic case:
cloud.json's own guard sits on theLAUNCH seam (
defaults.engine_for), which a teardown never runs, and the empty{}record thesandbox pre-creates is the DEFAULT state on any install that has ever spawned an agent. So an
aliased
cloud.jsonplus that default handedcloud destroy --yesa forged tag with no alias checkanywhere between the file and the deletion.
clear_tagstill reads both files unguarded, because itruns after the stack is already gone.
The sibling sweep that finding asked for, by enumeration rather than by reasoning: three consumers
read the tag (
wizardline 365,cli_cloud._resolve,cli_cloud._resolve_tag) and all three reachthe guarded
load. Two readers touch the credential-selecting config --engine_for, guarded atthe seam, and
provisioners, which renders the recipient for DISPLAY. The display one isdeliberately not guarded and cannot deliver a credential: a launch from a forged display is refused
at
engine_for, and if the alias is removed in between, the confirmation is compared against thespec the launch actually builds, so a substituted recipient is refused rather than delivered.
The refusal takes the path being read, not a derived one, so the file checked and the file
consumed cannot be two different files. A test reads an alias-backed file while the crew home
holds an ordinary record; a derived-path guard passes every other test and fails that one,
because under a test that sets
KIROCREW_HOMEthe two paths coincide.clear_taguses an unguarded read, deliberately. It runs after the stack has already beendeleted, so a refusal there would abort a command whose irreversible work is finished -- the exact
shape this PR removed from the post-deploy write. The guard is not skipped: it ran at the consume
point that produced the tag being cleared.
It is a named refusal, not an escaping exception.
handle_cloudcatchesSandboxCeilingUnsealablefor the whole dispatch table, so every verb -- and any verb addedlater -- prints the file, the shape and the one command rather than a traceback. Each strict leaf
supplies its own harm and remedy to the shared check, with no default, because a message naming
the wrong consequence sends the operator at the wrong file.
And the command is the operator's own platform's. The first version rendered
rm <shlex.quote(path)>unconditionally, which on Windows producedrm 'C:\Users\...': acommand that shell does not have, quoted in a way
cmddoes not use, for a file that does exist.It reddened Backend Tests (Windows) (4) with four failures.
sandbox._delete_file_commandnowrenders it:
rm <posix-quoted path>del "<path>"cmdbuiltin AND a PowerShell alias forRemove-Item, so one spelling works in both shells;rmexists only in PowerShell, and a Windows path cannot contain"so no escaping question arisesThe platform is a parameter with the host as its default, not only a read of
IS_WINDOWS.That is the actual fix for the shape rather than for the instance: this is the fourth
platform-axis defect in this PR, and all four were a string written once, verified where it was
written, and asserted as general. A renderer that only reads the host leaves its other branch
measurable on that other host alone, which is how this reached CI. Three tests follow from that:
both renderings asserted from one host, the refusal MESSAGE asserted with the flag forced so the
exact string a Windows operator reads is exercised here, and the platform-dependent assertion in
the original test now written per platform instead of POSIX-only.
The sweep that finding asked for, over every operator-facing string this PR adds to
src/: onehit, the
rmabove. Grepping the added lines forrm/cp/mv/ln -s/chmod/sudo/$HOME/~///tmp/returns that line and one docstring mention of$HOMEthat names no command. Theother refusals added here are platform-neutral prose (
cloud.json's remedy names no command) orproduct commands that are the same everywhere (
kirocrew cloud list).Every pin here EXECUTES the path. Three times in this PR a test that read source text passed
while the behaviour it named was wrong, so none of these inspect source: they call the read, and
one drives the destroy verb end to end with
ec2.describeandec2.destroyreplaced by a raisingstub, so a refusal arriving late enough to describe or delete anything fails the test. Mutations:
7 of 7 red, baseline green before and after, failure counts 8 / 7 / 3 / 2 / 4 / 2 / 1.
One lock, for one read-modify-write, on all three platforms
clear_tagreads, compares and writes, so a launch recording its tag in between was overwrittenand the pointer to a live instance lost.
recordandclear_tagnow take one advisory lock.It uses
platform_compat.file_lock, notflock_compat.flock. That shim exists to keep theimport graph loadable on Windows and its
flockis a NO-OP there -- correct for the gatewaymachinery, which never runs on Windows, and wrong for this file, because
kirocrew cloudisexactly what a Windows client runs. So the one platform where the shim did nothing is a platform
where both writers are live, and a destroy completing alongside a launch could let the clear
overwrite the new tag. The compat lock serialises on all three: POSIX through
fcntl.flock,Windows through
msvcrt.lockingon the lock file's first byte, which is why the lock lives in adedicated
.lockfile rather than on the record.fcntl.flock, exclusivemsvcrt.locking, first byteA lock that cannot be taken RAISES rather than running the critical section unlocked. An
earlier revision logged and continued, which put
clear_tag's read, compare and write back intothree steps exactly when the lock was unavailable -- the failure the lock was added for. Strict is
affordable here because every writer's caller already answers that
OSError, and the two answersdiffer on purpose:
wizard._record_launchwizard._clear_prior_pointercli_cloud._cloud_destroy's clearSo a filesystem with no lock support degrades to "no pointer, with a warning", never to a failed
command and never to a silently overwritten pointer. That is the opposite call from the spawn-path
refusal this PR downgraded, for a concrete reason rather than a preference: there, strictness cost
every sandboxed spawn on the host and no caller was in a position to absorb it. Here three are,
and a test drives both wizard callers with the lock unavailable to show it.
This is not the stack deleted earlier in this PR. That one guarded the OPERATOR's file against a
person in a text editor -- a writer that takes no lock, which is why it needed a witness on every
replace, a bounded acquire and a livelock bound. Here both writers are Crew's own, both take this
one, and there are exactly two.
Pinned by three tests rather than by a comment: the lock is taken through the compat helper with
exclusive=True(observed at runtime, because the platform where the difference shows is not theplatform CI's POSIX shards run); the lock is really HELD during the critical section, proved by a
non-blocking acquire from a second file description being refused; and an unusable lock still
completes the write.
A failed pointer write can only leave "no target", never "the wrong target"
Letting a failed write warn and continue is only safe while the PREVIOUS pointer is already
gone. It was not. With
kc-oldsaved, a--newlaunch that came up healthy and then hit ENOSPCon the record write left the record naming
kc-oldwhilekc-newwas the stack that existed --and a later
cloud destroywith no--tagresolveskc-oldand deletes it. Irreversible, withits data, and nothing on screen says the pointer is stale.
So the pointer to the previous stack is cleared BEFORE provisioning, and a failure there aborts
the launch. The two halves are opposites deliberately, and the reason is WHEN each runs:
_clear_prior_pointer_record_launchcloud listdestroy'sclear_tagThat ordering is what makes the failure lossy instead of destructive: the worst reachable
outcome is a record with no tag, which
cloud listsettles. It is also the same move as thedecision this PR rests on -- remove the power rather than defend the write.
A declined clear aborts as well, and that took two attempts to get right.
clear_tagisconditional on the pointer still naming the tag this launch observed, and its
Falsewas beingread as success -- so when another launch had recorded tag B in between, this one provisioned
anyway, and a failed record write then left B saved while the new stack was the one that existed.
A no-tag
destroywould delete B, someone else's live stack.The first fix aborted on the bool, and four existing tests reddened. They were right:
Falsecovers two states and only one is a hazard.
The bool cannot tell those apart, so the decision uses the tag the compare actually saw:
LaunchState.try_clear_tagreturns(cleared, saved_tag)from inside the SAME hold of thewriter lock. Reading the record again after the decline would answer about a file that can have
moved on between the two reads, and in a stubbed test it answers from the stub rather than from
the file the compare used -- which is exactly how the first attempt produced four false failures.
clear_tagkeeps its bool contract, so its other caller is untouched.destroy's own ignored return was re-derived by the same question rather than left as anomission: a decline there means the pointer names the concurrent launch's live stack, which is
the correct pointer for it, and nothing follows that line but the success message. The comment
now says that.
A sweep for the same shape across this PR: every bare-call statement the diff adds to
src/wasenumerated from the diff and its callee's return type checked. Two call sites discard a real
bool, both
clear_tag-- the launch one, fixed here, and destroy's, correct and now justified inplace. Four others flagged by name (
ui.fail,LaunchState.record,_audit) returnNone; theflags were collisions with same-named functions in other modules.
One mutation survived the first sweep and earned a test: returning
""instead of the saved tagfrom a declined compare passed everything, because the wizard test stubs that method. Four tests
now drive the real one, and the abort test asserts the deploy function was never invoked rather
than only the exit code.
Four tests drive the real
launch()against a real record on disk, because the property is aboutwhat is on disk at two different moments and a stubbed
LaunchStatecannot show it: the finding'sown scenario end to end (rc 0 AND the pointer empty rather than
kc-old, so fixing this one doesnot undo the previous one); a failed clear aborting with the deploy stub set to raise if reached
and the pointer unchanged; the ordering observed from INSIDE the deploy; and a resume not clearing
a pointer that is still correct.
destroy's own semantics are unchanged. Corroborating the saved tag against live stacksbefore a teardown would add a further layer, but both reachable routes to a wrong pointer are now
closed -- an aliased record is refused where the tag is consumed, and the prior pointer is cleared
before a new stack exists -- so it is a separate decision rather than part of this fix. Recorded
in local backlog as
f-20260919-02with that reasoning, not as a public issue.Nothing after the irreversible AWS work can fail the command
destroycleared the saved pointer afterec2.destroyconfirmed the stack gone, so a full orread-only disk raised
OSErrorand the CLI exited non-zero with a traceback -- while the stackreally was deleted. Automation reading that exit code concludes the teardown failed, and the AWS
work cannot be retried. The clear now warns and the command still reports the removal; what is
left behind is a stale pointer, which
cloud listsettles.This is the same decision
wizard._record_launchalready makes on the launch side, one functionover, so the whole path was swept rather than waiting for the next round to name the next
instance. The result of that sweep:
LaunchState.clear_tagafter a confirmed teardownwizard._record_launchafter a billed deployconnect.register_instanceafter a deployexcept Exceptionand logsconnect.unregister_instanceafter a teardownsource.delete_sourceafter a teardownSo one fix, and four writes measured as already safe rather than assumed to be.
Known limitation, scoped separately
cloud.jsonkeeps its write-protection entry as defence in depth rather than as the propertythis design rests on. The crew-home leaf-seal mechanism those entries use is per-leaf and
shared by every governance leaf, so strengthening it is a change to all of them and belongs in
its own review rather than in this lane's PR.
Two advisory findings, fixed as a deletion and a sentence
The launch record's module docstring opened by saying "no read of it feeds a security decision",
which is the opposite of the destroy-target check further down the same file. That is not a
cosmetic mismatch: a comment asserting the inverse of a security property is what hid the Linux
spawn refusal for a whole round of this review, and it is what a future maintainer would cite
when removing the guard. It now says a read selects the default
destroytarget, which is whythe file is sealed and an alias-backed copy refused.
_PROVISIONING_WRITESreserved ingest room for fields the launch path used to write back intocloud.json. Nothing writes that file now, so the reservation described work no production codeperforms. Deleted, with the one test that asserted on its contents. Checked before deleting
rather than after: it had no reader in
src/, its only references were three lines in that test,and both length constants it derived from keep other users (
_TAG_MAX_LENin_TAG_RE,_MAX_STRING_LENin three validators), so no orphan is left behind. Net for this round: 17 linesadded, 47 removed, across three files, and the mutation sweep still reports 25 of 25 red with a
green baseline -- no behaviour moved.
A sweep over the prose, not another two fixes
Thirteen pushes of design change left comments describing designs that no longer exist, and
fixing them one finding at a time produced a fresh pair every round. So this pass takes the
class: every comment and docstring the diff adds was enumerated from the diff itself, filtered
to sentences ASSERTING something (refused, sealed, safe, unsealed, locked, never written, no
security role), and each hit read against the code beside it. 369 candidate lines across 20
files; the ones that were actually wrong all described a mechanism this PR MOVED, which is where
prose goes stale:
wrap_argvcloud.jsonsafe to leave unsealed"FargateLaunchSpec.confirmed_recipientdestroytarget (corrected in the previous push)cli_cloudand the provisioner selector both callCloudConfig.load()"cli_cloudreaches it through the launch record's legacy fallback now; the direct callers are the selector and that fallback_require_real_file_nofollowon the spawn pathwrap_argvblock_warn_if_alias_backedTwo claims that LOOK like the same defect were checked and left, because they are true:
_warn_unsealed_ceiling's docstring says the spawn is being refused, and both its callers raiseon the next line;
_warn_aliased_strict_leavessays it reports without refusing, which is whatit does.
Every function-local import the PR adds now carries the
# circular importannotation theconvention requires -- six imports in three places in
platform/defaults.py. The reason isMEASURED rather than asserted: importing any of
cloud.fargate.identity,cloud.fargate.runtask,cloud.fargate_engine,sandbox,cloud.configorcloud.launch_enginealready putskiro_crew.platform.defaultsinsys.modules, so amodule-scope import in that file closes the loop in every case. One annotation drops a module
count I had only measured loosely, since an unverifiable number in a comment is the same defect
class this sweep exists to remove.
Comments only: the mutation sweep still reports 25 of 25 red with a green baseline, so no
behaviour moved.
The reds on this branch, and who owns each
Five lanes are red and none of them is a defect in these files. Each is attributed by name,
measured against
kirocrew/mainrather than asserted:cloud/login.pyare byte-identical to main and no login file is in this difftest_theme_install.pycase-variant ancestor test; byte-identical to main, no theme file in this difftest_platform_log_append.py::test_concurrent_short_writers_serialize,FileNotFoundError: day.jsonl. It ran off the merge ref before the rebase -- the file was not in the branch at all -- and after it the file is byte-identical to main and no log module is in this diff. Re-measured on the rebased head; if it recurs it is main's and gets its own issue, since no issue names that test orday.jsonlcoverage xmlrefuses a source path inside the AppImage mount thattest_agent_home_isolation.py:448creates and unmounts; the file is byte-identical to main and Combine is skipped on most runs, which is why it sat latentTwo shard failures that WERE this branch's are fixed rather than attributed:
test_cloud_login_target.py::TestWizardTargetCompletion::test_assume_yes_without_region_refuses_instead_of_builder_idpatched a name the writer deletion removed, which is one defect that showed up on three
platforms (3.12 shard 4, Windows shard 4, and macOS shard 1). Coverage Gate was failing closed
downstream of those shards rather than on its own coverage reading.
The two macOS failures were confirmed deterministic rather than intermittent by finding them
byte-identical on an unrelated branch: run 35408578148 on
feat/schedule-once-autonudge, sametest ids, same assertions, same counts (1 failed / 38587 passed and 1 failed / 37442 passed).
A second identical failure on a foreign head is stronger evidence than a re-run on this one, so
no re-run was spent.
What remains mine, and what does not
Backward compatibility
Adding the
aws_fargateid is not a breakengine_for's contract is to raiseKeyErrorfor an id not inprovisioners(), and bothsides are gated on the SAME predicate rather than on two conditions that agree today:
So an id is in the list exactly when an engine exists for it, in both directions. An install
with no
fargateblock gets the built-in descriptor alone and aKeyErrorfor the new id,which is byte-identical to today. No caller could previously pass the id successfully, so
nothing that worked stops working, and the built-in
aws_ec2path is untouched.One honesty note on the strength of that claim:
_fargate_config()is read PER CALL, so anoperator deleting the block between a
provisioners()call and anengine_for()call seesthe id listed and then refused. That is the intended answer -- the lane really is gone, and
the handler reports
unknown_provisioner-- and per-call reads are deliberate so an edittakes effect on the next request rather than the next restart.
Two changes ARE backward incompatible, on purpose
cloud.jsonbecomes sealed. It moves from agent-writable to write-denied inside thesandbox, so anything that used to write it from a sandboxed process now fails. That is the
point of the change: the file selects the container image a Fargate launch runs, and the
task's execution role delivers the model credential into whatever image is named.
An alias-backed
cloud.jsonor launch record refuses the command that consumes it. A hostthat deployed its config as a symlink -- GNU stow, chezmoi, or an
rsync --link-destsnapshot --keeps spawning sessions normally, because the spawn path WARNS. What refuses is a Fargate launch
reading that config, and any
cloudverb reading an alias-backed launch record.Stated as an upgrade note, because the population that hits this is upgrading rather than reading
a diff. An earlier revision of this branch did refuse on the universal spawn path, which failed
every chat turn, cron job and subagent on such a host; that is the regression Design blocked, and
it is gone. Both refusals fire on a symlink and on a file with more than one hardlink, name the
file, and carry one command, rendered for the platform the operator is on. For the launch record
that command removes the file, because it holds a pointer the product rebuilds and
cloud listfinds the instance again. For
cloud.jsonthe bytes are the operator's, so the alias is replacedrather than removed -- reading through a symlink and giving a hardlink a new inode covers both
shapes at once:
POSIX:
Windows (
cmd;copyfollows a link and writes a new file):An install with no
cloud.jsonat all is unaffected: the precreate rule makes a plain emptyfile, which satisfies the requirement by construction. The four mechanisms this rides on, and
which agent action each one closes, are the table under "What changed" above.
That refusal is the wider blast radius of the two and it was taken deliberately, so the
reasoning belongs here rather than only the behaviour. Both candidate designs fail; they
differ in HOW. Refusing fails LOUDLY: the operator finds out immediately, the message names
the file and the remedy, and one command fixes it. Exempting the alias fails SILENTLY:
nobody finds out, and what happens instead is a model credential delivered into an
attacker-chosen image. A loud break the operator can fix beats a silent compromise they will
never notice, so the refusal reads no file contents at all -- contents are what an attacker
supplies, and any rule that reads them has the same hole.
A gentler shape exists and is NOT built here: seal a copied snapshot rather than failing the
spawn. It changes what an in-sandbox reader sees, which is a behaviour change deserving its
own review, so it is recorded as a follow-up instead of folded in beside a security fix.
One thing that looks like a third break and is not
ConcurrentEditRefusedreaching callers that never handled it was not a deliberateincompatibility. It is the defect this PR fixes, and the fix removed the write rather than
narrowing the refusal: no caller writes the operator's configuration at all now, so there is no
refusal for one to mishandle.
Tests
A green review lane is not a clean review
Worth stating for anyone reviewing this line, because it is the most reusable thing
this PR turned up. On the previous head, all five AI review lanes concluded
successwhile carrying four real findings in their comment bodies -- Design andFirst Principles as advisory
CONCERNS, GPT under "no blocking findings" with twoFINDINGlines inside a collapsed<details>. Every one of the four was verifiedreachable against live code and every one is fixed here:
successload()collapsed an incomplete block toNonewhilesave()re-emittedasdict, so an unrelated EC2 launch wrote"fargate": nulland destroyed a half-written blockconfig.pydocstring claimed ataskdefdrift pin that did not exist anywhere in the treeis_complete()never demanded the model-credential secret, so"secrets": []registered a lane the engine refuses on every launchbool(data.get("assign_public_ip"))read the string"false"as trueReading only the check conclusions on that head would have reported a clean review
and shipped all four.
Automated coverage
test/test_cloud_config.py::TestFargateConfig-- the boundary. A complete block isread; a non-dict block, a non-list
secrets, a secret entry that is not a two-stringpair, an empty name or ARN, a movable-tag image, an unknown CPU architecture, a block
naming no model-credential secret, a block whose secrets exist but none named for the
credential, an
assign_public_ipgiven as"false","0","true",1ornull,and each missing required field all read as
None. A boolean flag is read as written,an absent one defaults to
False, and the credential gate is shown to read only thesecret's name.
test/test_cloud_config.py::TestRespelledConstants-- the drift pin, which is whatmakes the docstring's claim true rather than aspirational.
_CPU_ARCHITECTURES,_DIGEST_IMAGE_RE.patternand_MODEL_CREDENTIAL_ENVare held equal totaskdef.CPU_ARCHITECTURES,taskdef._DIGEST_REF_RE.patternandtaskdef.MODEL_CREDENTIAL_ENV, and a further test assertscloud/config.pydoes notimport the engine -- the constraint that forces the respelling in the first place.
test/test_cloud_config.py::TestCloudConfigIsSealedAgainstAgentWrites-- the seal.An agent may not write
cloud.jsonunder either crew-home prefix, it stays readable,and the gateway can still save it. A positive control asserts an unprotected sibling
leaf under the same home comes back writable, so the class cannot pass vacuously
against a predicate that answered True for everything.
test/test_cloud_config.pyround-trip cases -- an incomplete block, and eachmalformed block shape, survive a load-mutate-save that changes only
last_tag.test/test_remote_provisioner_seam.py::TestFargateLane-- the lane. Unconfiguredoffers only
aws_ec2and raisesKeyErrorforaws_fargate; a complete block offersboth ids and builds a
FargateLaunchEnginewhose spec carries the block's placement,image, secrets and architecture; an incomplete block offers only
aws_ec2; a blockmissing only the credential secret also offers only
aws_ec2; deleting the fileafter a complete read drops the lane again; the
aws_ec2lane still returnsRealLaunchEnginethroughout; and importingkiro_crew.platformdoes not pull inkiro_crew.cloud.config, so a future module-level import fails here rather than atgateway start.
The existing seam test asserting the core composes exactly
DefaultRemoteProvisionerProvideris unchanged and still passes -- that is the pointof amending the provider in place.
Mutation matrix
Fourteen mutations for this revision, each reverting ONE behaviour it adds. The unmutated
baseline runs first and the sweep aborts if it is not green, restores come from a file copy
taken before the first mutation, and every row asserts its anchor applied exactly once so a
moved anchor reports NOT-APPLIED instead of a false kill. 14 of 14 red, and two later
rounds of review fixes add 9 of 9 and 10 of 10 on the same terms.
One row of the last batch reported NOT-APPLIED rather than red, and the reason is worth keeping:
its anchor was a 12-space-indented call line, which is a SUBSTRING of the 16-space-indented
identical call in the sibling loop, so it matched twice and measured nothing. Re-anchored on the
comment sentence only the intended branch carries, it reddens.
The twelve rows for the credential confirmation itself were measured on the previous head and
still hold; the engine's gate and its tests are unchanged by this revision.
The gate asks the engine instead of copying it
First Principles was right that the respelled-constants premise was void, and the
measurement backs it: importing
kiro_crew.cloud.configexecutescloud/__init__.py,which imports
cloud.awsand pullskiro_crew.sandbox-- 401 modules and 245 msbefore this module exists. Adding
fargate.identityandfargate.taskdefon top costs5 modules and about 4 ms, and
identityimports only the standard library, so thereis no cycle and no weight argument for a copy.
So all five copies are gone.
_names_model_credentialnow callsidentity.secret_env_name, and the architecture set and digest rule read the engine'sown values through small helpers.
TestRespelledConstantsand the three per-constantdrift pins went with them: there is nothing left to drift.
That also retires a defect that recurred three times, because each round fixed the
spelling that had been reported while the check remained an approximation:
"secrets": []-- no credential secret at allKIRO_API_KEY, and a wrong-prefixjunk/KIRO_API_KEYDelegating makes agreement structural rather than tested: no spelling can pass here and
fail at launch, because it is the same function deciding. The 180-combination probe now
confirms a tautology, and one earlier test had to invert -- a conforming NAME with a
mismatched ARN used to register on the argument that the pairing was the engine's job.
It no longer does. The boundary moved rather than being duplicated: still one copy of
the rule, and it now runs at config time too.
An aliased
cloud.jsonis refused where a launch CONSUMES itAn alias defeats both seal mechanisms -- a read-only bind seals a mount, a Seatbelt
deny file-write*matches a pathname, and in each case the alias reaches the same inode by aname the rule does not cover. So the refusal stays, and it is unconditional on content: an
agent with a writable alias does not need to swap a block it can create.
What changed is WHERE it fires.
wrap_argv)engine_for)Refusing on the spawn path failed EVERY sandboxed spawn on the host -- a chat turn, a cron job,
a subagent -- when
cloud.jsoncarried a second name. That is the shape an install laid down bystow, chezmoi or
rsync --link-desthas, for reasons with nothing to do with Fargate, and itmade the whole box unusable over one lane's exposure. The alias harm is a refused launch either
way, so that is what it now costs. The warning stays on the spawn path, because a log claiming
a seal that is reachable under another name is worse than the hole.
This does not weaken the load path's own rule. The earlier decision that a loud break beats a
silent compromise was about what happens when the configuration is READ for a launch, and that
is exactly where the refusal now lives.
Every secret is validated, not just the first that matches
_names_model_credentialreturned on the first reference whose destination was thecredential, so a valid credential ref sitting beside a malformed or cross-crew one
registered the lane and the engine then refused the whole document at launch. It now runs
the engine's own
secret_destinationsover ALL references andsole_bindingover theirARNs, so a set naming two crews, or containing an unusable ref, leaves the lane
unregistered. A same-crew sibling still registers.
A partly-malformed placement list voids the block
_bounded_string_tuplefiltered non-string members out, so a subnet list with one badentry launched the task in whichever subnets survived -- a placement the operator never
wrote. One bad member now voids the whole block, exactly as one bad secret entry does.
Pattern harvest: every finding on this PR was a class, and I kept patching instances
The most useful thing this PR learned, recorded because the next person editing
config.pyneeds it more than any individual fix. Three defect classes each came backtwo or three times, in a different field or a different line, because each round fixed
the instance that was reported:
bool()onassign_public_ipread"false"as truestr()onclusterturnedfalseinto"False"load()andsave()disagree about a boundsave()could write whatload()would refuseload()measured the compact form,save()emitted a larger pretty onecloud.mdsaid only a secret's NAME is judgedsave()after the deployopen(), then a stale-write refusal, in the same placeRule candidate: a rule with two implementations has no implementation. Every finding
above is two pieces of code encoding the same rule and drifting, not a missing check or a
wrong constant. The fix is never to correct the copy; it is to delete it, so the check and
the thing it checks are the same code executing.
Its counterpart for tests, learned the hard way three times on this PR: a comment must
not be able to satisfy an assertion about behaviour. A test that searched the source
text for a call name passed after the call was deleted, because the explanatory comment
beside it contained the name. Match real AST call nodes, not text. Two other tests here
passed for adjacent reasons -- one let
load()drop the block it was meant to preserve,and one measured a fixture that never reproduced the defect -- and in each case a mutation
staying green was the only thing that revealed it.
So each is now fixed once, where the class lives, not once per field:
a string field added later is covered without a new branch. A test pins the derivation
against
fields(FargateConfig).load()andsave()use it, so theycannot disagree about what fits.
secret_destinationsandsole_bindinginsteadof approximating them.
The alias refusal is one decision, not one per platform
require_unaliased_cloud_config()is a single function both platforms reach, because therefusal is a fact about the NAME and never depended on the sealing mechanism. A copy inside
each launcher would only give the two platforms something to drift on, which is how the macOS
branch came to skip the check while Linux applied it.
It reads no file contents at all --
lstatonly -- so there is no encoding to bypass andnothing to keep in step with the parser. An absent file costs nothing: the check returns on
FileNotFoundError.A delegated spawn is covered by refusing the SPAWN, not by sealing the file
A delegated spawn is confined by kiro-cli's own sandbox and Crew wraps nothing, so no seal of
ours holds there and the layers cannot nest. Two designs were tried and discarded before the
right one, and both failures are worth keeping because they are the argument for the shape that
worked.
Declining delegation when a Fargate block is configured was the first, and it is bypassable for
a reason already established on this change: an agent does not need to swap a field it can
CREATE, so with no block it writes a complete one. Any rule reading current contents has that
hole whatever the contents are. Declining delegation unconditionally was the second, and it is
not this change's to make: on macOS it wraps a kiro-cli spawn in Crew's seatbelt while kiro's
own sandbox is enabled, which the codebase states fails to initialize nested; on Windows there
is no Crew backend, so it refuses every session rather than this feature's.
The mechanism that fits already existed.
delegated_workspace_exposes_sealed_targetrefusesa delegated spawn whose workspace IS, CONTAINS or sits INSIDE the sealed kiro agents tree,
because Crew's launcher rule cannot reach a delegated child and refusing the spawn is the only
enforcement point left. That is the same category of rule with the same bypass, so the config
leaf joins its target list: the guard gained one entry and a per-target reason, and nothing new
was invented.
Three properties make this the right shape rather than a fifth patch:
a complete block -- pinned by a parametrized test over exactly those three.
delegated platform, usually a workspace containing the agents directory as well, and those are
already refused today. What is newly refused is a workspace that contains
~/.kiro/crewbutnot
~/.kiro/agents.leaves, so the twelve sibling governance ceilings could join it by being added to that tuple.
They are NOT added here: their exposure is main's, not this change's, and strengthening the
shared mechanism is the separately-scoped change noted above.
The list-shaped derivation had a shape-shaped hole, and that is the part worth reading. The
guard built its targets from the strict no-alias FILE leaves alone. A leaf sealed as a DIRECTORY
is not reached by a derivation over the file leaves, so such a leaf is uncovered with nothing
saying so, and no number of entries in either list closes it. The targets now come from one
mapping keyed by BOTH lists, with a module-level assert that the mapping and the two lists cannot
drift in either direction, so the next sealed leaf of either shape is covered by construction
rather than by someone remembering. The per-target wording comes from that same mapping, because
a lookup keyed by one list rendered the other list's consequence for any member it did not know.
That covers one leaf that is not mine:
playwright-cli, already a strict no-alias directory onmain. The incremental refusal is nil in practice -- a workspace over the crew home is refused by
cloud.jsonalready, so the only newly refused case is a workspace that IS that directory orsits inside it, which holds an executable the gateway runs and is why it is sealed. Leaving it
out would have meant re-creating the hole one member over.
cloud.jsonwritable by an agent?A record too deeply nested to serialize is refused at ingest
json.loadsaccepts nestingjson.dumpscannot emit, so a hand-editedfargatevalue canparse cleanly and then raise
RecursionErroron the way back out. The depth that breaks isnot a property of the document: the limit is on total stack, so the same value serializes
from a shallow caller and raises from a deep one. There is therefore no depth to validate
against, and only attempting the serialization can answer.
Both sides of the boundary answer it, which took two rounds to get right: the WRITER side
first, and then the reader.
json.loadsfails on documents that never become objects at all,and it does so through three different exception types -- a decode error, a
JSONDecodeError,the interpreter's integer-string limit raising plain
ValueErroron a 5,000-digit number thatis valid JSON syntax, and a
RecursionErroron depth it accepts less of than it can build.Naming those one at a time is what lets one be missed, so the read answers the whole class:
anything that cannot become a document reads as defaults, which is the same answer every
caller can act on.
JSONDecodeErroris aValueError, so that is a widening rather than areplacement.
Answered where the ceiling is answered, in the one place a record becomes text, and
reported as "does not fit" rather than raised. That puts the refusal at ingest, before
anything is provisioned, instead of in a
save()that runs after the deploy and is the callthat records the new instance.
Refused at the boundary, in other words, but the question "can this be written" is answered
by ASKING THE WRITER rather than by a depth limit of my own. A depth limit would be a second
shape rule free to drift from the serializer's real one, and it could not agree with it even
in principle: the serializer's limit is on total stack, so the same document is emittable
from one call site and not from another. The only thing that can answer for the writer is the
writer.
Nothing in the product writes
cloud.jsonThe launch path's own profile, region and tag live in
cloud_launch_state.json, a file itowns.
config.pyhas no writer left at all: nosave(), noapply_update(), no_writer_lock, no_merge_once, no precondition plumbing, no ingest reservation for what awrite-back would add. Roughly 550 lines of it are gone, and so are both
cloud.json.lockentries in the sandbox seal lists, because the lock existed only to serialise that write.
cloud.jsoncloud_launch_state.jsonfargateblock; the legacy pointerlast_tagLaunchState.record/clear_tagThe property is asserted on the module rather than on one path: no function in
config.pycalls a writing primitive, read off the call expressions so a runtime-built spelling cannot
pass. Two reviewer findings on the previous head were both about what that writer had to do
when the operator's file was not in a state it could use, and there is now no such moment.
The record is not sealed, deliberately. It carries no input to a security decision.
fargate.imageis the field that chooses which container receives the model credential and itstays in
cloud.json; this file holds a pointer, and every command acting on that pointerdescribes what it found first --
destroyprints the tag, describes the instance and asksbefore deleting anything.
The pointer belongs to the stack it names
destroyclearslast_tagonly while it still names the stack being deleted, soLaunchState.clear_tag(expect)compares before clearing and answers whether it did. Clearedunconditionally, a launch that recorded its own tag between the delete and the clear would have
its pointer wiped by a command that never saw it, and the operator's new instance would look
unlaunched. Only the tag is cleared: the profile and region still name where their other stacks
live.
There is no lock around that compare, and that is the simplification this file buys. Both
writers are product-side commands a person runs one at a time, and the value at stake is a
pointer rather than a configuration --
kirocrew cloud listenumerates the real stacks, so apointer lost to that window is rediscoverable. Bytes an operator hand-wrote are not, which is
why the same reasoning did not apply while this lived in their file.
The same question asked at the seal's boundary
Two of the findings are one question: the seal names a file, and both of them reach that
file's effect without touching that name. So the answer is the SET of ways this document can
be written, replaced, or have its write BLOCKED, and what covers each:
cloud.jsondeny file-write*(macOS), plus the alias refusal aboveO_NOFOLLOW, replaced when it is not a lone regular file, and the write proceeds without it rather than failingThe lock is the interesting row. It cannot join the read-only seal, because taking a lock
needs a writable descriptor, so a leaf sealed read-only would break locking on the very
platform that seals hardest. The answer is therefore not another rule about its name but
removing the dependence on it being trustworthy at all.
One red on this branch is not this branch's, and is not fixed here
Backend Tests (Windows) (7)failstest_snapshot_absent_vs_wrong_type.py::TestTheRollbackDirectoryBelongsToOneRestore::test_a_second_allocation_in_the_same_second_gets_its_own_directory.It is a pre-existing clock race in the TEST, and it is left alone deliberately: an
unrelated test fix inside a feature change makes both harder to review.
The test allocates two rollback directories and asserts the second's name starts with the
first's. That only holds when both land in the same UTC second, which the test's name
claims and its body never arranges -- it calls the allocator twice and hopes. On a slow
runner the second boundary is crossed in between, and the second allocation gets a fresh
timestamp instead of a suffix.
Verified by driving the clock rather than by re-running until it flaked, which is why the
answer is definite:
| both allocations at
...043200Z|pre-restore-20260918T043200Z-2| assertion holds || second at
...043201Z|pre-restore-20260918T043201Z| assertion fails |The second row reproduces CI's observed name exactly, and the same two runs on pristine
origin/main(420efd1a17) produce the same failure withsnapshot.pyand the test filebyte-identical to this branch's. This change touches zero snapshot, restore or rollback
files.
_allocate_rollback_diris correct in both rows: a different second already yieldsa distinct directory, which is all the production code has to guarantee. Only the
assertion depends on which row happened.
A fix belongs in its own change: freeze the clock across the two calls, or assert the
property that matters (the two directories differ) instead of the naming coincidence.
One finding deliberately not taken
First Principles also asked to delete the size bounds (
_MAX_FILE_BYTES,_MAX_LIST_ITEMS,_MAX_STRING_LENand thesave()refusal), arguing they defendagainst an actor outside every boundary the codebase names. That is a fair premise-level
argument, and it is the direct opposite of what the GPT lane blocked on: those bounds
exist because that lane raised the unbounded read as a security-class finding. GPT is a
hard gate and First Principles is advisory, so the bounds stay and the disagreement is
recorded here rather than resolved by quietly following the advisory lane. If a
maintainer prefers the subtraction, it is one commit and this note is the argument for
it.
The credential gate had to match the engine's whole name grammar
Three rounds of review found the same defect in this one check, each time in a
different spelling, because each fix addressed the spelling that had been reported:
"secrets": []-- no credential secret at allKIRO_API_KEY, and a wrong-prefixjunk/KIRO_API_KEYEvery one registered the lane and then refused at launch, which is the exact state
this PR claims to prevent, reached from inside the check written to prevent it. So the
gate now respells the engine's whole name grammar -- prefix, crew pattern, variable --
each pinned to its original, and the property test runs a 180-combination product of
prefixes, crew spellings and keys through
identity.secret_env_nameitself ratherthan restating the rule. Measured: zero names accepted here that the engine refuses.
A hand-picked list is what let this recur, so the test is a product.
The engine resolve moved off the event loop
_engine()was called directly inapi_cloud_launch_createwhile its sibling storecalls in the same handler are
await _in_executor(...), one of them commented "so aslow disk can't stall the gateway's other requests and its heartbeat behind it". That
was harmless before this PR, because resolving the built-in id constructs an engine and
reads nothing. This PR made the resolve read
cloud.json, so the blocking read isthis change's to fix, and it now goes through the executor like its siblings.
Two rows initially came back
ANCHOR AMBIGUOUSrather thangreen or red, because a text anchor matched several tuples; the harness refused to
mutate instead of scoring them, and they were redone with tuple-aware removal that
names the assignment. An anchor that silently stops matching is how a matrix prints
zero holes while verifying nothing.
cloud.jsonis also added totest_sandbox_governance_mask.py'sKEYSTONES, whichasserts the OS-level seal per crew-home prefix and per sandbox mode: 12 cases covering
the Linux read-only bind (present in
readonly, absent fromhidden) and the macOSseatbelt denials for
file-write*andfile-link, the latter being the hardlink shape.That list names paths individually on purpose -- a test derived from the same tuple the
production code reads would keep passing after someone emptied it.
The fifth row is there because the first run of this matrix
found a genuine gap:
_complete_blockhad been corrected and a comment described theproperty, but no seam test asserted it, so dropping the requirement passed the seam
suite untouched. That is the same shape as finding B -- prose asserting what no code
enforces -- one layer up, and it was the matrix rather than review that caught it.
Suite runs
On the rebased tree: the two touched suites plus
test_yaml_safe_loading.py-> 67passed. The whole
test/test_cloud_*.pysurface includingtest_cloud_wizard.pyandtest_cloud_cli.py, which exercise the load-then-save callers this change affects ->668 passed.
flake8,black --target-version py310,isort --check-only,scripts/check_black_formatting.py,scripts/check_comment_history.py(gated withCOMMENT_HISTORY_BASE_REF=origin/main),scripts/check_brand_name.pyandscripts/check_subprocess_encoding.pyall clean.Manual verification
N/A -- no AWS call and no UI surface is reachable from this diff. The lane's whole
observable behavior is which ids
provisioners()returns, which engineengine_forbuilds, and what
save()writes back, and all three are asserted directly in thesuites above; the before/after block is those same probes run by hand on both trees.
Related Issues
Part of #11328.