Compare commits

...
Sign in to create a new pull request.
Author SHA1 Message Date
140fbc3161 Merge pull request 'Static release carry: explicit 0444 under UMask 0027' (#9) from hands/static-carry-mode-0444 into main 2026-11-14 08:44:31 +00:00
d13d98a083 Carry comment: the web server reads the file, no verifier enforces it
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-14 08:44:30 +00:00
6c34758a30 Static release carry: explicit 0444 under UMask 0027
The carry file was created with .mode(0o444), which the service's UMask=0027
masks to 0440; www-data could not read it and the sealed-tree verifier
rejected it. Set the permissions on the open handle before the rename, and
prove it in a child process under umask 0027.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-14 08:21:12 +00:00
17edea299e Merge pull request 'Routing proof waits out nginx's reload handoff and names who answered' (#8) from hands/routing-proof-handoff into main 2026-11-14 04:28:18 +00:00
506df0a81f Merge pull request 'Liveness gates presence: route challenge and topology refresh only for a running incarnation' (#7) from hands/liveness-gates-presence into main 2026-11-14 04:28:06 +00:00
eace76870a Pin liveness cut: truthful past-due status, dead-topology test reaches its gate, report-once and empty-lease pins
Status says how overdue a route challenge is, not a cause it cannot see.
The dead-generation topology test engages the lifecycle brake so every tick
reaches the gate. New pins: observe/lease/demotion/stale-incarnation/projection
repair said once and cleared; a running target with an empty lease is not
route challenged.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-14 03:38:14 +00:00
c30f89f0df Pin the route handoff window, cadence, signer label and unchanged-route guard
The handoff loop reads its clock through a test-held virtual clock, so the
window and poll cadence are asserted exactly and no host load moves them; the
fails-at-once tests assert through stable_hits and the absence of sleeps.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-14 03:19:57 +00:00
47a9c3d89e Liveness cut: say lasting observe/lease/demotion faults once, mark a past-due route as waiting on a running incarnation
Applies Soul findings to cut-liveness-gates-presence: report_once+clear_fault
for the remaining per-tick eprintln sites in supervise_one_admitted_generation,
status marks a past-due challenge, tests for the unreadable-fragment and
HostUnobservable paths, F8 marked resolved in route-continuity-cut.md.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-14 03:02:47 +00:00
cdf987730e Routing proof waits out nginx's reload handoff and names who answered
systemctl reload only signals nginx's master; old workers keep answering
the stable listener until the new config is parsed and they are told to
quit, so Idunn's first challenge could reach the incumbent and fail the
attempt, rolling the fragment back. An answer naming the preflight's
incumbent instance is now not-yet for 10 s (one challenge per 250 ms,
never admitting, never actuating). Every failed proof now carries a
RouteProofAnswer context: the runtime instance and activation signer ids
the answer claimed (unauthenticated, ids only, 96 bytes each), so the
journal line and abort last_error say who answered.

Tests drive Routing through the stub runtime with incumbent-first,
never-lets-go, foreign-activation and stranger replies.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-14 02:39:27 +00:00
8dd9f8d503 Liveness gates presence: route challenge and topology refresh run only for an observed-running incarnation
Cut the pre-liveness route and topology supervision and the pre-challenge lease verdict; re-insert both calls after the running-branch incident close, with report_once and clear_fault per target. Rewrite the dead-unit test, add four tests, point the routed fixture's lifecycle brake store into the world.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-14 02:23:49 +00:00
7eae1c4ee1 Say why the stable route proof failed (#6) 2026-11-14 01:34:34 +00:00
74c04bbcc7 Merge pull request 'Steward-owned second deployment stop named by the binding' (#5) from eureka-self/brake-steward-store into main 2026-11-13 18:11:46 +00:00
c13e175bbf Steward brake: refuse a shared steward directory, name the proven owner, steward-only remedy
Binding validation refuses a steward store whose directory is shared with,
inside or around any other Idunn authority directory, since the steward owns
its directory and could unlink a root-owned store. The wait note names a
steward stop by the binding's steward user, not the record's claimed by. The
Unreadable hint for a steward store says only the owner uid can repair it.
Root-run tests skip with a message. Docs gain a provisioning runbook and the
sealed-binding recovery caveat.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 18:09:41 +00:00
c5a0ce3d23 Document the steward stop in deployment-authority
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 17:47:48 +00:00
37622db430 Deployment brake: a steward-owned second stop per target, named by the binding
BrakeBinding.steward = { user, store }. read_stops reads the operator store
as before and the steward store with the steward user's uid as the expected
owner, so the file owner proves who wrote it. Deploys admit iff every stop
admits; the wait note names each holding stop. Binding is stored as text in
the plan, so no persisted record changes. deployment-brake-status gains
--owner-user for the operator to read a steward's store.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 17:46:36 +00:00
58e744b745 Merge pull request 'Deployment brake is a stop: DeploymentStop record, signed release path deleted, record v6' (#4) from eureka-self/brake-is-a-stop into main 2026-11-13 17:43:21 +00:00
b230703a5c Idunn: a stop halts before irreversible steps; fail-closed reader; break-glass clear
- Re-read the stop at the static flip intent and at entry into Fencing for a
  deploy (stop_note, the same path as Sealing). After the intent or fencing
  the transaction runs to its end; documented.
- Absent means NotFound in an existing directory; every other lookup error,
  a zero-length file and a missing parent fail closed. Unreadable names the
  idunn-provision deployment-brake-clear command.
- replace_stop is the operator's break-glass: it replaces v1, foreign,
  ambiguous, zero-length and caller-owned undecodable stores, never a symlink
  or another user's file.
- Mutation-proven tests: foreign-owner Clear, Unreadable admitting at
  Sealing, author from USER.
- docs: stop semantics, v6 downgrade hazard and backup; legacy script no
  longer requires the store and drops the signed-grant wording; two stale
  doc lines.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 17:36:57 +00:00
a20568ef70 Idunn: the deployment brake is a stop, not a per-deploy gate
Delete the signed release path (deployment_brake_release, the operator
enroll/export verbs, the anchor option and flag, the consumed-once scan,
the durable re-verification, DeploymentAuthorization::validate_shape).
src/brake.rs is the one reader and writer of the stop
(idunn.deployment_stop.v1: engaged|clear, by from the process uid, reason,
at, sequence). Absent or clear admits; a foreign, corrupt, symlinked,
other-runtime or foreign-owned store fails closed. advance_sealing stamps
deployment_admitted_at_unix_millis (key 38) for Deploy and Rollback alike,
so static releases and rollbacks use the same stop.

Control record v6: key 38 changes canonical bytes, so v5 gets a legacy
layout, a lift, boot migration and pinned bytes tests. Key 16 stays a
never-written legacy field so old terminal records decode.

idunn-provision: deployment-brake-engage|clear|status take --store,
--runtime-id, --reason only; status exits nonzero unless deployments admit.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 17:24:34 +00:00
114803c63b Merge pull request 'idunn rollback: flip a static release back to the previous one' (#3) from eureka-self/static-rollback into main 2026-11-13 17:06:30 +00:00
7ba27c362e Idunn: rollback drift after freezing, cross-binding refusal, and docs
Tests: a previous release that drifts after the rollback was frozen ends
FailedBeforeFencing at the Starting-time verify with current untouched (fails if
that verify is removed); rollback_source refuses a previous release deployed
under another release root or current link. Docs: CommandKind::Rollback needs no
schema change but an Idunn at 9f15cee or earlier cannot decode it (forward-only);
flipped_at ordering and the observed-link check; a rollback cannot be cancelled.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 17:03:48 +00:00
01b6016193 Idunn: idunn rollback <target>, a brake-gated transaction flipping to the previous static release
CommandKind::Rollback (command ids rollback-*). The daemon freezes the command
into one transaction built like from_continuity: plan, sealed release and
installed release copied from the transaction that flipped the previous release;
no source, no build, source cleanup SkippedContinuity, no admitted generation.
It reaches the deployment brake and advance_static unchanged. The previous
release is derived from the newest Admitted static flip (control.cc + history.cc)
and the observed link, and refused as a rejected transaction when there is no
completed release, no previous release, current is not the newest flip, the
previous directory is gone, or an artifact digest drifted (new port method
verify_installed, also checked before any flip intent). Rollback counts as a
deploy for the busy and live-per-target checks. CLI: idunn rollback via
parse_up(kind); commit_deployment_command and submit take the kind.

Tests: control_plane::tests::static_rollback_ (7) and parse_rollback (1).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 16:55:43 +00:00
9f15cee11f Merge pull request 'Static release target: StaticRelease binding, carry, atomic flip, control record v5' (#2) from eureka-self/static-release into main 2026-11-13 16:50:20 +00:00
be98521120 Idunn: pin static redeploy and stuck-flip behavior; document both
Release ids are per transaction, so redeploying an unchanged tree with a changed
site file yields a new release (the test asserts distinct ids, the first release
keeping its carry, current carrying the new file); previous_release_id can never
equal release_id and no refusal is needed. A flip whose current link was replaced
by a directory after the intent retries visibly: last_error is shown by idunn
status as 'waiting on', cancel is refused, and the docs name the by-hand fix.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 16:48:16 +00:00
dc86c6326c Idunn: a static flip that moved current can no longer end before fencing
carry_and_flip returns FlipRefused only before the rename (the last fallible
step); the parent-directory sync after it is best-effort. Once a flip intent is
recorded, any error that is not FlipRefused leaves the transaction resumable
instead of taking the pre-fencing abort, and a resumed step that finds current
already naming the release records the carry already in it (new port method
carried_sha256) instead of flipping again. validate refuses a pre-fencing abort
beside a landed flip.

Tests: post-rename port fault and post-landing observe fault both end Admitted
with current on the new release; validation refuses FailedBeforeFencing with a
landed flip; a refused flip over a real directory writes no carry; a populated
v4 record lifts to the exact v5 field by field.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 16:44:04 +00:00
74d6ef31e1 Idunn: v5 control record, v4 legacy layout, lift and boot migration
d5ea779 named this work but did not contain it: the working-tree edits were never
staged. LegacyDeploymentTransactionV4, the v5 schema constant, the v4 lift in
read_transaction_record and history decode, the boot-migration case, and the
pinned v5 / legacy v4 tests.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 16:41:25 +00:00
d5ea779096 Idunn: static release transaction (flip in Starting) and the v5 control record
A static release is the same DeploymentTransaction in three phases: Sealing,
Starting (carry and flip, behind the deployment brake) and Complete. It has no
Expected, activation, workload, warming, isolation, fencing, leasing, ready or
routing, and creates no AdmittedGeneration.

DeploymentTransaction gains key 37 `flip` (FlipEvidence: release, previous
release, carry source, carried sha256, time). Adding a key changes the bytes of
every record, and the control store refuses a record that does not re-encode to
what is stored, so this is schema idunn.deployment_transaction.v5. The v4
layout is kept as LegacyDeploymentTransactionV4 and lifted by the existing
mechanism (read_transaction_record, history decode, and the boot migration,
which rewrites v4 records in control.cc to v5). Migration is forward-only: an
Idunn that predates v5 cannot read a migrated control.cc.

Also: is_static() and brake_subject() (the brake names the binding's runtime id
and the sealed release, read by deployment_authorization, durable-authority
validation and status); validate_static; advance_sealing skips readiness_class
and expected_projection for static; advance_starting delegates to
advance_static (intent with the previous release read from current_link,
carry_and_flip then record, observe link == release, then Complete with
Admitted{generation-<tx>} and post_commit_cleanup(SkippedNoIncumbent, source
Pending)); a failure in Starting takes the existing pre-fencing abort;
Engine.static_release Arc<dyn StaticReleasePort>. Docs: a Static release
section in deployment-authority.md and a scope line in
deploy-provenance-target.md.

Tests: control_plane::tests::static_release_ (3), a pinned v4 record lifts and
re-encodes as the pinned v5, a v4 control store copy in a temp dir migrates to
v5 and an already-v5 store is untouched byte for byte, and the pinned-bytes
test now pins v5 with the v4 bytes kept as a legacy fixture. The test runner is
a stand-in over the real seal_artifact behind a cfg(test) Engine seam, because
DockerRunnerDriver workspace ownership requires root.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 16:32:06 +00:00
6c8fd12335 Idunn: StaticReleasePort and the filesystem flip driver
install_release and validate_installed_release read the release root through
WorkloadBinding::release_root(), so a static release installs through the
same copy, digest and harden path as a systemd one. StaticReleasePort
{ observe_current, carry_and_flip } with FilesystemStaticRelease: reads the
operator's site file (regular file, not a link, 1 MiB cap) and hashes it
before anything moves; writes <release>/<destination> by temp + rename at mode
0444 outside every artifact digest; then renames a fresh symlink over
current_link (a stale flip link a crash left is replaced; a real directory in
the link's place is never replaced). observe_current refuses a link that names
anything but a release under the release root.

Tests on a tempdir stand-in site (fake vite dist with .br/.gz twins, fake site
config): cargo test -p idunn --lib drivers::tests::static_release_ (5 passed).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 16:28:07 +00:00
46ec8241a2 Idunn: StaticRelease target declaration and workload binding
A target may declare [static_release] artifact = "<id>" instead of
[service], and bind driver = "static-release" (release_root, current_link,
one carry source/destination). TargetDeclaration.service becomes Option with
a service() accessor; admission refuses both-or-neither, state/provides/
dependencies/conflicts/route/write lease on a static target, stop-then-start,
retain_releases < 2, a carry destination that is not a single leaf or collides
with an artifact destination, a carry source inside the release root, and a
current link overlapping the release root or an authority path.

Read-only audit of TransactionCompletion::Admitted / admitted_for readers
(cut spec step 2); a static Admitted transaction has no AdmittedGeneration:
- control_plane.rs:1781 (deadline_for_current_activity, Complete): reads the
  variant and drains_incumbent only. Tolerates.
- :1828 (carries_a_deadline): variant only. Tolerates.
- :2086 (is_terminal): variant plus post_commit_cleanup. Tolerates.
- :2550 (validate, Complete): requires Admitted and generation-<tx>; the
  generation record is never read. Tolerates; static gets its own branch.
- :5085 (derived_command_status): variant only. Tolerates.
- :6567 region (command admission; the admitted_for read is at :6587): passes
  an Option incumbent, None for a static target. Tolerates. Anchor drifted by
  ~20 lines; the code matches.
- :8371 (advance_committing): the only writer of Admitted with a generation;
  a static transaction never enters Committing. Unchanged.
Other admitted_for readers (3517 fenced-incumbent check, 4963 render, 5482
incident close, 9571 provider rehydrate, 9654/9712/9777 rebase, continuity,
take_target): all handle None; a static target has no fencing, no incident,
no capability to be a provider.

Fallout: runner_for/workload_for gain a StaticRelease arm (docker runner; the
systemd driver serves install only), and the service-only readers in host.rs,
drivers.rs and deployment_plan.rs go through service()?.

Tests: cargo test -p idunn --lib deployment::tests::static_ (6 passed).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 16:27:56 +00:00
4b6a58c692 Merge pull request 'docs: drop references to deleted legacy Windows Idunn scripts' (#1) from eureka-substrate/stale-legacy-idunn-script-refs into main 2026-11-11 08:57:53 +00:00
157610adb7 Soul fixes: grammar; cite the gamecult-ops merge
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 08:57:51 +00:00
1c23b6e217 docs: drop references to deleted legacy Windows Idunn scripts
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 08:56:46 +00:00
Meta Vens
64d63cb417 Merge steward orders 1 (r3): an order is one systemd job; refusal reads the named unit only
Soul cut-steward-orders-1.s5 holds at 77e2295. Not installed: steward-orders-2 installs it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 23:57:39 +01:00
Meta Vens
77e2295e97 Steward orders: refuse Upholds and ConsistsOf units, pin the rule's gaps, README names the residuals
A unit with Upholds= is refused for start and restart (systemd would start the
upheld unit in a full transaction). A wrapper with ConsistsOf= is refused for
stop, restart and reload with a typed Refused::Wrapper naming the first member,
so it cannot report ran while touching nothing. Tests pin empty BoundBy, a
single show per refusal, no show for a refused name and each posted reason.
README: the one-job rule's residual full transactions. Removes the unused
BTreeMap import and the never_loop in the host actuator test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 23:32:30 +01:00
Meta Vens
fb1e7b5dd9 Steward orders: README states the one-job rule; pin the end-to-end argv
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 22:45:08 +01:00
Meta Vens
8ebe0208a6 Steward orders: pin the one-job rule on the real unit set and a real user manager
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 22:41:56 +01:00
Meta Vens
a859914b0b Steward orders: run every unit verb as one job and check only the named unit
Delete the transaction model (Edge, EDGES, action_target, Transaction, the
early-boot rule). Every unit verb runs systemctl <verb>
--job-mode=ignore-requirements -- <unit>; refusal_for reads one systemctl show
of the ordered unit: its names, the host-ending names, what fires when it
ends, and who is bound to it. Targets are no longer orderable.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 22:40:58 +01:00
Meta Vens
4894ad20df README: an order's transaction follows emergency actions and OnFailure/OnSuccess; stopped boot units are refused
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 21:52:41 +01:00
Meta Vens
879b76a842 Steward orders: pin every emergency action spelling to its target
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 21:50:23 +01:00
Meta Vens
631fb7836b Steward orders: pin the new show properties; the unknown-action probe counts runs instead of expecting none
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 21:29:13 +01:00
Meta Vens
d29bf93be6 Steward orders: refuse a start or stop whose unit ends by emergency action or isolates; boot and recovery units are never started from stopped
refusal_for now reads SuccessAction, FailureAction, StartLimitAction and
JobTimeoutAction (each mapped to the target it runs, so reboot, poweroff,
halt, kexec, soft-reboot and exit, with -force and -immediate) and OnFailure
and OnSuccess as units a touched unit fires, followed through what they pull
in and what those fire. An action it does not know fails the order closed.
A stopped DefaultDependencies=no unit in the transaction is refused (Via::
EarlyBoot): rescue.service ends by isolating default.target, which no edge
describes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 21:26:29 +01:00
Meta Vens
d9710c988a Steward orders: the ledger reads an order only under its own schema too
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 06:35:43 +01:00
Meta Vens
caacbb4bba Steward orders: the end-to-end test waits 10 s for its posts
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 06:35:31 +01:00
Meta Vens
9653d270e5 Steward orders: pin the ledger schema guards, invocation ids and post backoff; tests fail fast instead of waiting
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 06:16:04 +01:00
Meta Vens
8a1beb5c87 README: an order is gated by the steward bound at execution; the socket is the steward's; root reads
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 05:35:30 +01:00
Meta Vens
7e15bf1a7b Steward orders: the Synapse deadline test fails instead of hanging when the deadline is gone
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 05:33:23 +01:00
Meta Vens
572f9e6aa4 Steward orders: the end-to-end test keeps serve's umask until it has read control.cc
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 05:31:34 +01:00
Meta Vens
56edad95c1 Steward orders: one steward gate for fresh and recovered orders; the orders unit leaks no group or umask; root reads; kernel-attested issuer; end-to-end serve test
execute refuses, with a record and a post, an order whose principal or issuing
uid is not the steward bound now, before grammar, scope and brake; the brake
is asked for the bound principal only. idunn-orders.service drops Group= and
UMask=: bind_socket gives the socket to the steward uid at 0600 and serve sets
Idunn's own umask, so a deploy order writes control.cc 0640. Root may show and
list, never order. The issuer unit is the first unit under system.slice, never
a name the peer chose below it. Synapse waits for a reply within one deadline.
due_posts takes the deploy-state reader so a finished deploy's post is tested.
Tests: the gate both ways, root, per-order posts, deploy result, intake and
Synapse timeouts, parse_serve, user_uid, socket and store modes, and the whole
service as root with a fake systemctl, systemd-run and homeserver.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 05:03:17 +01:00
Meta Vens
ca439a29ff Pin the systemctl show property list and unquoted backslashes
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 04:17:12 +01:00
Meta Vens
27ca875194 Steward orders tests: clear four clippy hits in the module
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 03:53:41 +01:00
Meta Vens
be3b95bc21 Import BTreeMap for the transaction facts cache
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 03:50:20 +01:00
Meta Vens
cea17c06a7 README: a unit order is refused by the systemd transaction; a package order installs only what it names
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 03:49:36 +01:00
Meta Vens
ec6222e2a1 Steward unit orders: refuse by the systemd transaction, install exactly the named packages
An order is refused when the closure systemd would build for it reaches an
always-refused unit: a start pulls Requires/Requisite/BindsTo/Wants/Upholds and
stops Conflicts/ConflictedBy, a stop takes down RequiredBy/BoundBy/RequisiteOf/
ConsistsOf/PropagatesStopTo/StopPropagatedFrom, a restart does both. A refused
unit already running is left alone by a start. Names are unquoted from
systemctl show; a unit systemd cannot show fails the order.

Package installs run apt-get --no-remove with ?exact-name(<name>) per package
and a final dpkg -s step that fails unless every named package is installed.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 03:49:26 +01:00
Meta Vens
7d5cd85728 Reword a test comment so the no-brake-release tripwire reads clean
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 02:33:12 +01:00
Meta Vens
1a3634e046 Document idunn order and add the idunn-orders unit
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 02:33:02 +01:00
Meta Vens
e50a721dbc Steward orders: typed package, unit and deploy orders from one steward, in a sibling root unit
idunn orders serve takes orders over a root-only socket from the steward uid, records
order/start/outcome/post in its own orders.cc, and posts acceptance and result to
#operator as a retried projection. Unit orders may act on any unit except the compiled
always-refused set (idunn-*, mind-self@*, mind-persona@*), matched on a unit's Id and every
name, and for stop and restart on the units systemd stops with it. A refusal names a field
and a code, never the value. A started order is never run twice. Deploy orders commit
through the same primitive as idunn up.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 02:33:01 +01:00
23 changed files with 9812 additions and 1227 deletions

1
Cargo.lock generated
View file

@ -482,6 +482,7 @@ dependencies = [
"libc",
"rmp-serde",
"serde",
"serde_json",
"sha2",
"tempfile",
"toml",

View file

@ -38,6 +38,7 @@ serde = { version = "1", features = ["derive"] }
ed25519-dalek = "2.2"
toml = "0.8"
uuid = { version = "1", features = ["v4"] }
serde_json = "1"
[dev-dependencies]
tempfile = "3"

View file

@ -58,6 +58,64 @@ idunn status --command <id>
the bindings, so `idunn up profile:full-gamecult` brings up everything bound
into that profile.
### Steward orders
A second root unit from the same binary, `idunn-orders` (`idunn orders serve`),
takes typed orders from one steward Mind over `/run/idunn-orders/steward.sock`.
It has its own store, `orders.cc`, and its own binding, `steward.toml`; the
survival daemon takes no order. There is still no command string:
```bash
idunn order package-install <pkg>[=version]... --reason TEXT # apt-get update, install named packages, check them
idunn order unit <start|stop|restart|reload> <unit> --reason TEXT
idunn order deploy <service|profile:name> --reason TEXT # the same commit as `idunn up`
idunn order show <id> # status and output tails
idunn order list
```
A unit order submits exactly one job, for the unit it names: every verb runs
`systemctl <verb> --job-mode=ignore-requirements -- <unit>`, so systemd builds a
transaction of one job. It does not start what the unit requires or restart what
is part of it: order the dependency first, and order `postgresql@16-main.service`
rather than the `postgresql.service` wrapper. Targets are not orderable. The job is one; what the unit does afterwards is
not: systemd still runs full transactions of its own for `Restart=` after a
failure, for a `StopWhenUnneeded=` dependency left without a user, and for a
`Conflicts=` partner of a unit that fails, so an ordered stop of a unit
that something restarts does not last, and a start of a `Restart=always`
unit can report failure and be active seconds later. A unit
order may act on any unit except Idunn's own (`idunn-*`) and the minds' own
(`mind-self@*`, `mind-persona@*`), and the units that end or take the host
(`systemd-suspend`, `systemd-hibernate`, `systemd-hybrid-sleep`,
`systemd-suspend-then-hibernate`, `rescue`, `emergency`). That set is compiled
into the binary and read from no configuration. An order is refused, recorded
and posted when the ordered unit, or an alias it resolves from, is one of them;
when it has an emergency action (`SuccessAction=`, `FailureAction=`,
`StartLimitAction=`, `JobTimeoutAction=`) other than `none` or an `OnFailure=`
or `OnSuccess=` unit (not for a reload); or, for a stop or restart, when another
unit is `BoundBy=` it, because systemd stops that unit with it whatever the job
mode; for a start or restart, when it has an `Upholds=` unit, which systemd
starts in a full transaction whatever the job mode; or, for a stop, restart or
reload, when it has a `ConsistsOf=` member, a wrapper such as
`postgresql.service` whose verbs would exit 0 and touch nothing. A unit
`systemctl show` cannot resolve fails the order. Slices, scopes,
targets and globs are not units an order can name.
A package order installs the packages it names and nothing else: apt runs with
`--no-remove`, each name is passed as an exact-name pattern so `.` and `+`
match themselves, and a last step fails the order unless every named package
is installed.
An order runs once, after the steward's uid is checked and the instance's
brake check (`mind-control --instance <principal> check`) exits 0. The check
that the order's principal and uid are the bound steward's runs again at every
execution, so an order accepted before `steward.toml` changed is refused and
recorded, not run. The socket belongs to the steward user alone (mode 0600);
root may `show` and `list` orders but never issue one. An order that had
started when the service died is recorded as lost and never run again. No order releases a brake. Acceptance and result are posted to
`#operator` as a retried projection of `orders.cc`: a chat outage delays the
posts and not the orders. A refusal names the field and a code, never the value
it refused.
## Authority
**Owner.** Deployment admission, and the continuity of installed bodies.

View file

@ -0,0 +1,47 @@
[Unit]
Description=Idunn steward orders: typed package, unit and deploy orders from the steward
# Deliberately no After= or Requires= on any managed target, Synapse or
# idunn-yggdrasil: orders are how an operator repairs those, so none of them
# may be a condition of this unit starting. Posts are a retried projection and
# wait for Synapse on their own.
[Service]
Type=simple
# Root, from the same binary as idunn-yggdrasil, with its own store and socket.
# idunn-yggdrasil keeps its no-imperative-input invariant and its write set:
# no order code runs in `idunn serve`.
#
# The unit name matches idunn-*, which is in the always-refused set, so no
# order can stop or restart this service.
User=root
# No Group= and no UMask=: the service gives its socket to the steward user
# (mode 0600) itself and sets Idunn's own umask for the files it writes, so
# nothing here reaches control.cc. The steward user is the only peer the
# service answers: it checks SO_PEERCRED on every connection.
ExecStart=/usr/local/bin/idunn orders serve \
--store /var/lib/gamecult/idunn-orders \
--state-store /var/lib/gamecult/idunn/control.cc \
--steward-binding /etc/gamecult/idunn/steward.toml \
--socket /run/idunn-orders/steward.sock
Restart=always
RestartSec=5
TimeoutStopSec=20
RuntimeDirectory=idunn-orders
RuntimeDirectoryMode=0755
# The Synapse access token of @idunn, copied from a root-only file, and read
# through $CREDENTIALS_DIRECTORY; the service names it in steward.toml.
LoadCredential=idunn-matrix-token:/etc/gamecult/idunn/matrix-token
PrivateTmp=yes
ProtectHome=yes
ProtectSystem=strict
# Its own order store, and the control store a deploy order commits a command
# to. Transient units started with systemd-run run in the manager's namespace,
# so packages and units are not limited by this list.
ReadWritePaths=/var/lib/gamecult/idunn-orders /var/lib/gamecult/idunn
[Install]
WantedBy=multi-user.target

View file

@ -45,7 +45,6 @@ ExecStart=/usr/local/bin/idunn serve \
--idunn-identity-store /var/lib/gamecult/idunn/idunn-service-identity.cc \
--odin-correlation-store /var/lib/gamecult/odin/topology.cc \
--odin-trust-anchor /etc/gamecult/idunn/odin-topology-anchor.cc \
--deployment-brake-operator-anchor /etc/gamecult/idunn/deployment-brake-operator-anchor.cc \
--host-actuator-bind 10.77.0.1:17890 \
--source-uid 986 \
--source-gid 978

View file

@ -16,7 +16,6 @@ target="${2:-}"
compose=/srv/compose/yggdrasil-apps.yaml
brake_store=/var/lib/gamecult/idunn-authority/deployment-brake.cc
brake_lock=/var/lib/gamecult/idunn-authority/deployment-brake.cc.lock
brake_anchor=/etc/gamecult/idunn/deployment-brake-operator-anchor.cc
generation_lock=/var/lib/gamecult/idunn-authority/idunn-generation.lock
idunn_provision=/usr/local/bin/idunn-provision
@ -154,7 +153,7 @@ deployment_target_policy() {
esac
}
require_signed_deployment_grant() {
require_deployment_admission() {
source_commit="$3"
deployment_request_id="$4"
release_authority_id="$5"
@ -180,28 +179,17 @@ require_signed_deployment_grant() {
[ -z "$release_authority_sha256" ] || { echo "source-observed release cannot claim Bifrost authority digest" >&2; exit 1; }
require_root_owned_resolved_executable "$idunn_provision"
require_root_owned_regular_path "$brake_store"
require_root_owned_regular_path "$brake_lock"
require_root_owned_regular_path "$brake_anchor"
# This validation is the deployment-admission point. The signed expiry is a
# start-before deadline: it denies a later transaction, but does not become a
# timer-shaped veto over one already admitted. The root actuator remains the
# sole shared-lock holder through the synchronous consequence, so an explicit
# engage/release transition cannot race or rewrite that transaction.
exec 9<"$brake_lock"
# This validation is the deployment-admission point. An absent or clear stop
# admits; an engaged or unreadable one makes the status verb exit nonzero.
# The root actuator remains the sole shared-lock holder through the
# synchronous consequence, so an engage or clear cannot race or rewrite it.
# The lock file is created here when no store has ever been written.
exec 9>>"$brake_lock"
/usr/bin/flock --shared 9
now_unix_millis="$(/usr/bin/date +%s%3N)"
case "$now_unix_millis" in
''|*[!0-9]*) echo "root actuator clock did not produce Unix milliseconds" >&2; exit 1 ;;
esac
"$idunn_provision" deployment-brake-status \
--store "$brake_store" \
--operator-anchor "$brake_anchor" \
--runtime-id yggdrasil \
--release-id "$source_commit" \
--deployment-id "$deployment_request_id" \
--now-unix-millis "$now_unix_millis"
--runtime-id yggdrasil
if [ "$minimum_source_revision_required" = true ]; then
require_root_owned_resolved_executable /usr/local/bin/idunn
@ -322,7 +310,7 @@ case "$action:$target" in
manifest="/srv/odin/deploy-manifests/$target"
require_root_owned_regular_path "$manifest"
[ -x "$manifest" ] || { echo "root actuator manifest is not executable: $manifest" >&2; exit 1; }
require_signed_deployment_grant "$@"
require_deployment_admission "$@"
export IDUNN_ACTUATOR=1
export IDUNN_COMMAND_AUTHORITY=idunn-daemon
export IDUNN_SOURCE_COMMIT="$source_commit"

View file

@ -240,7 +240,7 @@ Fencing retries its phase forward on a capped backoff and never stops its live
candidate, since that is the only running copy of the admitted body; the
deadline opens the same incident. The one exception is yielding: a continuity
whose route proof has not succeeded gives way, through its own post-fencing
abort, to a deployment the deployment brake has released and that awaits the
abort, to a deployment the deployment stop admits and that awaits the
handover; a continuity that has proven its route never yields. The
`ContinuityExhausted` incident (six charged attempts in an hour,
`restarts_page`) pages and gates nothing. When continuity next acts is derived
@ -257,9 +257,14 @@ held until a lift succeeds. It is a migration with a deletion line (follow-up
still owe dependency failures not growing the streak and the dead-generation
route refresh.
The deployment brake gates changes to source, release, configuration, schema,
unit, or authority binding. The lifecycle brake separately gates restart of an
already-admitted incarnation. Neither target brake may gate Idunn itself or an
The deployment brake is a stop, not a per-deploy gate: it gates changes to
source, release, configuration, schema, unit, or authority binding only while
engaged. Its one reader and writer is `src/brake.rs` (`idunn.deployment_stop.v1`:
engaged or clear, who, why, when, sequence). An absent or clear store admits;
a store that is present but unreadable, foreign, for another runtime, a symlink
or owned by another uid fails closed. Nothing is signed, bound to a release or
consumed, and one clear admits every deploy until it is engaged again. The
lifecycle brake separately gates restart of an already-admitted incarnation. Neither target brake may gate Idunn itself or an
unrelated service.
If Odin is unavailable, Idunn preserves existing routes and continuity for

View file

@ -4,6 +4,15 @@ Status: target, Self, 2026-10-19 (campaign `idunn-deploy-provenance` in
Eureka's mind). It states the ends. The map will live in
`deploy-provenance-map.md`.
Live as of cut `brake-is-a-stop` (2026-11-13): the deployment brake is the
stop of invariant 3 and the signed per-deploy release is gone. `src/brake.rs`
reads and writes it; `idunn-provision deployment-brake-engage|clear|status`
take only `--store`, `--runtime-id` and `--reason`; the writer's login name and
the verb's clock are recorded; an absent or clear store admits. The
transaction stamps `deployment_admitted_at_unix_millis` (record v6). Still
planned: the typed authority provenance on the transaction (invariant 2), and a
steward-scoped store.
## Why
Operator, 2026-10-19:
@ -53,6 +62,11 @@ In:
(`heimdall-discord-launch.md`, `idunn-host-raven.md`, the StreamPixels
runbook).
- A static release (a sealed tree published by repointing a link, with no
workload): its transaction records `flip` (release, previous release, the
sha256 of the carried per-site file) beside the brake bytes. See
`deployment-authority.md`, "Static release".
Out:
- `idunn-reincarnation`. This campaign is mapped after that campaign's cut 2

View file

@ -48,8 +48,8 @@ and health. CultMesh carries typed projections between them.
scaling, restart, host reboot recovery, and crash recovery use the same
source-to-recipe-to-artifact provenance and the same distinct write-lease and
route-membership primitives.
Deployment may change that chain only while the deployment brake admits the
exact transaction. Continuity may restart only the already-admitted chain and
Deployment may change that chain only while the deployment stop admits it
(absent or clear; an engaged stop halts). Continuity may restart only the already-admitted chain and
is governed by a separate lifecycle brake.
- **Deletion line:** hard-coded target copies, raw `deploy_command` and
`restart_command` state, `sh -c` actuation, root Git inspection, staged
@ -171,6 +171,96 @@ different semantic capability.
`gamecult-ops` publishes these fleet bindings and provisions host substrate. It
does not own application build or deployment programs.
## Static release
A target whose product is a sealed tree, with no process to run (a built web
front end), declares `[static_release] artifact = "<id>"` in place of
`[service]`, and its binding declares `driver = "static-release"` with a
`release_root`, a `current_link` and one `[workload.carry]`. It is the same
transaction as any deployment, in three phases: Sealing (source, build, seal,
install: unchanged), Starting (the one external change, behind the deployment
brake) and Complete. It never enters Warming through Committing, has no
Expected projection, no activation and no workload, publishes nothing to
Odin, and its Complete creates no admitted generation, so continuity never
supervises it. It declares no state, capabilities, dependencies, conflicts,
route or write lease, and its rollout is `candidate-then-promote` with at least
two retained releases.
What Starting does, in three durable steps recorded as `flip` on the
transaction: the release to name and the release the link names now are
written first; then Idunn copies the operator's carry source into
`<release_root>/<sealed release id>/<carry.destination>` (mode 0444) and
renames a fresh symlink over `current_link`; then it observes the link naming
the release and completes. A failure before the rename ends the transaction
through the ordinary pre-fencing abort with `current_link` untouched. A crash
resumes at the recorded intent and repeats the flip, which is harmless.
The carry is a copy of one per-site file (for example `config.json`) taken at
flip time. It sits beside the artifacts, never inside one, so it is outside
every sealed digest: changing the site file changes no release id, and the
sha256 of the bytes carried is provenance on the transaction
(`flip.carried_sha256`), beside the brake bytes and the requester. The
destination is a single leaf name that no artifact uses. The web server reads
`current_link/<artifact destination>` for the tree and `current_link/<carry
destination>` for the carried file (a one-time root edit of the vhost, an
`alias` for the carried file beside the root for the tree). A missing or
non-regular carry source fails the deployment before anything moves.
What `current_link` names is observed from the symlink and confirmed by the
latest Admitted static transaction's `flip.release_id`; it is stored nowhere
else. A rollback is a flip back to `flip.previous_release_id`: release
directories stay, and Idunn prunes none. The deployment stop is read exactly as for a
service, by the binding's runtime id. Release ids are per transaction, so
redeploying an unchanged tarball with a changed site file is a new release that
carries the new file, never an in-place re-carry of an existing one: the carry
is part of a release. If `current_link` is replaced by a directory or by a link
that names nothing under the release root after the flip was recorded, the
transaction keeps retrying with backoff: `idunn status --command <id>` shows the
error as "waiting on ...", operator cancel is refused (Starting, not held), and
the fix is by hand (restore the link or remove the directory); it then
completes. A bounded retry is follow-up work. A new
upstream tarball enters as a recipe `external_input` with a pinned url and
sha256, so each release is a recipe commit whose pin is its provenance.
### Rollback
`idunn rollback <target> [--state-store PATH] [--no-wait]` writes a
`rollback-` command and nothing else. The daemon freezes it into one new
transaction (`CommandKind::Rollback`) that reuses the previous release exactly:
the plan, sealed release and installed release are copied from the transaction
that flipped it, so there is no source, no build and no source cleanup, and it
creates no admitted generation. It starts at Sealing with that evidence and
reaches the same deployment stop as a deploy, which admits it unless engaged;
then `advance_static` flips, with the same three durable steps, the same
nothing-aborts-after-the-rename rule and the same stuck-flip behavior.
The previous release is derived, never stored: the newest Admitted static
transaction for the target (control.cc and history.cc) names the release
`current` must point at (`flip.release_id`) and the one it displaced
(`flip.previous_release_id`); the newest transaction that flipped that release
supplies the evidence. A rollback of a rollback therefore flips forward again.
The command is refused, recorded as a rejected transaction, when the target has
no completed static release, when the newest release is the first one, when
`current` does not name the newest flip, when the previous release directory is
gone, or when an artifact in it no longer digests to its sealed receipt. A
failed check at flip time ends the transaction before fencing with `current`
untouched.
The rollback reuses the old plan verbatim, so its binding snapshot, brake path
and carry source are the old ones: if the operator moved the site file the
rollback fails before the link moves. The carry is re-applied from the site file
as it is at rollback time, and its sha256 is recorded in the rollback's own
flip evidence (it may differ from the original release's; the copy inside the
rolled-back-to release is replaced). Nothing prunes release directories.
`CommandKind::Rollback` is stored in the existing v5 command and transaction
records with no schema change; an Idunn at 9f15cee or earlier cannot decode
them, so this is forward-only, like v5 itself. The newest flip is ordered by
`flipped_at` wall clock, and the observed-link check makes a clock step refuse
the rollback rather than mis-flip. A rollback cannot be cancelled, like a static
deploy. A rollback is also refused when the previous release was deployed under
a different release root or current link than the newest one.
## Typed deployment state
Mutable control-plane state will be CultCache. Runtime integration must use
@ -209,6 +299,82 @@ names both content addresses and the executable artifact digest. Present and
Ready remain Odin-owned correlations over independently verified runtime
evidence; the deployment-plan module deliberately does not model them.
## The deployment stop
`src/brake.rs` is the only reader and writer of the stop. A stop halts work
that has not crossed an irreversible step, and it is read again at each such
step: Sealing (`advance_sealing`), the static flip intent (`advance_static`) and
the entry into Fencing for a deploy (`advance_warming`). An engaged stop there
makes the transaction wait with a note naming who engaged it and why; nothing
aborts and nothing moves. After the flip intent is recorded, or once a deploy
has fenced, the transaction runs to its end: a stop halts before the
irreversible step, never mid-fence or mid-flip. Continuity is never gated.
The sequence of a stop record is positive and advances by one per verb; nothing
reads it for authority, so it is not validated further.
Absent means the store file is missing in an existing directory. Anything else
Idunn cannot judge (a symlink, a zero-length or undecodable file, another
runtime's record, another owner, an unsearchable or non-directory parent) reads
as unreadable and fails closed; the wait note carries the
`idunn-provision deployment-brake-clear` command that replaces it.
A binding may name a second stop, the target's steward:
```toml
[brakes.steward]
user = "mind-streampixels" # a login, never root
store = "/var/lib/gamecult/idunn-steward/streampixels/deployment-brake.cc"
```
Deploys admit only when every stop admits. The steward's store is read as owned
by that user's uid: the owner uid proves who wrote the file, and the wait note
names the stop by the binding's steward user, never by the record's `by` (which
is the verb's own text). Idunn never writes the steward directory and no key,
group or ACL is involved. The operator's store is a separate stop the steward
cannot clear, and the wait note names each holding stop.
The steward owns its directory, so it could unlink any file in it. Binding
validation therefore refuses a steward store whose directory is shared with,
inside or around the directory of any other Idunn authority store (deployment
and lifecycle brakes, trust anchor, write-lease record, release authority).
Validation cannot see the file system: the root who provisions the directory
makes it contain the steward's store and nothing else.
A steward store owned by another uid, or a steward user that does not resolve
to a non-root uid, is unreadable and fails closed. Only the steward (the
owner uid) can repair it: a clear run as root leaves a root-owned file that is
still unreadable.
### Provisioning a steward (root, once per target)
1. Create the store directory, owned by the steward and holding nothing else:
`install -d -o mind-streampixels -g mind-streampixels -m 0755
/var/lib/gamecult/idunn-steward/streampixels`. It must not be, contain or sit
inside any other authority directory, and no workload `ReadWritePaths` may
cover it. Idunn (root) reads it without further grants; no group or ACL.
2. Add the stanza above to the target's operator binding, after `[brakes]`,
with the steward's real login. Deploys planned afterwards see it.
3. The steward engages and clears as itself, never through root:
`idunn-provision deployment-brake-engage --store <store> --runtime-id <id>
--reason <text>` and `deployment-brake-clear` with the same flags.
4. The operator reads it with `idunn-provision deployment-brake-status --store
<store> --runtime-id <id> --owner-user mind-streampixels`.
The binding is sealed into each plan. A deploy already planned keeps the
binding it was sealed with: editing the stanza does not apply to it. If the
steward's login is deleted or its directory is lost, that deploy stays
unreadable-held at Sealing (or the static flip intent). `idunn cancel` withdraws
only a deploy held for a readiness disagreement before Fencing, and `idunn
expire` only one in Warming through Committing, so neither frees a deploy held
by the stop. Recovery is to restore the steward's login or recreate the
directory owned by it (and have the steward clear its store).
Record v6 (`deployment_admitted_at_unix_millis`, key 38) is forward-only: an
Idunn that predates v6 cannot read a migrated `control.cc`, so, as for v5 (see
`route-continuity-cut.md`, "An older Idunn refuses the v5 store"), take a
byte-compared pre-install backup of `control.cc` and `history.cc` with Idunn
stopped, and roll back by restoring the backup, never by swapping the binary.
## Initial drivers and replaceable boundary
The first Yggdrasil implementation uses:
@ -247,7 +413,7 @@ For a singleton incarnation:
declaration, binding, launch contract, and input digests.
5. Derive the release-bound Expected incarnation from the validated sealed
release and its exact compiled plan. Publish it only once the deployment
brake has admitted this exact transaction, under the candidate's own
stop has admitted this transaction (stamping `deployment_admitted_at_unix_millis`), under the candidate's own
incarnation key, beside whatever the target's admitted incarnation projects.
6. Issue one opaque runtime-instance activation bound to the Expected digest,
pass the exact Expected and activation documents through the actuator's
@ -270,8 +436,8 @@ For a singleton incarnation:
and stop the incumbent.
Sealing resolves the source, freezes it, runs every recipe step, and installs
the release before the deployment brake is consulted at all (`advance_sealing`).
The brake gates step 5, the first Verse-visible change: publishing the
the release before the deployment stop is consulted at all (`advance_sealing`).
The stop gates step 5, the first Verse-visible change: publishing the
candidate's Expected incarnation on the move into `Starting`. Build and test
already run unbraked, inside the sealing phase.
@ -302,7 +468,7 @@ identity, and route membership. Every restart receives a new runtime-instance
activation and, for a state writer, a new process-bound lease only after the new
warming presence is observed. A lease from the dead process is never reused. A
continuity restart does not fetch a branch, rebuild, rerun a migration, alter
the launch contract, or consume the deployment brake. An explicit lifecycle
the launch contract, or pass the deployment stop. An explicit lifecycle
brake may suspend this actuation without changing deployment authority.
Continuity never stops. Six charged attempts in an hour only open the
@ -335,7 +501,7 @@ the admitted body. Both operator cases open an `operator-required` incident
on.
The one yield: a continuity whose route proof has not succeeded gives way to a
deployment the deployment brake has released that awaits the handover of the
deployment the deployment stop admits that awaits the handover of the
target. It begins its own post-fencing abort and the deployment fences what is
admitted. A continuity that has proven its route is serving never yields.

View file

@ -112,22 +112,12 @@ cargo run --release --bin idunn -- --daemon demo --rudp-health-bind <idunn-rudp-
`--rudp-health-bind` is explicit. Bare one-daemon Idunn does not open a
localhost health ingress.
Install the local Starfire boot watchdog:
```powershell
.\scripts\install-idunn-startup.ps1
```
That task starts one `idunn.exe` swarm supervisor at user logon. The Rust
runtime owns the target catalog for Odin, Stonks, Muninn, the enforced
The Rust runtime owns the target catalog for Odin, Stonks, Muninn, the enforced
Yggdrasil source artifact lanes, and the Nightwing display services. The
current Mimir dashboard is observed but not restarted until its restart
authority is named.
It also starts `idunn-swarm-deployment-coverage`, which watches the deployment
target catalog in `scripts/idunn-deployment-targets.ps1`. A repo/service is not
allowed to vanish into shrug-space: it is either enforced by Idunn, explicitly
blocked with the missing authority named, external-owned, or not a runtime.
authority is named. A repo/service is not allowed to vanish into shrug-space:
it is either enforced by Idunn, explicitly blocked with the missing authority
named, external-owned, or not a runtime.
To record that a daemon has not published health, run a manual target without a
matching `idunn.daemon_health` RUDP publication:
@ -185,12 +175,7 @@ Idunn should not guess private service truth. A daemon should publish:
If that information is missing, Idunn should fail closed and create an operator
alarm instead of improvising.
For the repo swarm, deployment ownership begins with catalog coverage. Use:
```powershell
.\scripts\show-idunn-deployment-targets.ps1
.\scripts\health-idunn-swarm-deployment-coverage.cmd
```
For the repo swarm, deployment ownership begins with catalog coverage.
The enforced targets are Nightwing Gjallar plus the Yggdrasil source artifact
lanes whose ops runbooks can produce and verify deployment manifests. Each
@ -258,9 +243,9 @@ surface, then let Idunn run the rollout. Direct script execution without
`IDUNN_ACTUATOR=1` fails on purpose; the little hand reaching for the deploy
button has been removed from the machine.
`scripts/start-idunn-local.ps1` launches the local swarm with
`--rudp-health-bind 0.0.0.0:17870` so host-local and explicitly configured peers
can publish to the configured Idunn health endpoint. It accepts raw
A local swarm daemon started with
`--rudp-health-bind 0.0.0.0:17870` lets host-local and explicitly configured peers
publish to the configured Idunn health endpoint. It accepts raw
`idunn.daemon_health` document puts on the canonical CNR0 RUDP `schema` channel
and writes them into the keepalive store. That is daemon-owned health
publication, not restart/deploy authority. On Windows, UDP reset reports from

View file

@ -390,6 +390,8 @@ read-only command on Yggdrasil on 2026-09-29. Nothing was written to the host.
(`:3670`, `:3715`), and topology refresh (`:3780`). After three refused
continuity restarts, supervision stops restarting (`:3522-3528`) but keeps
supervising the route of a dead incarnation. Read.
Resolved by `cut-liveness-gates-presence`: route challenge and topology
refresh now run only for an incarnation observed running.
- F9. The continuity restart limit counts refused restarts per generation
(`is_refused_restart`, `:3469-3488`). A restart that succeeds admits a new
generation and resets the count. A unit that starts, is admitted, and then
@ -1160,7 +1162,7 @@ target's generation or to its `TargetSupervision` ends that target's iteration:
- **Why no existing owner can serve:**
- The generation does not exist for a first deploy (the ruling).
- The transaction dies with each attempt.
- Brakes are operator-signed and are not Idunn's to write.
- The deployment brake is a stop that a steward or the operator writes (`src/brake.rs`); Idunn writes no brake.
- **What it replaces:** two carry compensators, `for_new_incarnation` and the backoff copy in
`from_transaction`, plus a history scan.

View file

@ -155,7 +155,7 @@ cleaned up.
`idunn redeploy --daemon …`. The installed binary has no `redeploy` command
(probe of its usage text), so the script is dead and is **not** the current
pattern. The current pattern is `idunn up` followed by
`idunn-provision deployment-brake-release`
`idunn-provision deployment-brake-clear` when a stop is engaged (an absent or clear store admits)
(`runbooks/idunn-host-raven.md`, "Deploy Muninn to Raven").
- F24. Build placement (`gamecult-ops/inventory.md:559-566`): build on or for the
target's host. Yggdrasil has 16 vCPU and 62 GiB and carries live services, so

701
src/brake.rs Normal file
View file

@ -0,0 +1,701 @@
//! The deployment stop: the one reader and the one writer of the record that
//! halts deployments of a runtime. Engaged halts; absent or clear admits. Who
//! engaged it and why are on the record, and nothing is signed, issued, bound
//! to a release or consumed: the brake is a stop, not a per-deploy gate (ruling
//! brake-is-a-stop). The lifecycle brake is a different record and a different
//! store; nothing here touches it.
//!
//! The reader fails closed. A store that is present but foreign, ambiguous,
//! noncanonical, for another runtime, a symlink, or owned by anyone but the
//! expected uid reads as `Unreadable`, which does not admit.
use std::path::Path;
use crate::deployment::BrakeBinding;
use anyhow::{Context, Result, anyhow, bail, ensure};
use cultcache_rs::{CultCacheEnvelope, DatabaseEntry, SingleFileMessagePackBackingStore};
use serde::{Deserialize, Serialize};
pub(crate) const DEPLOYMENT_STOP_SCHEMA: &str = "idunn.deployment_stop.v1";
pub(crate) const DEPLOYMENT_STOP_KEY: &str = "deployment-stop";
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub(crate) enum StopState {
Engaged,
Clear,
}
impl StopState {
pub(crate) fn name(self) -> &'static str {
match self {
Self::Engaged => "engaged",
Self::Clear => "clear",
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)]
#[cultcache(type = "idunn.deployment_stop", schema = "idunn.deployment_stop.v1")]
pub(crate) struct DeploymentStop {
#[cultcache(key = 0)]
pub(crate) schema_version: String,
#[cultcache(key = 1)]
pub(crate) runtime_id: String,
#[cultcache(key = 2)]
pub(crate) state: StopState,
/// The login name of the user who ran the verb, read from the process uid.
#[cultcache(key = 3)]
pub(crate) by: String,
#[cultcache(key = 4)]
pub(crate) reason: String,
/// The verb's clock.
#[cultcache(key = 5)]
pub(crate) at_unix_millis: u64,
/// The previous record's sequence plus one; 1 for the first.
#[cultcache(key = 6)]
pub(crate) sequence: u64,
}
fn bounded(value: &str, label: &str, max: usize) -> Result<()> {
ensure!(
!value.trim().is_empty() && value.len() <= max && !value.chars().any(char::is_control),
"deployment stop {label} is empty, oversized, or contains control characters"
);
Ok(())
}
impl DeploymentStop {
pub(crate) fn validate(&self) -> Result<()> {
ensure!(
self.schema_version == DEPLOYMENT_STOP_SCHEMA,
"deployment stop schema is unsupported"
);
bounded(&self.runtime_id, "runtime id", 256)?;
bounded(&self.by, "author", 256)?;
bounded(&self.reason, "reason", 1024)?;
ensure!(
self.at_unix_millis > 0 && self.sequence > 0,
"deployment stop time or sequence is zero"
);
Ok(())
}
fn envelope(&self) -> Result<CultCacheEnvelope> {
self.validate()?;
let stored_at = chrono::DateTime::from_timestamp_millis(i64::try_from(self.at_unix_millis)?)
.ok_or_else(|| anyhow!("deployment stop time is out of range"))?
.to_rfc3339();
Ok(CultCacheEnvelope {
key: DEPLOYMENT_STOP_KEY.into(),
r#type: Self::TYPE.into(),
payload: rmp_serde::to_vec(self)?,
stored_at,
schema_id: Some(DEPLOYMENT_STOP_SCHEMA.into()),
})
}
fn decode(envelope: &CultCacheEnvelope) -> Result<Self> {
ensure!(
envelope.r#type == Self::TYPE
&& envelope.key == DEPLOYMENT_STOP_KEY
&& envelope.schema_id.as_deref() == Some(DEPLOYMENT_STOP_SCHEMA),
"deployment stop store holds a foreign record"
);
let record: Self = rmp_serde::from_slice(&envelope.payload)?;
ensure!(
rmp_serde::to_vec(&record)? == envelope.payload,
"deployment stop is noncanonical"
);
record.validate()?;
Ok(record)
}
}
/// What one store says about a runtime's deployments.
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum Stop {
/// No store, or an empty one: nothing halts.
Absent,
Clear(DeploymentStop),
Engaged(DeploymentStop),
/// Present but not a record this runtime can trust. Does not admit.
Unreadable(String),
}
impl Stop {
pub(crate) fn admits(&self) -> bool {
matches!(self, Self::Absent | Self::Clear(_))
}
}
/// One stop a binding names, with how to name it in a wait note.
pub(crate) struct NamedStop {
pub(crate) label: String,
/// The login the file system proves wrote the store: the steward user, whose
/// uid owns the file. None for the operator's store, whose record carries
/// only the verb's own claim of `by`.
pub(crate) proven_writer: Option<String>,
pub(crate) stop: Stop,
}
impl NamedStop {
/// The wait-note line for a stop that does not admit; None when it admits.
/// A steward stop is named by the proven owner, never by the record's `by`.
pub(crate) fn note(&self) -> Option<String> {
let label = &self.label;
match &self.stop {
Stop::Absent | Stop::Clear(_) => None,
Stop::Engaged(held) => Some(match &self.proven_writer {
Some(_) => format!("{label} engaged: {}", held.reason),
None => format!("{label} engaged by {}: {}", held.by, held.reason),
}),
Stop::Unreadable(why) => Some(format!("{label} is unreadable and fails closed: {why}")),
}
}
}
/// Every stop a binding names, each with the words that identify its store in
/// a wait note: the operator's, then the steward's when the binding names one.
/// Deployments admit iff every one admits. The operator's store is read as
/// owned by this process's uid; the steward's as owned by the steward user's
/// uid, so the file system proves who wrote it. A steward that does not
/// resolve to a non-root uid is an unreadable stop, never an absent one.
pub(crate) fn read_stops(brakes: &BrakeBinding, runtime_id: &str) -> Vec<NamedStop> {
let mut stops = vec![NamedStop {
label: "deployment brake".to_string(),
proven_writer: None,
stop: read_stop(&brakes.deployment_store, runtime_id, process_uid()),
}];
if let Some(steward) = &brakes.steward {
let label = format!("steward {} deployment brake", steward.user);
let stop = match crate::steward_orders::user_uid(&steward.user) {
Ok(uid) => read_stop_with_remedy(&steward.store, runtime_id, uid, |path| {
// Only the owner uid can mend it: a clear run as root leaves a
// root-owned file, which this reader refuses again.
format!(
"only {} (the store's owner uid) can repair it, by running as that user: \
idunn-provision deployment-brake-clear --store {} --runtime-id {runtime_id} \
--reason <text>; a clear run as root stays unreadable",
steward.user,
path.display()
)
}),
Err(why) => Stop::Unreadable(format!(
"{why:#}; the binding's steward user {} must be a non-root login",
steward.user
)),
};
stops.push(NamedStop {
label,
proven_writer: Some(steward.user.clone()),
stop,
});
}
stops
}
#[cfg(unix)]
pub(crate) fn process_uid() -> u32 {
// SAFETY: geteuid has no failure mode and no arguments.
unsafe { libc::geteuid() }
}
#[cfg(not(unix))]
pub(crate) fn process_uid() -> u32 {
0
}
#[cfg(unix)]
pub(crate) fn login_name(uid: u32) -> Result<String> {
// SAFETY: getpwuid returns null or a pointer into libc's static buffer,
// copied before any other call; the verbs are single threaded.
unsafe {
let entry = libc::getpwuid(uid);
ensure!(!entry.is_null(), "uid {uid} has no login name");
Ok(std::ffi::CStr::from_ptr((*entry).pw_name)
.to_string_lossy()
.into_owned())
}
}
#[cfg(not(unix))]
pub(crate) fn login_name(_: u32) -> Result<String> {
std::env::var("USERNAME").context("USERNAME is unset")
}
/// Open without following a final symlink and judge the file by fstat before
/// anything is read from it.
#[cfg(unix)]
fn check_file(path: &Path, expected_owner_uid: u32) -> Result<()> {
use std::os::unix::fs::{MetadataExt, OpenOptionsExt};
let file = std::fs::OpenOptions::new()
.read(true)
.custom_flags(libc::O_NOFOLLOW)
.open(path)
.with_context(|| format!("opening deployment stop store {}", path.display()))?;
let metadata = file.metadata()?;
ensure!(
metadata.is_file(),
"deployment stop store is not a regular file"
);
ensure!(
metadata.uid() == expected_owner_uid,
"deployment stop store is owned by uid {}, not {expected_owner_uid}",
metadata.uid()
);
Ok(())
}
#[cfg(not(unix))]
fn check_file(path: &Path, _: u32) -> Result<()> {
ensure!(
std::fs::metadata(path)?.is_file(),
"deployment stop store is not a regular file"
);
Ok(())
}
/// Absent means exactly this: the final component does not exist and its
/// parent is an existing directory. Every other failure to look (permission,
/// a parent that is a file, a symlink loop) is a store this runtime cannot
/// judge, and fails closed.
fn is_absent(path: &Path) -> Result<bool> {
match std::fs::symlink_metadata(path) {
Ok(_) => Ok(false),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
let parent = path.parent().filter(|p| !p.as_os_str().is_empty());
let parent = parent.unwrap_or_else(|| Path::new("."));
ensure!(
std::fs::metadata(parent).is_ok_and(|m| m.is_dir()),
"deployment stop store directory {} does not exist",
parent.display()
);
Ok(true)
}
Err(error) => Err(error)
.with_context(|| format!("looking for deployment stop store {}", path.display())),
}
}
fn read_checked(path: &Path, runtime_id: &str, owner: u32) -> Result<Option<DeploymentStop>> {
if is_absent(path)? {
return Ok(None);
}
check_file(path, owner)?;
ensure!(
std::fs::metadata(path)?.len() > 0,
"deployment stop store is zero length"
);
let entries = SingleFileMessagePackBackingStore::new(path).pull_all_read_only_snapshot()?;
match entries.as_slice() {
[] => bail!("deployment stop store holds no record"),
[entry] => {
let record = DeploymentStop::decode(entry)?;
ensure!(
record.runtime_id == runtime_id,
"deployment stop belongs to runtime {}",
record.runtime_id
);
Ok(Some(record))
}
_ => bail!("deployment stop store is ambiguous"),
}
}
pub(crate) fn read_stop(path: &Path, runtime_id: &str, expected_owner_uid: u32) -> Stop {
read_stop_with_remedy(path, runtime_id, expected_owner_uid, |path| {
format!(
"to replace it run: idunn-provision deployment-brake-clear \
--store {} --runtime-id {runtime_id} --reason <text> (or deployment-brake-engage)",
path.display()
)
})
}
fn read_stop_with_remedy(
path: &Path,
runtime_id: &str,
expected_owner_uid: u32,
remedy: impl FnOnce(&Path) -> String,
) -> Stop {
match read_checked(path, runtime_id, expected_owner_uid) {
Ok(None) => Stop::Absent,
Ok(Some(record)) if record.state == StopState::Clear => Stop::Clear(record),
Ok(Some(record)) => Stop::Engaged(record),
Err(error) => Stop::Unreadable(format!("{error:#}; {}", remedy(path))),
}
}
/// Write the next record under a compare-exchange of the whole store, so a
/// concurrent verb or a store that moved since it was read is refused. The
/// author is the login name of the process uid and the sequence is the
/// predecessor's plus one (1 when there is none or it cannot be decoded);
/// neither is an argument.
///
/// This is also the operator's break-glass. A predecessor that is a retired v1
/// brake, another runtime's record, ambiguous, or zero length is replaced. A
/// file that is not a CultCache store at all (junk bytes) is replaced only
/// when it is a regular file owned by the caller, by removing it first. A
/// symlink or another user's file is refused. The sequence is not validated
/// beyond being positive: nothing reads it for authority.
pub(crate) fn replace_stop(
path: &Path,
runtime_id: &str,
state: StopState,
reason: &str,
now_unix_millis: u64,
) -> Result<DeploymentStop> {
let store = SingleFileMessagePackBackingStore::new(path);
let before = match store.pull_all_read_only_snapshot() {
Ok(entries) => entries,
Err(undecodable) => {
check_file(path, process_uid()).with_context(|| {
format!("deployment stop store is undecodable ({undecodable:#}) and not the caller's to replace")
})?;
std::fs::remove_file(path)?;
Vec::new()
}
};
let sequence = match before.as_slice() {
[entry] => match DeploymentStop::decode(entry) {
Ok(previous) => previous.sequence.saturating_add(1),
Err(_) => 1,
},
_ => 1,
};
let record = DeploymentStop {
schema_version: DEPLOYMENT_STOP_SCHEMA.into(),
runtime_id: runtime_id.into(),
state,
by: login_name(process_uid())?,
reason: reason.into(),
at_unix_millis: now_unix_millis,
sequence,
};
let next = record.envelope()?;
ensure!(
store.compare_exchange_snapshot(&before, &[next])?,
"deployment stop changed during transition"
);
Ok(record)
}
#[cfg(test)]
mod tests {
use super::*;
fn engage(path: &Path, reason: &str, at: u64) -> Result<DeploymentStop> {
replace_stop(path, "runtime", StopState::Engaged, reason, at)
}
#[test]
fn absent_and_empty_stores_admit_a_clear_one_admits_an_engaged_one_does_not() -> Result<()> {
let dir = tempfile::tempdir()?;
let path = dir.path().join("stop.cc");
let me = process_uid();
assert_eq!(read_stop(&path, "runtime", me), Stop::Absent);
engage(&path, "freeze for the audit", 100)?;
let Stop::Engaged(held) = read_stop(&path, "runtime", me) else {
bail!("an engaged stop did not read as engaged")
};
assert_eq!(held.reason, "freeze for the audit");
assert_eq!(held.by, login_name(me)?);
assert!(!Stop::Engaged(held).admits());
replace_stop(&path, "runtime", StopState::Clear, "audit done", 200)?;
let cleared = read_stop(&path, "runtime", me);
assert!(matches!(&cleared, Stop::Clear(record) if record.sequence == 2));
assert!(cleared.admits());
// Clear is not consumed: the same record admits again.
assert!(read_stop(&path, "runtime", me).admits());
Ok(())
}
#[test]
fn corrupt_foreign_other_runtime_symlinked_or_foreign_owned_stores_stop() -> Result<()> {
let dir = tempfile::tempdir()?;
let me = process_uid();
let path = dir.path().join("stop.cc");
engage(&path, "held", 100)?;
// Another runtime's record.
assert!(!read_stop(&path, "other", me).admits());
// Owned by someone other than the expected uid: even a CLEAR record
// from a foreign owner must not admit.
let cleared = dir.path().join("cleared.cc");
replace_stop(&cleared, "runtime", StopState::Clear, "thaw", 100)?;
assert!(read_stop(&cleared, "runtime", me).admits());
assert!(matches!(read_stop(&cleared, "runtime", me + 1), Stop::Unreadable(_)));
// A symlink to a valid, clear store.
let real = dir.path().join("real.cc");
replace_stop(&real, "runtime", StopState::Clear, "clear", 100)?;
let link = dir.path().join("link.cc");
#[cfg(unix)]
std::os::unix::fs::symlink(&real, &link)?;
#[cfg(unix)]
assert!(matches!(read_stop(&link, "runtime", me), Stop::Unreadable(_)));
// Bytes that are no store at all.
let junk = dir.path().join("junk.cc");
std::fs::write(&junk, b"not msgpack at all")?;
assert!(matches!(read_stop(&junk, "runtime", me), Stop::Unreadable(_)));
// A record of another type under another key (the retired v1 brake).
let foreign = dir.path().join("foreign.cc");
let store = SingleFileMessagePackBackingStore::new(&foreign);
let envelope = CultCacheEnvelope {
key: "deployment".into(),
r#type: "idunn.deployment_brake".into(),
payload: vec![0x90],
stored_at: "1970-01-01T00:00:00+00:00".into(),
schema_id: Some("idunn.deployment_brake.v1".into()),
};
assert!(store.compare_exchange_snapshot(&[], &[envelope])?);
assert!(matches!(read_stop(&foreign, "runtime", me), Stop::Unreadable(_)));
// A noncanonical payload under the right identity.
let mut stop = DeploymentStop::decode(&store_entry(&path)?)?;
stop.sequence = 9;
let mut loose = stop.envelope()?;
loose.payload.push(0xc0);
let noncanonical = dir.path().join("noncanonical.cc");
assert!(SingleFileMessagePackBackingStore::new(&noncanonical)
.compare_exchange_snapshot(&[], &[loose])?);
assert!(matches!(read_stop(&noncanonical, "runtime", me), Stop::Unreadable(_)));
Ok(())
}
/// A binding whose steward is the user running the test, so the steward's
/// store can really be owned by the steward. None when run as root, which
/// no steward may be.
fn binding_with_steward(dir: &Path, user: &str) -> BrakeBinding {
BrakeBinding {
deployment_store: dir.join("operator.cc"),
lifecycle_store: dir.join("lifecycle.cc"),
steward: Some(crate::deployment::StewardBrakeBinding {
user: user.into(),
store: dir.join("steward.cc"),
}),
}
}
fn admits_all(stops: &[NamedStop]) -> bool {
stops.iter().all(|named| named.stop.admits())
}
#[test]
fn the_steward_store_is_a_second_stop_and_the_operator_store_is_one_it_cannot_clear() -> Result<()> {
let me = process_uid();
if me == 0 {
eprintln!("SKIPPED: a steward is never root, and this run is root");
return Ok(());
}
let dir = tempfile::tempdir()?;
let binding = binding_with_steward(dir.path(), &login_name(me)?);
let (operator, steward) = (&binding.deployment_store, &binding.steward.as_ref().unwrap().store);
// Both absent: admits.
assert!(admits_all(&read_stops(&binding, "runtime")));
// Steward engaged alone: halts, and the stop names the steward's store.
replace_stop(steward, "runtime", StopState::Engaged, "steward freeze", 10)?;
let stops = read_stops(&binding, "runtime");
assert!(!admits_all(&stops));
assert!(matches!(&stops[1].stop, Stop::Engaged(held) if held.reason == "steward freeze"));
// The note names the proven owner, and never the record's claimed `by`.
assert_eq!(
stops[1].note().unwrap(),
format!("steward {} deployment brake engaged: steward freeze", login_name(me)?)
);
// Both engaged, then the steward clears its own: the operator's holds.
replace_stop(operator, "runtime", StopState::Engaged, "operator hold", 11)?;
replace_stop(steward, "runtime", StopState::Clear, "steward thaw", 12)?;
let stops = read_stops(&binding, "runtime");
assert!(matches!(&stops[0].stop, Stop::Engaged(_)) && matches!(&stops[1].stop, Stop::Clear(_)));
assert!(!admits_all(&stops));
// The other order: operator clear, steward engaged still halts.
replace_stop(operator, "runtime", StopState::Clear, "operator thaw", 13)?;
replace_stop(steward, "runtime", StopState::Engaged, "steward again", 14)?;
assert!(!admits_all(&read_stops(&binding, "runtime")));
// Both clear: admits.
replace_stop(steward, "runtime", StopState::Clear, "steward thaw", 15)?;
assert!(admits_all(&read_stops(&binding, "runtime")));
Ok(())
}
#[test]
fn steward_store_owned_by_another_uid_stops() -> Result<()> {
let me = process_uid();
let dir = tempfile::tempdir()?;
// Steward is "nobody" (a real non-root user that is not the writer);
// the file is written by this process, so even a Clear record fails.
if me == 65534 || user_missing("nobody") {
eprintln!("SKIPPED: needs a user `nobody` other than the caller");
return Ok(());
}
let binding = binding_with_steward(dir.path(), "nobody");
let steward = &binding.steward.as_ref().unwrap().store;
replace_stop(steward, "runtime", StopState::Clear, "forged clear", 10)?;
let stops = read_stops(&binding, "runtime");
assert!(matches!(&stops[1].stop, Stop::Unreadable(why) if why.contains("is owned by uid")
&& why.contains("only nobody (the store's owner uid) can repair it")
&& why.contains("stays unreadable")
&& why.contains("idunn-provision deployment-brake-clear")));
// The operator's stop keeps the operator's remedy.
replace_stop(&binding.deployment_store, "other-runtime", StopState::Clear, "x", 11)?;
assert!(matches!(&read_stops(&binding, "runtime")[0].stop, Stop::Unreadable(why)
if why.contains("to replace it run:") && !why.contains("only ")));
assert!(!admits_all(&stops));
Ok(())
}
fn user_missing(name: &str) -> bool {
crate::steward_orders::user_uid(name).is_err()
}
#[test]
fn an_unresolvable_or_root_steward_user_is_an_unreadable_stop_not_an_absent_one() -> Result<()> {
let dir = tempfile::tempdir()?;
for user in ["no-such-login-zz", "root"] {
let binding = binding_with_steward(dir.path(), user);
let stops = read_stops(&binding, "runtime");
assert!(matches!(&stops[1].stop, Stop::Unreadable(_)), "{user}");
assert!(!admits_all(&stops));
}
Ok(())
}
#[test]
fn a_binding_without_a_steward_reads_only_the_operator_store() -> Result<()> {
let dir = tempfile::tempdir()?;
let mut binding = binding_with_steward(dir.path(), "nobody");
binding.steward = None;
let stops = read_stops(&binding, "runtime");
assert_eq!(stops.len(), 1);
assert!(admits_all(&stops));
Ok(())
}
fn store_entry(path: &Path) -> Result<CultCacheEnvelope> {
let mut entries = SingleFileMessagePackBackingStore::new(path).pull_all_read_only_snapshot()?;
entries.pop().context("no entry")
}
#[test]
fn a_verb_replaces_a_retired_brake_record_and_the_sequence_advances_by_one() -> Result<()> {
let dir = tempfile::tempdir()?;
let path = dir.path().join("stop.cc");
let store = SingleFileMessagePackBackingStore::new(&path);
let retired = CultCacheEnvelope {
key: "deployment".into(),
r#type: "idunn.deployment_brake".into(),
payload: vec![0x90],
stored_at: "1970-01-01T00:00:00+00:00".into(),
schema_id: Some("idunn.deployment_brake.v1".into()),
};
assert!(store.compare_exchange_snapshot(&[], &[retired])?);
assert_eq!(engage(&path, "first", 10)?.sequence, 1);
assert_eq!(store.pull_all_read_only_snapshot()?.len(), 1);
assert_eq!(engage(&path, "second", 11)?.sequence, 2);
assert_eq!(
replace_stop(&path, "runtime", StopState::Clear, "third", 12)?.sequence,
3
);
assert_eq!(DeploymentStop::decode(&store_entry(&path)?)?.reason, "third");
Ok(())
}
#[test]
fn a_stale_exchange_is_refused_and_a_record_without_a_reason_is_not_written() -> Result<()> {
let dir = tempfile::tempdir()?;
let path = dir.path().join("stop.cc");
engage(&path, "held", 10)?;
let store = SingleFileMessagePackBackingStore::new(&path);
let stale = store.pull_all_read_only_snapshot()?;
engage(&path, "moved", 11)?;
let next = DeploymentStop {
schema_version: DEPLOYMENT_STOP_SCHEMA.into(),
runtime_id: "runtime".into(),
state: StopState::Clear,
by: "someone".into(),
reason: "late".into(),
at_unix_millis: 12,
sequence: 2,
}
.envelope()?;
assert!(!store.compare_exchange_snapshot(&stale, &[next])?);
assert!(replace_stop(&path, "runtime", StopState::Clear, " ", 13).is_err());
assert_eq!(DeploymentStop::decode(&store_entry(&path)?)?.reason, "moved");
Ok(())
}
#[test]
fn only_a_missing_file_in_an_existing_directory_is_absent() -> Result<()> {
let dir = tempfile::tempdir()?;
let me = process_uid();
// Parent is a regular file: ENOTDIR, not absence.
let file = dir.path().join("plain");
std::fs::write(&file, b"x")?;
assert!(matches!(read_stop(&file.join("stop.cc"), "runtime", me), Stop::Unreadable(_)));
// Parent does not exist.
assert!(matches!(
read_stop(&dir.path().join("nope/stop.cc"), "runtime", me),
Stop::Unreadable(_)
));
// Zero-length file.
let empty = dir.path().join("empty.cc");
std::fs::write(&empty, b"")?;
assert!(matches!(read_stop(&empty, "runtime", me), Stop::Unreadable(_)));
// An existing directory with no store is absent.
assert_eq!(read_stop(&dir.path().join("stop.cc"), "runtime", me), Stop::Absent);
// A parent that cannot be searched (skipped as root, which can).
#[cfg(unix)]
if me != 0 {
use std::os::unix::fs::PermissionsExt;
let locked = dir.path().join("locked");
std::fs::create_dir(&locked)?;
std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o000))?;
let reading = read_stop(&locked.join("stop.cc"), "runtime", me);
std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o700))?;
assert!(matches!(reading, Stop::Unreadable(_)), "{reading:?}");
}
Ok(())
}
#[test]
fn the_author_is_the_uid_login_never_the_environment() -> Result<()> {
let dir = tempfile::tempdir()?;
let path = dir.path().join("stop.cc");
// SAFETY: no other test reads USER, LOGNAME or LNAME.
unsafe {
std::env::set_var("USER", "spoof");
std::env::set_var("LOGNAME", "spoof");
}
let written = engage(&path, "held", 10)?;
assert_eq!(written.by, login_name(process_uid())?);
assert_ne!(written.by, "spoof");
Ok(())
}
#[test]
fn unreadable_names_the_command_and_a_break_glass_clear_replaces_junk_and_v1() -> Result<()> {
let dir = tempfile::tempdir()?;
let me = process_uid();
let path = dir.path().join("stop.cc");
std::fs::write(&path, b"junk that is no store")?;
let Stop::Unreadable(why) = read_stop(&path, "runtime", me) else {
bail!("junk admitted")
};
assert!(why.contains("idunn-provision deployment-brake-clear --store"), "{why}");
assert!(why.contains("--runtime-id runtime"), "{why}");
let cleared = replace_stop(&path, "runtime", StopState::Clear, "operator break-glass", 50)?;
assert_eq!(cleared.sequence, 1);
assert!(read_stop(&path, "runtime", me).admits());
// A symlink is not the caller's to replace.
let real = dir.path().join("real.cc");
std::fs::write(&real, b"junk")?;
let link = dir.path().join("link.cc");
#[cfg(unix)]
{
std::os::unix::fs::symlink(&real, &link)?;
assert!(replace_stop(&link, "runtime", StopState::Clear, "x", 60).is_err());
assert_eq!(std::fs::read(&real)?, b"junk");
}
Ok(())
}
}

File diff suppressed because it is too large Load diff

View file

@ -45,7 +45,12 @@ pub struct TargetDeclaration {
#[serde(default)]
pub external_inputs: Vec<ExternalInput>,
pub artifacts: Vec<ArtifactOutput>,
pub service: ServiceDeclaration,
/// A running workload. Exactly one of `service` and `static_release`.
#[serde(default)]
pub service: Option<ServiceDeclaration>,
/// A sealed tree that is published by repointing a link, with no process.
#[serde(default)]
pub static_release: Option<StaticReleaseDeclaration>,
#[serde(default)]
pub state: Option<StateDeclaration>,
#[serde(default)]
@ -126,6 +131,15 @@ pub enum ArtifactSource {
WorktreeTree,
}
/// A target that is a sealed tree and nothing else: Idunn installs the release
/// and repoints the binding's current link at it. `artifact` names the tree a
/// web server reads through that link.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct StaticReleaseDeclaration {
pub artifact: String,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ServiceDeclaration {
@ -475,20 +489,42 @@ pub struct DockerRunnerBinding {
pub enum WorkloadBinding {
SystemdTransient(SystemdWorkloadBinding),
HostActuator(HostWorkloadBinding),
/// No process: a release directory and the link that names the current one.
StaticRelease(StaticReleaseBinding),
}
static NO_ENVIRONMENT: BTreeMap<String, String> = BTreeMap::new();
impl WorkloadBinding {
pub fn systemd(&self) -> Result<&SystemdWorkloadBinding> {
match self {
Self::SystemdTransient(binding) => Ok(binding),
Self::HostActuator(_) => bail!("workload is host-actuator, not systemd-transient"),
Self::StaticRelease(_) => bail!("workload is a static release, not systemd-transient"),
}
}
pub fn static_release(&self) -> Result<&StaticReleaseBinding> {
match self {
Self::StaticRelease(binding) => Ok(binding),
_ => bail!("workload is not a static release"),
}
}
/// Where Idunn installs sealed releases on its own host: the one thing a
/// systemd workload and a static release share.
pub fn release_root(&self) -> Result<&Path> {
match self {
Self::SystemdTransient(binding) => Ok(&binding.release_root),
Self::StaticRelease(binding) => Ok(&binding.release_root),
Self::HostActuator(_) => bail!("a host-actuator workload installs on its own host"),
}
}
pub fn host(&self) -> Result<&HostWorkloadBinding> {
match self {
Self::HostActuator(binding) => Ok(binding),
Self::SystemdTransient(_) => bail!("workload is systemd-transient, not host-actuator"),
_ => bail!("workload is not host-actuator"),
}
}
@ -496,6 +532,7 @@ impl WorkloadBinding {
match self {
Self::SystemdTransient(binding) => binding.state_root.is_some(),
Self::HostActuator(binding) => binding.state_root.is_some(),
Self::StaticRelease(_) => false,
}
}
@ -503,6 +540,7 @@ impl WorkloadBinding {
match self {
Self::SystemdTransient(binding) => &binding.environment,
Self::HostActuator(binding) => &binding.environment,
Self::StaticRelease(_) => &NO_ENVIRONMENT,
}
}
@ -510,6 +548,7 @@ impl WorkloadBinding {
match self {
Self::SystemdTransient(binding) => binding.secret_files.keys().collect(),
Self::HostActuator(binding) => binding.secret_files.keys().collect(),
Self::StaticRelease(_) => Vec::new(),
}
}
@ -517,6 +556,7 @@ impl WorkloadBinding {
match self {
Self::SystemdTransient(binding) => &binding.argument_bindings,
Self::HostActuator(binding) => &binding.argument_bindings,
Self::StaticRelease(_) => &NO_ENVIRONMENT,
}
}
@ -551,6 +591,49 @@ impl WorkloadBinding {
}
}
/// A static release on the Idunn host. `current_link` is the symlink a web
/// server's root reads through; Idunn repoints it at one sealed release.
/// `carry` names one operator-owned file (a per-site config) that Idunn copies
/// into each release as `destination` when it flips: the copy sits beside the
/// artifacts, outside every sealed digest.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct StaticReleaseBinding {
pub release_root: PathBuf,
pub current_link: PathBuf,
pub carry: StaticCarryBinding,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct StaticCarryBinding {
pub source: PathBuf,
pub destination: PathBuf,
}
impl StaticReleaseBinding {
fn validate(&self) -> Result<()> {
require_absolute_path(&self.release_root, "static release root")?;
require_absolute_path(&self.current_link, "static current link")?;
require_absolute_path(&self.carry.source, "static carry source")?;
require_leaf_path(&self.carry.destination, "static carry destination")?;
ensure!(
!paths_overlap(&self.current_link, &self.release_root),
"static current link and release root overlap"
);
ensure!(
!self.carry.source.starts_with(&self.release_root),
"static carry source is inside the release root"
);
ensure!(
self.carry.source != self.current_link
&& !self.carry.source.starts_with(&self.current_link),
"static carry source is the current link"
);
Ok(())
}
}
/// A workload on a managed host. Every path is the host's and is validated by
/// the actuator that owns the host; here they are opaque non-empty values.
/// The host's actuator is authenticated against `host_trust_anchor_store`,
@ -670,6 +753,20 @@ impl ProcessWriteLeaseBinding {
pub struct BrakeBinding {
pub deployment_store: PathBuf,
pub lifecycle_store: PathBuf,
/// A second deployment stop, written by the target's steward in a
/// directory only the steward can write. Absent means the operator's store
/// is the only stop.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub steward: Option<StewardBrakeBinding>,
}
/// The steward's own stop: the file's owner uid proves who wrote it.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct StewardBrakeBinding {
/// Login name; must resolve to a non-root uid when the store is read.
pub user: String,
pub store: PathBuf,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
@ -977,57 +1074,76 @@ impl TargetDeclaration {
"target declaration uses no runner classes"
);
ensure!(
artifact_ids.contains(self.service.executable_artifact.as_str()),
"service executable artifact is not declared"
);
for artifact in &self.service.required_adjacent_artifacts {
match (&self.service, &self.static_release) {
(Some(service), None) => {
ensure!(
artifact_ids.contains(service.executable_artifact.as_str()),
"service executable artifact is not declared"
);
for artifact in &service.required_adjacent_artifacts {
ensure!(
artifact_ids.contains(artifact.as_str()),
"adjacent service artifact {artifact} is not declared"
);
}
for argument in &service.arguments {
validate_launch_argument(argument)?;
}
require_capability(&service.health.contract, "health contract")?;
for name in &service.required_environment {
require_environment_name(name)?;
}
ensure!(
artifact_ids.contains(artifact.as_str()),
"adjacent service artifact {artifact} is not declared"
service
.required_environment
.contains(IDUNN_RUNTIME_BUNDLE_ENVIRONMENT),
"service does not require the standard Idunn runtime bundle"
);
}
for argument in &self.service.arguments {
validate_launch_argument(argument)?;
}
require_capability(&self.service.health.contract, "health contract")?;
for name in &self.service.required_environment {
require_environment_name(name)?;
}
ensure!(
self.service
.required_environment
.contains(IDUNN_RUNTIME_BUNDLE_ENVIRONMENT),
"service does not require the standard Idunn runtime bundle"
);
ensure!(
self.service
.required_environment
.contains(IDUNN_RUNTIME_CANDIDATE_BIND_ENVIRONMENT)
== self.service.route_required,
"routed services must require exactly one Idunn-owned candidate bind"
);
ensure!(
!self
.service
.required_environment
.contains(IDUNN_RUNTIME_MEMBER_BIND_ENVIRONMENT)
|| self.service.route_required,
"only routed services may require the Idunn-owned member bind"
);
ensure!(
self.service
.required_environment
.contains(IDUNN_PROCESS_WRITE_LEASE_ENVIRONMENT)
== self.write_lease_required(),
"state-writing services must require exactly one Idunn-owned process write lease"
);
for name in &self.service.optional_environment {
require_environment_name(name)?;
ensure!(
!self.service.required_environment.contains(name),
"service environment {name} is both required and optional"
service
.required_environment
.contains(IDUNN_RUNTIME_CANDIDATE_BIND_ENVIRONMENT)
== service.route_required,
"routed services must require exactly one Idunn-owned candidate bind"
);
ensure!(
!service
.required_environment
.contains(IDUNN_RUNTIME_MEMBER_BIND_ENVIRONMENT)
|| service.route_required,
"only routed services may require the Idunn-owned member bind"
);
ensure!(
service
.required_environment
.contains(IDUNN_PROCESS_WRITE_LEASE_ENVIRONMENT)
== self.write_lease_required(),
"state-writing services must require exactly one Idunn-owned process write lease"
);
for name in &service.optional_environment {
require_environment_name(name)?;
ensure!(
!service.required_environment.contains(name),
"service environment {name} is both required and optional"
);
}
}
(None, Some(static_release)) => {
ensure!(
artifact_ids.contains(static_release.artifact.as_str()),
"static release artifact is not declared"
);
ensure!(
self.state.is_none()
&& self.provides.is_empty()
&& self.dependencies.is_empty()
&& self.conflicts.is_empty(),
"a static release declares no state, capability, dependency or conflict"
);
}
(Some(_), Some(_)) => bail!("target declares both a service and a static release"),
(None, None) => bail!("target declares neither a service nor a static release"),
}
if let Some(state) = &self.state {
@ -1144,6 +1260,14 @@ impl TargetDeclaration {
Ok(())
}
/// The service of a service target. A static release has none, and a code
/// path that asks for one has been reached by the wrong kind of target.
pub fn service(&self) -> Result<&ServiceDeclaration> {
self.service
.as_ref()
.context("target declares no service")
}
pub fn write_lease_required(&self) -> bool {
self.state.as_ref().is_some_and(|state| {
state
@ -1320,6 +1444,39 @@ impl OperatorBinding {
self.brakes.deployment_store != self.brakes.lifecycle_store,
"deployment and lifecycle brakes are identical"
);
if let Some(steward) = &self.brakes.steward {
require_absolute_path(&steward.store, "steward deployment brake")?;
ensure!(
crate::steward_orders::login_grammar_ok(&steward.user) && steward.user != "root",
"steward brake user is invalid or root"
);
ensure!(
steward.store != self.brakes.deployment_store
&& steward.store != self.brakes.lifecycle_store,
"steward brake store is identical to another brake store"
);
// The steward owns its store's directory, so it could unlink any
// file there. Every other authority store must therefore live
// outside that directory, and the steward's directory must be
// clear of every directory an operator store lives in.
let steward_dir = steward.store.parent().unwrap_or(&steward.store);
let others = [
Some(&self.brakes.deployment_store),
Some(&self.brakes.lifecycle_store),
Some(&self.runtime_identity.trust_anchor_store),
self.process_write_lease.as_ref().map(|lease| &lease.record_path),
self.repository.release_authority_store.as_ref(),
];
for other in others.into_iter().flatten() {
let other_dir = other.parent().unwrap_or(other);
ensure!(
!paths_overlap(steward_dir, other_dir),
"steward brake directory {} is shared with or nested in the directory of Idunn authority {}: the steward owns its directory and could remove that file",
steward_dir.display(),
other.display()
);
}
}
self.workload.validate_launch_environment()?;
let workload = match &self.workload {
WorkloadBinding::HostActuator(workload) => {
@ -1338,6 +1495,32 @@ impl OperatorBinding {
);
return self.validate_shared_tail();
}
WorkloadBinding::StaticRelease(workload) => {
workload.validate()?;
ensure!(
self.process_write_lease.is_none() && self.route.is_none(),
"a static release has no write lease or route"
);
ensure!(
self.rollout.strategy == RolloutStrategy::CandidateThenPromote,
"a static release rolls out candidate-then-promote: it never stops an incumbent"
);
for authority in [
&self.brakes.deployment_store,
&self.brakes.lifecycle_store,
&self.runtime_identity.trust_anchor_store,
]
.into_iter()
.chain(self.brakes.steward.as_ref().map(|steward| &steward.store))
{
ensure!(
!paths_overlap(authority, &workload.release_root)
&& !paths_overlap(authority, &workload.current_link),
"static release path overlaps an Idunn authority path"
);
}
return self.validate_shared_tail();
}
WorkloadBinding::SystemdTransient(workload) => {
ensure!(
self.rollout.strategy == RolloutStrategy::CandidateThenPromote,
@ -1398,6 +1581,7 @@ impl OperatorBinding {
self.brakes.deployment_store.clone(),
self.brakes.lifecycle_store.clone(),
];
authority_paths.extend(self.brakes.steward.as_ref().map(|steward| steward.store.clone()));
if let Some(write_lease) = &self.process_write_lease {
authority_paths.push(write_lease.record_path.clone());
authority_paths.push(write_lease.lock_path());
@ -1565,6 +1749,11 @@ impl OperatorBinding {
self.target == declaration.target,
"binding target does not match declaration"
);
ensure!(
declaration.static_release.is_some()
== matches!(self.workload, WorkloadBinding::StaticRelease(_)),
"a static release declaration needs a static-release workload, and only it"
);
let bound_gitlinks: BTreeSet<_> = self.repository.gitlinks.keys().cloned().collect();
ensure!(
bound_gitlinks == declaration.required_gitlinks,
@ -1676,6 +1865,19 @@ impl OperatorBinding {
input.id
);
}
let Some(service) = declaration.service.as_ref() else {
let WorkloadBinding::StaticRelease(workload) = &self.workload else {
bail!("a static release declaration needs a static-release workload");
};
ensure!(
declaration
.artifacts
.iter()
.all(|artifact| artifact.destination != workload.carry.destination),
"static carry destination collides with an artifact destination"
);
return Ok(());
};
let workload_names: BTreeSet<&String> = self
.workload
.environment()
@ -1702,7 +1904,7 @@ impl OperatorBinding {
if host_workload {
available_environment.insert(IDUNN_ACTIVATION_CREDENTIAL_ENVIRONMENT.into());
}
if declaration.service.route_required {
if service.route_required {
available_environment.insert(IDUNN_RUNTIME_CANDIDATE_BIND_ENVIRONMENT.into());
if self.route.as_ref().is_some_and(|route| route.member.is_some()) {
available_environment.insert(IDUNN_RUNTIME_MEMBER_BIND_ENVIRONMENT.into());
@ -1712,16 +1914,14 @@ impl OperatorBinding {
available_environment.insert(IDUNN_PROCESS_WRITE_LEASE_ENVIRONMENT.into());
}
ensure!(
declaration
.service
service
.required_environment
.is_subset(&available_environment),
"operator service environment omits a required launch input"
);
let declared_environment: BTreeSet<_> = declaration
.service
let declared_environment: BTreeSet<_> = service
.required_environment
.union(&declaration.service.optional_environment)
.union(&service.optional_environment)
.cloned()
.collect();
// On the Idunn host the presence identity reaches the workload as a
@ -1741,8 +1941,7 @@ impl OperatorBinding {
available_environment.is_subset(&declared_environment),
"operator service environment contains an undeclared launch input"
);
let required_arguments: BTreeSet<_> = declaration
.service
let required_arguments: BTreeSet<_> = service
.arguments
.iter()
.filter_map(|argument| match argument {
@ -1758,6 +1957,7 @@ impl OperatorBinding {
.as_ref()
.map(|path| path.display().to_string()),
WorkloadBinding::HostActuator(workload) => workload.state_root.clone(),
WorkloadBinding::StaticRelease(_) => None,
};
match (
state_root.as_deref(),
@ -1780,8 +1980,8 @@ impl OperatorBinding {
"operator argument bindings do not exactly match the launch contract"
);
match (
declaration.service.route_required,
declaration.service.transport,
service.route_required,
service.transport,
self.route.as_ref(),
) {
(true, ServiceTransport::Http, Some(route))
@ -2344,7 +2544,7 @@ nodes = ["yggdrasil"]
)
.is_err()
);
assert!(recipe.service.route_required);
assert!(recipe.service().unwrap().route_required);
}
#[test]
@ -2832,4 +3032,230 @@ max_connections = {value}"),
"v2",
));
}
/// A static release: a vite-style tree published by repointing a link.
pub(crate) const STATIC_RECIPE: &str = r#"
schema = "gamecult.idunn.target_declaration.v1"
target = "service"
source_stamp_environment = "SERVICE_BUILD_COMMIT"
[[steps]]
id = "build"
phase = "build"
runner = "rust"
argv = ["true"]
[[artifacts]]
id = "dist"
source_kind = "worktree-tree"
source = "dist"
destination = "dist"
[static_release]
artifact = "dist"
"#;
/// `@SITE@` stands for the stand-in site tree a test lays out.
pub(crate) const STATIC_BINDING: &str = r#"
schema = "gamecult.idunn.operator_binding.v2"
target = "service"
[repository]
origin = "https://github.com/GameCult/Service.git"
admitted_ref = "refs/heads/main"
minimum_revision = "1111111111111111111111111111111111111111"
selection = "ref-head"
checkout = "/srv/build/Service"
recipe_path = "deployment/idunn/recipe.toml"
[runners.rust]
driver = "docker"
image = "rust@sha256:4c2fd73ef19c5ef9d54bee03b06b2839a392604fbfcd578ed948b71b37c1d7fb"
user = "1000:1000"
affordances = ["source-read", "artifact-write"]
allowed_programs = ["true"]
memory_mebibytes = 1024
cpu_quota_percent = 100
pids_limit = 128
tmpfs_mebibytes = 64
[workload]
driver = "static-release"
release_root = "@SITE@/releases"
current_link = "@SITE@/www/current"
[workload.carry]
source = "@SITE@/config/site.json"
destination = "config.json"
[runtime_identity]
runtime_id = "site-yggdrasil"
expected_signer_identity_id = "site-runtime-signer"
trust_anchor_store = "@SITE@/trust/site.cc"
[brakes]
deployment_store = "@SITE@/authority/deployment-brake.cc"
lifecycle_store = "@SITE@/authority/lifecycle-brake.cc"
[rollout]
strategy = "candidate-then-promote"
drain_seconds = 1
retain_releases = 2
[placement]
desired_replicas = 1
nodes = ["yggdrasil"]
"#;
fn static_binding(replace: &[(&str, &str)]) -> String {
let mut text = STATIC_BINDING.replace("@SITE@", "/srv/site");
for (from, to) in replace {
assert!(text.contains(from), "the fixture lost {from}");
text = text.replace(from, to);
}
text
}
const STEWARD: &str = "\n[brakes.steward]\nuser = \"mind-streampixels\"\nstore = \"/var/lib/gamecult/idunn-steward/streampixels/deployment-brake.cc\"\n";
#[test]
fn binding_without_steward_parses_and_admits_on_operator_store_only() {
for text in [BINDING.to_string(), static_binding(&[])] {
assert_eq!(OperatorBinding::parse(&text).unwrap().brakes.steward, None);
}
let steward = OperatorBinding::parse(&BINDING.replace("\n[rollout]", &format!("{STEWARD}\n[rollout]")))
.unwrap()
.brakes
.steward
.unwrap();
assert_eq!(steward.user, "mind-streampixels");
}
#[test]
fn a_steward_brake_must_be_a_distinct_absolute_non_root_login_and_clear_of_the_workload() {
let with = |steward: &str| BINDING.replace("\n[rollout]", &format!("{steward}\n[rollout]"));
let store = "/var/lib/gamecult/idunn-steward/x/deployment-brake.cc";
for bad in [
format!("\n[brakes.steward]\nuser = \"root\"\nstore = \"{store}\"\n"),
format!("\n[brakes.steward]\nuser = \"Bad User\"\nstore = \"{store}\"\n"),
"\n[brakes.steward]\nuser = \"mind\"\nstore = \"relative.cc\"\n".into(),
"\n[brakes.steward]\nuser = \"mind\"\nstore = \"/var/lib/gamecult/idunn-authority/test-service-deployment-brake.cc\"\n".into(),
"\n[brakes.steward]\nuser = \"mind\"\nstore = \"/var/lib/gamecult/idunn-authority/test-service-lifecycle-brake.cc\"\n".into(),
format!("\n[brakes.steward]\nuser = \"mind\"\nstore = \"{store}\"\nextra = 1\n"),
] {
assert!(OperatorBinding::parse(&with(&bad)).is_err(), "{bad}");
}
// A steward directory shared with, or enclosing, an operator store
// lets the steward unlink a root-owned file: refused.
for (deployment, steward_store) in [
("/var/lib/gamecult/steward-x/op.cc", "/var/lib/gamecult/steward-x/s.cc"),
("/var/lib/gamecult/steward-x/sub/op.cc", "/var/lib/gamecult/steward-x/s.cc"),
("/var/lib/gamecult/op.cc", "/var/lib/gamecult/steward-x/s.cc"),
] {
let shared = BINDING
.replace("/var/lib/gamecult/idunn-authority/test-service-deployment-brake.cc", deployment)
.replace("\n[rollout]", &format!("\n[brakes.steward]\nuser = \"mind\"\nstore = \"{steward_store}\"\n\n[rollout]"));
assert!(OperatorBinding::parse(&shared).is_err(), "{deployment} {steward_store}");
}
// Disjoint directories are the one admitted shape.
let disjoint = BINDING.replace(
"\n[rollout]",
"\n[brakes.steward]\nuser = \"mind\"\nstore = \"/var/lib/gamecult/steward-x/s.cc\"\n\n[rollout]",
);
OperatorBinding::parse(&disjoint).unwrap();
// steward_store_overlap_with_workload_path_refused
let overlapping = BINDING
.replace("\n[rollout]", &format!("\n[brakes.steward]\nuser = \"mind\"\nstore = \"{store}\"\n\n[rollout]"))
.replace(
"cpu_quota_percent = 200\n\n[workload.argument_bindings]",
"cpu_quota_percent = 200\nread_write_paths = [\"/var/lib/gamecult/idunn-steward/x\"]\n\n[workload.argument_bindings]",
);
assert!(OperatorBinding::parse(&overlapping).is_err());
let static_overlap = static_binding(&[("[rollout]", "[brakes.steward]\nuser = \"mind\"\nstore = \"/srv/site/releases/x/brake.cc\"\n\n[rollout]")]);
assert!(OperatorBinding::parse(&static_overlap).is_err());
}
#[test]
fn static_recipe_and_binding_admit() {
let recipe = TargetDeclaration::parse(STATIC_RECIPE).unwrap();
let binding = OperatorBinding::parse(&static_binding(&[])).unwrap();
binding.admit(&recipe).unwrap();
assert!(recipe.service().is_err());
assert_eq!(binding.workload.release_root().unwrap(), Path::new("/srv/site/releases"));
}
#[test]
fn static_recipe_declares_exactly_one_of_service_and_static_release() {
let both = format!("{RECIPE}\n[static_release]\nartifact = \"daemon\"\n");
let error = TargetDeclaration::parse(&both).unwrap_err();
assert!(format!("{error:#}").contains("both a service and a static release"));
let neither = STATIC_RECIPE.replace("[static_release]\nartifact = \"dist\"\n", "");
let error = TargetDeclaration::parse(&neither).unwrap_err();
assert!(format!("{error:#}").contains("neither a service nor a static release"));
let unknown = STATIC_RECIPE.replace("artifact = \"dist\"", "artifact = \"nope\"");
assert!(TargetDeclaration::parse(&unknown).is_err());
}
#[test]
fn static_release_refuses_a_workload_contract() {
for extra in [
"\n[[provides]]\ncapability = \"site.runtime\"\nschema = \"site.v1\"\ncompatibility = \"v1\"\n",
"\n[[conflicts]]\ncapability = \"site.old\"\nreason = \"replaced\"\n",
"\n[state]\nschema_generation = \"v1\"\n\n[[state.slots]]\nid = \"world\"\nrelative_path = \"world.cc\"\nkind = \"cultcache-file\"\nschema = \"site.v1\"\nwriter = \"none\"\nrecovery = \"preserve\"\nstartup = \"open-at-start\"\n",
] {
let error = TargetDeclaration::parse(&format!("{STATIC_RECIPE}{extra}")).unwrap_err();
assert!(
format!("{error:#}").contains("a static release declares no state"),
"{extra}: {error:#}"
);
}
for (from, to, refusal) in [
("[rollout]", "[route]\ndriver = \"nginx-stream-tcp\"\nroute_id = \"r\"\nstable_endpoint = \"http://127.0.0.1:18830\"\nprivate_host = \"127.0.0.1\"\nprivate_port_start = 18831\nprivate_port_end = 18839\nconfig_path = \"/etc/nginx/r.conf\"\nreload_unit = \"nginx.service\"\n\n[rollout]", "no write lease or route"),
("[rollout]", "[process_write_lease]\nrecord_path = \"/srv/site/lease.cc\"\n\n[rollout]", "no write lease or route"),
("retain_releases = 2", "retain_releases = 1", "retain at least current and prior"),
("candidate-then-promote", "stop-then-start", "never stops an incumbent"),
] {
let error = OperatorBinding::parse(&static_binding(&[(from, to)])).unwrap_err();
assert!(format!("{error:#}").contains(refusal), "{to}: {error:#}");
}
}
#[test]
fn static_release_and_service_recipes_need_their_own_binding_kind() {
let static_recipe = TargetDeclaration::parse(STATIC_RECIPE).unwrap();
let service_recipe = TargetDeclaration::parse(RECIPE).unwrap();
let static_binding = OperatorBinding::parse(&static_binding(&[])).unwrap();
let service_binding = OperatorBinding::parse(BINDING).unwrap();
assert!(static_binding.admit(&service_recipe).is_err());
assert!(service_binding.admit(&static_recipe).is_err());
}
#[test]
fn static_carry_destination_must_not_be_an_artifact_destination() {
let recipe = TargetDeclaration::parse(STATIC_RECIPE).unwrap();
let binding =
OperatorBinding::parse(&static_binding(&[("destination = \"config.json\"", "destination = \"dist\"")]))
.unwrap();
let error = binding.admit(&recipe).unwrap_err();
assert!(format!("{error:#}").contains("collides with an artifact destination"));
for destination in ["a/b", "../b", "/b", ""] {
let line = format!("destination = \"{destination}\"");
assert!(
OperatorBinding::parse(&static_binding(&[("destination = \"config.json\"", &line)])).is_err(),
"{destination}"
);
}
}
#[test]
fn static_carry_source_and_link_stay_out_of_the_release_root() {
for (from, to) in [
("source = \"/srv/site/config/site.json\"", "source = \"/srv/site/releases/site.json\""),
("current_link = \"/srv/site/www/current\"", "current_link = \"/srv/site/releases/current\""),
("source = \"/srv/site/config/site.json\"", "source = \"site.json\""),
("release_root = \"/srv/site/releases\"", "release_root = \"/srv/site/www\""),
] {
assert!(OperatorBinding::parse(&static_binding(&[(from, to)])).is_err(), "{to}");
}
}
}

View file

@ -854,14 +854,15 @@ impl SealedRelease {
) -> Result<ExpectedIncarnation> {
self.validate_against(plan)?;
let (declaration, binding) = plan.parsed_inputs()?;
let service = declaration.service()?;
let route = match (&binding.route, plan.candidate_port) {
(Some(bound), Some(port)) => Some(IdunnExpectedRoute {
route_id: bound.route_id.clone(),
transport: endpoint_scheme(declaration.service.transport)?.into(),
transport: endpoint_scheme(service.transport)?.into(),
stable_endpoint: bound.stable_endpoint.clone(),
candidate_endpoint: format!(
"{}://{}:{port}",
endpoint_scheme(declaration.service.transport)?,
endpoint_scheme(service.transport)?,
bound.private_host
),
}),
@ -871,7 +872,7 @@ impl SealedRelease {
let artifact_sha256 = self
.artifacts
.iter()
.find(|artifact| artifact.artifact_id == declaration.service.executable_artifact)
.find(|artifact| artifact.artifact_id == service.executable_artifact)
.context("sealed release has no executable service artifact")?
.sha256
.clone();
@ -918,7 +919,7 @@ impl SealedRelease {
.runtime_identity
.expected_signer_identity_id
.clone(),
health_contract: declaration.service.health.contract.clone(),
health_contract: service.health.contract.clone(),
artifact_sha256,
state_schema_generation: declaration
.state

View file

@ -25,7 +25,8 @@ use crate::deployment::{
IDUNN_RUNTIME_CANDIDATE_BIND_ENVIRONMENT, IDUNN_RUNTIME_MEMBER_BIND_ENVIRONMENT,
LaunchArgument, OperatorBinding,
RUNTIME_PRESENCE_IDENTITY_BINDING, RUNTIME_PRESENCE_IDENTITY_FD_NAME, RouteBinding,
RouteDriver, SourceSelectionPolicy, TargetDeclaration, WorkloadNetwork,
RouteDriver, SourceSelectionPolicy, StaticReleaseBinding, TargetDeclaration,
WorkloadNetwork,
};
use crate::deployment_plan::{
ArtifactReceipt, CompiledDeploymentPlan, ExternalInputMaterializationReceipt, GitlinkTreeFact,
@ -624,6 +625,273 @@ pub trait WorkloadPort {
) -> Result<bool>;
}
/// The largest per-site file a static release will carry.
const STATIC_CARRY_LIMIT_BYTES: u64 = 1024 * 1024;
/// What the flip landed: the digest of the exact bytes now inside the release.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct StaticFlip {
pub carried_sha256: String,
}
/// A flip that was refused before the link moved. It is the only error that may
/// end a static transaction before fencing: once the rename has happened,
/// nothing may say the flip did not.
#[derive(Debug)]
pub(crate) struct FlipRefused(pub(crate) String);
impl std::fmt::Display for FlipRefused {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter.write_str(&self.0)
}
}
impl std::error::Error for FlipRefused {}
/// The one external change a static release makes: copy the operator's site
/// file into an installed release and repoint the current link at it. The port
/// decides nothing; the engine decides when, and records what it reports.
pub trait StaticReleasePort {
/// The sealed release id the current link names: `None` when the link does
/// not exist yet, an error when it names anything but a release under the
/// binding's release root.
fn observe_current(&self, binding: &StaticReleaseBinding) -> Result<Option<String>>;
/// Copy the carry into `release_id` and repoint the link at it. Nothing
/// moves unless the carry source was read, so a missing site file leaves
/// the link where it was. Repeating it is harmless.
///
/// An error is `FlipRefused` exactly when the link did not move; the rename
/// is the last fallible step, and what follows it cannot fail the flip.
fn carry_and_flip(&self, binding: &StaticReleaseBinding, release_id: &str)
-> Result<StaticFlip>;
/// The release is installed where the binding says and every artifact in it
/// still digests to its sealed receipt. A rollback reuses a release sealed
/// long ago, so this is the check that it is still what was released.
fn verify_installed(&self, binding: &StaticReleaseBinding, release: &SealedRelease) -> Result<()>;
/// The digest of the carry already inside an installed release: what a
/// resumed flip records when an earlier attempt landed.
fn carried_sha256(&self, binding: &StaticReleaseBinding, release_id: &str) -> Result<String>;
}
#[derive(Clone, Copy, Debug, Default)]
pub struct FilesystemStaticRelease;
#[cfg(unix)]
impl StaticReleasePort for FilesystemStaticRelease {
fn observe_current(&self, binding: &StaticReleaseBinding) -> Result<Option<String>> {
let metadata = match fs::symlink_metadata(&binding.current_link) {
Ok(metadata) => metadata,
Err(error) if error.kind() == ErrorKind::NotFound => return Ok(None),
Err(error) => {
return Err(error).with_context(|| {
format!("reading current link {}", binding.current_link.display())
});
}
};
ensure!(
metadata.file_type().is_symlink(),
"current {} is not a symlink",
binding.current_link.display()
);
let target = fs::read_link(&binding.current_link)?;
let target = if target.is_absolute() {
target
} else {
binding
.current_link
.parent()
.context("current link has no parent")?
.join(target)
};
ensure!(
target.parent() == Some(binding.release_root.as_path()),
"current link names {}, which is not a release under {}",
target.display(),
binding.release_root.display()
);
let id = target
.file_name()
.and_then(OsStr::to_str)
.context("current link names no release")?;
require_sha256_id(id, "release named by the current link")?;
Ok(Some(id.to_owned()))
}
fn verify_installed(&self, binding: &StaticReleaseBinding, release: &SealedRelease) -> Result<()> {
let root = binding.release_root.join(&release.sealed_release_id);
ensure!(
fs::symlink_metadata(&root).is_ok_and(|metadata| metadata.is_dir()),
"release {} is no longer installed under {}",
release.sealed_release_id,
binding.release_root.display()
);
for artifact in &release.artifacts {
let (sha256, size_bytes) = digest_artifact(&root.join(&artifact.destination))
.with_context(|| format!("digesting installed artifact {}", artifact.artifact_id))?;
ensure!(
format!("sha256-{sha256}") == artifact.sha256 && size_bytes == artifact.size_bytes,
"installed artifact {} of release {} differs from its sealed receipt",
artifact.artifact_id,
release.sealed_release_id
);
}
Ok(())
}
fn carried_sha256(&self, binding: &StaticReleaseBinding, release_id: &str) -> Result<String> {
require_sha256_id(release_id, "release carrying the site file")?;
let carried = binding
.release_root
.join(release_id)
.join(&binding.carry.destination);
ensure!(
fs::symlink_metadata(&carried)?.is_file(),
"carried {} is not a regular file",
carried.display()
);
let mut hasher = Sha256::new();
hash_file_exact(&carried, fs::metadata(&carried)?.len(), &mut hasher)?;
Ok(format!("sha256-{:x}", hasher.finalize()))
}
fn carry_and_flip(
&self,
binding: &StaticReleaseBinding,
release_id: &str,
) -> Result<StaticFlip> {
use std::os::unix::fs::{OpenOptionsExt, PermissionsExt, symlink};
// Everything up to and including the rename can refuse, and only that
// refuses: the link has not moved when `FlipRefused` is returned.
let refuse = |error: anyhow::Error| anyhow::Error::new(FlipRefused(format!("{error:#}")));
let staged = (|| -> Result<(PathBuf, PathBuf, String)> {
require_sha256_id(release_id, "release to flip to")?;
let release = binding.release_root.join(release_id);
let release_metadata = fs::symlink_metadata(&release)
.with_context(|| format!("installed release {}", release.display()))?;
ensure!(
release_metadata.is_dir(),
"installed release {} is not a directory",
release.display()
);
let link_parent = binding
.current_link
.parent()
.context("current link has no parent")?;
match fs::symlink_metadata(&binding.current_link) {
Ok(metadata) => ensure!(
metadata.file_type().is_symlink(),
"current {} is not a symlink and will not be replaced",
binding.current_link.display()
),
Err(error) if error.kind() == ErrorKind::NotFound => {}
Err(error) => return Err(error).context("reading current link"),
}
let source = &binding.carry.source;
let source_metadata = fs::symlink_metadata(source)
.with_context(|| format!("reading carry source {}", source.display()))?;
ensure!(
source_metadata.is_file(),
"carry source {} is not a regular file",
source.display()
);
ensure!(
source_metadata.len() <= STATIC_CARRY_LIMIT_BYTES,
"carry source {} is larger than {STATIC_CARRY_LIMIT_BYTES} bytes",
source.display()
);
let mut bytes = Vec::new();
fs::File::open(source)?
.take(STATIC_CARRY_LIMIT_BYTES + 1)
.read_to_end(&mut bytes)?;
ensure!(
bytes.len() as u64 <= STATIC_CARRY_LIMIT_BYTES,
"carry source {} grew past {STATIC_CARRY_LIMIT_BYTES} bytes",
source.display()
);
let carried_sha256 = format!("sha256-{:x}", Sha256::digest(&bytes));
let carried = release.join(&binding.carry.destination);
let temporary_carry = release.join(format!(".carry-{}", Uuid::new_v4()));
let written = (|| -> Result<()> {
let mut file = OpenOptions::new()
.write(true)
.create_new(true)
.mode(0o444)
.open(&temporary_carry)?;
// The creation mode is masked by the service's umask
// (UMask=0027 yields 0440), and the web server reads this file
// as "other"; say 0444 on the open handle.
file.set_permissions(fs::Permissions::from_mode(0o444))?;
file.write_all(&bytes)?;
file.sync_all()?;
fs::rename(&temporary_carry, &carried)?;
fs::File::open(&release)?.sync_all()?;
Ok(())
})();
if let Err(error) = written {
let _ = fs::remove_file(&temporary_carry);
return Err(error)
.with_context(|| format!("carrying the site file into {}", release.display()));
}
// A link is renamed over, never edited: a reader sees the old
// release or the new one. A temporary link a crashed flip left is
// replaced.
let temporary_link = link_parent.join(format!(
".{}.flip",
binding
.current_link
.file_name()
.and_then(OsStr::to_str)
.context("current link has no name")?
));
if fs::symlink_metadata(&temporary_link).is_ok() {
fs::remove_file(&temporary_link).context("removing a stale flip link")?;
}
symlink(&release, &temporary_link).context("creating the flip link")?;
Ok((temporary_link, release, carried_sha256))
})()
.map_err(refuse)?;
let (temporary_link, _, carried_sha256) = staged;
if let Err(error) = fs::rename(&temporary_link, &binding.current_link) {
let _ = fs::remove_file(&temporary_link);
return Err(refuse(
anyhow::Error::new(error).context("repointing the current link"),
));
}
// The link has moved and nothing below can say it did not. The parent
// directory sync is durability only, so it is best-effort.
if let Some(parent) = binding.current_link.parent() {
let _ = fs::File::open(parent).and_then(|directory| directory.sync_all());
}
Ok(StaticFlip { carried_sha256 })
}
}
#[cfg(not(unix))]
impl StaticReleasePort for FilesystemStaticRelease {
fn observe_current(&self, _: &StaticReleaseBinding) -> Result<Option<String>> {
bail!("a static release flip requires Unix symlinks")
}
fn carry_and_flip(&self, _: &StaticReleaseBinding, _: &str) -> Result<StaticFlip> {
bail!("a static release flip requires Unix symlinks")
}
fn carried_sha256(&self, _: &StaticReleaseBinding, _: &str) -> Result<String> {
bail!("a static release flip requires Unix symlinks")
}
fn verify_installed(&self, _: &StaticReleaseBinding, _: &SealedRelease) -> Result<()> {
bail!("a static release flip requires Unix symlinks")
}
}
pub trait TopologyPort {
fn publish_expected(
&self,
@ -2903,7 +3171,7 @@ impl SystemdTransientWorkloadDriver {
) -> Result<InstalledReleaseObservation> {
release.release.validate_against(plan)?;
let (_, binding) = plan.parsed_inputs()?;
let release_root = &binding.workload.systemd()?.release_root;
let release_root = binding.workload.release_root()?;
fs::create_dir_all(release_root)
.with_context(|| format!("creating release root {}", release_root.display()))?;
let installed = release_root.join(&release.release.sealed_release_id);
@ -2955,8 +3223,7 @@ impl SystemdTransientWorkloadDriver {
&& installed.root
== binding
.workload
.systemd()?
.release_root
.release_root()?
.join(&release.sealed_release_id),
"installed release observation belongs to another sealed release"
);
@ -3435,11 +3702,11 @@ impl SystemdTransientWorkloadDriver {
installed: &Path,
) -> Result<Vec<OsString>> {
let executable_artifact =
release_artifact(declaration, &declaration.service.executable_artifact)?;
release_artifact(declaration, &declaration.service()?.executable_artifact)?;
let executable = installed.join(&executable_artifact.destination);
ensure!(executable.is_file(), "sealed service executable is absent");
let mut command = vec![executable.into_os_string()];
for argument in &declaration.service.arguments {
for argument in &declaration.service()?.arguments {
command.push(match argument {
LaunchArgument::Literal { value } => value.into(),
LaunchArgument::Binding { name } => binding.workload.systemd()?.argument_bindings
@ -3734,7 +4001,7 @@ impl SystemdTransientWorkloadDriver {
) -> Result<()> {
ensure!(
declaration
.service
.service()?
.required_environment
.contains(IDUNN_RUNTIME_BUNDLE_ENVIRONMENT),
"target does not declare the standard Idunn runtime bundle"
@ -3757,7 +4024,7 @@ impl SystemdTransientWorkloadDriver {
parent_only_open_file_properties(parent_only_file_descriptors)?;
let environment = self.launch_environment(binding, bundle, expected, unit)?;
let executable_artifact =
release_artifact(declaration, &declaration.service.executable_artifact)?;
release_artifact(declaration, &declaration.service()?.executable_artifact)?;
let executable = installed.join(&executable_artifact.destination);
ensure!(executable.is_file(), "sealed service executable is absent");
let unit_description = format!(
@ -3967,7 +4234,7 @@ impl WorkloadPort for SystemdTransientWorkloadDriver {
let (declaration, binding) = plan.parsed_inputs()?;
self.validate_writable_bindings(&binding)?;
let executable_artifact =
release_artifact(&declaration, &declaration.service.executable_artifact)?;
release_artifact(&declaration, &declaration.service()?.executable_artifact)?;
let executable = installed.root.join(&executable_artifact.destination);
let unit = self.unit_name(
&binding.workload.systemd()?.unit_prefix,
@ -8524,7 +8791,7 @@ fn require_git_sha(value: &str, label: &str) -> Result<()> {
Ok(())
}
fn require_sha256_id(value: &str, label: &str) -> Result<()> {
pub(crate) fn require_sha256_id(value: &str, label: &str) -> Result<()> {
let digest = value
.strip_prefix("sha256-")
.with_context(|| format!("{label} has no sha256 prefix"))?;
@ -16698,4 +16965,204 @@ processes 9
Ok(())
}
// END runner-failure-evidence tests
// ---------------------------------------------------------------------
// A static release flips on a stand-in site tree: releases/, a www/ that
// holds the current link, and the operator's per-site config. Nothing here
// is a real site.
// ---------------------------------------------------------------------
#[cfg(unix)]
struct StandInSite {
_temp: tempfile::TempDir,
binding: StaticReleaseBinding,
}
#[cfg(unix)]
const RELEASE_A: &str = "sha256-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
#[cfg(unix)]
const RELEASE_B: &str = "sha256-bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb";
/// Two installed releases, each a fake vite build with compressed twins,
/// and a site config the operator owns.
#[cfg(unix)]
fn stand_in_site() -> Result<StandInSite> {
let temp = tempfile::tempdir()?;
let root = temp.path();
for release in [RELEASE_A, RELEASE_B] {
let dist = root.join("releases").join(release).join("dist");
fs::create_dir_all(dist.join("assets"))?;
fs::write(dist.join("index.html"), format!("<html>{release}</html>"))?;
fs::write(dist.join("index.html.br"), b"br")?;
fs::write(dist.join("index.html.gz"), b"gz")?;
fs::write(dist.join("assets/app.js"), b"app")?;
}
fs::create_dir_all(root.join("www"))?;
fs::create_dir_all(root.join("config"))?;
fs::write(root.join("config/site.json"), br#"{"api":"https://example.test"}"#)?;
Ok(StandInSite {
binding: StaticReleaseBinding {
release_root: root.join("releases"),
current_link: root.join("www/current"),
carry: crate::deployment::StaticCarryBinding {
source: root.join("config/site.json"),
destination: "config.json".into(),
},
},
_temp: temp,
})
}
#[cfg(unix)]
#[test]
fn static_release_flip_carries_the_site_file_and_names_the_release() -> Result<()> {
use std::os::unix::fs::PermissionsExt;
let site = stand_in_site()?;
let port = FilesystemStaticRelease;
assert_eq!(port.observe_current(&site.binding)?, None, "no link before the first flip");
let flip = port.carry_and_flip(&site.binding, RELEASE_A)?;
assert_eq!(port.observe_current(&site.binding)?.as_deref(), Some(RELEASE_A));
let carried = site.binding.current_link.join("config.json");
let bytes = fs::read(&carried)?;
assert_eq!(bytes, fs::read(&site.binding.carry.source)?);
assert_eq!(flip.carried_sha256, format!("sha256-{:x}", Sha256::digest(&bytes)));
assert_eq!(fs::metadata(&carried)?.permissions().mode() & 0o777, 0o444);
assert!(fs::symlink_metadata(&carried)?.is_file(), "the carry is a copy, never a link");
// The web root reads the release's own tree through the link.
assert_eq!(fs::read(site.binding.current_link.join("dist/index.html.br"))?, b"br");
// The site file changes between releases: the second release carries
// the new bytes and the first keeps the ones it was flipped with.
fs::write(&site.binding.carry.source, br#"{"api":"https://other.test"}"#)?;
let second = port.carry_and_flip(&site.binding, RELEASE_B)?;
assert_ne!(second.carried_sha256, flip.carried_sha256);
assert_eq!(port.observe_current(&site.binding)?.as_deref(), Some(RELEASE_B));
assert_eq!(fs::read(&carried)?, br#"{"api":"https://other.test"}"#);
assert_eq!(
fs::read(site.binding.release_root.join(RELEASE_A).join("config.json"))?,
br#"{"api":"https://example.test"}"#
);
// Rolling back is the same flip to the release the link named before.
port.carry_and_flip(&site.binding, RELEASE_A)?;
assert_eq!(port.observe_current(&site.binding)?.as_deref(), Some(RELEASE_A));
Ok(())
}
/// The service runs with UMask=0027, which masks the create mode to 0440
/// and hides the carry from the web user. The umask is process-global, so
/// the proof runs in a child copy of this test binary and no sibling test
/// ever sees it.
#[cfg(unix)]
#[test]
fn static_release_carry_is_0444_under_the_service_umask() -> Result<()> {
use std::os::unix::fs::PermissionsExt;
const CHILD: &str = "IDUNN_TEST_CARRY_UMASK_CHILD";
const NAME: &str = "static_release_carry_is_0444_under_the_service_umask";
if std::env::var_os(CHILD).is_none() {
let path = format!("{}::{NAME}", module_path!().split_once("::").map_or("", |(_, rest)| rest));
let output = std::process::Command::new(std::env::current_exe()?)
.args(["--exact", path.as_str(), "--nocapture", "--test-threads=1"])
.env(CHILD, "1")
.output()?;
assert!(
output.status.success(),
"child under umask 0027 failed:\n{}\n{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
assert!(
String::from_utf8_lossy(&output.stdout).contains("1 passed"),
"the child filter matched no test:\n{}",
String::from_utf8_lossy(&output.stdout)
);
return Ok(());
}
unsafe { libc::umask(0o027) };
let site = stand_in_site()?;
FilesystemStaticRelease.carry_and_flip(&site.binding, RELEASE_A)?;
let carried = site.binding.current_link.join("config.json");
assert_eq!(fs::metadata(&carried)?.permissions().mode() & 0o777, 0o444);
Ok(())
}
#[cfg(unix)]
#[test]
fn static_release_missing_site_config_fails_before_the_link_moves() -> Result<()> {
let site = stand_in_site()?;
let port = FilesystemStaticRelease;
port.carry_and_flip(&site.binding, RELEASE_A)?;
fs::remove_file(&site.binding.carry.source)?;
let error = port.carry_and_flip(&site.binding, RELEASE_B).unwrap_err();
assert!(format!("{error:#}").contains("carry source"), "{error:#}");
assert!(error.downcast_ref::<FlipRefused>().is_some(), "a pre-rename refusal is typed");
assert_eq!(port.observe_current(&site.binding)?.as_deref(), Some(RELEASE_A));
assert!(
!site.binding.release_root.join(RELEASE_B).join("config.json").exists(),
"a failed flip wrote its carry"
);
Ok(())
}
#[cfg(unix)]
#[test]
fn static_release_refuses_a_site_file_that_is_not_a_plain_small_file() -> Result<()> {
let site = stand_in_site()?;
let port = FilesystemStaticRelease;
let source = site.binding.carry.source.clone();
fs::remove_file(&source)?;
fs::write(source.with_extension("real"), b"{}")?;
std::os::unix::fs::symlink(source.with_extension("real"), &source)?;
assert!(port.carry_and_flip(&site.binding, RELEASE_A).is_err(), "a linked site file was carried");
fs::remove_file(&source)?;
fs::write(&source, vec![b'x'; STATIC_CARRY_LIMIT_BYTES as usize + 1])?;
assert!(port.carry_and_flip(&site.binding, RELEASE_A).is_err(), "an oversize site file was carried");
assert_eq!(port.observe_current(&site.binding)?, None);
Ok(())
}
#[cfg(unix)]
#[test]
fn static_release_replaces_a_stale_flip_link_a_crash_left() -> Result<()> {
let site = stand_in_site()?;
let port = FilesystemStaticRelease;
let stale = site.binding.current_link.with_file_name(".current.flip");
std::os::unix::fs::symlink("/nowhere", &stale)?;
port.carry_and_flip(&site.binding, RELEASE_A)?;
assert_eq!(port.observe_current(&site.binding)?.as_deref(), Some(RELEASE_A));
assert!(fs::symlink_metadata(&stale).is_err(), "the stale flip link survived");
// Repeating the flip, as a resumed transaction does, changes nothing.
port.carry_and_flip(&site.binding, RELEASE_A)?;
assert_eq!(port.observe_current(&site.binding)?.as_deref(), Some(RELEASE_A));
Ok(())
}
#[cfg(unix)]
#[test]
fn static_release_will_not_replace_or_trust_what_is_not_its_link() -> Result<()> {
let site = stand_in_site()?;
let port = FilesystemStaticRelease;
// A real directory where the link belongs is left alone.
fs::create_dir(&site.binding.current_link)?;
let error = port.carry_and_flip(&site.binding, RELEASE_A).unwrap_err();
assert!(error.downcast_ref::<FlipRefused>().is_some(), "{error:#}");
assert!(site.binding.current_link.is_dir());
assert!(
!site.binding.release_root.join(RELEASE_A).join("config.json").exists(),
"a refused flip wrote its carry"
);
assert!(port.observe_current(&site.binding).is_err());
fs::remove_dir(&site.binding.current_link)?;
// A link that names something outside the release root has no release
// to roll back to, and Idunn says so instead of guessing.
std::os::unix::fs::symlink("/usr", &site.binding.current_link)?;
let error = port.observe_current(&site.binding).unwrap_err();
assert!(format!("{error:#}").contains("not a release under"), "{error:#}");
// A release that was never installed is not flipped to.
fs::remove_file(&site.binding.current_link)?;
let missing = format!("sha256-{}", "c".repeat(64));
assert!(port.carry_and_flip(&site.binding, &missing).is_err());
assert_eq!(port.observe_current(&site.binding)?, None);
Ok(())
}
}

View file

@ -631,11 +631,11 @@ impl Actuator {
workload: &HostWorkloadBinding,
installed: &Path,
) -> Result<(PathBuf, Vec<String>)> {
let artifact = release_artifact(declaration, &declaration.service.executable_artifact)?;
let artifact = release_artifact(declaration, &declaration.service()?.executable_artifact)?;
let executable = installed.join(&artifact.destination);
ensure!(executable.is_file(), "sealed service executable is absent");
let mut arguments = Vec::new();
for argument in &declaration.service.arguments {
for argument in &declaration.service()?.arguments {
arguments.push(match argument {
LaunchArgument::Literal { value } => value.clone(),
LaunchArgument::Binding { name } => workload

View file

@ -1151,7 +1151,7 @@ mod tests {
let answerer = thread::spawn(move || -> Result<()> {
for _ in 0..500 {
client.poll_resends()?;
while let Some(frame) = client.receive_once()? {
if let Some(frame) = client.receive_once()? {
let envelope = HostActuatorEnvelope::decode(&frame.payload)?;
let request = envelope.open_request("raven", &idunn_anchor)?;
assert_eq!(envelope.session_nonce, nonce);

View file

@ -1,3 +1,4 @@
mod brake;
pub mod control_plane;
pub mod deployment;
pub mod deployment_plan;
@ -9,3 +10,5 @@ pub mod launcher;
mod incident;
mod runner_evidence;
pub mod provisioning;
#[cfg(unix)]
mod steward_orders;

View file

@ -1,4 +1,5 @@
use anyhow::{Context, Result, anyhow, bail};
use crate::brake::{Stop, StopState, process_uid, read_stop, replace_stop};
use anyhow::{Context, Result, anyhow, bail, ensure};
use cultcache_rs::{
CultCacheEnvelope, CultCacheExpectedEnvelope, DatabaseEntry, SingleFileMessagePackBackingStore,
};
@ -6,15 +7,13 @@ use cultnet_rs::{
GAMECULT_SERVICE_TRUST_ANCHOR_SCHEMA, GameCultProviderHealthIdentity,
GameCultServiceTrustAnchorRecord, IDUNN_AUTHENTICATED_PROVIDER_HEALTH_PROJECTION_SCHEMA,
IDUNN_AUTHENTICATED_PROVIDER_HEALTH_PROJECTION_SIGNING_PURPOSE,
IDUNN_DAEMON_HEALTH_TRUST_BINDING_SCHEMA, IDUNN_DEPLOYMENT_BRAKE_AUTHORITY,
IDUNN_DEPLOYMENT_BRAKE_ID, IDUNN_DEPLOYMENT_BRAKE_SCHEMA, IDUNN_DEPLOYMENT_BRAKE_SCOPE,
IDUNN_DEPLOYMENT_RELEASE_PURPOSE, IDUNN_LIFECYCLE_BRAKE_AUTHORITY,
IDUNN_DAEMON_HEALTH_TRUST_BINDING_SCHEMA,
IDUNN_LIFECYCLE_BRAKE_AUTHORITY,
IDUNN_LIFECYCLE_BRAKE_SCHEMA, IDUNN_LIFECYCLE_BRAKE_SCOPE, IdunnDaemonHealthTrustBindingRecord,
IdunnDeploymentBrakeObservation, IdunnDeploymentBrakeOperatorIdentity,
IdunnDeploymentBrakeRecord, IdunnDeploymentBrakeReleasePurpose, IdunnLifecycleBrakeObservation,
IdunnLifecycleBrakeObservation,
IdunnLifecycleBrakeRecord, IdunnServiceIdentity, OdinTopologyIdentity, ServiceIdentityProfile,
ServiceIdentityTrustAnchor, derive_service_identity_id, enroll_service_identity_at,
evaluate_idunn_continuity_restart, evaluate_idunn_deployment_brake,
evaluate_idunn_continuity_restart,
export_service_identity_trust_anchor, open_service_identity_at,
};
use std::collections::{BTreeMap, BTreeSet};
@ -80,17 +79,8 @@ pub fn run(args: impl IntoIterator<Item = String>) -> Result<()> {
"export-odin-topology-public-anchor" => {
export_identity_anchor::<OdinTopologyIdentity>(&options, "Odin topology public anchor")?
}
"enroll-deployment-brake-operator" => {
enroll_identity::<IdunnDeploymentBrakeOperatorIdentity>(&options)?
}
"export-deployment-brake-operator-anchor" => {
export_identity_anchor::<IdunnDeploymentBrakeOperatorIdentity>(
&options,
"deployment brake operator anchor",
)?
}
"deployment-brake-engage" => deployment_brake_engage(&options)?,
"deployment-brake-release" => deployment_brake_release(&options)?,
"deployment-brake-engage" => deployment_brake_write(&options, StopState::Engaged)?,
"deployment-brake-clear" => deployment_brake_write(&options, StopState::Clear)?,
"deployment-brake-status" => deployment_brake_status(&options)?,
"lifecycle-brake-engage" => lifecycle_brake_engage(&options)?,
"lifecycle-brake-release" => lifecycle_brake_release(&options)?,
@ -157,153 +147,60 @@ fn provider_health_public_key(options: &BTreeMap<String, String>) -> Result<Stri
encode_public_key(&signer.entry().public_key)
}
fn deployment_brake_engage(options: &BTreeMap<String, String>) -> Result<()> {
require_only(
options,
&[
"store",
"runtime-id",
"owner",
"reason",
"observed-at-unix-millis",
],
/// Engage or clear the deployment stop. The author is the process uid's login
/// name and the time is this verb's clock: neither is an argument.
fn deployment_brake_write(options: &BTreeMap<String, String>, state: StopState) -> Result<()> {
require_only(options, &["store", "runtime-id", "reason"])?;
let now = u64::try_from(
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)?
.as_millis(),
)?;
let observed = parse_u64(options, "observed-at-unix-millis")?;
let record = IdunnDeploymentBrakeRecord {
schema_version: IDUNN_DEPLOYMENT_BRAKE_SCHEMA.into(),
brake_id: IDUNN_DEPLOYMENT_BRAKE_ID.into(),
authority: IDUNN_DEPLOYMENT_BRAKE_AUTHORITY.into(),
runtime_id: required(options, "runtime-id")?.into(),
status: "engaged".into(),
scope: IDUNN_DEPLOYMENT_BRAKE_SCOPE.into(),
reason: required(options, "reason")?.into(),
observed_at_unix_millis: observed,
expires_at_unix_millis: None,
authorization_id: None,
authorization_purpose: None,
authorized_release_id: None,
authorized_deployment_id: None,
authorized_by: None,
authorization_issued_at_unix_millis: None,
authorization_expires_at_unix_millis: None,
signature_algorithm: None,
signature: None,
private_state_exposed: false,
updated_by: required(options, "owner")?.into(),
};
record.validate()?;
replace_brake(&path(options, "store")?, record, observed)
}
fn deployment_brake_release(options: &BTreeMap<String, String>) -> Result<()> {
require_only(
options,
&[
"store",
"private-store",
"runtime-id",
"owner",
"reason",
"authorization-id",
"release-id",
"deployment-id",
"issued-at-unix-millis",
"expires-at-unix-millis",
],
)?;
let issued = parse_u64(options, "issued-at-unix-millis")?;
let expires = parse_u64(options, "expires-at-unix-millis")?;
let signer = open_service_identity_at::<IdunnDeploymentBrakeOperatorIdentity>(&path(
options,
"private-store",
)?)?;
let mut record = IdunnDeploymentBrakeRecord {
schema_version: IDUNN_DEPLOYMENT_BRAKE_SCHEMA.into(),
brake_id: IDUNN_DEPLOYMENT_BRAKE_ID.into(),
authority: IDUNN_DEPLOYMENT_BRAKE_AUTHORITY.into(),
runtime_id: required(options, "runtime-id")?.into(),
status: "released".into(),
scope: IDUNN_DEPLOYMENT_BRAKE_SCOPE.into(),
reason: required(options, "reason")?.into(),
observed_at_unix_millis: issued,
expires_at_unix_millis: Some(expires),
authorization_id: Some(required(options, "authorization-id")?.into()),
authorization_purpose: Some(IDUNN_DEPLOYMENT_RELEASE_PURPOSE.into()),
authorized_release_id: Some(required(options, "release-id")?.into()),
authorized_deployment_id: Some(required(options, "deployment-id")?.into()),
authorized_by: Some(signer.trust_anchor()?.identity_id),
authorization_issued_at_unix_millis: Some(issued),
authorization_expires_at_unix_millis: Some(expires),
signature_algorithm: Some("ed25519".into()),
signature: None,
private_state_exposed: false,
updated_by: required(options, "owner")?.into(),
};
record.signature = Some(
signer
.sign::<IdunnDeploymentBrakeReleasePurpose>(&rmp_serde::to_vec(&record)?)
.signature,
);
record.validate()?;
replace_brake(&path(options, "store")?, record, issued)
}
fn deployment_brake_status(options: &BTreeMap<String, String>) -> Result<()> {
allow_only(
options,
&[
"store",
"operator-anchor",
"runtime-id",
"release-id",
"deployment-id",
"now-unix-millis",
],
)?;
let exact_actuation_fields = ["release-id", "deployment-id", "now-unix-millis"];
let exact_actuation_field_count = exact_actuation_fields
.into_iter()
.filter(|field| options.contains_key(*field))
.count();
if exact_actuation_field_count != 0
&& exact_actuation_field_count != exact_actuation_fields.len()
{
bail!("exact deployment-brake actuation validation requires release, deployment, and time");
}
let record = read_brake(&path(options, "store")?)?;
if record.runtime_id != required(options, "runtime-id")? {
bail!("deployment brake belongs to another runtime")
}
if record.status == "engaged" {
if exact_actuation_field_count != 0 {
bail!("engaged deployment brake denies exact actuation validation");
}
println!(
"engaged runtime={} scope={} owner={} reason={}",
record.runtime_id, record.scope, record.updated_by, record.reason
);
return Ok(());
}
let anchor = read_operator_anchor(&path(options, "operator-anchor")?)?;
evaluate_idunn_deployment_brake(
IdunnDeploymentBrakeObservation::Present(&record),
&anchor,
let record = replace_stop(
&path(options, "store")?,
required(options, "runtime-id")?,
required(options, "release-id")?,
required(options, "deployment-id")?,
parse_u64(options, "now-unix-millis")?,
)
.map_err(|d| anyhow!("deployment brake denied actuation: {d:?}"))?;
state,
required(options, "reason")?,
now,
)?;
println!(
"released runtime={} release={} deployment={} owner={}",
"{} runtime={} by={} sequence={}",
record.state.name(),
record.runtime_id,
record.authorized_release_id.unwrap(),
record.authorized_deployment_id.unwrap(),
record.updated_by
record.by,
record.sequence
);
Ok(())
}
/// Print the stop and exit nonzero unless deployments admit, so a script can
/// gate on it as it could on the retired exact-actuation validation.
fn deployment_brake_status(options: &BTreeMap<String, String>) -> Result<()> {
allow_only(options, &["store", "runtime-id", "owner-user"])?;
// A steward's store is owned by the steward: the operator names that user
// to read it, and the owner check is the same one Idunn makes.
let owner = match options.get("owner-user") {
Some(user) => crate::steward_orders::user_uid(user)?,
None => process_uid(),
};
let stop = read_stop(&path(options, "store")?, required(options, "runtime-id")?, owner);
match &stop {
Stop::Absent => println!("absent: deployments admit"),
Stop::Unreadable(why) => println!("unreadable: deployments wait ({why})"),
Stop::Clear(record) | Stop::Engaged(record) => println!(
"{} runtime={} by={} at={} sequence={} reason={}",
record.state.name(),
record.runtime_id,
record.by,
record.at_unix_millis,
record.sequence,
record.reason
),
}
ensure!(stop.admits(), "the deployment brake does not admit deployments");
Ok(())
}
fn lifecycle_brake_engage(options: &BTreeMap<String, String>) -> Result<()> {
require_only(
options,
@ -407,7 +304,7 @@ fn lifecycle_brake_status(options: &BTreeMap<String, String>) -> Result<()> {
Ok(())
}
fn replace_lifecycle_brake(path: &Path, record: IdunnLifecycleBrakeRecord) -> Result<()> {
pub(crate) fn replace_lifecycle_brake(path: &Path, record: IdunnLifecycleBrakeRecord) -> Result<()> {
record.validate()?;
let store = SingleFileMessagePackBackingStore::new(path);
let entries = store.pull_all_read_only_snapshot()?;
@ -482,70 +379,6 @@ fn lifecycle_identifier<'a>(options: &'a BTreeMap<String, String>, name: &str) -
Ok(value)
}
fn replace_brake(path: &Path, record: IdunnDeploymentBrakeRecord, millis: u64) -> Result<()> {
let store = SingleFileMessagePackBackingStore::new(path);
let entries = store.pull_all_read_only_snapshot()?;
let current = match entries.as_slice() {
[] => None,
[entry]
if entry.r#type == IdunnDeploymentBrakeRecord::TYPE
&& entry.key == IDUNN_DEPLOYMENT_BRAKE_ID =>
{
Some(entry.clone())
}
_ => bail!("deployment brake store is corrupt or ambiguous"),
};
let next = typed_envelope(
IDUNN_DEPLOYMENT_BRAKE_ID,
&record,
IDUNN_DEPLOYMENT_BRAKE_SCHEMA,
millis,
)?;
if !store.compare_exchange(
&[CultCacheExpectedEnvelope {
r#type: IdunnDeploymentBrakeRecord::TYPE.into(),
key: IDUNN_DEPLOYMENT_BRAKE_ID.into(),
current,
}],
&[next],
)? {
bail!("deployment brake changed during transition");
}
Ok(())
}
fn read_brake(path: &Path) -> Result<IdunnDeploymentBrakeRecord> {
let entries = SingleFileMessagePackBackingStore::new(path).pull_all_read_only_snapshot()?;
let [entry] = entries.as_slice() else {
bail!("deployment brake is missing or ambiguous")
};
if entry.r#type != IdunnDeploymentBrakeRecord::TYPE
|| entry.key != IDUNN_DEPLOYMENT_BRAKE_ID
|| entry.schema_id.as_deref() != Some(IDUNN_DEPLOYMENT_BRAKE_SCHEMA)
{
bail!("deployment brake is foreign")
}
let record: IdunnDeploymentBrakeRecord = rmp_serde::from_slice(&entry.payload)?;
if rmp_serde::to_vec(&record)? != entry.payload {
bail!("deployment brake is noncanonical")
}
record.validate()?;
Ok(record)
}
fn read_operator_anchor(path: &Path) -> Result<ServiceIdentityTrustAnchor> {
let entries = SingleFileMessagePackBackingStore::new(path).pull_all_read_only_snapshot()?;
let [entry] = entries.as_slice() else {
bail!("operator anchor is missing or ambiguous")
};
if entry.r#type != IdunnDeploymentBrakeOperatorIdentity::TRUST_ANCHOR_TYPE
|| entry.key != IdunnDeploymentBrakeOperatorIdentity::TRUST_ANCHOR_KEY
{
bail!("operator anchor is foreign")
}
Ok(rmp_serde::from_slice(&entry.payload)?)
}
fn validate_health_binding_store(path: &Path) -> Result<()> {
let entries = SingleFileMessagePackBackingStore::new(path).pull_all_read_only_snapshot()?;
validated_health_bindings(&entries)?;
@ -1127,7 +960,7 @@ fn normalized(path: &Path) -> Result<PathBuf> {
}
fn usage() -> &'static str {
"Usage: idunn-provision enroll-provider-health-identity --private-store <path>\n idunn-provision provider-health-public-key --private-store <path>\n idunn-provision export-provider-health-public-anchor --private-store <path> --public-anchor <path>\n idunn-provision enroll-idunn-identity --private-store <path>\n idunn-provision export-idunn-public-anchor --private-store <path> --public-anchor <path>\n idunn-provision enroll-odin-topology-identity --private-store <path>\n idunn-provision export-odin-topology-public-anchor --private-store <path> --public-anchor <path>\n idunn-provision enroll-deployment-brake-operator --private-store <path>\n idunn-provision export-deployment-brake-operator-anchor --private-store <path> --public-anchor <path>\n idunn-provision deployment-brake-engage --store <path> --runtime-id <id> --owner <principal> --reason <text> --observed-at-unix-millis <u64>\n idunn-provision deployment-brake-release --store <path> --private-store <path> --runtime-id <id> --owner <principal> --reason <text> --authorization-id <id> --release-id <id> --deployment-id <id> --issued-at-unix-millis <u64> --expires-at-unix-millis <u64>\n idunn-provision deployment-brake-status --store <path> --operator-anchor <path> --runtime-id <id> [--release-id <id> --deployment-id <id> --now-unix-millis <u64>]\n idunn-provision lifecycle-brake-engage --store <path> --runtime-id <id> --target <id> --reason <text> --updated-at-unix-millis <u64>\n idunn-provision lifecycle-brake-release --store <path> --runtime-id <id> --target <id> --reason <text> --updated-at-unix-millis <u64> [--released-until-unix-millis <u64>]\n idunn-provision lifecycle-brake-status --store <path> --runtime-id <id> --target <id> --now-unix-millis <u64>\n idunn-provision create-daemon-health-trust-binding --output <path> --binding-id <id> --daemon <id> --health-contract <id> --source-runtime <id> --signer-public-key-hex <hex> --bound-at-unix-millis <u64> --release-binding-required <true|false>\n idunn-provision add-daemon-health-trust-binding --output <path> --binding-id <id> --daemon <id> --health-contract <id> --source-runtime <id> --signer-public-key-hex <hex> --bound-at-unix-millis <u64> --release-binding-required <true|false>\n idunn-provision require-daemon-health-release-binding --store <path> --binding-id <id> --daemon <id> --health-contract <id> --source-runtime <id> --signer-public-key-hex <hex>\n idunn-provision rotate-daemon-health-trust-signer --output <path> --binding-id <id> --signer-public-key-hex <hex> --bound-at-unix-millis <u64>\n idunn-provision validate-daemon-health-trust-binding --input <path>\n idunn-provision create-provider-projection-trust-anchor --output <path> --trust-anchor-id <id> --runtime-id <id> --idunn-public-anchor <path> --bound-at-unix-millis <u64> --expires-at-unix-millis <u64>\n idunn-provision validate-provider-projection-trust-anchor --input <path> --idunn-public-anchor <path>"
"Usage: idunn-provision enroll-provider-health-identity --private-store <path>\n idunn-provision provider-health-public-key --private-store <path>\n idunn-provision export-provider-health-public-anchor --private-store <path> --public-anchor <path>\n idunn-provision enroll-idunn-identity --private-store <path>\n idunn-provision export-idunn-public-anchor --private-store <path> --public-anchor <path>\n idunn-provision enroll-odin-topology-identity --private-store <path>\n idunn-provision export-odin-topology-public-anchor --private-store <path> --public-anchor <path>\n idunn-provision deployment-brake-engage --store <path> --runtime-id <id> --reason <text>\n idunn-provision deployment-brake-clear --store <path> --runtime-id <id> --reason <text>\n idunn-provision deployment-brake-status --store <path> --runtime-id <id> [--owner-user <login>]\n idunn-provision lifecycle-brake-engage --store <path> --runtime-id <id> --target <id> --reason <text> --updated-at-unix-millis <u64>\n idunn-provision lifecycle-brake-release --store <path> --runtime-id <id> --target <id> --reason <text> --updated-at-unix-millis <u64> [--released-until-unix-millis <u64>]\n idunn-provision lifecycle-brake-status --store <path> --runtime-id <id> --target <id> --now-unix-millis <u64>\n idunn-provision create-daemon-health-trust-binding --output <path> --binding-id <id> --daemon <id> --health-contract <id> --source-runtime <id> --signer-public-key-hex <hex> --bound-at-unix-millis <u64> --release-binding-required <true|false>\n idunn-provision add-daemon-health-trust-binding --output <path> --binding-id <id> --daemon <id> --health-contract <id> --source-runtime <id> --signer-public-key-hex <hex> --bound-at-unix-millis <u64> --release-binding-required <true|false>\n idunn-provision require-daemon-health-release-binding --store <path> --binding-id <id> --daemon <id> --health-contract <id> --source-runtime <id> --signer-public-key-hex <hex>\n idunn-provision rotate-daemon-health-trust-signer --output <path> --binding-id <id> --signer-public-key-hex <hex> --bound-at-unix-millis <u64>\n idunn-provision validate-daemon-health-trust-binding --input <path>\n idunn-provision create-provider-projection-trust-anchor --output <path> --trust-anchor-id <id> --runtime-id <id> --idunn-public-anchor <path> --bound-at-unix-millis <u64> --expires-at-unix-millis <u64>\n idunn-provision validate-provider-projection-trust-anchor --input <path> --idunn-public-anchor <path>"
}
#[cfg(test)]
@ -2157,120 +1990,74 @@ mod tests {
}
#[test]
fn brake_operator_can_issue_one_exact_bounded_rollout_grant() -> Result<()> {
fn provision_engage_clear_sequence() -> Result<()> {
let temp = TempDir::new()?;
let private = temp.path().join("operator-private.cc");
let anchor = temp.path().join("operator-public.cc");
let store = temp.path().join("brake.cc");
invoke(&[
"enroll-deployment-brake-operator",
"--private-store",
private.to_str().unwrap(),
])?;
invoke(&[
"export-deployment-brake-operator-anchor",
"--private-store",
private.to_str().unwrap(),
"--public-anchor",
anchor.to_str().unwrap(),
])?;
invoke(&[
"deployment-brake-engage",
"--store",
store.to_str().unwrap(),
"--runtime-id",
"yggdrasil",
"--owner",
"operator/metacrat",
"--reason",
"sleep mode",
"--observed-at-unix-millis",
"100",
])?;
assert_eq!(read_brake(&store)?.status, "engaged");
let me = process_uid();
let engage = |verb: &str, reason: &str| {
invoke(&[
verb,
"--store",
store.to_str().unwrap(),
"--runtime-id",
"yggdrasil",
"--reason",
reason,
])
};
assert_eq!(read_stop(&store, "yggdrasil", me), Stop::Absent);
invoke(&[
"deployment-brake-status",
"--store",
store.to_str().unwrap(),
"--operator-anchor",
anchor.to_str().unwrap(),
"--runtime-id",
"yggdrasil",
])?;
assert!(
engage("deployment-brake-engage", "freeze")?;
let status = || {
invoke(&[
"deployment-brake-status",
"--store",
store.to_str().unwrap(),
"--operator-anchor",
anchor.to_str().unwrap(),
"--runtime-id",
"yggdrasil",
"--release-id",
"commit-4",
"--deployment-id",
"request-4",
"--now-unix-millis",
"150",
])
.is_err()
);
invoke(&[
"deployment-brake-release",
"--store",
store.to_str().unwrap(),
"--private-store",
private.to_str().unwrap(),
"--runtime-id",
"yggdrasil",
"--owner",
"operator/metacrat",
"--reason",
"one rollout",
"--authorization-id",
"auth/r4",
"--release-id",
"commit-4",
"--deployment-id",
"request-4",
"--issued-at-unix-millis",
"200",
"--expires-at-unix-millis",
"800",
])?;
invoke(&[
"deployment-brake-status",
"--store",
store.to_str().unwrap(),
"--operator-anchor",
anchor.to_str().unwrap(),
"--runtime-id",
"yggdrasil",
"--release-id",
"commit-4",
"--deployment-id",
"request-4",
"--now-unix-millis",
"500",
])?;
assert!(
invoke(&[
"deployment-brake-status",
"--store",
store.to_str().unwrap(),
"--operator-anchor",
anchor.to_str().unwrap(),
"--runtime-id",
"yggdrasil",
"--release-id",
"substituted",
"--deployment-id",
"request-4",
"--now-unix-millis",
"500"
])
.is_err()
);
};
assert!(status().is_err(), "an engaged stop must not pass status");
let Stop::Engaged(first) = read_stop(&store, "yggdrasil", me) else {
bail!("engage did not engage")
};
assert_eq!((first.sequence, first.reason.as_str()), (1, "freeze"));
assert!(!first.by.is_empty() && first.at_unix_millis > 0);
engage("deployment-brake-clear", "thawed")?;
status()?;
let Stop::Clear(second) = read_stop(&store, "yggdrasil", me) else {
bail!("clear did not clear")
};
assert_eq!((second.sequence, second.by), (2, first.by));
assert!(second.at_unix_millis >= first.at_unix_millis);
// The author and the time are not arguments, and the retired
// signing arguments are refused.
for stray in ["--owner", "--observed-at-unix-millis", "--private-store"] {
assert!(
invoke(&[
"deployment-brake-engage",
"--store",
store.to_str().unwrap(),
"--runtime-id",
"yggdrasil",
"--reason",
"x",
stray,
"y",
])
.is_err(),
"{stray}"
);
}
for gone in ["deployment-brake-release", "enroll-deployment-brake-operator"] {
assert!(invoke(&[gone]).is_err(), "{gone}");
}
Ok(())
}
@ -2309,7 +2096,6 @@ mod tests {
assert_eq!(engaged.status, "engaged");
assert_eq!(engaged.runtime_id, "idunn-yggdrasil");
assert_eq!(engaged.target, "ghostlight");
assert!(read_brake(&store).is_err());
assert!(
invoke(&[
"lifecycle-brake-status",
@ -2426,57 +2212,4 @@ mod tests {
assert_eq!(std::fs::read(&store)?, released_bytes);
Ok(())
}
#[test]
fn brake_compare_exchange_rejects_stale_transition_snapshot() -> Result<()> {
let temp = TempDir::new()?;
let store_path = temp.path().join("brake.cc");
let base = IdunnDeploymentBrakeRecord {
schema_version: IDUNN_DEPLOYMENT_BRAKE_SCHEMA.into(),
brake_id: IDUNN_DEPLOYMENT_BRAKE_ID.into(),
authority: IDUNN_DEPLOYMENT_BRAKE_AUTHORITY.into(),
runtime_id: "yggdrasil".into(),
status: "engaged".into(),
scope: IDUNN_DEPLOYMENT_BRAKE_SCOPE.into(),
reason: "first".into(),
observed_at_unix_millis: 100,
expires_at_unix_millis: None,
authorization_id: None,
authorization_purpose: None,
authorized_release_id: None,
authorized_deployment_id: None,
authorized_by: None,
authorization_issued_at_unix_millis: None,
authorization_expires_at_unix_millis: None,
signature_algorithm: None,
signature: None,
private_state_exposed: false,
updated_by: "operator/a".into(),
};
replace_brake(&store_path, base.clone(), 100)?;
let stale = SingleFileMessagePackBackingStore::new(&store_path)
.pull_all_read_only_snapshot()?
.remove(0);
let mut changed = base.clone();
changed.reason = "racing writer".into();
changed.observed_at_unix_millis = 101;
replace_brake(&store_path, changed, 101)?;
let candidate = typed_envelope(
IDUNN_DEPLOYMENT_BRAKE_ID,
&base,
IDUNN_DEPLOYMENT_BRAKE_SCHEMA,
102,
)?;
assert!(
!SingleFileMessagePackBackingStore::new(&store_path).compare_exchange(
&[CultCacheExpectedEnvelope {
r#type: IdunnDeploymentBrakeRecord::TYPE.into(),
key: IDUNN_DEPLOYMENT_BRAKE_ID.into(),
current: Some(stale)
}],
&[candidate]
)?
);
Ok(())
}
}

View file

@ -366,7 +366,7 @@ pub(crate) fn show_status(
/// printable ASCII and tab pass; every other code point is a visible
/// `\u{..}` escape and every invalid UTF-8 byte a `\x..` escape. A newline
/// inside a line is escaped too: this function writes the only ones.
fn emit(out: &mut impl std::io::Write, lines: &[Vec<u8>]) -> std::io::Result<()> {
pub(crate) fn emit(out: &mut impl std::io::Write, lines: &[Vec<u8>]) -> std::io::Result<()> {
for line in lines {
out.write_all(escape(line).as_bytes())?;
out.write_all(b"\n")?;
@ -374,7 +374,7 @@ fn emit(out: &mut impl std::io::Write, lines: &[Vec<u8>]) -> std::io::Result<()>
Ok(())
}
fn escape(bytes: &[u8]) -> String {
pub(crate) fn escape(bytes: &[u8]) -> String {
let mut shown = String::with_capacity(bytes.len());
for chunk in bytes.utf8_chunks() {
for character in chunk.valid().chars() {

4086
src/steward_orders.rs Normal file

File diff suppressed because it is too large Load diff