From 7c8677689b1beb659d97c75d9f75d04417e9a8fd Mon Sep 17 00:00:00 2001 From: TudorAndrei Date: Thu, 12 Nov 2026 03:23:03 +0200 Subject: [PATCH 1/3] fix(scheduler): drop a kept cancel when a run ends without a turn A lease renewal that failed before the start was confirmed left a cancel in the adapter that no turn took. When the task was leased again, the adapter cancelled its turn at the start, and the task ended as unknown_result although no agent turn ran. run_execution now calls Agent::forget after the renewal thread stops. ExecutionLease.tla models the kept cancels and the single cancel of the renewal thread, and checks NoSpuriousCancel. Co-Authored-By: Claude Fable 5.2 --- crates/aether/src/agent.rs | 17 ++++ crates/aether/src/agent/codex.rs | 6 ++ crates/aether/src/agent/connected.rs | 31 ++++++++ crates/aether/src/execution.rs | 4 + crates/aether/src/proof/scheduler.rs | 4 + specs/ExecutionLease.cfg | 1 + specs/ExecutionLease.tla | 112 +++++++++++++++++++-------- 7 files changed, 141 insertions(+), 34 deletions(-) diff --git a/crates/aether/src/agent.rs b/crates/aether/src/agent.rs index 0a5c0b9..dc21281 100644 --- a/crates/aether/src/agent.rs +++ b/crates/aether/src/agent.rs @@ -111,6 +111,12 @@ impl EarlyCancels { fn end(&mut self, task_id: &str) { remember(&mut self.ended, task_id); } + + /// Drops a kept cancel for `task_id`: the run that it was for is over, + /// and its turn did not take it. + fn forget(&mut self, task_id: &str) { + self.cancelled.retain(|id| id != task_id); + } } fn remember(ids: &mut VecDeque, task_id: &str) { @@ -140,6 +146,17 @@ mod tests { assert!(!cancels.take("task")); } + #[test] + fn a_forgotten_cancel_does_not_stop_a_later_start() { + let mut cancels = EarlyCancels::default(); + cancels.cancel("task"); + cancels.forget("task"); + assert!(!cancels.take("task")); + // A cancel after it is kept again. + cancels.cancel("task"); + assert!(cancels.take("task")); + } + #[test] fn only_the_latest_cancels_are_kept() { let mut cancels = EarlyCancels::default(); diff --git a/crates/aether/src/agent/codex.rs b/crates/aether/src/agent/codex.rs index bb4c850..7290e8f 100644 --- a/crates/aether/src/agent/codex.rs +++ b/crates/aether/src/agent/codex.rs @@ -583,6 +583,12 @@ impl Agent for CodexAppServer { }); let _ = write_json_line(&active.input, &request); } + + fn forget(&self, task_id: &str) { + if let Ok(mut turns) = self.turns.lock() { + turns.cancels.forget(task_id); + } + } } pub(crate) fn valid_environment_value(value: &str) -> bool { diff --git a/crates/aether/src/agent/connected.rs b/crates/aether/src/agent/connected.rs index 637e6a2..43fede3 100644 --- a/crates/aether/src/agent/connected.rs +++ b/crates/aether/src/agent/connected.rs @@ -319,6 +319,12 @@ impl Agent for ConnectedAgent { } cancels.cancel(task_id); } + + fn forget(&self, task_id: &str) { + if let Ok(mut cancels) = self.shared.cancels.lock() { + cancels.forget(task_id); + } + } } #[cfg(test)] @@ -645,6 +651,31 @@ mod tests { ); } + #[test] + fn a_cancel_for_a_run_that_started_no_turn_does_not_stop_the_next_run() { + let directory = tempfile::tempdir().expect("directory must create"); + let path = crate::data_dir::DataDir::new(directory.path()).agent_socket(); + let agent = ConnectedAgent::listen(&path).expect("listen"); + let mut peer = + Peer::attach(&agent, &path, &json!({"type": "ready", "protocol": 1})); + peer.stream + .set_read_timeout(Some(Duration::from_secs(5))) + .expect("timeout must set"); + // The lease renewal of a run failed before its turn started, and + // the run ended. + agent.cancel("task-1"); + agent.forget("task-1"); + let deadline = + Instant::now().checked_add(Duration::from_secs(5)).expect("deadline"); + let mut runner = agent; + let turn = std::thread::spawn(move || { + runner.start_turn(&turn_ctx("task-1", "hello", deadline)) + }); + assert_eq!(peer.read()["type"], "task"); + peer.write(&json!({"type": "result", "id": "task-1", "text": "answer"})); + assert_eq!(turn.join().expect("turn joins"), Ok("answer".to_owned())); + } + #[test] fn a_cancel_after_the_turn_ended_is_not_kept_for_a_later_start() { let directory = tempfile::tempdir().expect("directory must create"); diff --git a/crates/aether/src/execution.rs b/crates/aether/src/execution.rs index d327810..cd75e87 100644 --- a/crates/aether/src/execution.rs +++ b/crates/aether/src/execution.rs @@ -120,6 +120,10 @@ pub trait Agent { self.start_turn_with_events(ctx, &mut |_| {}) } fn cancel(&self, task_id: &str); + /// The node's run of `task_id` is over. An adapter that keeps a cancel + /// for a turn that has not started drops it here, so that the cancel + /// does not stop a later turn of the same task. + fn forget(&self, _task_id: &str) {} } pub struct Executor

{ process: P, diff --git a/crates/aether/src/proof/scheduler.rs b/crates/aether/src/proof/scheduler.rs index 154b4f9..4e94311 100644 --- a/crates/aether/src/proof/scheduler.rs +++ b/crates/aether/src/proof/scheduler.rs @@ -495,6 +495,10 @@ where let _ = renewal.0.send(()); let _ = renewal.1.join(); slot.deactivate(); + // A renewal that failed before the turn started left a cancel that + // no turn took. The task may be queued again; its next run must not + // be stopped by it. + self.canceller.forget(&task_id); let run = RunReport { result, renewal_failed: renewal_failed.load(Ordering::Acquire), diff --git a/specs/ExecutionLease.cfg b/specs/ExecutionLease.cfg index 6a675ea..d500ab5 100644 --- a/specs/ExecutionLease.cfg +++ b/specs/ExecutionLease.cfg @@ -10,5 +10,6 @@ INVARIANTS LeaseIffActive AtMostOneStart TurnMatchesState + NoSpuriousCancel PROPERTIES CancelReachesTurn diff --git a/specs/ExecutionLease.tla b/specs/ExecutionLease.tla index 66327ea..7558222 100644 --- a/specs/ExecutionLease.tla +++ b/specs/ExecutionLease.tla @@ -7,13 +7,17 @@ (* `mark_succeeded`, `mark_failed`, `mark_unknown_result`, *) (* `mark_rejected`, `cancel`, `requeue_leased`, *) (* `recover_expired_leases`). *) -(* Node side: `SchedulerContext` in crates/aether/src/proof.rs *) +(* Node side: `SchedulerContext` in crates/aether/src/proof/scheduler.rs *) (* (`prepare_execution`, `prepare_leased`, `run_execution` with its *) -(* lease-renewal thread and `on_confirmed_start`, `maintain`), and *) -(* `ProofNode::cancel` / `ProofNode::shutdown`. *) -(* Agent side: `Agent::start_turn` and `Agent::cancel` in *) -(* crates/aether/src/agent/{codex,connected}.rs. Both adapters drop a *) -(* cancel for a turn that they did not register yet. *) +(* lease-renewal thread and `on_confirmed_start`, `settlement`, *) +(* `maintain`), and `ProofNode::cancel` / `ProofNode::shutdown` in *) +(* crates/aether/src/proof/mod.rs. *) +(* Agent side: `Agent::start_turn_with_events` and `Agent::cancel` in *) +(* crates/aether/src/agent/{codex,connected}.rs, and `EarlyCancels` in *) +(* crates/aether/src/agent.rs. An adapter keeps a cancel for a turn that *) +(* it did not register yet, and cancels that turn when it registers it. *) +(* It drops a cancel for a turn that ended, and `Agent::forget` drops a *) +(* kept cancel when the execution ends. *) (* *) (* One node process runs one scheduler, so at most one execution is *) (* active. The process can stop (crash or exit) and start again. Each *) @@ -22,7 +26,8 @@ (* *) (* Abstracted away: task input and output, events, retention, the order *) (* in which `lease_next` picks a queued task, queue limits, and the *) -(* `event_error` path of `run_execution`. *) +(* `event_error` path of `run_execution`, and the bound of 256 task IDs *) +(* in each `EarlyCancels` list. *) (***************************************************************************) EXTENDS Naturals, FiniteSets @@ -62,7 +67,8 @@ VARIABLES nextExec, \* the next fresh execution ID grant, \* whether policy and access groups still allow the task w, \* the one execution thread (`run_execution`) - turn, \* the agent turn that the execution started + turn, \* the agent turn that the execution started, and the + \* adapter's `EarlyCancels` signals, \* tasks with an `Agent::cancel` call that is not made yet shutdown, \* the `shutdown` flag restarts, \* how often the process stopped @@ -73,8 +79,16 @@ vars == < "idle", task |-> CHOOSE t \in Tasks : TRUE, exec |-> 0, confirmed |-> FALSE, renewFailed |-> FALSE, outcome |-> "none"] +\* `early` and `ended` are the two lists of `EarlyCancels`. `spurious` is a +\* ghost: the adapter cancelled a turn at its start with a cancel that an +\* earlier execution of the task left behind (see NoSpuriousCancel). NoTurn == [live |-> FALSE, registered |-> FALSE, interrupted |-> FALSE, - task |-> CHOOSE t \in Tasks : TRUE] + task |-> CHOOSE t \in Tasks : TRUE, early |-> {}, ended |-> {}, + spurious |-> FALSE] + +\* The turn is over: `NoTurn`, with the adapter's lists kept. +TurnOver(early, ended, spurious) == + [NoTurn EXCEPT !.early = early, !.ended = ended, !.spurious = spurious] TypeOK == /\ state \in [Tasks -> States] @@ -85,7 +99,8 @@ TypeOK == /\ w \in [phase : Phases, task : Tasks, exec : 0..MaxExec, confirmed : BOOLEAN, renewFailed : BOOLEAN, outcome : Outcomes] /\ turn \in [live : BOOLEAN, registered : BOOLEAN, interrupted : BOOLEAN, - task : Tasks] + task : Tasks, early : SUBSET Tasks, ended : SUBSET Tasks, + spurious : BOOLEAN] /\ signals \subseteq Tasks /\ shutdown \in BOOLEAN /\ restarts \in 0..MaxRestarts @@ -131,10 +146,14 @@ Requeue(t) == Apply(r) == state' = r.st /\ lease' = r.ls -\* `Agent::cancel`: it reaches only a turn that the adapter registered. +\* `Agent::cancel`: it interrupts a turn that the adapter registered. +\* Otherwise `EarlyCancels::cancel` keeps it, unless the turn of the task +\* already ended. Interrupt(t) == turn' = IF turn.live /\ turn.registered /\ turn.task = t - THEN [turn EXCEPT !.interrupted = TRUE] ELSE turn + THEN [turn EXCEPT !.interrupted = TRUE] + ELSE IF t \in turn.ended THEN turn + ELSE [turn EXCEPT !.early = @ \cup {t}] ----------------------------------------------------------------------------- (* The environment. *) @@ -265,7 +284,8 @@ ConfirmRunning == /\ w.phase = "confirm" /\ LET t == w.task IN CASE shutdown -> - UNCHANGED <> + \* `requeue_leased`, and `settled_at_start`. + Apply(Requeue(t)) /\ w' = [w EXCEPT !.phase = "finish", !.outcome = "cancelled"] [] ~grant[t] -> Apply(MarkRejected(t, w.exec)) @@ -288,20 +308,28 @@ ConfirmCheck == /\ UNCHANGED <> [] state[t] \in {"leased", "running"} -> /\ w' = [w EXCEPT !.phase = "starting", !.confirmed = TRUE] - /\ turn' = [live |-> TRUE, registered |-> FALSE, - interrupted |-> FALSE, task |-> t] + /\ turn' = [turn EXCEPT !.live = TRUE, !.registered = FALSE, + !.interrupted = FALSE, !.task = t] /\ starts' = [starts EXCEPT ![t] = @ + 1] [] OTHER -> w' = [w EXCEPT !.phase = "finish", !.outcome = "err"] /\ UNCHANGED <> /\ UNCHANGED <> -\* The adapter registers the turn (Codex `active_turns` after `turn/start`; -\* the connected agent's `pending` map). From now on `Agent::cancel` works. +\* The adapter registers the turn (Codex `turns.active` after `turn/start`; +\* the connected agent's `pending` map). `EarlyCancels::take`: a cancel +\* that came first ends the turn here as cancelled. Otherwise +\* `Agent::cancel` interrupts the turn from now on. Register == /\ w.phase = "starting" - /\ w' = [w EXCEPT !.phase = "turn"] - /\ turn' = [turn EXCEPT !.registered = TRUE] + /\ LET t == w.task IN + IF t \in turn.early + THEN /\ w' = [w EXCEPT !.phase = "finish", !.outcome = "cancelled"] + /\ turn' = TurnOver(turn.early \ {t}, turn.ended \cup {t}, + turn.spurious \/ (state[t] = "running" + /\ ~w.renewFailed /\ ~shutdown)) + ELSE /\ w' = [w EXCEPT !.phase = "turn"] + /\ turn' = [turn EXCEPT !.registered = TRUE] /\ UNCHANGED <> @@ -309,7 +337,7 @@ Register == StartFails == /\ w.phase = "starting" /\ w' = [w EXCEPT !.phase = "finish", !.outcome = "err"] - /\ turn' = NoTurn + /\ turn' = TurnOver(turn.early, turn.ended \cup {w.task}, turn.spurious) /\ UNCHANGED <> @@ -318,20 +346,19 @@ TurnEnds == /\ w.phase = "turn" /\ \E o \in IF turn.interrupted THEN {"cancelled"} ELSE {"ok", "err"} : w' = [w EXCEPT !.phase = "finish", !.outcome = o] - /\ turn' = NoTurn + /\ turn' = TurnOver(turn.early, turn.ended \cup {w.task}, turn.spurious) /\ UNCHANGED <> \* The renewal thread of `run_execution` -> `renew_lease`. On failure it -\* calls `canceller.cancel`, and then calls it again at each interval until -\* the execution stops the thread: an adapter drops a cancel for a turn -\* that it has not registered yet. A cancel deletes the lease, so it also -\* makes the renewal fail. +\* calls `canceller.cancel` once and stops. A cancel deletes the lease, so +\* it also makes the renewal fail: this is the cancel's second signal. Renew == /\ w.phase \in {"confirm", "confirm_check", "starting", "turn"} /\ ~shutdown + /\ ~w.renewFailed /\ LET t == w.task IN - IF ~w.renewFailed /\ LeaseIs(t, w.exec) /\ lease[t].exp > now + IF LeaseIs(t, w.exec) /\ lease[t].exp > now THEN /\ lease' = [lease EXCEPT ![t].exp = now + TTL] /\ UNCHANGED <> ELSE /\ w' = [w EXCEPT !.renewFailed = TRUE] @@ -348,6 +375,10 @@ ShutdownSignal == /\ UNCHANGED <> +\* `Agent::forget`, which `run_execution` calls after the executor returns +\* and the renewal thread stops: the adapter drops a kept cancel. +Forget(t) == turn' = [turn EXCEPT !.early = @ \ {t}] + \* `run_execution` after the executor returns and the renewal thread stops. Finish == /\ w.phase = "finish" @@ -356,12 +387,14 @@ Finish == IN IF w.renewFailed THEN /\ Apply(IF w.outcome = "ok" THEN MarkEnd(t, e, "succeeded") ELSE Same) /\ w' = [w EXCEPT !.phase = "finish_renewal"] + /\ Forget(t) ELSE /\ Apply(CASE w.outcome = "ok" -> MarkEnd(t, e, "succeeded") [] w.outcome = "cancelled" -> Same [] OTHER -> IF w.confirmed THEN MarkEnd(t, e, "unknown_result") ELSE MarkEnd(t, e, "failed")) /\ w' = IdleWorker - /\ UNCHANGED <> + /\ Forget(t) + /\ UNCHANGED <> \* `run_execution`, the renewal-failed branch after the late result. FinishRenewal == @@ -383,9 +416,11 @@ Next == Spec == Init /\ [][Next]_vars -\* The renewal thread and the shutdown loop run while the execution runs. -\* The turn itself gets no fairness: an agent may run until `max_seconds`. +\* The renewal thread and the shutdown loop run while the execution runs, +\* and each `canceller.cancel` that follows a store call is made. The turn +\* itself gets no fairness: an agent may run until `max_seconds`. FairSpec == Spec /\ WF_vars(Renew) /\ WF_vars(ShutdownSignal) + /\ \A t \in Tasks : WF_vars(Signal(t)) ----------------------------------------------------------------------------- (* Properties. *) @@ -407,14 +442,23 @@ TurnMatchesState == \* Every cancel reaches the turn: a registered turn whose task is cancelled \* or unknown_result is interrupted, or it ends. \* -\* The first `Agent::cancel` can come before the adapter registers the turn -\* (Codex inserts it into `active_turns` only after `turn/start` answers; -\* the connected agent inserts into `pending` in `start_turn_with_events`), -\* and then it does nothing. The cancel deleted the lease, so the renewal -\* fails and says the cancel again at each interval until the turn stops. +\* An `Agent::cancel` can come before the adapter registers the turn +\* (Codex inserts it into `turns.active` only after `turn/start` answers; +\* the connected agent inserts into `pending` in `run_turn`). The adapter +\* keeps it, and the turn ends as cancelled when it registers. No signal +\* is repeated: the cancel itself and one renewal failure are all. CancelReachesTurn == [](turn.live /\ turn.registered /\ state[turn.task] \in {"cancelled", "unknown_result"} => <>(turn.interrupted \/ ~turn.live)) +\* The adapter cancels a turn at its start only for a cancel, a lost lease +\* or a shutdown of this execution. Before `run_execution` called +\* `Agent::forget`, this failed: a renewal that failed before +\* `on_confirmed_start` left a kept cancel, recovery gave the task back to +\* the queue, and the kept cancel ended the turn of the next execution. +\* `settlement` writes nothing for `ExecutionError::Cancelled`, so the task +\* stayed `running` with no turn and ended as `unknown_result`. +NoSpuriousCancel == ~turn.spurious + ============================================================================= From c35f4ed04b1f81d65a1ebc2e05f3f4328a4a38c3 Mon Sep 17 00:00:00 2001 From: TudorAndrei Date: Thu, 12 Nov 2026 03:23:03 +0200 Subject: [PATCH 2/3] test(specs): add TLA+ models for invites, admission, paging, agents, rosters and admin changes DirectInvite, Admission, EventPaging, ConnectedAgent, ManagedRoster and PendingChange. specs/README.md lists what each model checks and each property that TLC finds false, with the reason. Co-Authored-By: Claude Fable 5.2 --- specs/Admission.cfg | 35 +++ specs/Admission.tla | 426 +++++++++++++++++++++++++++ specs/ConnectedAgent.cfg | 30 ++ specs/ConnectedAgent.tla | 596 +++++++++++++++++++++++++++++++++++++ specs/DirectInvite.cfg | 26 ++ specs/DirectInvite.tla | 352 ++++++++++++++++++++++ specs/EventPaging.cfg | 29 ++ specs/EventPaging.tla | 388 ++++++++++++++++++++++++ specs/ManagedRoster.cfg | 34 +++ specs/ManagedRoster.tla | 602 ++++++++++++++++++++++++++++++++++++++ specs/PendingChange.cfg | 28 ++ specs/PendingChange.tla | 617 +++++++++++++++++++++++++++++++++++++++ specs/README.md | 36 ++- 13 files changed, 3196 insertions(+), 3 deletions(-) create mode 100644 specs/Admission.cfg create mode 100644 specs/Admission.tla create mode 100644 specs/ConnectedAgent.cfg create mode 100644 specs/ConnectedAgent.tla create mode 100644 specs/DirectInvite.cfg create mode 100644 specs/DirectInvite.tla create mode 100644 specs/EventPaging.cfg create mode 100644 specs/EventPaging.tla create mode 100644 specs/ManagedRoster.cfg create mode 100644 specs/ManagedRoster.tla create mode 100644 specs/PendingChange.cfg create mode 100644 specs/PendingChange.tla diff --git a/specs/Admission.cfg b/specs/Admission.cfg new file mode 100644 index 0000000..3ab7f1a --- /dev/null +++ b/specs/Admission.cfg @@ -0,0 +1,35 @@ +\* Admission: one wire request on the host. See Admission.tla. +\* Two endpoints, and the owner can give the name `alice` to both, so that +\* the shared per-peer limit is in the model. NoTaskIdClash, NoSharedQuota +\* and NoReplayBeforeExpiry are false; the spec explains each one. +CONSTANTS + Eps = {e1, e2} + Names = {alice, mallory} + HonestName = alice + HonestEp = e1 + TaskIds = {t1, t2} + Keys = {k1, k2} + Data = {d1, d2} + Nonces = {n1, n2} + ReplayLimit = 1 + Global = 2 + PerPeer = 1 + DirectScope = direct + OtherScope = other + +SPECIFICATION Spec + +INVARIANTS + TypeOK + OwnerIsAuthenticated + AdmittedWasCovered + RowOfInvitedPerson + OneTaskPerKey + QueueWithinLimits + OnlyGoodFramesChange + NoForeignRead + OnlyOwnerCancels + +PROPERTIES + RowsAreStable + HonestGetsIn diff --git a/specs/Admission.tla b/specs/Admission.tla new file mode 100644 index 0000000..d5fbb3e --- /dev/null +++ b/specs/Admission.tla @@ -0,0 +1,426 @@ +----------------------------- MODULE Admission ----------------------------- +(***************************************************************************) +(* Admission: the host side of one wire request, from the endpoint that *) +(* QUIC authenticated to a row in the `tasks` table. *) +(* *) +(* Code that this spec models: *) +(* crates/aether/src/transport/server.rs serve_connected (the endpoint *) +(* is `connection.remote_id()`, not a field of the frame) *) +(* crates/aether/src/transport/wire.rs A2aRequest::policy_data *) +(* crates/aether/src/a2a_transport.rs A2aTransport::handle, cancel *) +(* crates/aether/src/proof/admission.rs ProofNode::admit, check_group, *) +(* enqueue *) +(* crates/aether/src/proof/mod.rs cancel_from, revoke_grant, *) +(* apply_grant_inner *) +(* crates/aether-core/src/lib.rs PolicyEngine::admit, *) +(* match_grant *) +(* crates/aether/src/identity.rs SignedClaims::verify, *) +(* verify_grant *) +(* crates/aether-store/src/tasks.rs admit_with_replay, *) +(* accept_replay_key, admit, *) +(* count, cancel_if_owned *) +(* crates/aether-store/src/access_groups.rs access_group_allows *) +(* *) +(* Every endpoint is an attacker here: it can send any frame under its own *) +(* authenticated endpoint. A frame can name another endpoint, another *) +(* agent name, the claim of another person, and the task ID, idempotency *) +(* key and nonce of any other frame, also of its own old frames. `Honest` *) +(* is one of the people; some properties look at it only. *) +(* *) +(* A person is a pair <>. `access[p]` is the signed access *) +(* of the person: the claim that the caller keeps and the grant in the *) +(* live policy. Both are signed in one call (`sign_access`) with one *) +(* expiry. Signatures are perfect: a claim verifies only when the host *) +(* signed it. *) +(* *) +(* Each request is one atomic step. `enqueue` holds `dispatch_serial`, and *) +(* `admit_with_replay` is one IMMEDIATE transaction. The policy check and *) +(* the group check come before it without a lock; a revocation between *) +(* them and the transaction is the same as a revocation after the step. *) +(* *) +(* Abstracted away: frame syntax, the A2A task parts, the rate limiter and *) +(* the connection limit, the shutdown flag, the clock (an expiry is an *) +(* action), event pages (see EventPaging), the scheduler (a queued task *) +(* ends in one step; see ExecutionLease), changes of the queue limits, and *) +(* the managed and pact scopes. All requests are in the direct scope: a *) +(* frame for another scope has no claim that fits, and `policy_data` *) +(* refuses it. Only a cancel frame carries a scope here. The request ID *) +(* (`tasks.request_id`, also UNIQUE) is the task ID, as in `direct.rs`. *) +(* The replay table has one part for each endpoint and scope; with one *) +(* scope it has one part for each endpoint. All replay entries have the *) +(* same lifetime (REPLAY_TTL), so the oldest entry expires first, and an *) +(* expired entry is the same as no entry: `accept_replay_key` deletes the *) +(* expired entries before it reads. *) +(***************************************************************************) +EXTENDS Naturals, Sequences, FiniteSets + +CONSTANTS + Eps, \* caller endpoints (QUIC keys) + Names, \* agent names that the owner gives to callers + HonestName, \* the name of the person that the last properties look at + HonestEp, \* and the endpoint of that person + TaskIds, \* task IDs (UUIDs that the caller chooses) + Keys, \* idempotency keys + Data, \* the rest of a request: its fingerprint + Nonces, \* `exchangeId:requestNonce` values + ReplayLimit, \* REPLAY_LIMIT + Global, \* QueueLimits.global + PerPeer, \* QueueLimits.per_peer + DirectScope, \* the scope of every task + OtherScope \* another scope of the node + +AllPeople == Names \X Eps +Honest == <> +\* The <> pairs that the owner can invite. The owner knows +\* the honest endpoint under one name only. It can give any name to another +\* endpoint, also the name of the honest person. +People == {p \in AllPeople : p[2] = HonestEp => p[1] = HonestName} +Scopes == {DirectScope, OtherScope} + +\* The signed access of a person. "revoked": the owner removed the grant +\* from the live policy; the caller still has a claim that verifies. +\* A claim and a grant that passed `expires_at` are the same as none: the +\* claim does not verify, and `match_grant` skips the grant. +AccessStates == {"none", "live", "revoked"} + +\* "ended": succeeded, failed, rejected or cancelled (see ExecutionLease). +TaskStates == {"queued", "ended"} +NoTask == [owner |-> "none"] + +\* A `tasks` row. `auth` and `covered` are ghosts: the authenticated +\* endpoint of the frame that made the row, and whether that endpoint had +\* a live grant and a group membership under the name of the row then. +TaskRow == [owner : Eps, agent : Names, key : Keys, data : Data, + state : TaskStates, auth : Eps, covered : BOOLEAN] + +\* A request frame. `cep` and `agent` are the caller endpoint and name in +\* the authorization. `claim` is the person that the claim names; a claim +\* that the host did not sign is a claim of a person without access. +Frames == [cep : Eps, agent : Names, claim : AllPeople, id : TaskIds, + key : Keys, data : Data, nonce : Nonces] + +VARIABLES + access, \* the claim and the grant of each person + members, \* access_group_members, of any group + tasks, \* the `tasks` table, by task ID + replay, \* replay_entries of each endpoint, oldest first + wrongAdmit, \* ghost: a frame that the host must refuse changed something + leaked, \* ghost: an answer showed a task of another endpoint + badCancel \* ghost: a cancel changed a task of another endpoint or scope + +vars == <> + +Range(s) == {s[i] : i \in 1..Len(s)} + +TypeOK == + /\ access \in [AllPeople -> AccessStates] + /\ members \subseteq People + /\ tasks \in [TaskIds -> TaskRow \cup {NoTask}] + /\ replay \in [Eps -> Seq(Nonces)] + /\ \A e \in Eps : Len(replay[e]) <= ReplayLimit + /\ wrongAdmit \in BOOLEAN + /\ leaked \in BOOLEAN + /\ badCancel \in BOOLEAN + +Init == + /\ access = [p \in AllPeople |-> "none"] + /\ members = {} + /\ tasks = [id \in TaskIds |-> NoTask] + /\ replay = [e \in Eps |-> <<>>] + /\ wrongAdmit = FALSE + /\ leaked = FALSE + /\ badCancel = FALSE + +Rows == {id \in TaskIds : tasks[id] # NoTask} +Queued == {id \in Rows : tasks[id].state = "queued"} +\* `count(tx, Some(peer))`: the queued tasks of one agent NAME. +QueuedOf(name) == {id \in Queued : tasks[id].agent = name} + +----------------------------------------------------------------------------- +(* The owner and the clock. *) + +\* admin_ui/host.rs sign_invite -> `sign_access`, then `apply_grant_inner` +\* -> `replace_grant`: a new claim and a new grant for the person. +Grant(p) == + /\ p \in People + /\ access[p] # "live" + /\ access' = [access EXCEPT ![p] = "live"] + /\ UNCHANGED <> + +\* Administration::revoke_inner -> ProofNode::revoke_grant -> +\* `remove_grant`. The claim that the caller keeps is not changed. +Revoke(p) == + /\ access[p] = "live" + /\ access' = [access EXCEPT ![p] = "revoked"] + /\ UNCHANGED <> + +\* Time passes `expires_at` of the claim and of the grant. +Expire(p) == + /\ access[p] \in {"live", "revoked"} + /\ access' = [access EXCEPT ![p] = "none"] + /\ UNCHANGED <> + +\* `add_access_group_member` (access_groups.rs `join_and_apply`, the +\* groups page) and `remove_access_group_member`. +Join(p) == + /\ p \in People \ members + /\ members' = members \cup {p} + /\ UNCHANGED <> + +Leave(p) == + /\ p \in members + /\ members' = members \ {p} + /\ UNCHANGED <> + +\* REPLAY_TTL passes for the oldest entry of an endpoint. +ReplayExpires(e) == + /\ replay[e] # <<>> + /\ replay' = [replay EXCEPT ![e] = Tail(@)] + /\ UNCHANGED <> + +\* The scheduler takes a task from the queue and ends it (ExecutionLease). +HostRuns(id) == + /\ id \in Queued + /\ tasks' = [tasks EXCEPT ![id].state = "ended"] + /\ UNCHANGED <> + +----------------------------------------------------------------------------- +(* One request frame. *) + +\* `PolicyEngine::admit` for a frame that `ep` sent, in the order of the +\* code: the endpoint of the request, the subject of the claim, the claim +\* expiry and `SignedClaims::verify`, then `match_grant`, which wants a +\* grant in the live policy for the name and the endpoint of the request. +PolicyAdmits(ep, f) == + /\ f.cep = ep \* else EndpointMismatch + /\ f.claim = <> \* else ScopeMismatch + /\ access[f.claim] \in {"live", "revoked"} \* else ClaimExpired, ClaimDenied + /\ access[<>] = "live" \* else LocalGrantMissing, -Expired + +\* `check_group` -> `access_group_allows(agent, endpoint)`. +GroupAllows(ep, f) == <> \in members + +\* Ghost: what a frame needs before it may change anything, said without +\* the fields that only the frame claims: the AUTHENTICATED endpoint has a +\* grant in the live policy and a group membership under the name of the +\* frame, and the nonce is not in the replay table of that endpoint. +Covered(name, ep) == access[<>] = "live" /\ <> \in members +MayChange(ep, f) == + /\ f.cep = ep + /\ Covered(f.agent, ep) + /\ f.nonce \notin Range(replay[ep]) + +\* `accept_replay_key`: keep the nonce; at the limit the oldest entry goes. +Keep(s, n) == Append(IF Len(s) >= ReplayLimit THEN Tail(s) ELSE s, n) + +\* The row of `ep` with this idempotency key +\* (`WHERE caller_endpoint_id=?1 AND idempotency_key=?2`). +KeyRows(ep, key) == {id \in Rows : tasks[id].owner = ep /\ tasks[id].key = key} + +\* `stored == *request && fingerprint == input.request_fingerprint`. +SameRequest(id, f) == + /\ id = f.id + /\ tasks[id].agent = f.agent + /\ tasks[id].data = f.data + +\* `admit`: the queue is full for this frame (StoreError::Overloaded). +Full(f) == + \/ Cardinality(Queued) >= Global + \/ Cardinality(QueuedOf(f.agent)) >= PerPeer + +\* `A2aTransport::handle` -> `ProofNode::admit` -> `enqueue` -> +\* `admit_with_replay`, and then `task_progress` of the admitted task. A +\* frame that the policy, the group or the replay table refuses changes +\* nothing, so it is no step here. An error of the transaction (a changed +\* request under a known key, a full queue, a failed INSERT) rolls back the +\* replay entry too, so it is no step either. +Request(ep, f) == + /\ PolicyAdmits(ep, f) + /\ GroupAllows(ep, f) + /\ f.nonce \notin Range(replay[ep]) \* else DuplicateConflict + /\ replay' = [replay EXCEPT ![ep] = Keep(@, f.nonce)] + /\ IF KeyRows(ep, f.key) # {} + THEN \* TaskAdmission::Existing; else DuplicateConflict. + \E id \in KeyRows(ep, f.key) : + /\ SameRequest(id, f) + /\ leaked' = (leaked \/ tasks[id].owner # ep) + /\ wrongAdmit' = (wrongAdmit \/ ~MayChange(ep, f) + \/ id # f.id \/ tasks[id].data # f.data) + /\ UNCHANGED tasks + ELSE \* TaskAdmission::Accepted; else Overloaded, or the INSERT + \* fails: `tasks.id` is the PRIMARY KEY of the whole table. + /\ ~Full(f) + /\ tasks[f.id] = NoTask + /\ tasks' = [tasks EXCEPT ![f.id] = + [owner |-> ep, agent |-> f.agent, key |-> f.key, + data |-> f.data, state |-> "queued", auth |-> ep, + covered |-> Covered(f.agent, ep)]] + /\ wrongAdmit' = (wrongAdmit \/ ~MayChange(ep, f)) + /\ UNCHANGED leaked + /\ UNCHANGED <> + +\* `A2aTransport::cancel` -> `ProofNode::cancel_from` -> `cancel_if_owned` +\* -> `cancel`. It needs no claim and no grant: the authenticated endpoint +\* and the scope must be those of the row. A task that ended stays as it +\* is (`TaskState::allows`), and a cancelled task stays cancelled. +Cancel(ep, id, scope) == + /\ id \in Rows + /\ tasks[id].owner = ep /\ scope = DirectScope \* else Unauthorized + /\ tasks[id].state = "queued" + /\ tasks' = [tasks EXCEPT ![id].state = "ended"] + /\ badCancel' = (badCancel \/ tasks[id].auth # ep \/ scope # DirectScope) + /\ UNCHANGED <> + +\* A first frame of the honest caller: its own name, endpoint and claim, a +\* key that it did not use, and a task ID that no row has. +HonestFrame(f) == + /\ f.cep = HonestEp /\ f.agent = HonestName /\ f.claim = Honest + /\ KeyRows(HonestEp, f.key) = {} + /\ tasks[f.id] = NoTask + +\* The host accepts a first frame of the honest caller. +HonestAdmitted == + \E id \in TaskIds, key \in Keys, data \in Data, nonce \in Nonces : + LET f == [cep |-> HonestEp, agent |-> HonestName, claim |-> Honest, + id |-> id, key |-> key, data |-> data, nonce |-> nonce] + IN HonestFrame(f) /\ Request(HonestEp, f) + +Next == + \/ \E p \in People : Grant(p) \/ Revoke(p) \/ Expire(p) \/ Join(p) \/ Leave(p) + \/ \E e \in Eps : ReplayExpires(e) + \/ \E id \in TaskIds : HostRuns(id) + \* Any endpoint sends any frame. The policy reads only the first three + \* fields, so they come first: TLC then drops a refused frame early. + \/ \E e \in Eps, cep \in Eps, agent \in Names, claim \in AllPeople : + /\ PolicyAdmits(e, [cep |-> cep, agent |-> agent, claim |-> claim]) + /\ \E id \in TaskIds, key \in Keys, data \in Data, nonce \in Nonces : + Request(e, [cep |-> cep, agent |-> agent, claim |-> claim, + id |-> id, key |-> key, data |-> data, + nonce |-> nonce]) + \/ \E e \in Eps, id \in TaskIds, s \in Scopes : Cancel(e, id, s) + +\* The scheduler keeps working, and the honest caller sends its task again +\* (see Outbox) with a new nonce for as long as it must. +Fairness == + /\ \A id \in TaskIds : WF_vars(HostRuns(id)) + /\ SF_vars(HonestAdmitted) + +Spec == Init /\ [][Next]_vars /\ Fairness + +----------------------------------------------------------------------------- +(* Safety. *) + +\* The owner of a row is the endpoint that QUIC authenticated for the frame +\* that made it, whatever endpoint, name or claim the frame carried. +OwnerIsAuthenticated == + \A id \in Rows : tasks[id].owner = tasks[id].auth + +\* When a row was made, its endpoint had a grant in the live policy that +\* had not expired, and a group membership, both under the name of the row. +AdmittedWasCovered == + \A id \in Rows : tasks[id].covered + +\* A row names only a person that the owner invited. +RowOfInvitedPerson == + \A id \in Rows : <> \in People + +\* One task for an endpoint and an idempotency key. +OneTaskPerKey == + \A a, b \in Rows : + tasks[a].owner = tasks[b].owner /\ tasks[a].key = tasks[b].key => a = b + +\* The queue holds at most `global` tasks, and at most `per_peer` tasks of +\* one agent name. +QueueWithinLimits == + /\ Cardinality(Queued) <= Global + /\ \A n \in Names : Cardinality(QueuedOf(n)) <= PerPeer + +\* A frame changes the tasks or the replay table only when the endpoint +\* that sent it has a live grant and a membership and the nonce is new. A +\* frame that gets its task back (`Existing`) has the task ID and the data +\* of that task: the same key with changed data returns nothing. +OnlyGoodFramesChange == ~wrongAdmit + +\* An answer never shows the task of another endpoint: `handle` reads the +\* task ID that the admission returned, not the one in the frame. +NoForeignRead == ~leaked + +\* Only the owner endpoint, in the scope of the task, cancels a task. +OnlyOwnerCancels == ~badCancel + +\* A row keeps its owner, name, key and data for ever: the same key with +\* changed data never changes the task, and no frame takes a task over. +\* Only the state changes, and an ended task does not change. +RowsAreStable == + [][\A id \in Rows : + /\ tasks'[id] # NoTask + /\ [tasks'[id] EXCEPT !.state = "queued"] = [tasks[id] EXCEPT !.state = "queued"] + /\ tasks[id].state # "queued" => tasks'[id] = tasks[id]]_vars + +(***************************************************************************) +(* Properties that TLC finds false. They are not in Admission.cfg; each *) +(* comment gives the counterexample. *) +(***************************************************************************) + +\* A frame of `ep` that has everything it needs (access, a new nonce, a new +\* key, room in the queue) and still fails: another endpoint has a row with +\* its task ID. +ClashRefused(ep, f) == + /\ PolicyAdmits(ep, f) /\ GroupAllows(ep, f) + /\ f.nonce \notin Range(replay[ep]) + /\ KeyRows(ep, f.key) = {} + /\ ~Full(f) + /\ tasks[f.id] # NoTask /\ tasks[f.id].owner # ep + +\* FALSE: a caller is never refused because of a task ID that another +\* endpoint used. `tasks.id` is the PRIMARY KEY of the table (and +\* `request_id` is UNIQUE), not unique for each endpoint, and `admit` looks +\* only for a row of the same endpoint before the INSERT. Trace: the owner +\* invites two people; the second person sends a task with the ID t1 and +\* the host ends it; the first person sends its own task with the ID t1; +\* the INSERT fails with a constraint error, the caller gets "task store +\* unavailable", and every resend fails the same way, because rows stay. +\* The second person must know the ID. It is a random UUID that only the +\* first person and the host see, so the IDs keep the two apart, not the +\* table. +NoTaskIdClash == \A ep \in Eps, f \in Frames : ~ClashRefused(ep, f) + +\* FALSE: the honest caller is refused as overloaded only for its own +\* queued tasks or a full global queue. `count` uses `caller_agent_id` for +\* the per-peer limit, so two endpoints that the owner invited under one +\* name share one limit. Trace: the owner invites <> and +\* <>; e2 fills the per-peer limit; the first task of e1 gets +\* "overloaded". A caller cannot choose its name: the claim and the grant +\* carry the name that the owner gave to that endpoint (PolicyAdmits). +NoSharedQuota == + ~ /\ Covered(HonestName, HonestEp) + /\ Cardinality(Queued) < Global + /\ Cardinality({id \in Queued : tasks[id].owner = HonestEp}) < PerPeer + /\ Cardinality(QueuedOf(HonestName)) >= PerPeer + +\* FALSE: a nonce stays in the replay table until REPLAY_TTL passes. At +\* REPLAY_LIMIT entries `accept_replay_key` removes the oldest entry, so an +\* endpoint that sends REPLAY_LIMIT more frames can send its own old frame +\* again before the time passes. The frame then finds its task by the +\* idempotency key (`Existing`) and makes no second task: OneTaskPerKey. +\* (Only ReplayExpires makes the table of an endpoint shorter.) +NoReplayBeforeExpiry == + [][\A e \in Eps : + Len(replay'[e]) >= Len(replay[e]) + => Range(replay[e]) \subseteq Range(replay'[e])]_vars + +----------------------------------------------------------------------------- +(* Liveness. *) + +HonestCovered == Covered(HonestName, HonestEp) +HonestHasTask == \E id \in Rows : tasks[id].owner = HonestEp +\* Every task ID has a row, so this small model has no ID left. +IdsUsedUp == Rows = TaskIds + +\* An honest caller that keeps its grant and its group membership gets a +\* task in, whatever the other endpoints send: the queue gets room again, +\* and no frame of another endpoint uses up its nonces or its keys. +HonestGetsIn == + <>[]HonestCovered => <>(HonestHasTask \/ IdsUsedUp) + +============================================================================= diff --git a/specs/ConnectedAgent.cfg b/specs/ConnectedAgent.cfg new file mode 100644 index 0000000..840a506 --- /dev/null +++ b/specs/ConnectedAgent.cfg @@ -0,0 +1,30 @@ +\* ConnectedAgent: the agent socket. See ConnectedAgent.tla. +\* One task ID that gets two turns, and two connections (the second +\* replaces the first, or attaches after it closed). Two tasks with one turn +\* each pass the safety properties too, but that run takes 8 minutes. +\* NoStaleCancel, NoLostCancel, TaskOnlyToAttached, AnswerWhileAttached, +\* AnswerAfterSent and NoOrphanWait are false; the spec explains each one. +CONSTANTS + Tasks = {t1} + MaxConns = 2 + MaxTurns = 2 + +SPECIFICATION Spec + +INVARIANTS + TypeOK + PendingIsOpenTurn + NoProtocolError + AnswerFromHolder + TurnEndsOnce + HonestNoOrphanWait + +PROPERTIES + NoAgentNoTask + EarlyCancelHonored + LateCancelDropped + CancelToldToHolder + HonestAnswerAfterSent + TurnEnds + LostAgentFailsTurn + CancelStopsHonestTurn diff --git a/specs/ConnectedAgent.tla b/specs/ConnectedAgent.tla new file mode 100644 index 0000000..a874f15 --- /dev/null +++ b/specs/ConnectedAgent.tla @@ -0,0 +1,596 @@ +--------------------------- MODULE ConnectedAgent --------------------------- +(***************************************************************************) +(* The agent socket: a connected agent (the Hermes and OpenClaw plugins, *) +(* the Grok Bot bridge) attaches to the node and answers the turns that *) +(* the node sends it. *) +(* *) +(* Code that this spec models: *) +(* crates/aether/src/agent/connected.rs Shared::serve (attach, the *) +(* replace path, the read loop, the end of a connection), *) +(* ConnectedAgent::connection, run_turn, start_turn_with_events, *) +(* cancel *) +(* crates/aether/src/agent.rs EarlyCancels (cancel, take, *) +(* end) *) +(* protocol/agent-socket/README.md the rules of both sides *) +(* integrations/openclaw-plugin/src/task-runner.ts the honest agent *) +(* *) +(* A connection is a number: the `generation` that `serve` gives it. Each *) +(* connection has its own `pending` map. A turn is one call of *) +(* `start_turn_with_events`; each task has one thread that can run *) +(* MaxTurns turns, one after the other. Turns of different tasks can run *) +(* at the same time, which is more than the scheduler does (it runs one *) +(* execution at a time). *) +(* *) +(* The agent is not trusted to follow the protocol. When `honest` is *) +(* FALSE, an agent can answer any task ID that the node ever sent to an *) +(* agent, at any time and more than once, can ignore a cancel, can never *) +(* answer, and can close only its sending side. When `honest` is TRUE, *) +(* the agent follows task-runner.ts. `limit` says whether the time limit *) +(* of a turn (`ctx.deadline`) ever ends. Both are chosen in Init and do *) +(* not change, so one TLC run checks all four cases. *) +(* *) +(* Abstracted away: the socket file and its mode, the `ready` check and *) +(* the protocol number, bad and long lines (a long line is an agent *) +(* close), `progress` messages (they end nothing), the answer text, and *) +(* the 256-entry bound of each EarlyCancels list. A write and its receipt *) +(* by the agent are one step, and so are an agent message and its read by *) +(* `serve`. `generation.fetch_add` and `connection.replace` are one step. *) +(* A turn reads only the first final reply in its channel, so the channel *) +(* keeps only that one. The variables of a turn are reset when it ends. *) +(***************************************************************************) +EXTENDS Naturals, FiniteSets + +CONSTANTS + Tasks, \* task IDs + MaxConns, \* how many connections attach + MaxTurns \* how many turns one task ID gets (the node gives it one) + +Conns == 1..MaxConns +NoConn == 0 + +Stages == {"unused", "drain", "shut", "live", "eof", "detached", "done"} +Pcs == {"idle", "got", "send", "wait", "remove", "tcancel", "ending"} +Results == {"none", "answered", "failed", "cancelled", "timeout", "gone", + "protocol"} +ReplyKinds == {"result", "failed", "cancelled"} + +\* `from` is the connection whose agent sent the reply, or NoConn for a +\* `Reply::Cancelled` that the replace path made and for a dropped sender. +Reply == [kind : ReplyKinds \cup {"none", "dropped"}, from : 0..MaxConns] +NoReply == [kind |-> "none", from |-> NoConn] + +VARIABLES + honest, \* whether the agents follow the protocol (fixed in Init) + limit, \* whether a turn's time limit ever ends (fixed in Init) + cur, \* Shared.connection: the attached connection, or NoConn + gen, \* Shared.generation + st, \* where the `serve` thread of each connection is + repl, \* the connection that a new connection replaces + nodeShut, \* the node called `shutdown` on the connection + agentEnd, \* "open", "half" (the agent closed its sending side), "closed" + pending, \* Connection.pending: the open task IDs + open, \* honest agent: its open tasks (TaskRunner #open) + cpend, \* honest agent: `cancelled` messages on their way to the node + known, \* task IDs that the node ever wrote to an agent + lock, \* who holds the `cancels` mutex across two steps + cancelled, \* EarlyCancels.cancelled + ended, \* EarlyCancels.ended + pc, \* where the turn thread of each task is + tc, \* the connection that the turn took in `connection()` + chan, \* the first final reply in the turn's channel + res, \* the result of the turn, until it ends + turns, \* how many turns the task started + ends, \* ghost: how many turns of the task ended + told \* ghost: the agent got a `cancel` after this turn's `task` + +vars == <> + +connVars == <> +agentVars == <> +turnVars == <> +fixed == <> + +Free == "free" + +TypeOK == + /\ honest \in BOOLEAN + /\ limit \in BOOLEAN + /\ cur \in 0..MaxConns + /\ gen \in 0..MaxConns + /\ st \in [Conns -> Stages] + /\ repl \in [Conns -> 0..MaxConns] + /\ nodeShut \in [Conns -> BOOLEAN] + /\ agentEnd \in [Conns -> {"open", "half", "closed"}] + /\ pending \in [Conns -> SUBSET Tasks] + /\ open \in [Conns -> SUBSET Tasks] + /\ cpend \in [Conns -> SUBSET Tasks] + /\ known \subseteq Tasks + /\ lock \in Tasks \cup {Free} + /\ cancelled \subseteq Tasks + /\ ended \subseteq Tasks + /\ pc \in [Tasks -> Pcs] + /\ tc \in [Tasks -> 0..MaxConns] + /\ chan \in [Tasks -> Reply] + /\ res \in [Tasks -> Results] + /\ turns \in [Tasks -> 0..MaxTurns] + /\ ends \in [Tasks -> 0..MaxTurns] + /\ told \in [Tasks -> BOOLEAN] + +Init == + /\ honest \in BOOLEAN + /\ limit \in BOOLEAN + /\ cur = NoConn + /\ gen = 0 + /\ st = [c \in Conns |-> "unused"] + /\ repl = [c \in Conns |-> NoConn] + /\ nodeShut = [c \in Conns |-> FALSE] + /\ agentEnd = [c \in Conns |-> "open"] + /\ pending = [c \in Conns |-> {}] + /\ open = [c \in Conns |-> {}] + /\ cpend = [c \in Conns |-> {}] + /\ known = {} + /\ lock = Free + /\ cancelled = {} + /\ ended = {} + /\ pc = [t \in Tasks |-> "idle"] + /\ tc = [t \in Tasks |-> NoConn] + /\ chan = [t \in Tasks |-> NoReply] + /\ res = [t \in Tasks |-> "none"] + /\ turns = [t \in Tasks |-> 0] + /\ ends = [t \in Tasks |-> 0] + /\ told = [t \in Tasks |-> FALSE] + +----------------------------------------------------------------------------- +(* Helpers. *) + +\* `write_json_line` succeeds: the node did not shut the stream down and +\* the agent still reads. +Writable(c) == ~nodeShut[c] /\ agentEnd[c] # "closed" + +\* `read_message` in the read loop of `serve` returns None. +EofVisible(c) == nodeShut[c] \/ agentEnd[c] # "open" + +\* The node wrote the `task` message of the turn of t to the connection +\* that the turn took. +Sent(t) == pc[t] = "wait" \/ (pc[t] = "remove" /\ res[t] = "timeout") + +\* The read loop of `serve`: `pending.get(&id)` and `sender.send(reply)`. +\* The node ignores an answer for a task that is not open on this +\* connection. A later reply is never read, so only the first is kept. +Deliver(c, t, kind) == + chan' = IF t \in pending[c] /\ chan[t].kind = "none" + THEN [chan EXCEPT ![t] = [kind |-> kind, from |-> c]] + ELSE chan + +\* The agent of connection c gets `cancel` for the tasks in S. The honest +\* agent (TaskRunner.handle) answers `cancelled` at once for each open one +\* and ignores the others. +AgentGetsCancel(c, S) == + IF honest + THEN /\ open' = [open EXCEPT ![c] = @ \ S] + /\ cpend' = [cpend EXCEPT ![c] = @ \cup (S \cap open[c])] + ELSE UNCHANGED agentVars + +----------------------------------------------------------------------------- +(* Connections: `Shared::serve`. *) + +\* An agent connects and says `ready`: `serve` takes the next generation +\* and puts the connection in `Shared.connection`. +Attach == + /\ gen < MaxConns + /\ LET c == gen + 1 IN + /\ gen' = c + /\ cur' = c + /\ repl' = [repl EXCEPT ![c] = cur] + /\ st' = [st EXCEPT ![c] = IF cur = NoConn THEN "live" ELSE "drain"] + /\ UNCHANGED <> + +\* `serve`, the replace path, part 1: for each open task of the replaced +\* connection, write `cancel` to it and send `Reply::Cancelled`. +Drain(c) == + /\ st[c] = "drain" + /\ LET r == repl[c] IN + /\ chan' = [t \in Tasks |-> + IF t \in pending[r] /\ chan[t].kind = "none" + THEN [kind |-> "cancelled", from |-> NoConn] + ELSE chan[t]] + /\ IF Writable(r) THEN AgentGetsCancel(r, pending[r]) + ELSE UNCHANGED agentVars + /\ st' = [st EXCEPT ![c] = "shut"] + /\ UNCHANGED <> + +\* `serve`, the replace path, part 2: `replaced.stream.shutdown`. The read +\* loop of the new connection starts. The honest agent of the replaced +\* connection sees the close and forgets its open tasks. +ShutOld(c) == + /\ st[c] = "shut" + /\ nodeShut' = [nodeShut EXCEPT ![repl[c]] = TRUE] + /\ open' = [open EXCEPT ![repl[c]] = {}] + /\ repl' = [repl EXCEPT ![c] = NoConn] + /\ st' = [st EXCEPT ![c] = "live"] + /\ UNCHANGED <> + +\* The agent process stops or closes the connection. An agent that does +\* not follow the protocol can close only its sending side. The honest +\* agent forgets its open tasks (TaskRunner.close). +AgentClose(c, how) == + /\ st[c] # "unused" + /\ \/ agentEnd[c] = "open" /\ how \in {"half", "closed"} + \/ agentEnd[c] = "half" /\ how = "closed" + /\ how = "half" => ~honest + /\ agentEnd' = [agentEnd EXCEPT ![c] = how] + /\ open' = [open EXCEPT ![c] = {}] + /\ UNCHANGED <> + +\* `serve`: the read loop ends. No later message of the agent is read. +SeeEof(c) == + /\ st[c] = "live" + /\ EofVisible(c) + /\ st' = [st EXCEPT ![c] = "eof"] + /\ cpend' = [cpend EXCEPT ![c] = {}] + /\ UNCHANGED <> + +\* `serve`, after the loop: clear `Shared.connection` when it still holds +\* this generation. +Detach(c) == + /\ st[c] = "eof" + /\ cur' = IF cur = c THEN NoConn ELSE cur + /\ st' = [st EXCEPT ![c] = "detached"] + /\ UNCHANGED <> + +\* `serve`, the last step: `pending.clear()`. Each sender is dropped, so a +\* turn that waits gets `Disconnected`. +Clear(c) == + /\ st[c] = "detached" + /\ chan' = [t \in Tasks |-> + IF t \in pending[c] /\ chan[t].kind = "none" + THEN [NoReply EXCEPT !.kind = "dropped"] ELSE chan[t]] + /\ pending' = [pending EXCEPT ![c] = {}] + /\ st' = [st EXCEPT ![c] = "done"] + /\ UNCHANGED <> + +----------------------------------------------------------------------------- +(* The agent. *) + +\* The honest agent ends an open task with `result` or `failed`, once. +\* An agent that does not follow the protocol sends any final answer for +\* any task ID that it knows, at any time. `serve` reads the message. +AgentSays(c, t, kind) == + /\ st[c] = "live" + /\ agentEnd[c] = "open" + /\ ~nodeShut[c] + /\ IF honest + THEN /\ t \in open[c] + /\ kind \in {"result", "failed"} + /\ open' = [open EXCEPT ![c] = @ \ {t}] + /\ UNCHANGED cpend + ELSE /\ t \in known + /\ UNCHANGED agentVars + /\ Deliver(c, t, kind) + /\ UNCHANGED <> + +\* The `cancelled` that the honest agent sent for a cancel arrives. +CancelledArrives(c, t) == + /\ st[c] = "live" + /\ t \in cpend[c] + /\ cpend' = [cpend EXCEPT ![c] = @ \ {t}] + /\ Deliver(c, t, "cancelled") + /\ UNCHANGED <> + +----------------------------------------------------------------------------- +(* One turn: `start_turn_with_events` and `run_turn`. *) + +\* `run_turn`, under the `cancels` mutex: `cancels.take`, then +\* `connection()`. The mutex stays held until `Insert`. +Begin(t) == + /\ pc[t] = "idle" + /\ turns[t] < MaxTurns + /\ lock = Free + /\ turns' = [turns EXCEPT ![t] = @ + 1] + /\ CASE t \in cancelled -> + /\ cancelled' = cancelled \ {t} + /\ res' = [res EXCEPT ![t] = "cancelled"] + /\ pc' = [pc EXCEPT ![t] = "ending"] + /\ UNCHANGED <> + [] t \notin cancelled /\ cur = NoConn -> + /\ res' = [res EXCEPT ![t] = "gone"] + /\ pc' = [pc EXCEPT ![t] = "ending"] + /\ UNCHANGED <> + [] OTHER -> + /\ tc' = [tc EXCEPT ![t] = cur] + /\ pc' = [pc EXCEPT ![t] = "got"] + /\ lock' = t + /\ UNCHANGED <> + /\ UNCHANGED <> + +\* `run_turn`: `pending.insert`, then the `cancels` mutex is released. A +\* task ID that is already open is a protocol error. +Insert(t) == + /\ pc[t] = "got" + /\ lock' = Free + /\ IF t \in pending[tc[t]] + THEN /\ res' = [res EXCEPT ![t] = "protocol"] + /\ pc' = [pc EXCEPT ![t] = "ending"] + /\ UNCHANGED pending + ELSE /\ pending' = [pending EXCEPT ![tc[t]] = @ \cup {t}] + /\ pc' = [pc EXCEPT ![t] = "send"] + /\ UNCHANGED res + /\ UNCHANGED <> + +\* `run_turn`: write the `task` message. The honest agent starts a turn +\* for it, unless a task with this ID is open (TaskRunner #start). +WriteTask(t) == + /\ pc[t] = "send" + /\ LET c == tc[t] IN + IF Writable(c) + THEN /\ known' = known \cup {t} + /\ open' = IF honest /\ agentEnd[c] = "open" + THEN [open EXCEPT ![c] = @ \cup {t}] ELSE open + /\ pc' = [pc EXCEPT ![t] = "wait"] + /\ UNCHANGED res + ELSE /\ res' = [res EXCEPT ![t] = "gone"] + /\ pc' = [pc EXCEPT ![t] = "remove"] + /\ UNCHANGED <> + /\ UNCHANGED <> + +\* `run_turn`: `receiver.recv_timeout` gives a final reply, or +\* `Disconnected` after `pending.clear()`. +Receive(t) == + /\ pc[t] = "wait" + /\ chan[t].kind # "none" + /\ res' = [res EXCEPT ![t] = + CASE chan[t].kind = "result" -> "answered" + [] chan[t].kind = "failed" -> "failed" + [] chan[t].kind = "cancelled" -> "cancelled" + [] OTHER -> "gone"] + /\ pc' = [pc EXCEPT ![t] = "remove"] + /\ UNCHANGED <> + +\* `run_turn`: the time limit of the turn ends. +Timeout(t) == + /\ pc[t] = "wait" + /\ limit + /\ res' = [res EXCEPT ![t] = "timeout"] + /\ pc' = [pc EXCEPT ![t] = "remove"] + /\ UNCHANGED <> + +\* `run_turn`: `pending.remove`. +Remove(t) == + /\ pc[t] = "remove" + /\ pending' = [pending EXCEPT ![tc[t]] = @ \ {t}] + /\ pc' = [pc EXCEPT ![t] = IF res[t] = "timeout" THEN "tcancel" ELSE "ending"] + /\ UNCHANGED <> + +\* `run_turn`, after a timeout: write `cancel`. A failed write replaces +\* the timeout with `Unavailable`. +TimeoutCancel(t) == + /\ pc[t] = "tcancel" + /\ IF Writable(tc[t]) + THEN AgentGetsCancel(tc[t], {t}) /\ UNCHANGED res + ELSE res' = [res EXCEPT ![t] = "gone"] /\ UNCHANGED agentVars + /\ pc' = [pc EXCEPT ![t] = "ending"] + /\ UNCHANGED <> + +\* `start_turn_with_events`: `cancels.end`. The turn is over. +End(t) == + /\ pc[t] = "ending" + /\ lock = Free + /\ ended' = ended \cup {t} + /\ ends' = [ends EXCEPT ![t] = @ + 1] + /\ pc' = [pc EXCEPT ![t] = "idle"] + /\ tc' = [tc EXCEPT ![t] = NoConn] + /\ chan' = [chan EXCEPT ![t] = NoReply] + /\ res' = [res EXCEPT ![t] = "none"] + /\ told' = [told EXCEPT ![t] = FALSE] + /\ UNCHANGED <> + +----------------------------------------------------------------------------- +(* `Agent::cancel`. The node calls it at any time: for a task whose turn *) +(* did not start, runs, or ended (ProofNode::cancel, the lease renewal *) +(* thread, shutdown). *) + +\* The task is open on the attached connection, so `cancel` writes it. +CancelWrites(t) == cur # NoConn /\ t \in pending[cur] + +Cancel(t) == + /\ lock = Free + /\ IF CancelWrites(t) + THEN /\ IF Writable(cur) THEN AgentGetsCancel(cur, {t}) + ELSE UNCHANGED agentVars + /\ told' = [told EXCEPT ![t] = @ \/ (Writable(cur) /\ pc[t] = "wait")] + /\ UNCHANGED cancelled + ELSE \* `EarlyCancels::cancel`: keep it, unless the turn ended. + /\ cancelled' = IF t \in ended THEN cancelled ELSE cancelled \cup {t} + /\ UNCHANGED <> + /\ UNCHANGED <> + +----------------------------------------------------------------------------- + +Next == + \/ Attach + \/ \E c \in Conns : + \/ Drain(c) \/ ShutOld(c) \/ SeeEof(c) \/ Detach(c) \/ Clear(c) + \/ \E how \in {"half", "closed"} : AgentClose(c, how) + \/ \E t \in Tasks : + \/ CancelledArrives(c, t) + \/ \E kind \in ReplyKinds : AgentSays(c, t, kind) + \/ \E t \in Tasks : + \/ Begin(t) \/ Insert(t) \/ WriteTask(t) \/ Receive(t) \/ Timeout(t) + \/ Remove(t) \/ TimeoutCancel(t) \/ End(t) \/ Cancel(t) + +\* The node's threads keep running, and a message that the agent sent +\* arrives. The agent's own answer gets no fairness: a turn may take until +\* the time limit, and the limit ends only when `limit` is TRUE. +Fairness == + /\ \A t \in Tasks : + /\ WF_vars(Insert(t)) /\ WF_vars(WriteTask(t)) /\ WF_vars(Receive(t)) + /\ WF_vars(Timeout(t)) /\ WF_vars(Remove(t)) + /\ WF_vars(TimeoutCancel(t)) /\ WF_vars(End(t)) + /\ \A c \in Conns : + /\ WF_vars(Drain(c)) /\ WF_vars(ShutOld(c)) /\ WF_vars(SeeEof(c)) + /\ WF_vars(Detach(c)) /\ WF_vars(Clear(c)) + /\ \A t \in Tasks : WF_vars(CancelledArrives(c, t)) + +Spec == Init /\ [][Next]_vars /\ Fairness + +----------------------------------------------------------------------------- +(* Safety. *) + +\* An open task ID belongs to a turn that runs on that connection: no +\* sender stays in a `pending` map after its turn, so the protocol error +\* of `Insert` never happens. +PendingIsOpenTurn == + \A c \in Conns, t \in Tasks : + t \in pending[c] => pc[t] \in {"send", "wait", "remove"} /\ tc[t] = c + +NoProtocolError == \A t \in Tasks : res[t] # "protocol" + +\* An answer comes only from the agent of the connection that the turn is +\* open on, whatever task IDs the other agents send. +AnswerFromHolder == + \A t \in Tasks : + res[t] = "answered" => chan[t].kind = "result" /\ chan[t].from = tc[t] + +\* A result enters the channel of a turn only after the node sent the +\* turn's task to the connection of that agent. +AnswerAfterSentStep == + \A t \in Tasks : chan[t].kind = "none" /\ chan'[t].kind = "result" => Sent(t) + +\* With honest agents, the answer came after the node sent the turn. +HonestAnswerAfterSent == [][honest => AnswerAfterSentStep]_vars + +\* Each turn ends once. +TurnEndsOnce == + \A t \in Tasks : ends[t] = IF pc[t] = "idle" THEN turns[t] ELSE turns[t] - 1 + +\* A turn that starts while no agent is attached sends nothing and fails. +NoAgentNoTask == + [][\A t \in Tasks : + pc[t] = "idle" /\ pc'[t] # "idle" /\ cur = NoConn + => pc'[t] = "ending" /\ res'[t] \in {"gone", "cancelled"}]_vars + +\* A cancel that came before the turn started cancels it at the start, +\* and nothing is sent to the agent. +EarlyCancelHonored == + [][\A t \in Tasks : + pc[t] = "idle" /\ pc'[t] # "idle" /\ t \in cancelled + => pc'[t] = "ending" /\ res'[t] = "cancelled" + /\ t \notin cancelled']_vars + +\* A cancel that comes after `cancels.end` of a turn is not kept. +LateCancelDropped == + [][\A t \in Tasks : t \in ended /\ t \notin cancelled + => t \notin cancelled']_vars + +\* A cancel for a turn that the attached agent has is written to it. +CancelToldToHolder == + [][\A t \in Tasks : + Cancel(t) /\ pc[t] = "wait" /\ tc[t] = cur /\ Writable(cur) + => told'[t]]_vars + +\* With honest agents, a turn never waits on a connection that is over +\* with nothing in its channel. +OrphanWait(t) == + pc[t] = "wait" /\ st[tc[t]] = "done" /\ chan[t].kind = "none" +HonestNoOrphanWait == \A t \in Tasks : honest => ~OrphanWait(t) + +(***************************************************************************) +(* Properties that TLC finds false. They are not in ConnectedAgent.cfg; *) +(* each comment gives the counterexample. *) +(***************************************************************************) + +\* FALSE (a race, and only with a task ID that gets a second turn): a +\* cancel is not kept after a turn of its task ended. `cancel` keeps it +\* when the task is not open on the attached connection and `cancels.end` +\* did not run yet: Attach, Begin, Insert, WriteTask, AgentSays(result), +\* Receive, Remove, Cancel (not in `pending`, not in `ended`: kept), End. +\* A second turn with this task ID is then cancelled at its start. The +\* node starts one turn for a task ID (ExecutionLease, AtMostOneStart), so +\* the kept cancel only stays in the list. +NoStaleCancel == + \A t \in Tasks : pc[t] = "idle" /\ turns[t] > 0 => t \notin cancelled + +\* FALSE (a race): a `cancel` never reaches the agent before its `task`. +\* `run_turn` inserts the task into `pending` and releases the `cancels` +\* mutex before it writes `task`: Attach, Begin, Insert, Cancel (open on +\* the attached connection: `cancel` is written), WriteTask. The honest +\* agent ignores a cancel for a task that it does not have, then runs the +\* turn. A cancel deletes the lease, so the lease renewal thread calls +\* `cancel` once more within 10 s; that second signal stops the turn. +\* The property says that no state is in this window, in which `Cancel` +\* writes `cancel` and changes nothing else. +NoLostCancel == + \A t \in Tasks : ~(CancelWrites(t) /\ Writable(cur) /\ pc[t] = "send") + +\* FALSE (a race): a `task` goes only to the attached connection. +\* `run_turn` takes the connection, and `serve` replaces it before the +\* write: Attach, Begin, Attach, Insert, WriteTask. The replaced +\* connection is still open until ShutOld. The turn then fails. +TaskOnlyToAttached == + [][\A t \in Tasks : pc[t] = "send" /\ pc'[t] = "wait" => cur = tc[t]]_vars + +\* FALSE (the same race): the result of an agent that was replaced never +\* enters the channel of a turn. Attach, Begin, Insert, WriteTask, Attach, +\* AgentSays(result) by the first agent before Drain: the answer of the +\* agent that got the task is taken. Also Attach, Begin, Attach, Drain +\* (nothing open yet), Insert, WriteTask, AgentSays(result), before ShutOld. +AnswerWhileAttached == + [][\A t \in Tasks : chan[t].kind = "none" /\ chan'[t].kind = "result" + => chan'[t].from = cur]_vars + +\* FALSE (an agent that does not follow the protocol, and a task ID that +\* gets a second turn): the answer came after the node sent the turn. An +\* agent that knows the ID from the first turn answers the second turn +\* between Insert and WriteTask. It holds with MaxTurns = 1. The agent is a +\* process of the node owner, and the node starts one turn for a task ID. +AnswerAfterSent == [][AnswerAfterSentStep]_vars + +\* FALSE (a race, with an agent that closes only its sending side): a +\* turn never waits on a connection that is over with nothing in its +\* channel. Attach, Begin (takes the connection), AgentClose(half), SeeEof, +\* Detach, Clear (`pending` is still empty), Insert, WriteTask (the agent +\* still reads, so the write succeeds). No one drops the sender, so the +\* turn waits until its time limit instead of failing at once. +NoOrphanWait == \A t \in Tasks : ~OrphanWait(t) + +----------------------------------------------------------------------------- +(* Liveness. *) + +\* Every turn ends when its time limit ends, whatever the agent does. +TurnEnds == \A t \in Tasks : (limit /\ pc[t] # "idle") ~> pc[t] = "idle" + +\* Without the time limit: when the connection of a turn is closed (the +\* node replaced it, or the agent closed it), the turn stops waiting. The +\* turn of NoOrphanWait is left out: it waits for the time limit. +LostAgentFailsTurn == + \A t \in Tasks, c \in Conns : + (~limit /\ pc[t] = "wait" /\ tc[t] = c /\ ~OrphanWait(t) + /\ (nodeShut[c] \/ agentEnd[c] = "closed")) + ~> pc[t] # "wait" + +\* Without the time limit: when an honest agent got a cancel after the +\* task, the turn stops waiting. +CancelStopsHonestTurn == + \A t \in Tasks : + (honest /\ ~limit /\ pc[t] = "wait" /\ told[t]) ~> pc[t] # "wait" + +============================================================================= diff --git a/specs/DirectInvite.cfg b/specs/DirectInvite.cfg new file mode 100644 index 0000000..d92916a --- /dev/null +++ b/specs/DirectInvite.cfg @@ -0,0 +1,26 @@ +\* Two calls of sign_direct_invite that can interleave, one caller, one +\* attacker endpoint, two contact names. ReturnedLineWorks and NoStrayMember +\* are false (see DirectInvite.tla) and are not checked here. +CONSTANTS + Invites = {i1, i2} + CallerName = caller + CallerEp = callerEp + EvilName = evil + EvilEp = evilEp + HostName = host + OtherName = other + HostEp = hostEp + Faults = TRUE + +SPECIFICATION Spec + +INVARIANTS + TypeOK + NoOrphanGrant + AdmitOnlyInvited + KeptAuthIsOwn + OneNamePerEndpoint + +PROPERTIES + NameKeepsEndpoint + InviteEnds diff --git a/specs/DirectInvite.tla b/specs/DirectInvite.tla new file mode 100644 index 0000000..314b248 --- /dev/null +++ b/specs/DirectInvite.tla @@ -0,0 +1,352 @@ +---------------------------- MODULE DirectInvite ---------------------------- +(***************************************************************************) +(* Connecting two people: the host signs a direct invite for a caller's *) +(* connect code, the caller imports the invite line and keeps a contact, *) +(* and the caller's first request is admitted under that invite. *) +(* *) +(* Code that this spec models: *) +(* crates/aether/src/invites.rs sign_direct_invite_with *) +(* crates/aether/src/access_groups.rs join_and_apply, leave *) +(* crates/aether/src/direct.rs create_card, sign_invite_access, *) +(* encode_invite_after_grant, *) +(* import_bundle, *) +(* import_invitation_in, contact, *) +(* remove_contact_in *) +(* crates/aether/src/admin.rs Administration::apply, revoke *) +(* crates/aether/src/proof/admission.rs admit, check_group *) +(* crates/aether-core/src/lib.rs PolicyEngine::admit, match_grant *) +(* *) +(* sign_direct_invite has three callers that share no lock for the whole *) +(* call: the host page (admin_ui/host.rs create_invite), the admin socket *) +(* (admin_socket.rs create_invite_response, for an MCP client), and the *) +(* hub worker (hub_workers.rs sign_and_pin). So two calls can interleave; *) +(* each store call and each Administration call is one atomic step. *) +(* *) +(* An invite line holds two separate signed things: the invitation (agent *) +(* name and endpoint of the host, signed with a key that the invitation *) +(* itself carries, so anyone can make one for any name and endpoint) and *) +(* the authorization (a claim for the caller's endpoint, signed with the *) +(* host's issuer key, so only the host makes a real one). The attacker *) +(* reads every line that the host made, makes its own invitations, puts *) +(* any authorization in them, and sends requests from its own endpoint. *) +(* QUIC authenticates the endpoint of a sender. *) +(* *) +(* Abstracted away: days and the 1/7/30 choice (expiry is a flag that an *) +(* Expire action sets at any time; a claim expires with its grant), the *) +(* Agent Card (a bad card is the same as a line that does not import), *) +(* named groups other than the one that the invite joins, pending changes *) +(* (see PendingChange), the hub (see HubInvite), the queue and the replay *) +(* table (see Admission), the task after admission (see ExecutionLease), *) +(* a host restart, and a crash between the store calls of import_bundle *) +(* (it is one step here). *) +(***************************************************************************) +EXTENDS Naturals, FiniteSets + +CONSTANTS + Invites, \* calls of sign_direct_invite; each signs one grant + CallerName, \* the name that the host owner types for the caller + CallerEp, \* the endpoint of the caller node + EvilName, \* a name that the owner may type for the attacker + EvilEp, \* the endpoint of the attacker + HostName, \* the agent name of the host in its invitations + OtherName, \* another contact name of the caller + HostEp, \* the endpoint of the host node + Faults \* TRUE: the grant apply and the line encode can fail + +None == "none" + +\* A person on the host: the name that the owner typed and the endpoint of +\* the connect code. To keep the state space small, each connect code has +\* one name here; a grant and a group row match on both, so a second name +\* for a code is one more person of the same kind. +Persons == {<>, <>} + +ContactNames == {HostName, OtherName} +ContactEps == {HostEp, EvilEp} + +Pcs == {"idle", "signed", "joined", "applied", "done", "failed"} +Idle == [pc |-> "idle", who |-> <>, + was1 |-> FALSE, was2 |-> FALSE] + +NoContact == [ep |-> None, auth |-> None, expired |-> FALSE] + +VARIABLES + inv, \* host: where each sign_direct_invite call is + members, \* host: access_group_members of the invite's group + live, \* host: the grants in the live policy (one per invite) + gone, \* the invites whose grant and claim passed expires_at + lines, \* the invites whose line the host returned + invited, \* ghost: each person that the owner made an invite for + ownerRemoved, \* ghost: each person that the owner took out of the group + contacts, \* caller: the kept bundle of each contact name + admitted \* host: <> of each admitted request + +vars == <> + +TypeOK == + /\ inv \in [Invites -> [pc : Pcs, who : Persons, was1 : BOOLEAN, + was2 : BOOLEAN]] + /\ members \subseteq Persons + /\ live \subseteq Invites + /\ gone \subseteq Invites + /\ lines \subseteq Invites + /\ invited \subseteq Persons + /\ ownerRemoved \subseteq Persons + /\ contacts \in [ContactNames -> + [ep : ContactEps \cup {None}, + auth : Invites \cup {None, "fake"}, + expired : BOOLEAN]] + /\ admitted \subseteq ({CallerEp, EvilEp} \X Invites) + +Init == + /\ inv = [i \in Invites |-> Idle] + /\ members = {} + /\ live = {} + /\ gone = {} + /\ lines = {} + /\ invited = {} + /\ ownerRemoved = {} + /\ contacts = [n \in ContactNames |-> NoContact] + /\ admitted = {} + +----------------------------------------------------------------------------- +(* The host: one call of sign_direct_invite_with. *) + +\* create_card, sign_invite_access, and the first is_member read +\* (`was_member` of sign_direct_invite_with). +Start(i, p) == + /\ inv[i].pc = "idle" + /\ inv' = [inv EXCEPT ![i] = [pc |-> "signed", who |-> p, + was1 |-> p \in members, was2 |-> FALSE]] + /\ invited' = invited \cup {p} + /\ UNCHANGED <> + +\* join_and_apply, first half: its own member_of read (`was_member` of +\* join_and_apply), then add_access_group_member. +Join(i) == + /\ inv[i].pc = "signed" + /\ inv' = [inv EXCEPT ![i].pc = "joined", + ![i].was2 = inv[i].who \in members] + /\ members' = members \cup {inv[i].who} + /\ UNCHANGED <> + +\* join_and_apply, second half: Administration::apply puts the grant in the +\* live policy. When it fails (a store error, a refusal), a person who was +\* not a member at the join leaves the group again. +Apply(i) == + /\ inv[i].pc = "joined" + /\ \/ /\ live' = live \cup {i} + /\ inv' = [inv EXCEPT ![i].pc = "applied"] + /\ UNCHANGED members + \/ /\ Faults + /\ inv' = [inv EXCEPT ![i].pc = "failed"] + /\ members' = IF inv[i].was2 THEN members ELSE members \ {inv[i].who} + /\ UNCHANGED live + /\ UNCHANGED <> + +\* encode_invite_after_grant. When it fails, revoke takes the grant back, +\* and a person who was not a member at the start leaves the group. +Encode(i) == + /\ inv[i].pc = "applied" + /\ \/ /\ lines' = lines \cup {i} + /\ inv' = [inv EXCEPT ![i].pc = "done"] + /\ UNCHANGED <> + \/ /\ Faults + /\ inv' = [inv EXCEPT ![i].pc = "failed"] + /\ live' = live \ {i} + /\ members' = IF inv[i].was1 THEN members ELSE members \ {inv[i].who} + /\ UNCHANGED lines + /\ UNCHANGED <> + +\* Administration::revoke from the host page or the admin socket. +Revoke(i) == + /\ i \in live + /\ live' = live \ {i} + /\ UNCHANGED <> + +\* access_groups::change with Action::Remove, on the host page. +RemoveMember(p) == + /\ p \in members + /\ members' = members \ {p} + /\ ownerRemoved' = ownerRemoved \cup {p} + /\ UNCHANGED <> + +\* Time passes expires_at of the grant and of its claim. +Expire(i) == + /\ inv[i].pc # "idle" + /\ i \notin gone + /\ gone' = gone \cup {i} + /\ UNCHANGED <> + +----------------------------------------------------------------------------- +(* The caller: import_bundle and the contacts. *) + +\* The endpoint that an authorization names (`caller_endpoint_id`). A real +\* one names the endpoint of its invite. The attacker makes a fake one for +\* any endpoint; `fakeFor` is that endpoint. +AuthEp(a, fakeFor) == IF a = "fake" THEN fakeFor ELSE inv[a].who[2] + +\* `contact`: the kept invitation of the name, when it is still valid. +Valid(n) == contacts[n].ep # None /\ ~contacts[n].expired + +\* import_bundle with a line that names `n` at `ep` and carries the +\* authorization `a`. The host's own lines name HostName at HostEp; every +\* other invitation is the attacker's. import_invitation_in refuses a name +\* that a valid contact holds at another endpoint. A contact with another +\* name at the same endpoint is removed (a rename). +Import(n, ep, a, fakeFor) == + /\ a \in lines \cup {"fake"} + /\ AuthEp(a, fakeFor) = CallerEp + /\ ~(Valid(n) /\ contacts[n].ep # ep) + /\ contacts' = [m \in ContactNames |-> + IF m = n THEN [ep |-> ep, auth |-> a, expired |-> FALSE] + ELSE IF contacts[m].ep = ep THEN NoContact + ELSE contacts[m]] + /\ UNCHANGED <> + +\* Time passes expires_at of the kept invitation. +ContactExpires(n) == + /\ Valid(n) + /\ contacts' = [contacts EXCEPT ![n].expired = TRUE] + /\ UNCHANGED <> + +\* remove_contact_in. +RemoveContact(n) == + /\ contacts[n].ep # None + /\ contacts' = [contacts EXCEPT ![n] = NoContact] + /\ UNCHANGED <> + +----------------------------------------------------------------------------- +(* Requests to the host. *) + +\* PolicyEngine::admit, then check_group. `sender` is the endpoint that +\* QUIC authenticated; `a` is the invite whose claim the request carries. +\* The claim must be for the sender and not expired. match_grant then takes +\* any live grant for the same name and endpoint that has not expired, not +\* only the grant that was signed with the claim. +Admits(sender, a) == + /\ a \in Invites + /\ inv[a].pc # "idle" + /\ inv[a].who[2] = sender + /\ a \notin gone + /\ \E g \in live : inv[g].who = inv[a].who /\ g \notin gone + /\ inv[a].who \in members + +\* The caller sends a task to a valid contact at the host's endpoint, with +\* the authorization that it kept. A request to a contact at EvilEp goes to +\* the attacker, which already has every line. +CallerRequest(n) == + /\ Valid(n) + /\ contacts[n].ep = HostEp + /\ Admits(CallerEp, contacts[n].auth) + /\ admitted' = admitted \cup {<>} + /\ UNCHANGED <> + +\* The attacker sends a request from its endpoint with the claim of any +\* invite. A claim that the host did not sign fails `verify`. +EvilRequest(a) == + /\ Admits(EvilEp, a) + /\ admitted' = admitted \cup {<>} + /\ UNCHANGED <> + +----------------------------------------------------------------------------- + +Next == + \/ \E i \in Invites : + \/ \E p \in Persons : Start(i, p) + \/ Join(i) \/ Apply(i) \/ Encode(i) \/ Revoke(i) \/ Expire(i) + \/ EvilRequest(i) + \/ \E p \in Persons : RemoveMember(p) + \/ \E n \in ContactNames : + \/ \E ep \in ContactEps, a \in Invites \cup {"fake"}, + f \in {CallerEp, EvilEp} : Import(n, ep, a, f) + \/ ContactExpires(n) \/ RemoveContact(n) \/ CallerRequest(n) + +\* A call of sign_direct_invite runs to its end. +Fairness == \A i \in Invites : WF_vars(Join(i)) /\ WF_vars(Apply(i)) + /\ WF_vars(Encode(i)) + +Spec == Init /\ [][Next]_vars /\ Fairness + +----------------------------------------------------------------------------- +(* Safety. *) + +\* A grant is live only while its call still runs or after the call +\* returned its line: a call that failed leaves no grant. +NoOrphanGrant == \A i \in live : inv[i].pc \in {"applied", "done"} + +\* The host admits a request only from an endpoint that the owner made an +\* invite for, and only with a claim that was signed for that endpoint. A +\* line that another person reads or copies gives them nothing. +AdmitOnlyInvited == + \A x \in admitted : + /\ inv[x[2]].who[2] = x[1] + /\ inv[x[2]].who \in invited + +\* The caller keeps only an authorization that names its own endpoint. +KeptAuthIsOwn == + \A n \in ContactNames : + contacts[n].auth \in Invites => inv[contacts[n].auth].who[2] = CallerEp + +\* The caller has at most one contact name for one endpoint. +OneNamePerEndpoint == + \A n, m \in ContactNames : + (n # m /\ contacts[n].ep # None) => contacts[n].ep # contacts[m].ep + +\* While a contact is valid, its name stays with its endpoint: no invite +\* from another key moves the name to another endpoint. +NameKeepsEndpoint == + [][\A n \in ContactNames : + (Valid(n) /\ contacts'[n].ep # None) => contacts'[n].ep = contacts[n].ep + ]_vars + +(***************************************************************************) +(* Properties that TLC finds false. They are not in DirectInvite.cfg. *) +(***************************************************************************) + +\* FALSE: a person is in the group only through a call that reached the +\* join and did not fail, so failed calls alone leave nobody in the group. +\* +\* TLC, with two calls for one person: Start(i1) (was1 = FALSE), Join(i1), +\* Start(i2) (was1 = TRUE), Apply(i1) fails and takes the person out, +\* Join(i2) (was2 = FALSE) puts the person back, Apply(i2), Encode(i2) +\* fails. Encode uses the read of Start (was1 = TRUE), so it leaves the +\* person in the group. Both calls failed and no grant is live, but the +\* person stays a member. A member without a grant gets no task admitted +\* (AdmitOnlyInvited holds), so this is a leftover row, not an access. +NoStrayMember == + \A p \in members : + \E i \in Invites : inv[i].who = p /\ inv[i].pc \in {"joined", "applied", "done"} + +\* FALSE: a line that the host returned works. When no call for the person +\* still runs, the grant is live, and the owner did not take the person out +\* of the group, the person is in the group, so check_group admits them. +\* +\* TLC, with two calls for one person (for example the host page and an +\* MCP client, or a double click): Start(i1), Join(i1) (was2 = FALSE), +\* Start(i2) (was1 = TRUE), Join(i2) (was2 = TRUE), Apply(i1) fails and +\* takes the person out of the group, Apply(i2), Encode(i2). The line of i2 +\* is returned and its grant is live, but the person is in no group, and +\* every request with it is refused (ProofError::GroupDenied). The same +\* happens when Encode(i1) fails after Start(i1) read was1 = FALSE. +\* Each call decides "I added this person" from its own read and no lock +\* covers the read and the later removal. +ReturnedLineWorks == + \A i \in lines : + (/\ i \in live + /\ inv[i].who \notin ownerRemoved + /\ \A j \in Invites : + inv[j].who = inv[i].who => inv[j].pc \in {"idle", "done", "failed"}) + => inv[i].who \in members + +----------------------------------------------------------------------------- +(* Liveness. *) + +\* Each call of sign_direct_invite ends with a line or with a failure. +InviteEnds == + \A i \in Invites : inv[i].pc # "idle" ~> inv[i].pc \in {"done", "failed"} + +============================================================================= diff --git a/specs/EventPaging.cfg b/specs/EventPaging.cfg new file mode 100644 index 0000000..1cfd874 --- /dev/null +++ b/specs/EventPaging.cfg @@ -0,0 +1,29 @@ +\* EventPaging: the event journal, one poll page, and the polling loops. +\* A page has at most two events and a byte budget of 3; a progress event +\* has size 1 or 2, so two events do not always fit. See EventPaging.tla. +\* OutboxReadsToEnd is false (`follow` stops on the status alone); the spec +\* explains it. PageProgress needs Sizes within 1..Budget. +CONSTANTS + MaxEvents = 6 + PageLimit = 2 + Budget = 3 + Sizes = {1, 2} + MaxLost = 2 + +SPECIFICATION Spec + +INVARIANTS + TypeOK + Dense + PageIsRun + MoreIsHonest + SnapshotAtOneInstant + PageProgress + CursorInJournal + CliInOrder + CliComplete + +PROPERTIES + JournalNeverChanges + CursorNeverBack + EndedTaskStops diff --git a/specs/EventPaging.tla b/specs/EventPaging.tla new file mode 100644 index 0000000..ef70bc5 --- /dev/null +++ b/specs/EventPaging.tla @@ -0,0 +1,388 @@ +---------------------------- MODULE EventPaging ---------------------------- +(***************************************************************************) +(* How a caller reads the progress and the answer of one task: the event *) +(* journal of the host, one page of it for each poll, and the polling *) +(* loop of the caller. *) +(* *) +(* Host side: *) +(* crates/aether-store/src/tasks.rs `event` (the next sequence is *) +(* MAX(sequence)+1), `change`, `append_event`, `mark_succeeded` on a *) +(* cancelled task, `clear_expired_content`, `events_page`, *) +(* `task_progress`, `content_is_expired` *) +(* crates/aether/src/a2a_transport.rs `A2aTransport::handle`: the page *) +(* loop with `MAX_FRAMES - 1` and `EVENT_PAGE_BYTE_BUDGET`, `cursor`,*) +(* `more_events`, and the operator-review and expired-result errors *) +(* crates/aether/src/proof/scheduler.rs the event callback of *) +(* `run_execution`, which calls `append_event` *) +(* Caller side: *) +(* crates/aether/src/transport/client.rs `request_with_polling_on`, *) +(* `response_last_event_sequence`, `response_more_events_remain`, *) +(* `is_terminal_task_status` (`aether node request` and the other *) +(* `request_once*` callers) *) +(* crates/aether/src/outbox.rs `follow`, `outcome`, and the cursor that *) +(* `attempt_in` keeps in `sent_tasks.last_event_sequence` *) +(* crates/aether/src/direct.rs `resend_frame` *) +(* The contract: references/aether-wire-profile.md, "Event paging". *) +(* *) +(* One task and one caller. `mode` is chosen in Init and does not change, *) +(* so one TLC run checks both polling loops: "cli" is *) +(* `request_with_polling_on`, which keeps every event frame; "outbox" is *) +(* `follow`, which keeps only the cursor and the answer. *) +(* *) +(* `task_progress` reads the state and the page in one store call, so the *) +(* host read is one step. At most one exchange is in flight: each loop *) +(* waits for its answer before it polls again. *) +(* *) +(* Abstracted away: admission, replay keys and the grant (see Outbox and *) +(* Admission), the scheduler and the lease (see ExecutionLease; the task *) +(* here is admitted, runs, and ends in one step each), `pending_approval`, *) +(* `leased`, `rejected` and `operator_reviewed` (they page like `queued`, *) +(* `failed` and `unknown_result`), the answer text, the same frame that *) +(* `Link::exchange` sends again (see Outbox), and the gap between *) +(* `task_progress` and `content_is_expired`, which are two store calls. A *) +(* caller that sends a `lastEventSequence` past the end of the journal *) +(* gets an empty page with that cursor back; the callers here send only *) +(* the cursor that they got. The size of an event is a small number: real *) +(* event frames hold only a state and are far smaller than the budget. *) +(***************************************************************************) +EXTENDS Naturals, Sequences, FiniteSets + +CONSTANTS + MaxEvents, \* bound on the events in the journal + PageLimit, \* MAX_FRAMES - 1: the event frames of one page + Budget, \* EVENT_PAGE_BYTE_BUDGET + Sizes, \* the encoded sizes that a progress event can have + MaxLost \* bound on lost exchanges + +Active == {"queued", "running"} +Terminal == {"succeeded", "failed", "cancelled"} +States == Active \cup Terminal \cup {"unknown_result"} + +\* `a2a_status`, as far as the callers tell the values apart. +StatusOf(s) == + CASE s \in Active -> "working" + [] s = "succeeded" -> "completed" + [] OTHER -> "failed" \* failed, canceled + +Kinds == States \cup {"progress", "result", "content_expired"} + +None == [kind |-> "none"] + +VARIABLES + mode, \* "cli" or "outbox" (fixed in Init) + state, \* tasks.state + expired, \* tasks.content_expired_at IS NOT NULL + events, \* task_events rows of the task: [seq, kind, size] + termSeq, \* ghost: the sequence of the event that ended the task, or 0 + ran, \* ghost: an agent turn started, so late events can come + req, \* the request frame in flight, or None + rep, \* the answer in flight, or None + c, \* the caller: [phase, cursor, got] + lost \* how many exchanges were lost + +vars == <> + +End == Cardinality(events) +SizeOf(s) == (CHOOSE e \in events : e.seq = s).size + +Phases == {"idle", "sent", "done", "error", "aborted"} + +TypeOK == + /\ mode \in {"cli", "outbox"} + /\ state \in States + /\ expired \in BOOLEAN + /\ events \subseteq [seq : 1..MaxEvents, kind : Kinds, size : Nat] + /\ termSeq \in 0..MaxEvents + /\ ran \in BOOLEAN + /\ req \in {None} \cup [kind : {"req"}, after : 0..MaxEvents] + /\ rep.kind \in {"none", "page", "error"} + /\ c.phase \in Phases + /\ c.cursor \in 0..MaxEvents + /\ c.got \in Seq(1..MaxEvents) + /\ lost \in 0..MaxLost + +Init == + /\ mode \in {"cli", "outbox"} + \* `admit`: the task row and its first event in one transaction. + /\ state = "queued" + /\ expired = FALSE + /\ events = {[seq |-> 1, kind |-> "queued", size |-> 1]} + /\ termSeq = 0 + /\ ran = FALSE + /\ req = None + /\ rep = None + /\ c = [phase |-> "idle", cursor |-> 0, got |-> <<>>] + /\ lost = 0 + +----------------------------------------------------------------------------- +(* The host's store. Each action is one SQLite transaction. *) + +\* `event`: COALESCE(MAX(sequence),0)+1. +NextSeq == IF events = {} THEN 1 + ELSE (CHOOSE s \in {e.seq : e \in events} : + \A e \in events : e.seq <= s) + 1 + +AddEvent(kind, size) == + /\ End < MaxEvents + /\ events' = events \cup {[seq |-> NextSeq, kind |-> kind, size |-> size]} + +\* `change` -> `enter`: the new state and its event in one transaction. +Enter(s) == + /\ AddEvent(s, 1) + /\ state' = s + /\ termSeq' = IF s \in Terminal THEN NextSeq ELSE termSeq + +\* `mark_running`. +Start == + /\ state = "queued" + /\ Enter("running") + /\ ran' = TRUE + /\ UNCHANGED <> + +\* The event callback of `run_execution` -> `append_event`: the agent +\* reports progress. `append_event` checks only that the task exists, and +\* the callback holds back only a `Completed` event of a cancelled task, so +\* a progress event can also come after a cancel. +Progress == + /\ state = "running" \/ (state = "cancelled" /\ ran) + /\ \E size \in Sizes : AddEvent("progress", size) + /\ UNCHANGED <> + +\* `mark_succeeded`, `mark_failed`, `mark_unknown_result`. +Finish == + /\ state = "running" + /\ \E s \in {"succeeded", "failed", "unknown_result"} : Enter(s) + /\ UNCHANGED <> + +\* `cancel` / `cancel_if_owned`. +Cancel == + /\ state \in Active + /\ Enter("cancelled") + /\ UNCHANGED <> + +\* `mark_succeeded` on a cancelled task: the late answer is one more event. +LateResult == + /\ state = "cancelled" /\ ran + /\ AddEvent("result", 1) + /\ UNCHANGED <> + +\* `clear_expired_content`: 24 hours after the task ended. +ContentExpires == + /\ state \in Terminal + /\ ~expired + /\ AddEvent("content_expired", 1) + /\ expired' = TRUE + /\ UNCHANGED <> + +----------------------------------------------------------------------------- +(* One page: `A2aTransport::handle` after admission. *) + +RECURSIVE Bytes(_, _) +\* The encoded size of the k events after `after`. +Bytes(after, k) == IF k = 0 THEN 0 ELSE Bytes(after, k - 1) + SizeOf(after + k) + +\* `events_page`: at most PageLimit events after `after`. +Fetched(after) == + LET rest == IF End > after THEN End - after ELSE 0 + IN IF rest > PageLimit THEN PageLimit ELSE rest + +\* The page loop: the events that fit in the byte budget. +Sent(after) == + CHOOSE k \in 0..Fetched(after) : + /\ Bytes(after, k) <= Budget + /\ k = Fetched(after) \/ Bytes(after, k + 1) > Budget + +\* `end` and `term` are ghosts: the journal end and `termSeq` at the read. +Page(after) == + LET n == Sent(after) + IN [kind |-> "page", + after |-> after, + seqs |-> [i \in 1..n |-> after + i], + cursor |-> after + n, + \* `has_more` of `events_page`, or the byte budget stopped the loop. + more |-> (End - after > PageLimit) \/ n < Fetched(after), + status |-> StatusOf(state), + end |-> End, + term |-> termSeq] + +Error == [kind |-> "error"] + +\* `handle`: `task_progress` reads the state and the page together. A task +\* that waits for the operator, and an answer that expired, get an error +\* frame and no events. +HostRead == + /\ req # None + /\ rep' = IF state = "unknown_result" \/ (state = "succeeded" /\ expired) + THEN Error ELSE Page(req.after) + /\ req' = None + /\ UNCHANGED <> + +----------------------------------------------------------------------------- +(* The caller. *) + +\* One turn of either loop: a frame with `lastEventSequence` set to the +\* cursor (`request_with_polling_on`; `resend_frame` in `follow`). +Poll == + /\ c.phase = "idle" + /\ req' = [kind |-> "req", after |-> c.cursor] + /\ c' = [c EXCEPT !.phase = "sent"] + /\ UNCHANGED <> + +Max(a, b) == IF a > b THEN a ELSE b + +Ended(status) == status \in {"completed", "failed"} + +\* `request_with_polling_on`: keep the event frames, and stop on an error, +\* or on an ended task whose page has no `aetherMoreEvents`. +CliReceive == + /\ mode = "cli" + /\ c.phase = "sent" + /\ rep # None + /\ IF rep.kind = "error" + THEN c' = [c EXCEPT !.phase = "error"] + ELSE c' = [phase |-> IF Ended(rep.status) /\ ~rep.more + THEN "done" ELSE "idle", + cursor |-> Max(c.cursor, rep.cursor), + got |-> c.got \o rep.seqs] + /\ rep' = None + /\ UNCHANGED <> + +\* `follow` with `outcome`: stop when the state is not Working. It does not +\* read `aetherMoreEvents`, and it keeps no event frames. +OutboxReceive == + /\ mode = "outbox" + /\ c.phase = "sent" + /\ rep # None + /\ IF rep.kind = "error" + THEN c' = [c EXCEPT !.phase = "error"] + ELSE c' = [c EXCEPT !.phase = IF rep.status = "working" + THEN "idle" ELSE "done", + !.cursor = Max(c.cursor, rep.cursor)] + /\ rep' = None + /\ UNCHANGED <> + +\* The frame or its answer is lost, or the exchange times out. The cli loop +\* returns the error and drops what it collected. The outbox keeps the +\* cursor in `sent_tasks` (`record_sent_attempt`), and the next attempt +\* sends it again. +Lose == + /\ c.phase = "sent" + /\ lost < MaxLost + /\ lost' = lost + 1 + /\ req' = None + /\ rep' = None + /\ c' = [c EXCEPT !.phase = IF mode = "cli" THEN "aborted" ELSE "idle"] + /\ UNCHANGED <> + +\* `request_with_polling_on`: TASK_POLL_DEADLINE passed. +CliTimeout == + /\ mode = "cli" + /\ c.phase = "idle" + /\ c' = [c EXCEPT !.phase = "aborted"] + /\ UNCHANGED <> + +----------------------------------------------------------------------------- + +Next == + \/ Start \/ Progress \/ Finish \/ Cancel \/ LateResult \/ ContentExpires + \/ HostRead + \/ Poll \/ CliReceive \/ OutboxReceive \/ Lose \/ CliTimeout + +\* The caller keeps polling and the host answers. The task itself gets no +\* fairness: an agent may run for a long time. +Fairness == + /\ WF_vars(Poll) + /\ WF_vars(HostRead) + /\ WF_vars(CliReceive) + /\ WF_vars(OutboxReceive) + +Spec == Init /\ [][Next]_vars /\ Fairness + +----------------------------------------------------------------------------- +(* The journal. *) + +\* The sequences are 1, 2, 3, ... without a gap, and each is used once. +Dense == + /\ {e.seq : e \in events} = 1..End + /\ \A e1, e2 \in events : e1.seq = e2.seq => e1 = e2 + +\* An event never changes and never goes away. +JournalNeverChanges == [][events \subseteq events']_vars + +(* One page. *) + +\* A page is the ordered run of events right after the caller's cursor, +\* and its cursor is the last event in it. +PageIsRun == + rep.kind = "page" => + /\ \A i \in 1..Len(rep.seqs) : rep.seqs[i] = rep.after + i + /\ rep.cursor = rep.after + Len(rep.seqs) + /\ Len(rep.seqs) <= PageLimit + /\ rep.cursor <= rep.end + +\* A page says "no more events" only when it reached the end of the +\* journal as of its read, and "more events" only when it did not. +MoreIsHonest == + rep.kind = "page" => (rep.more <=> rep.cursor < rep.end) + +\* The state and the page are from one instant: a page that shows an ended +\* task was read when the event that ended it was in the journal, and a +\* page that shows a working task was read before that. +SnapshotAtOneInstant == + rep.kind = "page" => + (Ended(rep.status) <=> (rep.term > 0 /\ rep.term <= rep.end)) + +\* A page moves the cursor when events remain. It holds only while every +\* event fits in the byte budget alone (EventPaging.cfg: Sizes within +\* 1..Budget). With Sizes = {1, 3} and Budget = 2, TLC finds: Start, +\* Progress(3), Poll, HostRead (events 1 and 2 fit), CliReceive, Poll, +\* HostRead: event 3 is larger than the budget, so the loop in `handle` +\* breaks before the first event, and the page has no events, the same +\* cursor, and `aetherMoreEvents`. Each later poll gets the same page. A +\* real event frame is some hundred bytes and the budget is 4 MB less +\* 64 KB, so the code does not reach this. +PageProgress == + rep.kind = "page" /\ rep.end > rep.after => rep.cursor > rep.after + +(* The caller. *) + +\* The cursor never moves back, and never passes the end of the journal. +CursorNeverBack == [][c'.cursor >= c.cursor]_vars +CursorInJournal == c.cursor <= End + +\* The cli loop has each event up to its cursor once, in order. +CliInOrder == + mode = "cli" => + /\ Len(c.got) = c.cursor + /\ \A i \in 1..Len(c.got) : c.got[i] = i + +\* A cli loop that stops with an answer has every event up to the one that +\* ended the task. Events that come after its last page (a late result of a +\* cancelled task, `content_expired`) are not part of this. +CliComplete == + mode = "cli" /\ c.phase = "done" => termSeq > 0 /\ c.cursor >= termSeq + +\* An ended task lets the caller stop: with its last page, with an error +\* frame, or (cli) with a lost exchange or the poll deadline. +EndedTaskStops == + (state \in Terminal \cup {"unknown_result"}) + ~> (c.phase \in {"done", "error", "aborted"} \/ lost = MaxLost) + +(***************************************************************************) +(* A property that TLC finds false. It is not in EventPaging.cfg. *) +(***************************************************************************) + +\* FALSE: the cursor that the outbox keeps for an ended task covers the +\* event that ended it. `follow` stops as soon as `outcome` gives a state +\* that is not Working, and neither reads `aetherMoreEvents` +\* (outbox.rs `follow`, `outcome`). The wire profile says that a caller +\* polls on while `aetherMoreEvents` is true, also when the status looks +\* terminal. With PageLimit = 2 TLC finds: Start, Progress, Finish (4 +\* events), Poll, HostRead (events 1 and 2, status completed, more = TRUE), +\* OutboxReceive: the task is answered with the cursor at 2. +\* The outbox keeps only the answer, which is in every page of a succeeded +\* task, so it loses no answer; the cursor in `sent_tasks` is short. +OutboxReadsToEnd == + mode = "outbox" /\ c.phase = "done" => c.cursor >= termSeq + +============================================================================= diff --git a/specs/ManagedRoster.cfg b/specs/ManagedRoster.cfg new file mode 100644 index 0000000..63053d5 --- /dev/null +++ b/specs/ManagedRoster.cfg @@ -0,0 +1,34 @@ +\* ManagedRoster: the managed roster and the directory records. See +\* ManagedRoster.tla. Two agents, two tokens, two spellings of the control +\* URL, two sync processes, pages of two events. RevokeStays, +\* NoAdmitAfterServiceRevoke, ResolveIsForAgent, RevokedStaysOut, +\* EveryKeyCatchesUp and DirSyncCatchesUp are false; the spec explains +\* each one. +CONSTANTS + Agents = {a1, a2} + Eps = {e1, e2} + Tokens = {t1, t2} + Keys = {k1, k2} + Procs = {p1, p2} + Page = 2 + MaxRec = 2 + MaxDirLog = 3 + +SPECIFICATION Spec + +INVARIANTS + TypeOK + TokenOnce + RosterFromLog + AdmitIsMember + OneKeyExact + OneKeyRevokeStays + UsedRecordIsTrusted + HonestResolveIsForAgent + CacheIsSigned + +PROPERTIES + CursorForward + DirCursorForward + RevokeReaches + DirSyncUnlessPoisoned diff --git a/specs/ManagedRoster.tla b/specs/ManagedRoster.tla new file mode 100644 index 0000000..cc36ab2 --- /dev/null +++ b/specs/ManagedRoster.tla @@ -0,0 +1,602 @@ +--------------------------- MODULE ManagedRoster --------------------------- +(***************************************************************************) +(* The managed and directory trust scopes: how a node learns who is a *) +(* member from a control service, how it keeps signed directory records, *) +(* and how the kept roster decides whether a signed claim admits work. *) +(* *) +(* Code that this spec models: *) +(* crates/aether/src/control_service.rs publish, resolve, revoke, *) +(* changes_after, redeem_managed_invitation, revoke_managed_member, *) +(* managed_changes_after *) +(* crates/aether-store/src/control.rs redeem_managed_invitation, *) +(* revoke_managed_member, managed_events_after, *) +(* publish_signed_record, revoke_signed_record *) +(* crates/aether/src/managed_client.rs events_after, sync_managed *) +(* crates/aether-store/src/managed.rs managed_cursor, *) +(* apply_managed_member, revoke_managed_member, advance_cursor, *) +(* ManagedMember::is_active *) +(* crates/aether/src/identity.rs RosterClaims::verify *) +(* crates/aether/src/directory_client.rs validate, validate_event, *) +(* events_after, sync_directory, cached_directory_record, *) +(* request_via_directory *) +(* crates/aether-store/src/directory.rs cache_directory_record, *) +(* mark_directory_record_stale, advance_directory_cursor *) +(* crates/aether/src/discovery.rs validate_record *) +(* *) +(* The two scopes do not share state, so `mode` picks one of them in Init *) +(* and does not change. One TLC run checks both. *) +(* *) +(* Trust. The managed control service is TRUSTED: a roster event has no *) +(* signature, and the node knows the service only by its pinned TLS *) +(* certificate. A service that lies can add any member, so the model has *) +(* an honest managed service. The network can lose a reply, and a node *) +(* process can stop at any step. The directory service is NOT trusted for *) +(* the content of a record: one key that the caller trusts signs each *) +(* record. When `dirHonest` is FALSE, each answer of the directory can be *) +(* any record that the trusted key ever signed, or any record that the *) +(* attacker made. Signatures are perfect. *) +(* *) +(* A node keeps one roster for a scope, but one cursor for each pair of *) +(* control URL and scope (`cursor_key`). `Keys` are the spellings of the *) +(* control URL that the owner passes to `--managed-control` or to *) +(* `aether managed sync`. `OneKey` says that the node used one only. *) +(* *) +(* Abstracted away: the creation and the expiry of a token (each token *) +(* exists in Init), the expiry of a member (an expired member only loses *) +(* its access, in `is_active`), the role, other scopes of *) +(* one control service, the `members` list and the route of a caller to a *) +(* managed host (`request_task`), the claim itself (each pair of agent and *) +(* endpoint has a valid claim of the trusted issuer, the worst case), the *) +(* grant, addresses and capabilities of a record, `search`, the renewal *) +(* worker, and wall-clock time (each expiry is a flag that an `Expire*` *) +(* action sets at any moment). A directory page holds one event here; the *) +(* real page holds up to 128 (`EVENT_PAGE`), and one bad event refuses the *) +(* whole page. The directory cursor has one key here. *) +(***************************************************************************) +EXTENDS Naturals, Sequences, FiniteSets + +CONSTANTS + Agents, \* agent ids + Eps, \* endpoint ids + Tokens, \* managed invitation tokens + Keys, \* spellings of the control URL (one cursor for each) + Procs, \* processes that run `sync_managed` on one data directory + Page, \* events in one managed page + MaxRec, \* directory records that the trusted key signs + MaxDirLog \* bound on directory events + +None == "none" +MaxLog == 2 * Cardinality(Tokens) \* one join and one revoke for each token +Scopes == {"dir", "else"} \* the scope that the caller asks for, and another + +NoRow == [st |-> None, ep |-> None] +Rows == [st : {None, "active", "revoked"}, ep : Eps \cup {None}] +Events == [type : {"joined", "revoked"}, agent : Agents, ep : Eps \cup {None}] + +\* A directory record. `key` is the signing key, `sig` says whether the +\* signature fits the fields, and `n` is the serial of a record that the +\* trusted key signed (0 for a record that the attacker made). +Rec == [agent : Agents, scope : Scopes, key : {"trusted", "other"}, + sig : {"good", "bad"}, n : 0..MaxRec] +NoRec == [agent |-> None, scope |-> None, key |-> None, sig |-> None, n |-> 0] +\* Records of the attacker: its own key, or the trusted key with a +\* signature that does not fit. +Evil == {r \in Rec : r.n = 0 /\ ~(r.key = "trusted" /\ r.sig = "good")} +DirEvents == [type : {"put", "revoke"}, agent : Agents, scope : Scopes, + rec : Rec \cup {NoRec}] + +VARIABLES + mode, \* "managed" or "directory" (fixed in Init) + \* --- the managed control service --- + tok, \* managed_invitations: "issued" or "redeemed" + joins, \* ghost: how many members each token made + cm, \* managed_members of the service + log, \* managed_events of the scope, in order + \* --- the node, managed scope --- + roster, \* managed_members of the node + cur, \* the roster cursor of each control URL + proc, \* each sync process: its URL and the page that it holds + revApplied, \* ghost: members whose revoke event the node applied + \* --- the directory --- + dirHonest, \* whether the directory follows control_service.rs + signed, \* the records that the trusted key signed + rexp, \* serials whose expires_at passed + dstore, \* signed_records of the directory, by agent + dlog, \* directory_events, in order + revoked, \* ghost: records that a revoke removed from the directory + cache, \* the node's cached directory records, by scope and agent + dcur, \* the node's directory cursor + dpc, \* sync_directory: "idle", or "advance" before the cursor moves + badUse \* ghost: which wrong uses of a record happened + +mvars == <> +dvars == <> +vars == <> + +Idle(k) == [key |-> k, lo |-> 0, hi |-> 0] +NoEntry == [rec |-> NoRec, stale |-> FALSE] + +TypeOK == + /\ mode \in {"managed", "directory"} + /\ tok \in [Tokens -> {"issued", "redeemed"}] + /\ joins \in [Tokens -> Nat] + /\ cm \in [Agents -> Rows] + /\ log \in Seq(Events) /\ Len(log) <= MaxLog + /\ roster \in [Agents -> Rows] + /\ cur \in [Keys -> 0..MaxLog] + /\ proc \in [Procs -> [key : Keys, lo : 0..MaxLog, hi : 0..MaxLog]] + /\ revApplied \subseteq Agents + /\ dirHonest \in BOOLEAN + /\ signed \subseteq Rec + /\ rexp \subseteq 1..MaxRec + /\ dstore \in [Agents -> Rec \cup {NoRec}] + /\ dlog \in Seq(DirEvents) /\ Len(dlog) <= MaxDirLog + /\ revoked \subseteq Rec + /\ cache \in [Scopes -> [Agents -> [rec : Rec \cup {NoRec}, stale : BOOLEAN]]] + /\ dcur \in 0..MaxDirLog + /\ dpc \in {"idle", "advance"} + /\ badUse \subseteq {"untrusted", "resolved_other_agent"} + +Init == + /\ mode \in {"managed", "directory"} + /\ tok = [t \in Tokens |-> "issued"] + /\ joins = [t \in Tokens |-> 0] + /\ cm = [a \in Agents |-> NoRow] + /\ log = <<>> + /\ roster = [a \in Agents |-> NoRow] + /\ cur = [k \in Keys |-> 0] + /\ proc = [p \in Procs |-> Idle(CHOOSE k \in Keys : TRUE)] + /\ revApplied = {} + /\ dirHonest \in (IF mode = "directory" THEN BOOLEAN ELSE {TRUE}) + /\ signed = {} + /\ rexp = {} + /\ dstore = [a \in Agents |-> NoRec] + /\ dlog = <<>> + /\ revoked = {} + /\ cache = [s \in Scopes |-> [a \in Agents |-> NoEntry]] + /\ dcur = 0 + /\ dpc = "idle" + /\ badUse = {} + +----------------------------------------------------------------------------- +(* The managed control service. Each action is one SQLite transaction. *) + +\* ControlService::redeem_managed_invitation -> ControlStore:: +\* redeem_managed_invitation: the token must be unused and not expired, and +\* the INSERT fails for an agent id that has a row (PRIMARY KEY, also when +\* the row is revoked) or an endpoint that another member has (UNIQUE). +\* A failed INSERT rolls the token back to unused. +Redeem(t, a, e) == + /\ mode = "managed" + /\ tok[t] = "issued" + /\ cm[a] = NoRow + /\ \A b \in Agents : cm[b].ep # e + /\ tok' = [tok EXCEPT ![t] = "redeemed"] + /\ joins' = [joins EXCEPT ![t] = @ + 1] + /\ cm' = [cm EXCEPT ![a] = [st |-> "active", ep |-> e]] + /\ log' = Append(log, [type |-> "joined", agent |-> a, ep |-> e]) + /\ UNCHANGED <> + +\* ControlStore::revoke_managed_member: only a member that is not revoked. +RevokeMember(a) == + /\ mode = "managed" + /\ cm[a].st = "active" + /\ cm' = [cm EXCEPT ![a].st = "revoked"] + /\ log' = Append(log, [type |-> "revoked", agent |-> a, ep |-> None]) + /\ UNCHANGED <> + +----------------------------------------------------------------------------- +(* The node: sync_managed. *) + +Min(x, y) == IF x < y THEN x ELSE y + +\* `managed_cursor`, then ManagedClient::events_after: the page after the +\* cursor of this process's control URL. An honest service answers with the +\* next events in order, so `monotonic_cursors` passes. +Fetch(p) == + /\ mode = "managed" + /\ proc[p].lo = proc[p].hi + /\ LET c == cur[proc[p].key] IN + /\ c < Len(log) + /\ proc' = [proc EXCEPT ![p].lo = c, ![p].hi = Min(c + Page, Len(log))] + /\ UNCHANGED <> + +\* One event of the page: apply_managed_member or revoke_managed_member. +\* The cursor and the row change in one transaction. `advance_cursor` +\* refuses a cursor that does not move forward. A join replaces the row of +\* its agent and clears revoked_at (ON CONFLICT DO UPDATE); it fails when +\* another agent has the endpoint (UNIQUE). A revoke fails with NotFound +\* when no row of the agent is active. A failure ends the sync. +Apply(p) == + /\ mode = "managed" + /\ proc[p].lo < proc[p].hi + /\ LET k == proc[p].key + i == proc[p].lo + 1 + ev == log[i] + a == ev.agent + ok == /\ i > cur[k] + /\ IF ev.type = "joined" + THEN \A b \in Agents \ {a} : roster[b].ep # ev.ep + ELSE roster[a].st = "active" + IN IF ok + THEN /\ cur' = [cur EXCEPT ![k] = i] + /\ proc' = [proc EXCEPT ![p].lo = i] + /\ roster' = [roster EXCEPT ![a] = + IF ev.type = "joined" + THEN [st |-> "active", ep |-> ev.ep] + ELSE [@ EXCEPT !.st = "revoked"]] + /\ revApplied' = IF ev.type = "revoked" + THEN revApplied \cup {a} ELSE revApplied + ELSE /\ proc' = [proc EXCEPT ![p].lo = proc[p].hi] + /\ UNCHANGED <> + /\ UNCHANGED <> + +\* The process stops in the middle of a page, or the reply is lost. +Lose(p) == + /\ mode = "managed" + /\ proc[p].lo < proc[p].hi + /\ proc' = [proc EXCEPT ![p].lo = proc[p].hi] + /\ UNCHANGED <> + +\* The owner starts the node, or runs `aether managed sync`, with another +\* spelling of the control URL. The roster stays; the cursor is another one. +Rekey(p, k) == + /\ mode = "managed" + /\ proc[p].lo = proc[p].hi + /\ proc[p].key # k + /\ proc' = [proc EXCEPT ![p] = Idle(k)] + /\ UNCHANGED <> + +\* RosterClaims::verify for a claim of the trusted issuer that names agent +\* `a` at the authenticated endpoint `e`: a roster row of the agent with +\* that endpoint, not revoked. +\* It reads the roster and changes nothing, so it is a predicate here, not +\* an action: the claim admits work in each state where it holds. +Admits(a, e) == + roster[a].st = "active" /\ roster[a].ep = e + +----------------------------------------------------------------------------- +(* The directory. *) + +Serials == {r.n : r \in signed} + +\* The holder of the trusted key signs a record (`signed_record`). +Sign(a, s) == + /\ mode = "directory" + /\ Cardinality(signed) < MaxRec + /\ signed' = signed \cup {[agent |-> a, scope |-> s, key |-> "trusted", + sig |-> "good", n |-> Cardinality(signed) + 1]} + /\ UNCHANGED <> + +\* Time passes the record's expires_at. +ExpireRec(n) == + /\ mode = "directory" + /\ n \in Serials \ rexp + /\ rexp' = rexp \cup {n} + /\ UNCHANGED <> + +\* `validate_record` in the service: the signature fits the record's own +\* key, and the record has not expired. It does not know a trusted key. +ServiceAccepts(r) == r.sig = "good" /\ r.n \notin rexp + +\* ControlService::publish. The request is the record alone, so anyone who +\* holds a record can send it: its owner, or a reader of the directory. +\* The service takes a record of any key for an agent id that has no +\* record, and only the same key for an agent id that has one. +DirPublish(r) == + /\ mode = "directory" /\ dirHonest + /\ r \in signed \cup Evil + /\ ServiceAccepts(r) + /\ dstore[r.agent] = NoRec \/ dstore[r.agent].key = r.key + /\ Len(dlog) < MaxDirLog + /\ dstore' = [dstore EXCEPT ![r.agent] = r] + /\ dlog' = Append(dlog, [type |-> "put", agent |-> r.agent, + scope |-> r.scope, rec |-> r]) + /\ UNCHANGED <> + +\* ControlService::revoke. The request is a record of the same agent and +\* key that `validate_record` accepts; the stored record itself is one. +DirRevoke(a) == + /\ mode = "directory" /\ dirHonest + /\ dstore[a] # NoRec + /\ \E w \in signed \cup Evil : + w.agent = a /\ ServiceAccepts(w) /\ w.key = dstore[a].key + /\ Len(dlog) < MaxDirLog + /\ dstore' = [dstore EXCEPT ![a] = NoRec] + /\ dlog' = Append(dlog, [type |-> "revoke", agent |-> a, + scope |-> dstore[a].scope, rec |-> NoRec]) + /\ revoked' = revoked \cup {dstore[a]} + /\ UNCHANGED <> + +\* DirectoryClient::validate: the trusted key, a signature that fits, and +\* not expired. +ClientAccepts(r) == r.key = "trusted" /\ r.sig = "good" /\ r.n \notin rexp + +\* What a trusted record is, said without the client's checks. +Trusted(r) == r \in signed /\ r.n \notin rexp + +\* The next event that the node reads. An attacker directory can send any. +NextDirEvents == + IF dirHonest + THEN (IF dcur < Len(dlog) THEN {dlog[dcur + 1]} ELSE {}) + ELSE (IF dcur < MaxDirLog + THEN [type : {"put", "revoke"}, agent : Agents, scope : Scopes, + rec : signed \cup Evil \cup {NoRec}] + ELSE {}) + +\* DirectoryClient::validate_event. +EventOk(ev) == + IF ev.type = "put" + THEN /\ ev.rec # NoRec + /\ ev.rec.agent = ev.agent /\ ev.rec.scope = ev.scope + /\ ClientAccepts(ev.rec) + ELSE ev.rec = NoRec + +\* sync_directory, first half: events_after refuses a page with an event +\* that validate_event refuses, and then nothing changes. Else +\* cache_directory_record or mark_directory_record_stale. +DirApply == + /\ mode = "directory" + /\ dpc = "idle" + /\ \E ev \in NextDirEvents : + /\ EventOk(ev) + /\ cache' = [cache EXCEPT ![ev.scope][ev.agent] = + IF ev.type = "put" THEN [rec |-> ev.rec, stale |-> FALSE] + ELSE IF @.rec = NoRec THEN @ + ELSE [@ EXCEPT !.stale = TRUE]] + /\ dpc' = "advance" + /\ UNCHANGED <> + +\* sync_directory, second half: advance_directory_cursor. It is another +\* statement than the cache write, not the same transaction. +DirAdvance == + /\ mode = "directory" + /\ dpc = "advance" + /\ dcur' = dcur + 1 + /\ dpc' = "idle" + /\ UNCHANGED <> + +\* The process stops between the two halves. The next sync reads the same +\* event again. +DirCrash == + /\ mode = "directory" + /\ dpc = "advance" + /\ dpc' = "idle" + /\ UNCHANGED <> + +\* What `resolve` answers for the agent id `want`. ControlService::resolve +\* answers 410 for an expired record. +Resolved(want) == + IF dirHonest + THEN (IF dstore[want] # NoRec /\ dstore[want].n \notin rexp + THEN {dstore[want]} ELSE {}) + ELSE signed \cup Evil + +\* request_via_directory, when the directory answers: DirectoryClient:: +\* resolve checks the key, the signature and the expiry, and the caller +\* checks the scope. Nothing compares the record's agent id with `want`. +\* The caller caches the record under the record's own names and sends +\* the task to the record's endpoint. +Resolve(want) == + /\ mode = "directory" + /\ \E r \in Resolved(want) : + /\ ClientAccepts(r) + /\ r.scope = "dir" + /\ cache' = [cache EXCEPT ![r.scope][r.agent] = + [rec |-> r, stale |-> FALSE]] + /\ badUse' = badUse + \cup (IF Trusted(r) /\ r.scope = "dir" THEN {} ELSE {"untrusted"}) + \cup (IF r.agent = want THEN {} ELSE {"resolved_other_agent"}) + /\ UNCHANGED <> + +\* request_via_directory, when the directory cannot be reached: +\* cached_directory_record checks the names, the expiry (a stale record +\* has expires_at 0), the key and the signature. +UseCached(want) == + /\ mode = "directory" + /\ LET c == cache["dir"][want] IN + /\ c.rec # NoRec /\ ~c.stale + /\ c.rec.agent = want /\ c.rec.scope = "dir" + /\ ClientAccepts(c.rec) + /\ badUse' = badUse + \cup (IF Trusted(c.rec) /\ c.rec.scope = "dir" THEN {} + ELSE {"untrusted"}) + /\ UNCHANGED <> + +----------------------------------------------------------------------------- + +Next == + \/ \E t \in Tokens, a \in Agents, e \in Eps : Redeem(t, a, e) + \/ \E a \in Agents : RevokeMember(a) + \/ \E p \in Procs : Fetch(p) \/ Apply(p) \/ Lose(p) + \/ \E k \in Keys : Rekey(p, k) + \/ \E a \in Agents, s \in Scopes : Sign(a, s) + \/ \E n \in 1..MaxRec : ExpireRec(n) + \/ \E r \in Rec : DirPublish(r) + \/ \E a \in Agents : DirRevoke(a) \/ Resolve(a) \/ UseCached(a) + \/ DirApply \/ DirAdvance \/ DirCrash + +\* A node keeps syncing: the worker of `aether node serve` runs +\* sync_managed every 30 s. A reply can be lost again and again, but not +\* for ever (strong fairness of Apply and DirAdvance). +Fairness == + /\ \A p \in Procs : WF_vars(Fetch(p)) /\ SF_vars(Apply(p)) + /\ WF_vars(DirApply) + /\ SF_vars(DirAdvance) + +Spec == Init /\ [][Next]_vars /\ Fairness + +----------------------------------------------------------------------------- +(* Safety, managed scope. *) + +\* The node used at most one spelling of the control URL. +OneKey == Cardinality({k \in Keys : cur[k] > 0}) <= 1 + +\* A token makes at most one member. +TokenOnce == \A t \in Tokens : joins[t] <= 1 + +\* A row of the node's roster comes from a join event of the service for +\* that agent and that endpoint. +RosterFromLog == + \A a \in Agents : roster[a] # NoRow => + \E i \in 1..Len(log) : + log[i] = [type |-> "joined", agent |-> a, ep |-> roster[a].ep] + +\* A claim admits work only for an agent and an endpoint that joined. +AdmitIsMember == + \A a \in Agents, e \in Eps : Admits(a, e) => + \E i \in 1..Len(log) : log[i] = [type |-> "joined", agent |-> a, ep |-> e] + +\* The roster after the first n events of the service. +Last(a, n) == + LET is == {i \in 1..n : log[i].agent = a} IN + IF is = {} THEN 0 ELSE CHOOSE i \in is : \A j \in is : j <= i +RosterAt(n) == + [a \in Agents |-> + IF Last(a, n) = 0 THEN NoRow + ELSE [st |-> IF log[Last(a, n)].type = "joined" THEN "active" ELSE "revoked", + ep |-> cm[a].ep]] + +\* With one control URL the roster is exactly the events up to the cursor: +\* no event is skipped, applied twice, or applied out of order, whatever +\* the lost replies, the stops, and the processes that sync together. +OneKeyExact == + OneKey => \A k \in Keys : cur[k] > 0 => roster = RosterAt(cur[k]) + +\* With one control URL a revoke that the node applied stays, and no claim +\* of that member admits work again. +OneKeyRevokeStays == + OneKey => \A a \in revApplied : + /\ roster[a].st = "revoked" + /\ \A e \in Eps : ~Admits(a, e) + +\* A cursor moves forward by one event, or not at all. +CursorForward == + [][\A k \in Keys : cur'[k] = cur[k] \/ cur'[k] = cur[k] + 1]_vars + +(***************************************************************************) +(* Managed properties that TLC finds false. They are not in *) +(* ManagedRoster.cfg; each comment gives the counterexample. *) +(***************************************************************************) + +\* FALSE: a revoke that the node applied stays, and no claim of that member +\* admits work again. The cursor has the control URL in its key +\* (managed.rs cursor_key), the roster does not, and a join event clears +\* revoked_at (apply_managed_member, ON CONFLICT DO UPDATE). Trace: +\* Redeem(a), RevokeMember(a); the node syncs both events under URL k1 +\* (a is revoked); a sync under another spelling k2 starts at cursor 0 and +\* applies the join again (a is active); the process stops or loses the +\* next reply before the revoke; the claim of a admits work. A later sync under k1 reads +\* nothing new, so the member stays active for a node that runs under k1. +RevokeStays == + \A a \in revApplied : + /\ roster[a].st = "revoked" + /\ \A e \in Eps : ~Admits(a, e) + +\* FALSE, by design: no claim admits work after the service revoked the +\* member. The node learns of a revoke at its next sync (every 30 s), so +\* after Redeem(a), a sync and RevokeMember(a), the claim of a admits work +\* until then. +NoAdmitAfterServiceRevoke == + \A a \in Agents, e \in Eps : Admits(a, e) => cm[a].st # "revoked" + +----------------------------------------------------------------------------- +(* Safety, directory scope. Checked against the attacker directory. *) + +\* The caller uses only a record that the trusted key signed, that has not +\* expired, and that is for the scope that the caller asked for. +UsedRecordIsTrusted == "untrusted" \notin badUse + +\* An honest directory answers with the record of the agent that the +\* caller asked for. +HonestResolveIsForAgent == dirHonest => "resolved_other_agent" \notin badUse + +\* The cache holds only records that the trusted key signed, each under +\* its own scope and agent id, so a record from the cache is the record of +\* the agent that the caller asked for. +CacheIsSigned == + \A s \in Scopes, a \in Agents : + cache[s][a].rec # NoRec => + /\ cache[s][a].rec \in signed + /\ cache[s][a].rec.agent = a /\ cache[s][a].rec.scope = s + +DirCursorForward == [][dcur' = dcur \/ dcur' = dcur + 1]_vars + +(***************************************************************************) +(* Directory properties that TLC finds false. They are not in *) +(* ManagedRoster.cfg. *) +(***************************************************************************) + +\* FALSE: the caller sends its task to the agent that it asked for. +\* request_via_directory checks the scope of the resolved record but not +\* its agent id, and DirectoryClient::resolve checks only the key, the +\* signature and the expiry. Trace with an attacker directory: Sign(b), +\* Resolve(a) answers with the record of b; the caller caches it and +\* sends the task for a to the endpoint of b. cached_directory_record +\* does check the agent id. +ResolveIsForAgent == "resolved_other_agent" \notin badUse + +\* FALSE: a record that a revoke removed does not come back. A publish +\* request is the signed record alone, so anyone who read the record can +\* send it again while it has not expired. Trace with an honest directory: +\* Sign(a), DirPublish(r), DirRevoke(a), DirPublish(r). In the same way +\* anyone who read a record can revoke it. +RevokedStaysOut == \A a \in Agents : dstore[a] \notin revoked + +----------------------------------------------------------------------------- +(* Liveness. *) + +\* A revoke of the service reaches a node that keeps syncing under one +\* control URL. +RevokeReaches == + \A a \in Agents : + cm[a].st = "revoked" ~> (roster[a].st = "revoked" \/ ~OneKey) + +\* FALSE: the same without "one control URL". Trace: Redeem(a), +\* RevokeMember(a); a sync under k1 applies the join, a sync under k2 +\* applies the join, the sync under k1 applies the revoke; the sync under +\* k2 then fails at the revoke with NotFound (no active row) every time, +\* so the cursor of k2 stays at 1 and `aether node serve` with that URL +\* stops with "managed roster synchronization failed". Here the member is +\* revoked; with a later join and revoke of another member the node under +\* k2 never learns of them. +EveryKeyCatchesUp == + \A k \in Keys, p \in Procs : + <>[](proc[p].key = k /\ cur[k] > 0) => <>[](cur[k] = Len(log)) + +\* An event of the directory log is one that validate_event refuses for +\* ever: a record of another key, or a record that expired. +Poisoned == + \E j \in 1..Len(dlog) : dlog[j].type = "put" /\ ~ClientAccepts(dlog[j].rec) + +\* An honest directory's events reach a node that keeps syncing, unless +\* the log is poisoned. +DirSyncUnlessPoisoned == + dirHonest => \A i \in 1..MaxDirLog : + (Len(dlog) >= i) ~> (dcur >= i \/ Poisoned) + +\* FALSE: an honest directory's events reach a node that keeps syncing. +\* changes_after serves the stored event with its record whatever the +\* expiry, and validate_event refuses an expired record, so events_after +\* fails for the whole page. Trace: Sign(a), DirPublish(r), ExpireRec(r); +\* the node's cursor stays at 0 for ever, and a later DirRevoke never +\* reaches its cache. The same happens after DirPublish of a record of +\* another key, which the service accepts for a free agent id. +DirSyncCatchesUp == + dirHonest => \A i \in 1..MaxDirLog : (Len(dlog) >= i) ~> (dcur >= i) + +============================================================================= diff --git a/specs/PendingChange.cfg b/specs/PendingChange.cfg new file mode 100644 index 0000000..92385ff --- /dev/null +++ b/specs/PendingChange.cfg @@ -0,0 +1,28 @@ +\* PendingChange: local administration. See PendingChange.tla. +\* One change id, which is also the id of a grant in the policy file. Three +\* requests, one process stop, and store writes that can fail. +\* LiveFromUi, StaleRefused, StaleSeesRevoke, NoMcpRevival, +\* LiveMatchesStoreAlways and Audited are false; the spec explains each one. +CONSTANTS + Ids = {i1} + FileIds = {i1} + MaxOps = 3 + MaxRestarts = 1 + StoreFaults = TRUE + +SPECIFICATION Spec + +INVARIANTS + TypeOK + HighRiskGrantNeedsUi + CapabilityNeedsUi + ChangeNeedsUi + LiveFromUiOrPolicy + LiveMatchesStore + RevokedStaysOut + StaleRefusedWhileRecorded + AuditedWhileRecorded + +PROPERTIES + ExpiredRowStays + RequestEnds diff --git a/specs/PendingChange.tla b/specs/PendingChange.tla new file mode 100644 index 0000000..a3ad901 --- /dev/null +++ b/specs/PendingChange.tla @@ -0,0 +1,617 @@ +---------------------------- MODULE PendingChange ---------------------------- +(***************************************************************************) +(* Local administration: a change that an MCP client or the owner's UI *) +(* asks for, the rule that a high-risk change waits for a confirmation in *) +(* the UI, and how an applied change reaches the running node and the *) +(* store. *) +(* *) +(* Code that this spec models: *) +(* crates/aether/src/admin.rs Administration::submit, apply, *) +(* queue_pending, apply_now, finish_live, apply_live, *) +(* apply_live_inner, change_requires_confirmation, confirm_ui, *) +(* confirm_pending, check_not_stale, revoke, revoke_inner, *) +(* save_policy_settings, with_store; Change::is_high_risk *) +(* crates/aether-store/src/admin.rs apply_change, queue_change, *) +(* pending_revision, record_applied_change, admin_revision, *) +(* revert_change, confirm_pending_change, revoke_applied_grant, *) +(* set_current_workspace, grant_revoked *) +(* crates/aether/src/admin_socket.rs handle: Change, RevokeGrant and *) +(* UpdatePolicy always get AuditActor::Mcp; the socket has no *) +(* confirm request *) +(* crates/aether/src/admin_ui/advanced.rs the confirm and the policy *) +(* form of the UI (AuditActor::Ui) *) +(* crates/aether/src/policy.rs save_policy_settings_in_store, *) +(* stored_queue_limits *) +(* crates/aether/src/node_builder.rs the replay at node start: grants *) +(* of the policy file without the revoked ones, then the stored *) +(* grants, the stored limit, admin.current.workspace *) +(* crates/aether/src/node_service.rs impl LiveNode for RunningNode *) +(* *) +(* One process holds the Administration behind a mutex, so one request *) +(* runs at a time; `op` is that request between its store and node calls. *) +(* The process is `aether node serve` (mode "serve", with a live node) or *) +(* `aether node admin` (mode "admin", no live node). It can stop at any *) +(* step and start again. A store call can fail (StoreFaults). *) +(* *) +(* The MCP client is hostile inside its interface: it sends any socket *) +(* request in any order. It cannot sign a grant, but it can send again a *) +(* signed grant that it saw before. *) +(* *) +(* Abstracted away: dry runs, field validation, the 300 s expiry as a *) +(* clock (a pending change expires at any moment), the audit records *) +(* other than `applied` (an audit record has no value column, so it holds *) +(* no secret by its type), grant expiry and a stored grant that no longer *) +(* verifies at start, the approved-workspace set (a refusal is one *) +(* nondeterministic step), the two limit ids (one limit here), the *) +(* `admin..` values of workspace, capability and directory *) +(* changes (nothing reads them at start), set_relay, cancel_task, access *) +(* groups, and the two store writes of save_policy_settings_in_store, *) +(* which are one step here. A live revoke does not fail. *) +(***************************************************************************) +EXTENDS Naturals, FiniteSets + +CONSTANTS + Ids, \* change ids; a grant id is one of them + FileIds, \* ids of grants in the policy file (the owner wrote them) + MaxOps, \* bound on requests + MaxRestarts, \* bound on process stops + StoreFaults \* whether a store write can fail + +None == "none" +Actors == {"mcp", "ui"} +Kinds == {"grant", "workspace", "limit", "capability", "directory"} +\* "lo": a direct invite grant (direct::grant_is_low_risk_invite). "hi": +\* every other grant. +GVals == {"lo", "hi"} +WVals == {"w1", "w2"} +Limits == 1..3 +InitLimit == 2 +InitWs == "w1" + +\* The value of a change: `val` for a grant or a workspace, `num` for a +\* limit. Capability and directory changes have one value. +ValsOf(kind) == + CASE kind = "grant" -> [val : GVals, num : {0}] + [] kind = "workspace" -> [val : WVals, num : {0}] + [] kind = "limit" -> [val : {None}, num : Limits] + [] OTHER -> [val : {None}, num : {0}] + +\* Change::is_high_risk. +HighRisk(kind, v) == + \/ kind = "grant" /\ v.val = "hi" + \/ kind \in {"workspace", "capability"} + +Pcs == {"idle", "live", "ws_cur", "record", "revert", "rv_live", "rv_record"} + +VARIABLES + mode, \* "serve": a node runs in the process; "admin": none + op, \* the request that holds the Administration mutex + durGrant, \* store: admin.grant. + durLimit, \* store: admin.limit., 0 when not set + curWs, \* store: admin.current.workspace + pol, \* store: workspace and queue limit of the stored policy + revoked, \* store: admin.revoked. + pending, \* store: pending_changes and admin.pending_revision. + drev, \* store: admin.revision + mrev, \* Administration::revision, in memory + liveGrant, \* node: the grants of the live policy + liveLimit, \* node: the queue limit + liveWs, \* node: the workspace + liveCap, \* node: a capability was published + audits, \* store: the `applied` audit records + nOps, restarts, + \* Ghosts. + grOk, \* grants that a UI action asked for or confirmed + wsOk, \* workspaces that a UI action asked for or confirmed + limOk, \* the highest limit that a UI action asked for + capOk, \* a UI action confirmed a capability + wsPol, \* workspaces that MCP saved with UpdatePolicy + limPol, \* the highest limit that MCP saved with UpdatePolicy + dead, \* grants revoked, with no new apply of the id since + applies, \* changes and revokes that reached the node + lost, \* a live apply whose revision was not recorded + auditLost, \* an apply or revoke whose audit record was not written + faulted, \* a store write failed since the process started + mcpRevived, \* MCP applied a grant id that the owner had revoked + staleConfirmed, \* a confirm passed although a change landed after the queue + otherConfirmed \* the same, for a revoke or a policy save + +store == <> +node == <> +approvals == <> +flags == <> +vars == <> + +NoPending == [kind |-> None, val |-> None, num |-> 0, base |-> 0, + expired |-> FALSE, landed |-> "no"] +Idle == [pc |-> "idle", actor |-> "ui", kind |-> "grant", + id |-> CHOOSE i \in Ids : TRUE, val |-> None, num |-> 0, + prevVal |-> None, prevNum |-> 0] + +Max(a, b) == IF a >= b THEN a ELSE b + +TypeOK == + /\ mode \in {"serve", "admin"} + /\ op \in [pc : Pcs, actor : Actors, kind : Kinds, id : Ids, + val : GVals \cup WVals \cup {None}, num : 0..3, + prevVal : GVals \cup {None}, prevNum : 0..3] + /\ durGrant \in [Ids -> GVals \cup {None}] + /\ durLimit \in 0..3 + /\ curWs \in WVals \cup {None} + /\ pol \in [ws : WVals, limit : Limits] + /\ revoked \subseteq Ids + /\ pending \in [Ids -> [kind : Kinds \cup {None}, + val : GVals \cup WVals \cup {None}, num : 0..3, + base : 0..MaxOps, expired : BOOLEAN, + landed : {"no", "other", "change"}]] + /\ drev \in 0..MaxOps /\ mrev \in 0..MaxOps + /\ liveGrant \in [Ids -> GVals \cup {None}] + /\ liveLimit \in Limits + /\ liveWs \in WVals + /\ liveCap \in BOOLEAN + /\ audits \in 0..MaxOps /\ applies \in 0..MaxOps + /\ nOps \in 0..MaxOps /\ restarts \in 0..MaxRestarts + /\ grOk \subseteq Ids \X GVals + /\ wsOk \subseteq WVals /\ wsPol \subseteq WVals + /\ limOk \in Limits /\ limPol \in 0..3 + /\ capOk \in BOOLEAN + /\ dead \subseteq Ids + /\ lost \in BOOLEAN /\ auditLost \in BOOLEAN /\ faulted \in BOOLEAN + /\ mcpRevived \in BOOLEAN /\ staleConfirmed \in BOOLEAN + /\ otherConfirmed \in BOOLEAN + +\* node_builder: the grants that a node start makes live. The policy file +\* grants without the revoked ones, then each stored grant, which replaces +\* a file grant of the same id. +StartGrant(id) == + IF durGrant[id] # None THEN durGrant[id] + ELSE IF id \in FileIds /\ id \notin revoked THEN "hi" + ELSE None + +Init == + /\ mode = "serve" + /\ op = Idle + /\ durGrant = [id \in Ids |-> None] + /\ durLimit = 0 + /\ curWs = None + /\ pol = [ws |-> InitWs, limit |-> InitLimit] + /\ revoked = {} + /\ pending = [id \in Ids |-> NoPending] + /\ drev = 0 /\ mrev = 0 + /\ liveGrant = [id \in Ids |-> IF id \in FileIds THEN "hi" ELSE None] + /\ liveLimit = InitLimit + /\ liveWs = InitWs + /\ liveCap = FALSE + /\ audits = 0 /\ applies = 0 /\ nOps = 0 /\ restarts = 0 + /\ grOk = FileIds \X {"hi"} + /\ wsOk = {InitWs} /\ wsPol = {} + /\ limOk = InitLimit /\ limPol = 0 + /\ capOk = FALSE + /\ dead = {} + /\ lost = FALSE /\ auditLost = FALSE /\ faulted = FALSE + /\ mcpRevived = FALSE /\ staleConfirmed = FALSE /\ otherConfirmed = FALSE + +Fault == StoreFaults + +\* Something landed: each pending change remembers it (ghost). +Landed(p, what) == + [id \in Ids |-> + IF p[id].kind = None \/ p[id].landed = "change" THEN p[id] + ELSE [p[id] EXCEPT !.landed = what]] + +\* What a UI action approves (ghost). +Approve(kind, id, v) == + /\ grOk' = IF kind = "grant" THEN grOk \cup {<>} ELSE grOk + /\ wsOk' = IF kind = "workspace" THEN wsOk \cup {v.val} ELSE wsOk + /\ limOk' = IF kind = "limit" THEN Max(limOk, v.num) ELSE limOk + /\ capOk' = (capOk \/ kind = "capability") + /\ UNCHANGED <> + +----------------------------------------------------------------------------- +(* A change request: the socket's `Change` (MCP), or a UI action that *) +(* applies a change (the invite page, the consent page, the hub workers). *) + +\* change_requires_confirmation. A limit from MCP is free only when the +\* live node reads a limit that is not lower. +NeedsConfirmation(actor, kind, v) == + /\ actor = "mcp" + /\ IF kind = "limit" + THEN ~(mode = "serve" /\ v.num <= liveLimit) + ELSE HighRisk(kind, v) + +\* Administration::apply -> queue_pending -> queue_change. The row's key is +\* the id alone, so a second row for the id is a store error. +Queue(actor, kind, id, v) == + /\ op.pc = "idle" /\ nOps < MaxOps + /\ NeedsConfirmation(actor, kind, v) + /\ nOps' = nOps + 1 + /\ IF pending[id].kind = None + THEN \/ pending' = [pending EXCEPT ![id] = + [kind |-> kind, val |-> v.val, num |-> v.num, + base |-> mrev, expired |-> FALSE, landed |-> "no"]] + \/ Fault /\ UNCHANGED pending + ELSE UNCHANGED pending + /\ UNCHANGED <> + +\* Administration::apply -> apply_now, first half: apply_change keeps the +\* value in the store and returns the value that it replaced. +ApplyNow(actor, kind, id, v) == + /\ op.pc = "idle" /\ nOps < MaxOps + /\ ~NeedsConfirmation(actor, kind, v) + /\ nOps' = nOps + 1 + /\ \/ /\ op' = [pc |-> "live", actor |-> actor, kind |-> kind, id |-> id, + val |-> v.val, num |-> v.num, + prevVal |-> IF kind = "grant" THEN durGrant[id] ELSE None, + prevNum |-> IF kind = "limit" THEN durLimit ELSE 0] + /\ durGrant' = IF kind = "grant" THEN [durGrant EXCEPT ![id] = v.val] + ELSE durGrant + /\ durLimit' = IF kind = "limit" THEN v.num ELSE durLimit + /\ dead' = IF kind = "grant" THEN dead \ {id} ELSE dead + /\ mcpRevived' = (mcpRevived \/ (actor = "mcp" /\ kind = "grant" + /\ id \in revoked)) + /\ IF actor = "ui" THEN Approve(kind, id, v) ELSE UNCHANGED approvals + \/ /\ Fault + /\ UNCHANGED <> + /\ UNCHANGED <> + +\* Administration::confirm_ui -> confirm_pending: only the UI calls it. +\* check_not_stale compares the revision of the queue with the revision in +\* memory. confirm_pending_change refuses an expired row; else it keeps +\* the value and deletes the row in one transaction. +Confirm(id) == + /\ op.pc = "idle" /\ nOps < MaxOps + /\ pending[id].kind # None + /\ nOps' = nOps + 1 + /\ LET p == pending[id] + v == [val |-> p.val, num |-> p.num] + IN IF p.base # mrev \/ p.expired + THEN UNCHANGED <> + ELSE \/ /\ op' = [pc |-> "live", actor |-> "ui", kind |-> p.kind, + id |-> id, val |-> p.val, num |-> p.num, + prevVal |-> IF p.kind = "grant" THEN durGrant[id] + ELSE None, + prevNum |-> IF p.kind = "limit" THEN durLimit ELSE 0] + /\ durGrant' = IF p.kind = "grant" + THEN [durGrant EXCEPT ![id] = p.val] ELSE durGrant + /\ durLimit' = IF p.kind = "limit" THEN p.num ELSE durLimit + /\ pending' = [pending EXCEPT ![id] = NoPending] + /\ dead' = IF p.kind = "grant" THEN dead \ {id} ELSE dead + /\ Approve(p.kind, id, v) + /\ staleConfirmed' = (staleConfirmed \/ p.landed = "change") + /\ otherConfirmed' = (otherConfirmed \/ p.landed = "other") + \/ /\ Fault + /\ UNCHANGED <> + /\ UNCHANGED <> + +\* The live value is in the node: apply_live adds one to the revision in +\* memory. +LiveDone == + /\ mrev' = mrev + 1 + /\ applies' = applies + 1 + /\ pending' = Landed(pending, "change") + /\ op' = [op EXCEPT !.pc = "record"] + +\* finish_live -> apply_live -> apply_live_inner. Without a live node, a +\* grant, a limit and a workspace count as applied; a directory and a +\* capability change are unsupported. The node can refuse a grant (it does +\* not verify), a workspace (not approved), a directory and a capability. +ApplyLive == + /\ op.pc = "live" + /\ LET refuse == /\ op' = [op EXCEPT !.pc = "revert"] + /\ UNCHANGED <> + IN CASE op.kind = "grant" -> + \/ /\ LiveDone + /\ liveGrant' = IF mode = "serve" + THEN [liveGrant EXCEPT ![op.id] = op.val] + ELSE liveGrant + /\ UNCHANGED <> + \/ mode = "serve" /\ refuse + [] op.kind = "limit" -> + /\ LiveDone + /\ liveLimit' = IF mode = "serve" THEN op.num ELSE liveLimit + /\ UNCHANGED <> + [] op.kind = "workspace" -> + \/ /\ liveWs' = IF mode = "serve" THEN op.val ELSE liveWs + /\ op' = [op EXCEPT !.pc = "ws_cur"] + /\ UNCHANGED <> + \/ mode = "serve" /\ refuse + [] op.kind = "capability" -> + \/ /\ mode = "serve" + /\ LiveDone + /\ liveCap' = TRUE + /\ UNCHANGED <> + \/ refuse + [] OTHER -> + \/ mode = "serve" /\ LiveDone /\ UNCHANGED node + \/ refuse + /\ UNCHANGED <> + +\* apply_live_inner, the workspace branch after the node moved: +\* set_current_workspace. When it fails, finish_live reverts the store +\* value, but the node keeps the new workspace. +SetCurrentWorkspace == + /\ op.pc = "ws_cur" + /\ \/ /\ curWs' = op.val + /\ LiveDone + /\ UNCHANGED faulted + \/ /\ Fault + /\ faulted' = TRUE + /\ op' = [op EXCEPT !.pc = "revert"] + /\ UNCHANGED <> + /\ UNCHANGED <> + +\* finish_live, the success branch: record_applied_change writes the new +\* revision and the audit record in one transaction. +Record == + /\ op.pc = "record" + /\ op' = Idle + /\ \/ /\ drev' = mrev + /\ audits' = audits + 1 + /\ UNCHANGED <> + \/ /\ Fault + /\ lost' = TRUE /\ auditLost' = TRUE /\ faulted' = TRUE + /\ UNCHANGED <> + /\ UNCHANGED <> + +\* finish_live, the failure branch: revert_change puts back the value that +\* the change replaced. +Revert == + /\ op.pc = "revert" + /\ op' = Idle + /\ \/ /\ durGrant' = IF op.kind = "grant" + THEN [durGrant EXCEPT ![op.id] = op.prevVal] + ELSE durGrant + /\ durLimit' = IF op.kind = "limit" THEN op.prevNum ELSE durLimit + /\ UNCHANGED faulted + \/ /\ Fault + /\ faulted' = TRUE + /\ UNCHANGED <> + /\ UNCHANGED <> + +----------------------------------------------------------------------------- +(* Revoke and the policy settings. *) + +\* Administration::revoke -> revoke_inner, first half: +\* revoke_applied_grant removes the stored grant and keeps the mark. A +\* process without a node refuses. The socket's RevokeGrant (MCP) asks +\* first that the live policy has the grant. +Revoke(actor, id) == + /\ op.pc = "idle" /\ nOps < MaxOps + /\ mode = "serve" + /\ actor = "mcp" => liveGrant[id] # None + /\ nOps' = nOps + 1 + /\ \/ /\ revoked' = revoked \cup {id} + /\ durGrant' = [durGrant EXCEPT ![id] = None] + /\ op' = [Idle EXCEPT !.pc = "rv_live", !.actor = actor, !.id = id] + \/ Fault /\ UNCHANGED <> + /\ UNCHANGED <> + +\* revoke_inner: LiveNode::revoke_grant. It does not change the revision. +RevokeLive == + /\ op.pc = "rv_live" + /\ liveGrant' = [liveGrant EXCEPT ![op.id] = None] + /\ dead' = dead \cup {op.id} + /\ applies' = applies + 1 + /\ pending' = Landed(pending, "other") + /\ op' = [op EXCEPT !.pc = "rv_record"] + /\ UNCHANGED <> + +\* revoke_inner: record_change. +RevokeRecord == + /\ op.pc = "rv_record" + /\ op' = Idle + /\ \/ audits' = audits + 1 /\ UNCHANGED <> + \/ Fault /\ auditLost' = TRUE /\ faulted' = TRUE /\ UNCHANGED audits + /\ UNCHANGED <> + +\* The socket's UpdatePolicy (MCP, the tool aether.settings.update_policy) +\* and the UI's policy form -> Administration::save_policy_settings -> +\* save_policy_settings_in_store. It keeps the workspace and the limit in +\* the stored policy and removes the stored limit of `aether.change`. No +\* actor needs a confirmation. The running node keeps its settings until +\* it starts again. +UpdatePolicy(actor, w, l) == + /\ op.pc = "idle" /\ nOps < MaxOps + /\ nOps' = nOps + 1 + /\ \/ /\ pol' = [ws |-> w, limit |-> l] + /\ durLimit' = 0 + /\ applies' = applies + 1 + /\ pending' = Landed(pending, "other") + /\ IF actor = "ui" + THEN /\ wsOk' = wsOk \cup {w} /\ limOk' = Max(limOk, l) + /\ UNCHANGED <> + ELSE /\ wsPol' = wsPol \cup {w} /\ limPol' = Max(limPol, l) + /\ UNCHANGED <> + /\ \/ audits' = audits + 1 /\ UNCHANGED <> + \/ Fault /\ auditLost' = TRUE /\ faulted' = TRUE /\ UNCHANGED audits + \/ /\ Fault + /\ UNCHANGED <> + /\ UNCHANGED <> + +----------------------------------------------------------------------------- +(* The environment. *) + +\* 300 s pass after the queue. No function deletes an expired row. +Expire(id) == + /\ pending[id].kind # None /\ ~pending[id].expired + /\ pending' = [pending EXCEPT ![id].expired = TRUE] + /\ UNCHANGED <> + +\* The process stops at any step and starts again, with or without a +\* node. Administration::with_store reads the stored revision. A node +\* start replays the store (node_builder). A stop between the live apply +\* and record_applied_change loses the new revision and the audit record. +Restart(m) == + /\ restarts < MaxRestarts + /\ restarts' = restarts + 1 + /\ mode' = m + /\ op' = Idle + /\ mrev' = drev + /\ lost' = (lost \/ op.pc = "record") + /\ auditLost' = (auditLost \/ op.pc \in {"record", "rv_record"}) + /\ faulted' = FALSE + /\ liveGrant' = [id \in Ids |-> IF m = "serve" THEN StartGrant(id) ELSE None] + /\ liveLimit' = IF durLimit # 0 THEN durLimit ELSE pol.limit + /\ liveWs' = IF curWs # None THEN curWs ELSE pol.ws + /\ liveCap' = FALSE + /\ UNCHANGED <> + +Next == + \/ \E actor \in Actors, kind \in Kinds, id \in Ids : + \E v \in ValsOf(kind) : + Queue(actor, kind, id, v) \/ ApplyNow(actor, kind, id, v) + \/ \E id \in Ids : Confirm(id) \/ Expire(id) + \/ \E actor \in Actors, id \in Ids : Revoke(actor, id) + \/ \E actor \in Actors, w \in WVals, l \in Limits : UpdatePolicy(actor, w, l) + \/ ApplyLive \/ SetCurrentWorkspace \/ Record \/ Revert + \/ RevokeLive \/ RevokeRecord + \/ \E m \in {"serve", "admin"} : Restart(m) + +\* A request that started goes on to its end. +Fairness == + /\ WF_vars(ApplyLive) /\ WF_vars(SetCurrentWorkspace) /\ WF_vars(Record) + /\ WF_vars(Revert) /\ WF_vars(RevokeLive) /\ WF_vars(RevokeRecord) + +Spec == Init /\ [][Next]_vars /\ Fairness + +----------------------------------------------------------------------------- +(* Safety. *) + +\* A high-risk grant is in the store or in the live policy only when a UI +\* action asked for or confirmed that grant: the same id and value. The +\* socket has no confirm request, and the actor of a socket request is +\* always MCP, so an MCP client cannot lower the risk of its change. +HighRiskGrantNeedsUi == + \A id \in Ids : + (durGrant[id] = "hi" \/ liveGrant[id] = "hi") => <> \in grOk + +\* A capability is published only after a UI confirmation. +CapabilityNeedsUi == liveCap => capOk + +\* A pending change is not in force: its value reaches the store and the +\* node only through Confirm. The workspace that a change made live, and +\* the stored limit, come from a UI action, or the limit is not higher +\* than a limit that the node already had. +ChangeNeedsUi == + /\ curWs # None => curWs \in wsOk + /\ durLimit <= Max(limOk, limPol) + +\* The live workspace and limit come from a UI action or from a saved +\* policy (UpdatePolicy), from the UI or from MCP. +LiveFromUiOrPolicy == + /\ liveWs \in wsOk \cup wsPol + /\ liveLimit <= Max(limOk, limPol) + +\* After each complete request, the node and the store agree, unless a +\* store write failed since the process started. +Agree == + /\ \A id \in Ids : liveGrant[id] = StartGrant(id) + /\ curWs # None => liveWs = curWs + /\ durLimit # 0 => liveLimit = durLimit +LiveMatchesStore == + (mode = "serve" /\ op.pc = "idle" /\ ~faulted) => Agree + +\* A revoked grant is not live and not in the store, and a node start does +\* not bring it back, until someone applies a grant with that id again. +RevokedStaysOut == + \A id \in dead : liveGrant[id] = None /\ durGrant[id] = None + +\* A confirmation is refused when another change was applied after the +\* queue, as long as each applied change recorded its revision. +StaleRefusedWhileRecorded == staleConfirmed => lost + +\* Each change that reached the node has one `applied` audit record, as +\* long as each record was written. +AuditedWhileRecorded == + /\ audits <= applies + /\ (op.pc = "idle" /\ ~auditLost) => audits = applies + +\* A pending row that expired never changes (but for the ghost `landed`) +\* and never leaves the table: +\* only confirm_pending_change deletes a row, and it refuses this one. The +\* row's key is the id, so no change with this id can be queued again (see +\* Queue). +ExpiredRowStays == + [][\A id \in Ids : + (pending[id].kind # None /\ pending[id].expired) + => [pending'[id] EXCEPT !.landed = "no"] + = [pending[id] EXCEPT !.landed = "no"]]_vars + +(***************************************************************************) +(* Properties that TLC finds false. They are not in PendingChange.cfg; *) +(* each comment gives the counterexample. *) +(***************************************************************************) + +\* FALSE: the live workspace and limit come from a UI action only. +\* UpdatePolicy("mcp", w2, 3), Restart("serve"): the node starts in w2 +\* with the limit 3. admin_socket.rs gives UpdatePolicy to +\* save_policy_settings with no confirmation, and node_builder reads the +\* stored policy at start. An `aether.change` for the same workspace or +\* limit waits for the UI. +LiveFromUi == + /\ liveWs \in wsOk + /\ liveLimit <= limOk + +\* FALSE: a stale confirmation is always refused. MCP queues a change at +\* revision 0; the UI applies another change; the process stops after +\* apply_live and before record_applied_change; it starts again with the +\* stored revision 0, and Confirm passes. The store value of the other +\* change was written first, so a node start makes it live. +StaleRefused == ~staleConfirmed + +\* FALSE (by design): a revoke or a policy save after the queue makes the +\* confirmation stale. Neither changes the revision. +StaleSeesRevoke == ~otherConfirmed + +\* FALSE (by design): only the owner brings back a grant id that the owner +\* revoked. The UI applies a low-risk grant, the UI revokes it, and MCP +\* sends the same signed grant in a Change: it is low risk, so it applies. +\* The revoked mark only stops a grant of the policy file. +NoMcpRevival == ~mcpRevived + +\* FALSE with a store fault: the node and the store agree after each +\* complete request. (1) A workspace change moves the node, then +\* set_current_workspace fails, and revert_change restores the store only. +\* (2) The node refuses a grant and revert_change fails: the store keeps +\* the grant, the caller reads an error, and the next start makes it live. +LiveMatchesStoreAlways == (mode = "serve" /\ op.pc = "idle") => Agree + +\* FALSE with a store fault or a stop: each applied change has an audit +\* record. record_applied_change runs after the node has the change. +Audited == op.pc = "idle" => audits = applies + +(***************************************************************************) +(* Liveness. *) +(***************************************************************************) + +\* A request that holds the mutex ends: it is recorded or reverted, or the +\* process stops. +RequestEnds == (op.pc # "idle") ~> (op.pc = "idle") + +============================================================================= diff --git a/specs/README.md b/specs/README.md index 70417fb..faea214 100644 --- a/specs/README.md +++ b/specs/README.md @@ -8,19 +8,49 @@ change the model in the same commit. | Model | Code | Checked properties | |---|---|---| -| `ExecutionLease` | `NodeStore` lease functions, `SchedulerContext` in `proof.rs`, `Agent::cancel` | A lease row exists only while a task is leased or running; a turn starts at most once for a task; a live turn's task is running, cancelled, or `unknown_result`; every cancel reaches the turn (liveness) | +| `DirectInvite` | `invites.rs`, `join_and_apply` in `access_groups.rs`, `import_bundle` and the contact functions in `direct.rs`, `PolicyEngine::admit`, `check_group` | A call that failed leaves no grant; the host admits a request only from an endpoint that the owner invited, with a claim signed for that endpoint, so a copied line gives nothing; the caller keeps only an authorization for its own endpoint; one contact name for one endpoint; a valid contact's name stays with its endpoint; each invite call ends (liveness) | +| `Admission` | `a2a_transport.rs`, `proof/admission.rs`, `PolicyEngine::admit`, `admit_with_replay` and `cancel_if_owned` in `aether-store/src/tasks.rs` | A task's owner is the authenticated endpoint, which had a live grant and a group membership; one task for each endpoint and idempotency key; a refused, replayed or changed frame changes nothing; the queue stays within its limits; no answer shows another endpoint's task; only the owner cancels; an honest caller with access gets its task in (liveness) | +| `ExecutionLease` | `NodeStore` lease functions, `SchedulerContext` in `proof/scheduler.rs`, `Agent::cancel` and `EarlyCancels` in `agent.rs` | A lease row exists only while a task is leased or running; a turn starts at most once for a task; a live turn's task is running, cancelled, or `unknown_result`; a cancel that an earlier run left does not stop a turn; every cancel reaches the turn (liveness) | +| `ConnectedAgent` | `agent/connected.rs`, `EarlyCancels` in `agent.rs`, `protocol/agent-socket` | An open task ID belongs to a running turn on that connection; an answer comes only from the agent of the turn's connection; a turn ends once; no agent, no task sent; a cancel before the start cancels the turn, and a cancel after the end is not kept; every turn ends with its time limit, and a turn on a closed or replaced connection or with a cancelled honest agent stops (liveness) | +| `EventPaging` | `events_page`, `task_progress` and the event writers in `aether-store/src/tasks.rs`, `A2aTransport::handle`, `request_with_polling_on`, `follow` in `outbox.rs` | Event sequences have no gap and never change; a page is the ordered run after the caller's cursor; a page says "no more events" only at the end of the journal; the state and the page are from one instant; the cursor never moves back; a `node request` that stops with an answer has every event up to the one that ended the task; an ended task lets the caller stop (liveness) | | `Outbox` | `outbox.rs`, `sent_tasks` store functions, host admission | The host keeps one task for each sent task; an answer comes only from the host; a task that the host runs never shows as failed after a replay; an attempt whose lease another process claimed records nothing; an ended task does not change; each task ends (liveness) | | `HubInvite` | `hub_sync.rs`, `hub_membership.rs`, `admin_ui/hub.rs` workers, `server/lib/aether_hub` | A grant only for an approved row and its first endpoint; no grant for a blocked endpoint; one live grant for each approval, also when the store fails; a kept line belongs to the approval it was signed for; the caller keeps only lines that it accepted; an honest hub delivers an accepted invite (liveness) | +| `ManagedRoster` | `managed_client.rs`, `directory_client.rs`, `control_service.rs`, `aether-store/src/{managed,directory,control}.rs`, `RosterClaims::verify` in `identity.rs` | A token makes one member; a roster row comes from a join event; a claim admits work only for a member that joined; with one control URL the roster is exactly the events up to the cursor and a revoke stays; a cursor never moves back or skips; the caller uses only an unexpired record of the trusted key and its scope, also with an attacker directory; a revoke reaches a node that keeps syncing, and directory events reach it unless the log is poisoned (liveness) | +| `PendingChange` | `admin.rs` (`Administration`), `aether-store/src/admin.rs`, `admin_socket.rs`, the start replay in `node_builder.rs` | A high-risk grant or a capability is live or stored only after a UI action for that id and value; a workspace or limit is live only from a UI action or a saved policy; the node and the store agree after each request unless a store write failed; a revoked grant stays out, also after a restart; a stale confirmation is refused while each revision was recorded; an expired pending row never leaves; each request ends (liveness) | | `PactConsent` | `pact/`, `aether-store/src/pact.rs`, the dispatch recheck in `proof.rs` | One token for each device code; no token from a denied code; no task without a token; a failed approval leaves no grant; no task starts after its grant is revoked; an approved flow gets a token, and an admitted task ends (liveness) | ## Properties that are not checked -These properties are in the models but not in the `.cfg` files. The -comment above each one says why. +These properties are in the models but not in the `.cfg` files, because +TLC finds them false. The comment above each one gives the trace. "By +design" marks a property that the code does not intend to keep. The others +describe what the code does today. | Model | Property | Why | |---|---|---| +| `DirectInvite` | `ReturnedLineWorks` | Two calls of `sign_direct_invite` for one person share no lock: one fails and takes the person out of the group, the other returns its line. The grant is live but `check_group` refuses every request. | +| `DirectInvite` | `NoStrayMember` | In the same race, two failed calls can leave the person in the group. Without a grant the person gets no task in. | +| `Admission` | `NoTaskIdClash` | `tasks.id` is unique for the whole table, so a caller that reuses another endpoint's task ID blocks it. The random UUID keeps callers apart. | +| `Admission` | `NoSharedQuota` | The per-peer limit counts by agent name, so two endpoints that the owner invited under one name share it. | +| `Admission` | `NoReplayBeforeExpiry` | At `REPLAY_LIMIT` the oldest replay entry goes before its TTL. The idempotency key still gives one task. | +| `ConnectedAgent` | `NoLostCancel` | `run_turn` puts the task in `pending` before it writes `task`, so a cancel can reach the agent first. The second cancel from the lease renewal stops the turn. | +| `ConnectedAgent` | `NoOrphanWait` | An agent that closes only its sending side, in a race with the start of a turn, leaves the turn waiting until its time limit. | +| `ConnectedAgent` | `NoStaleCancel` | A cancel between `pending.remove` and `cancels.end` is kept. The node starts one turn for a task ID. | +| `ConnectedAgent` | `TaskOnlyToAttached`, `AnswerWhileAttached` | `serve` can replace the connection after a turn took it. The answer is still from the agent that got the task. | +| `ConnectedAgent` | `AnswerAfterSent` | By design, the agent is a process of the owner. It holds when a task ID gets one turn. | +| `EventPaging` | `OutboxReadsToEnd` | `follow` stops on the task status and does not read `aetherMoreEvents`. The outbox keeps only the answer, so only its stored cursor is short. | | `HubInvite` | `GrantToTypedName` | By design, the hub resolves the invite name, so an attacker hub chooses it. | | `HubInvite` | `KeptLineFromNamedHost` | By design, for an invite the caller takes the sender endpoint from the hub. A request checks the listing key. | +| `ManagedRoster` | `RevokeStays`, `EveryKeyCatchesUp` | The roster cursor is keyed by control URL but the roster is not: a second spelling of the URL replays the join over a revoke, or stops at the revoke for ever. | +| `ManagedRoster` | `NoAdmitAfterServiceRevoke` | By design, a revoke reaches the node at its next sync. | +| `ManagedRoster` | `ResolveIsForAgent` | `request_via_directory` does not compare the resolved record's agent ID with the one asked for. | +| `ManagedRoster` | `RevokedStaysOut` | Publish and revoke need only the signed record, which is public. | +| `ManagedRoster` | `DirSyncCatchesUp` | An expired or other-key record in the event log fails every later page. | | `Outbox` | `OneAttempt` | Two processes can work on one task when an attempt takes longer than the 90 s `LEASE`. `NoStaleRecord` checks that the late attempt changes nothing. | | `PactConsent` | `StartCovered` | A grant can expire between the dispatch recheck and `mark_running`. Expiry has no lock; `StartNotRevoked` checks revocation. | +| `PendingChange` | `LiveFromUi` | The MCP `UpdatePolicy` request saves a workspace and a higher limit with no confirmation; they apply at the next start. | +| `PendingChange` | `StaleRefused` | A stop between `apply_live` and `record_applied_change` loses the revision. | +| `PendingChange` | `StaleSeesRevoke` | By design, a revoke and a policy save do not change the revision. | +| `PendingChange` | `NoMcpRevival` | By design, a low-risk grant applies without confirmation, also for a revoked ID. | +| `PendingChange` | `LiveMatchesStoreAlways` | A failed `set_current_workspace` or `revert_change` leaves the node and the store different. | +| `PendingChange` | `Audited` | The audit record is written after the node has the change. | From 77f9c52fa04b40504986fc17ca0dc62d90ec5159 Mon Sep 17 00:00:00 2001 From: TudorAndrei Date: Thu, 12 Nov 2026 13:16:40 +0200 Subject: [PATCH 3/3] fix: close the races and gaps that the TLA+ models found Invites: one sign_direct_invite call at a time. Admission: per-peer limit by endpoint, no early replay eviction, node-made IDs on a task ID clash. Connected agent: no cancel before its task, no turn on a connection that is over, no cancel kept after its turn. Outbox: follow reads to the last event page. Rosters: a revoke stays, a resolved record is for the agent asked for, directory sync skips a record it cannot use, a revoked record cannot be published again. Admin: MCP policy changes that widen access need confirmation, and a change is stored with its revision and audit record before it goes live. Each model now checks the property that was false. Co-Authored-By: Claude Fable 5.2 --- .../control/006_directory_record_marks.sql | 11 + .../migrations/node/018_task_caller_ids.sql | 9 + crates/aether-store/src/admin.rs | 255 +++++++-- crates/aether-store/src/control.rs | 105 +++- crates/aether-store/src/lib.rs | 2 + crates/aether-store/src/managed.rs | 49 +- crates/aether-store/src/tasks.rs | 210 ++++++-- crates/aether/src/a2a_transport.rs | 17 +- crates/aether/src/admin.rs | 354 ++++++++++--- crates/aether/src/admin_socket.rs | 8 +- crates/aether/src/admin_ui/advanced.rs | 9 +- crates/aether/src/admin_ui/listing.rs | 8 +- crates/aether/src/agent.rs | 11 +- crates/aether/src/agent/connected.rs | 207 ++++++-- crates/aether/src/control_service.rs | 62 ++- crates/aether/src/directory_client.rs | 233 ++++++++- crates/aether/src/invites.rs | 88 ++++ crates/aether/src/mcp/tools/admin.rs | 47 +- crates/aether/src/node_builder.rs | 4 + crates/aether/src/node_service.rs | 12 +- crates/aether/src/outbox.rs | 95 +++- crates/aether/src/policy.rs | 10 +- crates/aether/src/proof/mod.rs | 32 +- docs/usage.md | 7 +- specs/Admission.cfg | 12 +- specs/Admission.tla | 226 ++++---- specs/ConnectedAgent.cfg | 13 +- specs/ConnectedAgent.tla | 323 ++++++------ specs/DirectInvite.cfg | 7 +- specs/DirectInvite.tla | 53 +- specs/EventPaging.cfg | 4 +- specs/EventPaging.tla | 36 +- specs/ExecutionLease.tla | 3 +- specs/ManagedRoster.cfg | 18 +- specs/ManagedRoster.tla | 251 +++++---- specs/PendingChange.cfg | 14 +- specs/PendingChange.tla | 484 ++++++++---------- specs/README.md | 37 +- 38 files changed, 2297 insertions(+), 1029 deletions(-) create mode 100644 crates/aether-store/migrations/control/006_directory_record_marks.sql create mode 100644 crates/aether-store/migrations/node/018_task_caller_ids.sql diff --git a/crates/aether-store/migrations/control/006_directory_record_marks.sql b/crates/aether-store/migrations/control/006_directory_record_marks.sql new file mode 100644 index 0000000..85c1f41 --- /dev/null +++ b/crates/aether-store/migrations/control/006_directory_record_marks.sql @@ -0,0 +1,11 @@ +-- For each agent ID and signing key: the latest expiry of a record that the +-- directory took, and the latest expiry at the last revocation. A record +-- that does not expire after `revoked_through` was public before the +-- revocation, so anyone could send it again; the directory refuses it. +CREATE TABLE directory_record_marks ( + agent_id TEXT NOT NULL, + signing_key BLOB NOT NULL, + latest_expires_at INTEGER NOT NULL, + revoked_through INTEGER, + PRIMARY KEY(agent_id, signing_key) +); diff --git a/crates/aether-store/migrations/node/018_task_caller_ids.sql b/crates/aether-store/migrations/node/018_task_caller_ids.sql new file mode 100644 index 0000000..c21d134 --- /dev/null +++ b/crates/aether-store/migrations/node/018_task_caller_ids.sql @@ -0,0 +1,9 @@ +-- The caller chooses the task ID and the request ID, and `tasks.id` and +-- `tasks.request_id` are unique for the whole table. When another endpoint +-- already has a row with one of them, the new row gets IDs that the node +-- makes, and these columns keep the IDs that the caller sent. NULL: the row +-- has the caller's IDs. +ALTER TABLE tasks ADD COLUMN caller_task_id TEXT; +ALTER TABLE tasks ADD COLUMN caller_request_id TEXT; + +CREATE INDEX tasks_caller_task_index ON tasks(caller_endpoint_id, caller_task_id); diff --git a/crates/aether-store/src/admin.rs b/crates/aether-store/src/admin.rs index 6a500c8..d4187f8 100644 --- a/crates/aether-store/src/admin.rs +++ b/crates/aether-store/src/admin.rs @@ -18,6 +18,8 @@ pub enum ChangeKind { Directory, Capability, Limit, + /// The policy settings that an MCP client asked to save. + Policy, } aether_core::named!(ChangeKind { @@ -26,11 +28,18 @@ aether_core::named!(ChangeKind { Directory => "directory", Capability => "capability", Limit => "limit", + Policy => "policy", }); impl ChangeKind { - const ALL: [Self; 5] = - [Self::Workspace, Self::Grant, Self::Directory, Self::Capability, Self::Limit]; + const ALL: [Self; 6] = [ + Self::Workspace, + Self::Grant, + Self::Directory, + Self::Capability, + Self::Limit, + Self::Policy, + ]; } #[derive(Debug, Clone, Copy, Eq, PartialEq)] @@ -87,6 +96,18 @@ pub struct AuditRecord { pub result: AuditResult, } +/// What an applied change replaced, so that [`NodeStore::revert_change`] +/// can put it back. +#[derive(Debug, Clone, Eq, PartialEq)] +pub struct Replaced { + /// The value of the change's id; `None` when the change created it. + pub value: Option, + /// The current workspace; read only for a workspace change. + workspace: Option, + /// The audit record of the change. + audit: i64, +} + fn change_key(kind: ChangeKind, id: &str) -> String { format!("admin.{}.{id}", kind.as_str()) } @@ -113,15 +134,58 @@ const CURRENT_WORKSPACE_KEY: &str = "admin.current.workspace"; /// revision is stale. const REVISION_KEY: &str = "admin.revision"; +/// Writes an audit record and returns its row id. fn audit( connection: &Connection, actor: AuditActor, result: AuditResult, -) -> Result<(), StoreError> { +) -> Result { connection.execute( "INSERT INTO audit_records(actor_type,action,result,created_at) VALUES(?1,?2,?3,?4)", params![actor, AuditAction::Change, result, now()], )?; + Ok(connection.last_insert_rowid()) +} + +/// Keeps `value` as the applied change `id` of `kind`, with the admin +/// `revision` that it moves the node to and its `applied` audit record. A +/// workspace change also becomes the current workspace. The caller commits. +fn keep_change( + transaction: &Connection, + kind: ChangeKind, + id: &str, + value: &str, + actor: AuditActor, + revision: u64, +) -> Result { + let key = change_key(kind, id); + let previous = config::get(transaction, &key)?; + config::put(transaction, &key, value)?; + let workspace = if kind == ChangeKind::Workspace { + let workspace = config::get(transaction, CURRENT_WORKSPACE_KEY)?; + config::put(transaction, CURRENT_WORKSPACE_KEY, value)?; + workspace + } else { + None + }; + config::put(transaction, REVISION_KEY, &revision.to_string())?; + let audit = audit(transaction, actor, AuditResult::Applied)?; + Ok(Replaced { value: previous, workspace, audit }) +} + +/// Removes each expired pending change with its revision. +fn delete_expired(transaction: &Connection) -> Result<(), StoreError> { + let expired = { + let mut statement = transaction + .prepare("SELECT id FROM pending_changes WHERE expires_at<=?1")?; + statement + .query_map([now()], |row| row.get::<_, String>(0))? + .collect::, _>>()? + }; + for id in expired { + transaction.execute("DELETE FROM pending_changes WHERE id=?1", [&id])?; + config::delete(transaction, &pending_revision_key(&id))?; + } Ok(()) } @@ -160,24 +224,29 @@ impl NodeStore { config::delete(&self.connection, &change_key(kind, id)) } - /// Keeps `value` as the applied change `id` of `kind`, and returns the - /// value it replaced. + /// Keeps `value` as the applied change `id` of `kind` in one + /// transaction with the admin `revision` it moves the node to and its + /// audit record, and returns what it replaced. The caller applies the + /// change to the running node after this, so a process that stops in + /// between has the revision and the record, and its next start makes + /// the value live. pub fn apply_change( &mut self, kind: ChangeKind, id: &str, value: &str, - ) -> Result, StoreError> { + actor: AuditActor, + revision: u64, + ) -> Result { let transaction = self.connection.transaction()?; - let key = change_key(kind, id); - let previous = config::get(&transaction, &key)?; - config::put(&transaction, &key, value)?; + let replaced = keep_change(&transaction, kind, id, value, actor, revision)?; transaction.commit()?; - Ok(previous) + Ok(replaced) } /// Queues the change `id` until the owner confirms it, with the admin - /// `revision` it was queued at. + /// `revision` it was queued at. An expired change leaves first, so that + /// its id is free again. pub fn queue_change( &mut self, kind: ChangeKind, @@ -187,6 +256,7 @@ impl NodeStore { revision: u64, ) -> Result<(), StoreError> { let transaction = self.connection.transaction()?; + delete_expired(&transaction)?; transaction.execute( "INSERT INTO pending_changes(id,change_type,value,expires_at) VALUES(?1,?2,?3,?4)", params![id, kind, value, expires_at], @@ -205,25 +275,21 @@ impl NodeStore { .transpose() } + /// Writes an audit record and returns its id for [`Self::fail_change`]. pub fn record_change( &self, actor: AuditActor, result: AuditResult, - ) -> Result<(), StoreError> { + ) -> Result { audit(&self.connection, actor, result) } - /// Records that `actor` applied a change live, which moved the admin - /// revision to `revision`. - pub fn record_applied_change( - &mut self, - actor: AuditActor, - revision: u64, - ) -> Result<(), StoreError> { - let transaction = self.connection.transaction()?; - config::put(&transaction, REVISION_KEY, &revision.to_string())?; - audit(&transaction, actor, AuditResult::Applied)?; - transaction.commit()?; + /// Marks the audit record `audit` as failed. + pub fn fail_change(&self, audit: i64) -> Result<(), StoreError> { + self.connection.execute( + "UPDATE audit_records SET result=?1 WHERE id=?2", + params![AuditResult::Failed, audit], + )?; Ok(()) } @@ -233,32 +299,44 @@ impl NodeStore { .map_or(Ok(0), |value| value.parse().map_err(|_| StoreError::InvalidState)) } - /// Restores the value that an applied change replaced and records the - /// failure. `previous` is `None` when the change created the value. + /// Restores what the applied change `id` of `kind` replaced and marks + /// its audit record as failed. The admin revision stays: a pending + /// change that was queued before the attempt is stale. pub fn revert_change( &mut self, kind: ChangeKind, id: &str, - previous: Option<&str>, - actor: AuditActor, + replaced: &Replaced, ) -> Result<(), StoreError> { let key = change_key(kind, id); let transaction = self.connection.transaction()?; - match previous { + match &replaced.value { Some(value) => config::put(&transaction, &key, value)?, None => config::delete(&transaction, &key)?, } - audit(&transaction, actor, AuditResult::Failed)?; + if kind == ChangeKind::Workspace { + match &replaced.workspace { + Some(path) => config::put(&transaction, CURRENT_WORKSPACE_KEY, path)?, + None => config::delete(&transaction, CURRENT_WORKSPACE_KEY)?, + } + } + transaction.execute( + "UPDATE audit_records SET result=?1 WHERE id=?2", + params![AuditResult::Failed, replaced.audit], + )?; transaction.commit()?; Ok(()) } - /// Applies the pending change `id` and returns the value it replaced. - /// An expired change is [`StoreError::InvalidState`]. + /// Applies the pending change `id` as [`Self::apply_change`] does, in + /// one transaction with the removal of its row, and returns what it + /// replaced. An expired change is [`StoreError::InvalidState`], and it + /// leaves the table. pub fn confirm_pending_change( &mut self, id: &str, - ) -> Result, StoreError> { + revision: u64, + ) -> Result { let transaction = self.connection.transaction()?; let (kind, value, expires_at): (ChangeKind, String, i64) = transaction .query_row( @@ -269,16 +347,17 @@ impl NodeStore { .optional()? .ok_or(StoreError::NotFound)?; if expires_at <= now() { + delete_expired(&transaction)?; + transaction.commit()?; return Err(StoreError::InvalidState); } - let key = change_key(kind, id); - let previous = config::get(&transaction, &key)?; - config::put(&transaction, &key, &value)?; transaction.execute("DELETE FROM pending_changes WHERE id=?1", [id])?; config::delete(&transaction, &pending_revision_key(id))?; audit(&transaction, AuditActor::Ui, AuditResult::Confirmed)?; + let replaced = + keep_change(&transaction, kind, id, &value, AuditActor::Ui, revision)?; transaction.commit()?; - Ok(previous) + Ok(replaced) } pub fn pending_changes(&self) -> Result, StoreError> { @@ -305,11 +384,17 @@ impl NodeStore { .ok_or(StoreError::NotFound) } - /// Removes the applied grant `id` and marks it revoked. - pub fn revoke_applied_grant(&mut self, id: &str) -> Result<(), StoreError> { + /// Removes the applied grant `id`, marks it revoked, and writes the + /// audit record of `actor`, in one transaction. + pub fn revoke_applied_grant( + &mut self, + id: &str, + actor: AuditActor, + ) -> Result<(), StoreError> { let transaction = self.connection.transaction()?; config::put(&transaction, &revoked_key(id), "revoked")?; config::delete(&transaction, &change_key(ChangeKind::Grant, id))?; + audit(&transaction, actor, AuditResult::Applied)?; transaction.commit()?; Ok(()) } @@ -373,7 +458,7 @@ mod tests { store .queue_change(ChangeKind::Grant, "grant", "private-credential", i64::MAX, 0) .expect("change must queue"); - store.confirm_pending_change("grant").expect("change must confirm"); + store.confirm_pending_change("grant", 1).expect("change must confirm"); drop(store); let store = NodeStore::in_dir(directory.path()).expect("store must reopen"); assert_eq!( @@ -385,7 +470,8 @@ mod tests { .collect::>(), [ (AuditActor::Mcp, AuditResult::Pending), - (AuditActor::Ui, AuditResult::Confirmed) + (AuditActor::Ui, AuditResult::Confirmed), + (AuditActor::Ui, AuditResult::Applied) ] ); store @@ -397,41 +483,99 @@ mod tests { #[test] fn a_confirmed_change_returns_the_value_it_replaced_and_its_revision_goes() { let (_directory, mut store) = test_support::temp_node_store(); - assert_eq!( - store.apply_change(ChangeKind::Limit, "queue_global", "2"), - Ok(None) - ); + let first = store + .apply_change(ChangeKind::Limit, "queue_global", "2", AuditActor::Ui, 1) + .expect("change must apply"); + assert_eq!(first.value, None); store .queue_change(ChangeKind::Limit, "queue_global", "9", i64::MAX, 4) .expect("change must queue"); assert_eq!(store.pending_revision("queue_global"), Ok(Some(4))); - assert_eq!( - store.confirm_pending_change("queue_global"), - Ok(Some("2".to_owned())) - ); + let replaced = + store.confirm_pending_change("queue_global", 5).expect("must confirm"); + assert_eq!(replaced.value.as_deref(), Some("2")); assert_eq!(store.pending_revision("queue_global"), Ok(None)); assert_eq!( store.applied_change(ChangeKind::Limit, "queue_global"), Ok(Some("9".to_owned())) ); + assert_eq!(store.admin_revision(), Ok(5)); store - .revert_change(ChangeKind::Limit, "queue_global", Some("2"), AuditActor::Ui) + .revert_change(ChangeKind::Limit, "queue_global", &replaced) .expect("change must revert"); assert_eq!( store.applied_change(ChangeKind::Limit, "queue_global"), Ok(Some("2".to_owned())) ); + assert_eq!(store.admin_revision(), Ok(5)); + } + + #[test] + fn a_change_keeps_its_revision_and_audit_record_with_its_value() { + let (_directory, mut store) = test_support::temp_node_store(); + let replaced = store + .apply_change(ChangeKind::Workspace, "w", "/work", AuditActor::Mcp, 7) + .expect("change must apply"); + assert_eq!(store.admin_revision(), Ok(7)); + assert_eq!(store.current_workspace(), Ok(Some("/work".to_owned()))); + assert_eq!(results(&store), [AuditResult::Applied]); + let second = store + .apply_change(ChangeKind::Workspace, "v", "/other", AuditActor::Mcp, 8) + .expect("change must apply"); + store.revert_change(ChangeKind::Workspace, "v", &second).expect("revert"); + assert_eq!(store.current_workspace(), Ok(Some("/work".to_owned()))); + assert_eq!(store.applied_change(ChangeKind::Workspace, "v"), Ok(None)); + assert_eq!(results(&store), [AuditResult::Applied, AuditResult::Failed]); + store.revert_change(ChangeKind::Workspace, "w", &replaced).expect("revert"); + assert_eq!(store.current_workspace(), Ok(None)); + } + + #[test] + fn an_expired_pending_change_frees_its_id() { + let (_directory, mut store) = test_support::temp_node_store(); + store + .queue_change(ChangeKind::Workspace, "w", "/old", 1, 3) + .expect("change must queue"); + assert_eq!(store.confirm_pending_change("w", 1), Err(StoreError::InvalidState)); + store + .queue_change(ChangeKind::Workspace, "w", "/new", i64::MAX, 5) + .expect("the id of an expired change must queue again"); + assert_eq!(store.pending_revision("w"), Ok(Some(5))); + assert_eq!( + store.pending_change_ignoring_expiry("w").map(|change| change.value), + Ok("/new".to_owned()) + ); + store.queue_change(ChangeKind::Workspace, "x", "/x", 1, 5).expect("queue"); + assert_eq!(store.confirm_pending_change("x", 1), Err(StoreError::InvalidState)); + assert_eq!( + store.pending_change_ignoring_expiry("x"), + Err(StoreError::NotFound) + ); + assert_eq!(store.pending_revision("x"), Ok(None)); + } + + fn results(store: &NodeStore) -> Vec { + store + .audit_records() + .expect("audit must load") + .into_iter() + .map(|record| record.result) + .collect() } #[test] fn counts_and_lists_hold_only_applied_changes_of_their_kind() { let (_directory, mut store) = test_support::temp_node_store(); - store.apply_change(ChangeKind::Grant, "b", "grant-b").expect("grant"); - store.apply_change(ChangeKind::Grant, "a", "grant-a").expect("grant"); - store.apply_change(ChangeKind::Workspace, "w", "/work").expect("workspace"); - store.set_current_workspace("/work").expect("workspace"); - store.revoke_applied_grant("b").expect("revocation"); - store.record_applied_change(AuditActor::Ui, 3).expect("revision"); + for (kind, id, value, revision) in [ + (ChangeKind::Grant, "b", "grant-b", 1), + (ChangeKind::Grant, "a", "grant-a", 2), + (ChangeKind::Workspace, "w", "/work", 3), + ] { + store + .apply_change(kind, id, value, AuditActor::Ui, revision) + .expect("change must apply"); + } + store.revoke_applied_grant("b", AuditActor::Ui).expect("revocation"); assert_eq!( store.applied_changes(ChangeKind::Grant), Ok(vec!["grant-a".to_owned()]) @@ -454,6 +598,7 @@ mod tests { (ChangeKind::Directory, "directory"), (ChangeKind::Capability, "capability"), (ChangeKind::Limit, "limit"), + (ChangeKind::Policy, "policy"), ] { assert_eq!(kind.as_str(), name); } diff --git a/crates/aether-store/src/control.rs b/crates/aether-store/src/control.rs index 2c7442b..86ea0d0 100644 --- a/crates/aether-store/src/control.rs +++ b/crates/aether-store/src/control.rs @@ -21,6 +21,7 @@ pub const CONTROL_MIGRATIONS: &[&str] = &[ include_str!("../migrations/control/003_managed_members.sql"), include_str!("../migrations/control/004_managed_events.sql"), include_str!("../migrations/control/005_drop_unused_tables.sql"), + include_str!("../migrations/control/006_directory_record_marks.sql"), ]; /// What happened to a directory record. The names are the @@ -80,18 +81,36 @@ impl ControlStore { Ok(Self { connection: open_connection(path.as_ref(), CONTROL_MIGRATIONS)? }) } - /// Keeps `record` and its `event`, which publishes or renews it. + /// Keeps `record`, which `signing_key` signed, and its `event`, which + /// publishes or renews it. + /// + /// A record that does not expire after the last revocation of this + /// agent ID and key is [`StoreError::InvalidState`]: it was public + /// before the revocation, so its sender need not be its owner. pub fn publish_signed_record( &mut self, record: &SignedRecord, + signing_key: &[u8; 32], event: DirectoryEventType, ) -> Result<(), StoreError> { if event == DirectoryEventType::Revoked { return Err(StoreError::InvalidState); } let transaction = self.connection.transaction()?; + let revoked_through: Option = transaction + .query_row( + "SELECT revoked_through FROM directory_record_marks WHERE agent_id=?1 AND signing_key=?2", + params![record.agent_id, signing_key], + |row| row.get(0), + ) + .optional()? + .flatten(); + if revoked_through.is_some_and(|through| record.expires_at <= through) { + return Err(StoreError::InvalidState); + } put_scope(&transaction, &record.scope_id, ScopeKind::Directory)?; upsert_record(&transaction, &record.agent_id, record)?; + mark_latest(&transaction, &record.agent_id, signing_key, record.expires_at)?; transaction.execute( "INSERT INTO directory_events(event_type,scope_id,agent_id,record,created_at) VALUES(?1,?2,?3,?4,?5)", params![event, record.scope_id, record.agent_id, record.record, now()], @@ -113,18 +132,31 @@ impl ControlStore { .ok_or(StoreError::NotFound) } - pub fn revoke_signed_record(&mut self, agent_id: &str) -> Result<(), StoreError> { + /// Removes the record of `agent_id`, which `signing_key` signed. No + /// record of that key that the directory had before this call can be + /// published again. + pub fn revoke_signed_record( + &mut self, + agent_id: &str, + signing_key: &[u8; 32], + ) -> Result<(), StoreError> { let transaction = self.connection.transaction()?; - let scope_id: String = transaction + let (scope_id, expires_at): (String, i64) = transaction .query_row( - "SELECT scope_id FROM signed_records WHERE agent_id=?1 ORDER BY expires_at DESC LIMIT 1", + "SELECT scope_id,expires_at FROM signed_records WHERE agent_id=?1 ORDER BY expires_at DESC LIMIT 1", [agent_id], - |row| row.get(0), + |row| Ok((row.get(0)?, row.get(1)?)), ) .optional()? .ok_or(StoreError::NotFound)?; transaction .execute("DELETE FROM signed_records WHERE agent_id=?1", [agent_id])?; + // A record from before the marks table has no mark yet. + mark_latest(&transaction, agent_id, signing_key, expires_at)?; + transaction.execute( + "UPDATE directory_record_marks SET revoked_through=latest_expires_at WHERE agent_id=?1 AND signing_key=?2", + params![agent_id, signing_key], + )?; transaction.execute( "INSERT INTO directory_events(event_type,scope_id,agent_id,record,created_at) VALUES(?1,?2,?3,NULL,?4)", params![DirectoryEventType::Revoked, scope_id, agent_id, now()], @@ -285,6 +317,22 @@ impl ControlStore { } } +/// Raises the latest expiry of the records of `agent_id` that `signing_key` +/// signed to `expires_at`. +fn mark_latest( + connection: &Connection, + agent_id: &str, + signing_key: &[u8; 32], + expires_at: i64, +) -> Result<(), StoreError> { + connection.execute( + "INSERT INTO directory_record_marks(agent_id,signing_key,latest_expires_at) VALUES(?1,?2,?3) + ON CONFLICT(agent_id,signing_key) DO UPDATE SET latest_expires_at=MAX(latest_expires_at,excluded.latest_expires_at)", + params![agent_id, signing_key, expires_at], + )?; + Ok(()) +} + #[cfg(test)] mod tests { use std::fs; @@ -301,6 +349,38 @@ mod tests { } } + const KEY: [u8; 32] = [7; 32]; + + #[test] + fn a_record_from_before_a_revocation_cannot_be_published_again() { + let directory = tempfile::tempdir().expect("directory must create"); + let mut store = + ControlStore::open(directory.path().join("control")).expect("open"); + let publish = |store: &mut ControlStore, expires_at, key: &[u8; 32]| { + store.publish_signed_record( + &record("agent", expires_at), + key, + DirectoryEventType::Published, + ) + }; + publish(&mut store, 20, &KEY).expect("the newer record must publish"); + // An older record of the owner replaces the newer one, as before. + publish(&mut store, 10, &KEY).expect("the older record must publish"); + store.revoke_signed_record("agent", &KEY).expect("record must revoke"); + // Both were public, so neither comes back. + assert_eq!(publish(&mut store, 10, &KEY), Err(StoreError::InvalidState)); + assert_eq!(publish(&mut store, 20, &KEY), Err(StoreError::InvalidState)); + assert_eq!(store.signed_record("agent"), Err(StoreError::NotFound)); + assert_eq!(store.directory_events_after(0, 10).expect("events").len(), 3); + // Another key has its own mark. + publish(&mut store, 5, &[8; 32]).expect("another key must publish"); + store.revoke_signed_record("agent", &[8; 32]).expect("record must revoke"); + // Only the owner can sign a record that expires later. + publish(&mut store, 21, &KEY).expect("a later record must publish"); + store.revoke_signed_record("agent", &KEY).expect("record must revoke"); + assert_eq!(publish(&mut store, 21, &KEY), Err(StoreError::InvalidState)); + } + #[test] fn published_records_are_durable_and_a_revocation_is_an_event() { let database = path("control-record"); @@ -308,22 +388,31 @@ mod tests { assert_eq!( store.publish_signed_record( &record("agent", 1), + &KEY, DirectoryEventType::Revoked ), Err(StoreError::InvalidState) ); store - .publish_signed_record(&record("agent", 1), DirectoryEventType::Published) + .publish_signed_record( + &record("agent", 1), + &KEY, + DirectoryEventType::Published, + ) .expect("record must publish"); store - .publish_signed_record(&record("agent", 2), DirectoryEventType::Renewed) + .publish_signed_record( + &record("agent", 2), + &KEY, + DirectoryEventType::Renewed, + ) .expect("record must renew"); drop(store); let mut store = ControlStore::open(&database).expect("control must reopen"); assert_eq!(store.signed_record("agent"), Ok(record("agent", 2))); assert_eq!(store.active_signed_records(1).expect("records must load").len(), 1); assert!(store.active_signed_records(2).expect("records must load").is_empty()); - store.revoke_signed_record("agent").expect("record must revoke"); + store.revoke_signed_record("agent", &KEY).expect("record must revoke"); assert_eq!(store.signed_record("agent"), Err(StoreError::NotFound)); assert_eq!( store diff --git a/crates/aether-store/src/lib.rs b/crates/aether-store/src/lib.rs index 37436ea..61e4c8d 100644 --- a/crates/aether-store/src/lib.rs +++ b/crates/aether-store/src/lib.rs @@ -25,6 +25,7 @@ pub use access_groups::{ }; pub use admin::{ AuditAction, AuditActor, AuditRecord, AuditResult, ChangeKind, PendingChange, + Replaced, }; pub use control::{ CONTROL_MIGRATIONS, ControlStore, DirectoryEvent, DirectoryEventType, ManagedEvent, @@ -66,6 +67,7 @@ pub const NODE_MIGRATIONS: &[&str] = &[ include_str!("../migrations/node/015_access_request_drafts.sql"), include_str!("../migrations/node/016_signed_record_kinds.sql"), include_str!("../migrations/node/017_drop_unused_grants.sql"), + include_str!("../migrations/node/018_task_caller_ids.sql"), ]; pub const NODE_DATABASE: &str = "node.sqlite"; diff --git a/crates/aether-store/src/managed.rs b/crates/aether-store/src/managed.rs index f35e8f3..12433ad 100644 --- a/crates/aether-store/src/managed.rs +++ b/crates/aether-store/src/managed.rs @@ -90,6 +90,11 @@ impl NodeStore { } /// Applies the roster event `cursor` of `control`: `member` joined. + /// + /// A member that this node knows as revoked stays revoked. The control + /// service never lets a revoked agent join its scope again, so such an + /// event is an old one that a second cursor of the scope reads again + /// (the cursor has the control URL in its key, the roster does not). pub fn apply_managed_member( &mut self, control: &str, @@ -103,7 +108,8 @@ impl NodeStore { transaction.execute( &format!( "INSERT INTO managed_members({MEMBER_COLUMNS}) VALUES(?1,?2,?3,?4,?5,NULL) - ON CONFLICT(scope_id,agent_id) DO UPDATE SET endpoint_id=excluded.endpoint_id,role=excluded.role,expires_at=excluded.expires_at,revoked_at=NULL" + ON CONFLICT(scope_id,agent_id) DO UPDATE SET endpoint_id=excluded.endpoint_id,role=excluded.role,expires_at=excluded.expires_at + WHERE managed_members.revoked_at IS NULL" ), params![member.scope_id, member.agent_id, member.endpoint_id, member.role, member.expires_at], )?; @@ -112,7 +118,9 @@ impl NodeStore { } /// Applies the roster event `cursor` of `control`: `agent_id` left - /// `scope_id`. + /// `scope_id`. For a member that is revoked already only the cursor + /// moves, so a second cursor of the scope gets past the event. An agent + /// that the roster does not have is [`StoreError::NotFound`]. pub fn revoke_managed_member( &mut self, control: &str, @@ -126,7 +134,7 @@ impl NodeStore { let transaction = self.connection.transaction()?; advance_cursor(&transaction, &cursor_key(control, scope_id), cursor)?; if transaction.execute( - "UPDATE managed_members SET revoked_at=?1 WHERE scope_id=?2 AND agent_id=?3 AND revoked_at IS NULL", + "UPDATE managed_members SET revoked_at=COALESCE(revoked_at,?1) WHERE scope_id=?2 AND agent_id=?3", params![now(), scope_id, agent_id], )? != 1 { return Err(StoreError::NotFound); @@ -242,6 +250,41 @@ mod tests { fs::remove_file(database).expect("database must remove"); } + /// The roster cursor has the control URL in its key. A second spelling + /// of the URL reads the events of the scope again from the start. + #[test] + fn a_second_control_url_does_not_bring_a_revoked_member_back() { + let directory = tempfile::tempdir().expect("directory must create"); + let mut store = NodeStore::in_dir(directory.path()).expect("store must open"); + let member = ManagedMember { + scope_id: "managed".to_owned(), + agent_id: "member-agent".to_owned(), + endpoint_id: "member-endpoint".to_owned(), + role: "member".to_owned(), + expires_at: i64::MAX, + revoked_at: None, + }; + store.apply_managed_member("https://control", 1, &member).expect("join"); + store + .revoke_managed_member("https://control", 2, "managed", "member-agent") + .expect("revoke"); + let revoked = store.managed_members("managed").expect("members must load"); + assert!(revoked[0].revoked_at.is_some()); + + store.apply_managed_member("https://control/", 1, &member).expect("old join"); + assert_eq!(store.managed_members("managed").expect("members"), revoked); + store + .revoke_managed_member("https://control/", 2, "managed", "member-agent") + .expect("the old revoke must move the second cursor"); + assert_eq!(store.managed_members("managed").expect("members"), revoked); + assert_eq!(store.managed_cursor("https://control/", "managed"), Ok(2)); + assert_eq!( + store.revoke_managed_member("https://control/", 3, "managed", "stranger"), + Err(StoreError::NotFound) + ); + assert_eq!(store.managed_cursor("https://control/", "managed"), Ok(2)); + } + #[test] fn a_managed_member_keeps_its_wire_form() { let member = ManagedMember { diff --git a/crates/aether-store/src/tasks.rs b/crates/aether-store/src/tasks.rs index 76ed1d3..607725d 100644 --- a/crates/aether-store/src/tasks.rs +++ b/crates/aether-store/src/tasks.rs @@ -360,32 +360,54 @@ fn admit( let existing = tx .query_row( &format!( - "SELECT {REQUEST_COLUMNS},request_fingerprint FROM tasks WHERE caller_endpoint_id=?1 AND idempotency_key=?2" + "SELECT {REQUEST_COLUMNS},request_fingerprint,caller_task_id,caller_request_id FROM tasks WHERE caller_endpoint_id=?1 AND idempotency_key=?2" ), params![request.caller_endpoint_id.as_str(), input.idempotency_key], - |row| Ok((request_from_row(row, 0)?, row.get::<_, String>(8)?)), + |row| { + Ok(( + request_from_row(row, 0)?, + row.get::<_, String>(8)?, + row.get::<_, Option>(9)?, + row.get::<_, Option>(10)?, + )) + }, ) .optional()?; - if let Some((stored, fingerprint)) = existing { - return if stored == *request && fingerprint == input.request_fingerprint { - Ok(TaskAdmission::Existing(stored.task_id.as_str().to_owned())) + if let Some((stored, fingerprint, caller_task_id, caller_request_id)) = existing { + let task_id = stored.task_id.as_str().to_owned(); + // The request as the caller sent it: a row that got its own IDs + // keeps the caller's IDs beside them. + let sent = Request { + task_id: caller_task_id.map_or_else(|| stored.task_id.clone(), TaskId::new), + id: caller_request_id.map_or_else(|| stored.id.clone(), RequestId::new), + ..stored + }; + return if sent == *request && fingerprint == input.request_fingerprint { + Ok(TaskAdmission::Existing(task_id)) } else { Err(StoreError::DuplicateConflict) }; } if count(tx, None)? >= limits.global - || count(tx, Some(request.caller_agent_id.as_str()))? >= limits.per_peer + || count(tx, Some(request.caller_endpoint_id.as_str()))? >= limits.per_peer { return Err(StoreError::Overloaded); } + let own_ids = own_ids(tx, request)?; + let (task_id, request_id) = own_ids.as_ref().map_or_else( + || (request.task_id.as_str(), request.id.as_str()), + |(task_id, request_id)| (task_id.as_str(), request_id.as_str()), + ); + let caller_ids = + own_ids.as_ref().map(|_| (request.task_id.as_str(), request.id.as_str())); tx.execute( &format!( - "INSERT INTO tasks({REQUEST_COLUMNS},idempotency_key,request_fingerprint,skill,remote_text,state,created_at) - VALUES(?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,?11,?12,?13,?14)" + "INSERT INTO tasks({REQUEST_COLUMNS},idempotency_key,request_fingerprint,skill,remote_text,state,created_at,caller_task_id,caller_request_id) + VALUES(?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,?11,?12,?13,?14,?15,?16)" ), params![ - request.task_id.as_str(), - request.id.as_str(), + task_id, + request_id, request.caller_agent_id.as_str(), request.caller_endpoint_id.as_str(), request.scope_id.as_str(), @@ -398,13 +420,62 @@ fn admit( input.remote_text, TaskState::Queued, now(), + caller_ids.map(|ids| ids.0), + caller_ids.map(|ids| ids.1), ], )?; - let task_id = request.task_id.as_str(); event(tx, task_id, EventType::Entered(TaskState::Queued))?; Ok(TaskAdmission::Accepted(task_id.to_owned())) } +/// The IDs that the row of a new request gets when it cannot have the IDs +/// that the caller sent, and `None` when it can. +/// +/// `tasks.id` and `tasks.request_id` are unique for the whole table, and the +/// caller chooses both. A row of another endpoint that has one of them must +/// not block this caller, and must not show that it exists, so the new row +/// gets IDs that the node makes. The same endpoint cannot use an ID again +/// for another idempotency key. +fn own_ids( + tx: &Transaction<'_>, + request: &Request, +) -> Result, StoreError> { + let endpoint = request.caller_endpoint_id.as_str(); + let mut statement = tx.prepare( + "SELECT caller_endpoint_id FROM tasks + WHERE id=?1 OR request_id=?2 + OR (caller_endpoint_id=?3 AND (caller_task_id=?1 OR caller_request_id=?2))", + )?; + let owners = statement + .query_map( + params![request.task_id.as_str(), request.id.as_str(), endpoint], + |row| row.get::<_, String>(0), + )? + .collect::, _>>()?; + if owners.is_empty() { + return Ok(None); + } + if owners.iter().any(|owner| owner == endpoint) { + return Err(StoreError::DuplicateConflict); + } + Ok(Some((random_id(tx)?, random_id(tx)?))) +} + +/// A random ID in the form of a UUID. +fn random_id(tx: &Transaction<'_>) -> Result { + let hex: String = + tx.query_row("SELECT lower(hex(randomblob(16)))", [], |row| row.get(0))?; + let part = |range: std::ops::Range| hex.get(range).unwrap_or_default(); + Ok(format!( + "{}-{}-{}-{}-{}", + part(0..8), + part(8..12), + part(12..16), + part(16..20), + part(20..32) + )) +} + impl NodeStore { pub fn state(&self, task_id: &str) -> Result { self.connection @@ -741,25 +812,31 @@ impl NodeStore { cancel(self.connection.transaction()?, task_id) } + /// Cancels the task that `caller_endpoint_id` sent as `task_id` in + /// `scope_id`, and returns the ID of its row. The two IDs differ only + /// for a row that got its own ID (see [`own_ids`]). pub fn cancel_if_owned( &mut self, task_id: &str, caller_endpoint_id: &str, scope_id: &str, - ) -> Result<(), StoreError> { + ) -> Result { let tx = self.connection.transaction()?; - let (owner, scope): (String, String) = tx + let (id, owner, scope): (String, String, String) = tx .query_row( - "SELECT caller_endpoint_id,scope_id FROM tasks WHERE id=?1", - [task_id], - |row| Ok((row.get(0)?, row.get(1)?)), + "SELECT id,caller_endpoint_id,scope_id FROM tasks + WHERE id=?1 OR (caller_endpoint_id=?2 AND caller_task_id=?1) + ORDER BY caller_task_id IS NULL LIMIT 1", + params![task_id, caller_endpoint_id], + |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)), ) .optional()? .ok_or(StoreError::NotFound)?; if owner != caller_endpoint_id || scope != scope_id { return Err(StoreError::Unauthorized); } - cancel(tx, task_id) + cancel(tx, &id)?; + Ok(id) } pub fn task_execution_data( @@ -861,14 +938,10 @@ fn accept_replay_key( params![caller_endpoint_id, scope_id], |row| row.get(0), )?; - let limit = sql_count(limit); - if count >= limit { - // Make room for the new entry: remove the oldest ones over the limit. - let excess = count.saturating_sub(limit).saturating_add(1); - tx.execute( - "DELETE FROM replay_entries WHERE rowid IN (SELECT rowid FROM replay_entries WHERE caller_endpoint_id=?1 AND scope_id=?2 ORDER BY expires_at, rowid LIMIT ?3)", - params![caller_endpoint_id, scope_id, excess], - )?; + if count >= sql_count(limit) { + // An entry stays until it expires. Removing the oldest one here + // would let the caller send that frame again. + return Err(StoreError::Overloaded); } tx.execute( "INSERT INTO replay_entries(caller_endpoint_id,scope_id,replay_key,expires_at) VALUES(?1,?2,?3,?4)", @@ -880,7 +953,7 @@ fn accept_replay_key( fn count(tx: &Transaction<'_>, peer: Option<&str>) -> Result { let count: i64 = match peer { Some(peer) => tx.query_row( - "SELECT COUNT(*) FROM tasks WHERE state=?1 AND caller_agent_id=?2", + "SELECT COUNT(*) FROM tasks WHERE state=?1 AND caller_endpoint_id=?2", params![TaskState::Queued, peer], |row| row.get(0), )?, @@ -1107,10 +1180,16 @@ mod tests { .expect("expired key must store"); accept_replay_key(&mut store, "a", "replacement", i64::MAX, 2) .expect("expired key must clear"); - accept_replay_key(&mut store, "a", "limited", i64::MAX, 2) - .expect("limited key must store"); - accept_replay_key(&mut store, "a", "newer", i64::MAX, 2) - .expect("oldest key must expire at the limit"); + assert_eq!( + accept_replay_key(&mut store, "a", "newer", i64::MAX, 2), + Err(StoreError::Overloaded), + "a full table must refuse the frame and keep its unexpired keys" + ); + assert_eq!( + accept_replay_key(&mut store, "a", "exchange", i64::MAX, 2), + Err(StoreError::DuplicateConflict), + "the oldest key must stay until it expires" + ); drop(store); fs::remove_file(database).expect("database must remove"); } @@ -1150,8 +1229,11 @@ mod tests { ); accept_replay_key(&mut store, "b", "peer-replay", i64::MAX, 1) .expect("other caller replay must store"); - accept_replay_key(&mut store, "b", "peer-replay-new", i64::MAX, 1) - .expect("other caller capacity may replace only its own key"); + assert_eq!( + accept_replay_key(&mut store, "b", "peer-replay-new", i64::MAX, 1), + Err(StoreError::Overloaded), + "a caller fills only its own part of the table" + ); assert_eq!( accept_replay_key(&mut store, "a", "replay-one", i64::MAX, 1), Err(StoreError::DuplicateConflict) @@ -1458,6 +1540,70 @@ mod tests { fs::remove_file(database).expect("database must remove"); } + #[test] + fn the_per_peer_limit_counts_each_endpoint_apart() { + let (mut store, database) = store(); + let limits = QueueLimits { global: 4, per_peer: 1 }; + store.admit(&input("one", "a"), limits).expect("task must admit"); + // The owner gave the same agent name to a second endpoint. + let mut other = input("two", "a"); + other.request.caller_endpoint_id = EndpointId::new("endpoint-second"); + assert_eq!( + store.admit(&other, limits), + Ok(TaskAdmission::Accepted("two".to_owned())), + "another endpoint with the same name must have its own limit" + ); + assert_eq!( + store.admit(&input("three", "a"), limits), + Err(StoreError::Overloaded), + "the first endpoint is at its limit" + ); + fs::remove_file(database).expect("database must remove"); + } + + #[test] + fn a_task_id_of_another_endpoint_does_not_block_a_caller() { + let (mut store, database) = store(); + let limits = QueueLimits { global: 4, per_peer: 2 }; + store.admit(&input("one", "a"), limits).expect("task must admit"); + // Endpoint b sends its own request with the task ID and the request + // ID of a's task. + let mut clash = input("one", "b"); + clash.idempotency_key = "key-b".to_owned(); + let (TaskAdmission::Accepted(own_id) | TaskAdmission::Existing(own_id)) = + store.admit(&clash, limits).expect("the clash must not refuse b"); + assert_ne!(own_id, "one", "b must not get the row of a"); + assert_eq!( + store.admit(&clash, limits), + Ok(TaskAdmission::Existing(own_id.clone())), + "the same request again must find the task of b" + ); + let mut changed = clash.clone(); + changed.request_fingerprint = "changed".to_owned(); + assert_eq!(store.admit(&changed, limits), Err(StoreError::DuplicateConflict)); + let data = store.task_execution_data(&own_id).expect("the task of b must load"); + assert_eq!(data.request.caller_endpoint_id, EndpointId::new("endpoint-b")); + // b cancels by the ID that it sent, and reaches only its own task. + assert_eq!( + store.cancel_if_owned("one", "endpoint-b", "scope"), + Ok(own_id.clone()) + ); + assert_eq!(store.state(&own_id), Ok(TaskState::Cancelled)); + assert_eq!(store.state("one"), Ok(TaskState::Queued)); + assert_eq!( + store.cancel_if_owned("one", "endpoint-a", "scope"), + Ok("one".to_owned()) + ); + // An endpoint cannot use its own task ID for a second request. + let mut reused = input("one", "a"); + reused.idempotency_key = "key-second".to_owned(); + assert_eq!(store.admit(&reused, limits), Err(StoreError::DuplicateConflict)); + let mut reused = clash; + reused.idempotency_key = "key-b-second".to_owned(); + assert_eq!(store.admit(&reused, limits), Err(StoreError::DuplicateConflict)); + fs::remove_file(database).expect("database must remove"); + } + #[test] fn queue_idempotency_events_and_recovery_work() { let (mut store, database) = store(); diff --git a/crates/aether/src/a2a_transport.rs b/crates/aether/src/a2a_transport.rs index 9820897..4029cb2 100644 --- a/crates/aether/src/a2a_transport.rs +++ b/crates/aether/src/a2a_transport.rs @@ -61,6 +61,10 @@ impl<'a, T, P> A2aTransport<'a, T, P> { } _ => return Err(TransportError::BadFrame), }; + // The ID that the caller sent. Every frame of the answer carries it; + // the node can keep the task under another ID (see `own_ids` in + // aether-store). + let sent_task_id = payload.task.id.clone(); let task = Task { id: payload.task.id, skill: skill_for_direct_a2a_entry( @@ -113,12 +117,12 @@ impl<'a, T, P> A2aTransport<'a, T, P> { let mut cursor = last_sequence; for event in events { let event_frame = Frame { - task_id: Some(task_id.clone()), + task_id: Some(sent_task_id.clone()), ..Frame::reply_to( &frame, FrameKind::Event, event_payload( - &task_id, + &sent_task_id, event_status(event.event_type, state), Some(event.sequence), ), @@ -135,12 +139,12 @@ impl<'a, T, P> A2aTransport<'a, T, P> { response.push(event_frame); } response.push(Frame { - task_id: Some(task_id.clone()), + task_id: Some(sent_task_id.clone()), ..Frame::reply_to( &frame, FrameKind::Result, text_result_payload_with_progress( - &task_id, + &sent_task_id, status, &result_text, cursor, @@ -166,7 +170,8 @@ impl<'a, T, P> A2aTransport<'a, T, P> { if cancel.id != task_id { return Err(TransportError::BadFrame); } - self.proof + let stored_task_id = self + .proof .cancel_from( task_id, &EndpointId::new(authenticated_endpoint), @@ -175,7 +180,7 @@ impl<'a, T, P> A2aTransport<'a, T, P> { .map_err(map_error)?; let event = self .proof - .events_after(task_id, 0) + .events_after(&stored_task_id, 0) .map_err(map_error)? .into_iter() .last() diff --git a/crates/aether/src/admin.rs b/crates/aether/src/admin.rs index d6a8860..19623ee 100644 --- a/crates/aether/src/admin.rs +++ b/crates/aether/src/admin.rs @@ -34,13 +34,36 @@ pub enum AdminError { #[allow(clippy::large_enum_variant)] #[derive(Debug, Clone, Eq, PartialEq)] pub enum ChangeRequest { - Workspace { id: String, path: String }, - Grant { id: String, grant: Grant }, - Directory { id: String, url: String }, - Capability { id: String, capability: String }, - Limit { id: aether_core::limits::QueueLimitId, limit: u32 }, + Workspace { + id: String, + path: String, + }, + Grant { + id: String, + grant: Grant, + }, + Directory { + id: String, + url: String, + }, + Capability { + id: String, + capability: String, + }, + Limit { + id: aether_core::limits::QueueLimitId, + limit: u32, + }, + /// The policy settings of `aether.settings.update_policy`. It has no + /// wire form: only [`Administration::save_policy_settings`] makes it. + Policy { + settings: crate::policy::PolicySettings, + }, } +/// The id of the one pending policy change. +const POLICY_CHANGE_ID: &str = "policy"; + // The wire form of a `ChangeRequest`, as MCP and the admin socket send it: // the grant travels encoded, and the limit id as its name. The MCP schema of // `aether.change` is this type's schema (a doc comment would enter it). @@ -101,6 +124,9 @@ impl TryFrom<&ChangeRequest> for ChangeRequestWire { ChangeRequest::Limit { id, limit } => { Self::Limit { id: id.as_str().to_owned(), limit: *limit } } + ChangeRequest::Policy { .. } => { + return Err("policy settings have no change form".to_owned()); + } }) } } @@ -179,6 +205,10 @@ impl ChangeRequest { } Self::Capability { capability, .. } => valid(capability, "capability")?, Self::Limit { .. } => {} + Self::Policy { settings } => { + crate::policy::validate_policy_settings(settings) + .map_err(|_| AdminError::InvalidField("policy"))?; + } } Ok(Change { request: self, expires_at }) } @@ -207,6 +237,9 @@ impl ChangeRequest { .map(|limit| Self::Limit { id: limit_id, limit }) .map_err(|_| AdminError::InvalidField("limit")) } + ChangeKind::Policy => serde_json::from_str(&value) + .map(|settings| Self::Policy { settings }) + .map_err(|_| AdminError::InvalidField("policy")), } } @@ -218,6 +251,7 @@ impl ChangeRequest { | Self::Directory { id, .. } | Self::Capability { id, .. } => id, Self::Limit { id, .. } => id.as_str(), + Self::Policy { .. } => POLICY_CHANGE_ID, } } @@ -229,6 +263,7 @@ impl ChangeRequest { Self::Directory { .. } => ChangeKind::Directory, Self::Capability { .. } => ChangeKind::Capability, Self::Limit { .. } => ChangeKind::Limit, + Self::Policy { .. } => ChangeKind::Policy, } } @@ -241,6 +276,9 @@ impl ChangeRequest { Self::Grant { grant, .. } => crate::identity::encode_grant(grant) .expect("a validated grant must encode"), Self::Limit { limit, .. } => limit.to_string(), + Self::Policy { settings } => { + serde_json::to_string(settings).expect("policy settings must encode") + } } } } @@ -279,6 +317,15 @@ pub struct Administration { live: Option>, /// Marked after each call that can write an audit record. audited: tokio::sync::watch::Sender<()>, + /// A change that the node refused and whose stored value is still to + /// put back, because the store failed. No request runs before that. + undo: Option, +} + +struct Undo { + kind: ChangeKind, + id: String, + replaced: aether_store::Replaced, } pub type SharedAdministration = Arc>; @@ -342,6 +389,11 @@ pub trait LiveNode: Send + Sync { /// path — see `NodeService::approved_workspace`. fn apply_workspace(&self, id: &str, path: &str) -> Result<(), AdminError>; + /// Whether [`Self::apply_workspace`] would take this id and path. The + /// administration asks before it stores a workspace change, because a + /// node start makes the stored workspace live without this check. + fn check_workspace(&self, id: &str, path: &str) -> Result<(), AdminError>; + fn workspace(&self) -> Option; fn apply_grant(&self, id: &str, grant: &str) -> Result<(), AdminError>; @@ -506,10 +558,15 @@ pub mod test_support { self.change(format!("limit {} {limit}", id.as_str())) } - fn apply_workspace(&self, id: &str, path: &str) -> Result<(), AdminError> { + fn check_workspace(&self, _id: &str, path: &str) -> Result<(), AdminError> { if self.existing_workspaces && !std::path::Path::new(path).is_dir() { return Err(AdminError::InvalidField("path")); } + Ok(()) + } + + fn apply_workspace(&self, id: &str, path: &str) -> Result<(), AdminError> { + self.check_workspace(id, path)?; self.change(format!("workspace {id} {path}"))?; *self.workspace.lock().expect("workspace must lock") = Some(path.to_owned()); @@ -576,6 +633,7 @@ impl Administration { store, live: None, audited: tokio::sync::watch::Sender::new(()), + undo: None, } } @@ -623,6 +681,7 @@ impl Administration { change: &Change, actor: AuditActor, ) -> Result { + self.settle()?; if self.change_requires_confirmation(change, actor) { self.queue_pending(change)?; Ok(ApplyOutcome::Pending) @@ -632,6 +691,19 @@ impl Administration { } } + /// Puts back the stored value of a change that the node refused, when + /// an earlier request could not. Until this works, the store and the + /// node differ, so the request that called it must not run. + fn settle(&mut self) -> Result<(), AdminError> { + if let Some(undo) = self.undo.take() + && self.store.revert_change(undo.kind, &undo.id, &undo.replaced).is_err() + { + self.undo = Some(undo); + return Err(AdminError::Store); + } + Ok(()) + } + fn queue_pending(&mut self, change: &Change) -> Result<(), AdminError> { let base_revision = self.revision.load(std::sync::atomic::Ordering::Acquire); self.store @@ -645,64 +717,79 @@ impl Administration { .map_err(|_| AdminError::Store) } - /// Writes the durable value first, then the live value. A live failure - /// restores the previous durable value, so a caller reads `applied` only - /// after both states hold the new value. + /// The admin revision that the next applied change moves the node to. + fn next_revision(&self) -> Result { + self.revision + .load(std::sync::atomic::Ordering::Acquire) + .checked_add(1) + .ok_or(AdminError::Store) + } + + /// Writes the durable value with the new admin revision and the audit + /// record in one transaction, then the live value. A process that stops + /// in between starts with the stored value, so the store and the node + /// agree again. A live failure restores the previous durable value, so + /// a caller reads `applied` only after both states hold the new value. fn apply_now( &mut self, change: &Change, actor: AuditActor, ) -> Result<(), AdminError> { - let previous = self + self.settle()?; + self.check_live(change)?; + let revision = self.next_revision()?; + let replaced = self .store - .apply_change(change.kind(), change.id(), &change.value()) + .apply_change(change.kind(), change.id(), &change.value(), actor, revision) .map_err(|_| AdminError::Store)?; - self.finish_live(change, previous.as_deref(), actor) + self.revision.store(revision, std::sync::atomic::Ordering::Release); + self.finish_live(change, replaced) + } + + /// Refuses, before the store has `change`, a workspace that the running + /// node would not take. + fn check_live(&self, change: &Change) -> Result<(), AdminError> { + match (&change.request, self.live.as_ref()) { + (ChangeRequest::Workspace { id, path }, Some(live)) => { + live.check_workspace(id, path) + } + _ => Ok(()), + } } - /// Applies `change` live once its durable value is written. Success - /// records the new admin revision with the audit record; a live failure - /// restores `previous`, the durable value that the change replaced. + /// Applies `change` live once its durable value is written. A live + /// failure restores `replaced`, what the change replaced in the store. + /// When the store cannot do that now, the next request does it first. fn finish_live( &mut self, change: &Change, - previous: Option<&str>, - actor: AuditActor, + replaced: aether_store::Replaced, ) -> Result<(), AdminError> { - match self.apply_live(change) { - Ok(revision) => self - .store - .record_applied_change(actor, revision) - .map_err(|_| AdminError::Store), - Err(error) => { - self.store - .revert_change(change.kind(), change.id(), previous, actor) - .map_err(|_| AdminError::Store)?; - Err(error) - } + let Err(error) = self.apply_live(change) else { + return Ok(()); + }; + if self.store.revert_change(change.kind(), change.id(), &replaced).is_err() { + self.undo = Some(Undo { + kind: change.kind(), + id: change.id().to_owned(), + replaced, + }); + return Err(AdminError::Store); } + Err(error) } - /// Applies `change` live and returns the admin revision it moved to. - fn apply_live(&self, change: &Change) -> Result { - self.apply_live_inner(change)?; - Ok(self - .revision - .fetch_add(1, std::sync::atomic::Ordering::AcqRel) - .wrapping_add(1)) - } - - fn apply_live_inner(&self, change: &Change) -> Result<(), AdminError> { + fn apply_live(&self, change: &Change) -> Result<(), AdminError> { let live = self.live.as_ref(); match &change.request { ChangeRequest::Limit { id, limit } => { live.map_or(Ok(()), |live| live.set_queue_limit(*id, *limit)) } + // Each workspace id keeps its own path, and one of them is + // live; the store has it as the current workspace, so a restart + // makes that one live again. ChangeRequest::Workspace { id, path } => { - live.map_or(Ok(()), |live| live.apply_workspace(id, path))?; - // Each workspace id keeps its own path, and one of them is - // live; a restart makes that one live again. - self.store.set_current_workspace(path).map_err(|_| AdminError::Store) + live.map_or(Ok(()), |live| live.apply_workspace(id, path)) } ChangeRequest::Grant { id, grant } => { let text = crate::identity::encode_grant(grant) @@ -724,6 +811,11 @@ impl Administration { ChangeRequest::Capability { capability, .. } => live .ok_or(AdminError::Unsupported("capability")) .and_then(|live| live.publish_capability(capability)), + // The running node keeps its settings until it starts again. + ChangeRequest::Policy { settings } => { + crate::policy::save_policy_settings_in_store(&self.store, settings) + .map_err(|_| AdminError::Store) + } } } @@ -737,9 +829,27 @@ impl Administration { live.queue_limit(*id).is_ok_and(|current| *limit <= current) }) } + ChangeRequest::Policy { settings } => self.policy_is_wider(settings), _ => change.is_high_risk(), } } + + /// Whether `settings` move the task folder root or raise a limit of the + /// stored policy. A policy that cannot be read proves nothing, so it + /// counts as wider. + fn policy_is_wider(&self, settings: &crate::policy::PolicySettings) -> bool { + use aether_core::limits::QueueLimitId::{Global, PerPeer}; + let Ok(Some(current)) = crate::policy::policy_settings_in_store(&self.store) + else { + return true; + }; + settings.workspace != current.workspace + || settings.max_context_tokens > current.max_context_tokens + || settings.max_seconds > current.max_seconds + || settings.queue.get(Global) > current.queue.get(Global) + || settings.queue.get(PerPeer) > current.queue.get(PerPeer) + } + /// Confirms a durably pending change the same way `apply_now` applies an /// immediate one: write the durable value, apply it live, and revert the /// durable value if the live application fails. @@ -749,6 +859,7 @@ impl Administration { } fn confirm_pending(&mut self, id: &str) -> Result<(), AdminError> { + self.settle()?; let pending = self.store.pending_change_ignoring_expiry(id).map_err( |error| match error { StoreError::NotFound => AdminError::ConfirmationRequired, @@ -757,17 +868,21 @@ impl Administration { )?; let change = change_from_pending(&pending)?; self.check_not_stale(id)?; - let previous = - self.store.confirm_pending_change(id).map_err(|error| match error { + self.check_live(&change)?; + let revision = self.next_revision()?; + let replaced = self.store.confirm_pending_change(id, revision).map_err( + |error| match error { StoreError::InvalidState => AdminError::Expired, StoreError::NotFound => AdminError::ConfirmationRequired, _ => AdminError::Store, - })?; - self.finish_live(&change, previous.as_deref(), AuditActor::Ui) + }, + )?; + self.revision.store(revision, std::sync::atomic::Ordering::Release); + self.finish_live(&change, replaced) } - /// Rejects confirming `id` if some other change was applied live after - /// it was queued. A change that an older node queued has no revision and + /// Rejects confirming `id` if some other change was stored after it was + /// queued, applied live or not. A change that an older node queued has no revision and /// is not checked. fn check_not_stale(&self, id: &str) -> Result<(), AdminError> { let base = self.store.pending_revision(id).map_err(|_| AdminError::Store)?; @@ -804,30 +919,52 @@ impl Administration { fn revoke_inner(&mut self, id: &str, actor: AuditActor) -> Result<(), AdminError> { valid(id, "id")?; + self.settle()?; let live = self.live.clone().ok_or(AdminError::Unsupported("revoke"))?; - self.store.revoke_applied_grant(id).map_err(|_| AdminError::Store)?; - live.revoke_grant(id)?; - self.store - .record_change(actor, AuditResult::Applied) - .map_err(|_| AdminError::Store) + // The audit record is in the store with the revocation, before the + // node drops the grant. + self.store.revoke_applied_grant(id, actor).map_err(|_| AdminError::Store)?; + live.revoke_grant(id) } + /// Saves the policy settings for the next node start. From MCP, settings + /// that move the task folder root or raise a limit wait for the owner's + /// confirmation in the UI, as a workspace or a limit change does. pub fn save_policy_settings( &mut self, settings: &crate::policy::PolicySettings, actor: AuditActor, - ) -> Result<(), AdminError> { - crate::policy::save_policy_settings_in_store(&self.store, settings).map_err( - |error| match error { - crate::policy::PolicyError::InvalidField(_) => { - AdminError::InvalidField("policy") - } - _ => AdminError::Store, - }, - )?; - self.store + ) -> Result { + let result = self.save_policy_settings_inner(settings, actor); + self.audited(result) + } + + fn save_policy_settings_inner( + &mut self, + settings: &crate::policy::PolicySettings, + actor: AuditActor, + ) -> Result { + self.settle()?; + let change = + ChangeRequest::Policy { settings: settings.clone() }.into_change()?; + if self.change_requires_confirmation(&change, actor) { + self.queue_pending(&change)?; + return Ok(ApplyOutcome::Pending); + } + // The audit record is written first, so that no saved policy is + // without one. + let audit = self + .store .record_change(actor, AuditResult::Applied) - .map_err(|_| AdminError::Store) + .map_err(|_| AdminError::Store)?; + if crate::policy::save_policy_settings_in_store(&self.store, settings).is_err() + { + // The record stays `applied` when this fails too: the policy + // may be saved in part. + let _ = self.store.fail_change(audit); + return Err(AdminError::Store); + } + Ok(ApplyOutcome::Applied) } pub fn set_relay(&self, relay: Option) -> Result<(), AdminError> { @@ -936,7 +1073,9 @@ impl Change { ChangeRequest::Grant { grant, .. } => { !crate::direct::grant_is_low_risk_invite(grant) } - ChangeRequest::Workspace { .. } | ChangeRequest::Capability { .. } => true, + ChangeRequest::Workspace { .. } + | ChangeRequest::Capability { .. } + | ChangeRequest::Policy { .. } => true, _ => false, } } @@ -1548,6 +1687,91 @@ mod tests { administration.confirm_ui("unknown"), Err(AdminError::ConfirmationRequired) ); + // The expired change left, so its id can be queued again. + assert_eq!( + administration.confirm_ui("workspace"), + Err(AdminError::ConfirmationRequired) + ); + assert_eq!( + administration.submit( + &ChangeRequest::Workspace { + id: "workspace".to_owned(), + path: "project".to_owned(), + } + .into_change() + .expect("change must parse"), + aether_store::AuditActor::Mcp, + false, + ), + Ok(ChangeOutcome::Pending) + ); + } + + #[test] + fn a_change_that_the_node_refused_makes_a_pending_change_stale() { + let (_directory, mut administration) = in_temp_dir(); + let node = Arc::new(FakeNode::default().with_queue_limit(10)); + administration.set_live(node.clone()); + administration + .submit( + &ChangeRequest::Capability { + id: "capability".to_owned(), + capability: "review".to_owned(), + } + .into_change() + .expect("change must parse"), + aether_store::AuditActor::Mcp, + false, + ) + .expect("high-risk change must queue"); + // The store has the limit and its revision before the node is + // asked, so a process that stops there starts with the limit and + // still refuses the older confirmation. + node.fail_with(AdminError::InvalidField("limit")); + assert_eq!( + administration.submit( + &limit_change(aether_core::limits::QueueLimitId::Global, 2), + aether_store::AuditActor::Mcp, + false + ), + Err(AdminError::InvalidField("limit")) + ); + assert_eq!(administration.store.admin_revision(), Ok(1)); + assert_eq!(administration.confirm_ui("capability"), Err(AdminError::Stale)); + assert_eq!(administration.audit().expect("audit"), ["pending", "failed"]); + } + + #[test] + fn a_workspace_that_the_node_refuses_never_reaches_the_store() { + let directory = tempfile::tempdir().expect("directory must create"); + let (_store_directory, mut administration) = in_temp_dir(); + let first = directory.path().display().to_string(); + let node = Arc::new(FakeNode::default().with_workspace(&first)); + administration.set_live(node.clone()); + let missing = directory.path().join("missing").display().to_string(); + let change = |path: &str| { + ChangeRequest::Workspace { id: "one".to_owned(), path: path.to_owned() } + .into_change() + .expect("change must parse") + }; + assert_eq!( + administration.apply(&change(&missing), aether_store::AuditActor::Ui), + Err(AdminError::InvalidField("path")) + ); + assert_eq!(administration.store.current_workspace(), Ok(None)); + assert_eq!( + administration + .store + .applied_change(aether_store::ChangeKind::Workspace, "one"), + Ok(None) + ); + assert!(node.calls().is_empty()); + // A workspace that the node takes is the stored current workspace + // in the same step as its value. + administration + .apply(&change(&first), aether_store::AuditActor::Ui) + .expect("an existing workspace must apply"); + assert_eq!(administration.store.current_workspace(), Ok(Some(first))); } #[test] diff --git a/crates/aether/src/admin_socket.rs b/crates/aether/src/admin_socket.rs index ed302d3..c5fa3cb 100644 --- a/crates/aether/src/admin_socket.rs +++ b/crates/aether/src/admin_socket.rs @@ -15,7 +15,8 @@ use serde::{Deserialize, Serialize}; use aether_store::AuditActor; use crate::admin::{ - AdminError, AuditEntry, ChangeOutcome, ChangeRequest, SharedAdministration, + AdminError, ApplyOutcome, AuditEntry, ChangeOutcome, ChangeRequest, + SharedAdministration, }; const MAX_SOCKET_BYTES: u64 = 65_536; @@ -318,7 +319,10 @@ fn handle( } } else { match administration.save_policy_settings(&settings, AuditActor::Mcp) { - Ok(()) => Response::Applied, + Ok(ApplyOutcome::Applied) => Response::Applied, + // A new task folder root or a higher limit waits for the + // owner's confirmation in the UI. + Ok(ApplyOutcome::Pending) => Response::Pending, Err(error) => error_response(&error), } } diff --git a/crates/aether/src/admin_ui/advanced.rs b/crates/aether/src/admin_ui/advanced.rs index f8dc59d..e989be5 100644 --- a/crates/aether/src/admin_ui/advanced.rs +++ b/crates/aether/src/admin_ui/advanced.rs @@ -378,9 +378,7 @@ mod tests { session_cookie_pair, }, }; - use aether_store::{ - AuditActor, AuditResult, ManagedMember, NodeStore, QueueLimits, TaskInput, - }; + use aether_store::{AuditActor, ManagedMember, NodeStore, QueueLimits, TaskInput}; #[test] fn a_failed_confirm_keeps_its_token_and_a_confirmed_one_uses_it_up() { @@ -518,11 +516,10 @@ mod tests { aether_store::ChangeKind::Capability, "review", "private-credential", + AuditActor::Mcp, + 1, ) .expect("change must apply"); - store - .record_change(AuditActor::Mcp, AuditResult::Applied) - .expect("change must record"); store .put_scope("scope", aether_core::ScopeKind::Direct) .expect("scope must store"); diff --git a/crates/aether/src/admin_ui/listing.rs b/crates/aether/src/admin_ui/listing.rs index 71131e0..854c183 100644 --- a/crates/aether/src/admin_ui/listing.rs +++ b/crates/aether/src/admin_ui/listing.rs @@ -209,7 +209,13 @@ mod tests { let (page, cookie, data_dir) = service_page(directory.path(), &hub).await; NodeStore::in_dir(&data_dir) .expect("store must open") - .apply_change(aether_store::ChangeKind::Limit, "queue_global", "3") + .apply_change( + aether_store::ChangeKind::Limit, + "queue_global", + "3", + aether_store::AuditActor::Ui, + 1, + ) .expect("limit must store"); let home = get_with(page, "/", &cookie).await; assert!( diff --git a/crates/aether/src/agent.rs b/crates/aether/src/agent.rs index dc21281..7d40fc0 100644 --- a/crates/aether/src/agent.rs +++ b/crates/aether/src/agent.rs @@ -107,8 +107,9 @@ impl EarlyCancels { } /// Notes that the turn of `task_id` ended, so that a later cancel for it - /// is dropped. + /// is dropped. A cancel that was kept while the turn ran is dropped too. fn end(&mut self, task_id: &str) { + self.forget(task_id); remember(&mut self.ended, task_id); } @@ -146,6 +147,14 @@ mod tests { assert!(!cancels.take("task")); } + #[test] + fn a_cancel_kept_while_the_turn_ran_is_dropped_at_its_end() { + let mut cancels = EarlyCancels::default(); + cancels.cancel("task"); + cancels.end("task"); + assert!(!cancels.take("task")); + } + #[test] fn a_forgotten_cancel_does_not_stop_a_later_start() { let mut cancels = EarlyCancels::default(); diff --git a/crates/aether/src/agent/connected.rs b/crates/aether/src/agent/connected.rs index 43fede3..62db8f6 100644 --- a/crates/aether/src/agent/connected.rs +++ b/crates/aether/src/agent/connected.rs @@ -48,7 +48,28 @@ struct Shared { type Writer = Arc>; -type Pending = Arc>>>; +type Pending = Arc>; + +/// The turns that are open on one connection. +/// +/// A turn holds this lock from the insert of its task until the `task` +/// message is written. A cancel therefore finds a task here only after the +/// agent got it, and `serve` closes the turns of a connection only between +/// two such writes. +#[derive(Default)] +struct Turns { + open: BTreeMap>, + /// The connection was replaced or ended. No turn starts on it. + closed: bool, +} + +impl Turns { + /// Closes the connection for turns and returns the open ones. + fn close(&mut self) -> BTreeMap> { + self.closed = true; + std::mem::take(&mut self.open) + } +} struct Connection { generation: u64, @@ -166,8 +187,17 @@ impl Shared { } let generation = self.generation.fetch_add(1, Ordering::Relaxed).wrapping_add(1); - let pending = Arc::new(Mutex::new(BTreeMap::new())); + let pending = Arc::new(Mutex::new(Turns::default())); let Ok(mut connection) = self.connection.lock() else { return }; + // The replaced connection is closed for turns before the new one + // takes its place. A turn that took it writes no task to it after + // this, and no answer of its agent is read into a turn. + let cancelled = connection + .as_ref() + .and_then(|replaced| { + replaced.pending.lock().ok().map(|mut turns| turns.close()) + }) + .unwrap_or_default(); let replaced = connection.replace(Connection { generation, stream: control, @@ -176,14 +206,12 @@ impl Shared { }); drop(connection); if let Some(replaced) = replaced { - if let Ok(pending) = replaced.pending.lock() { - for (task_id, sender) in pending.iter() { - let _ = write_json_line( - &replaced.writer, - &NodeMessage::Cancel { id: task_id.as_str() }, - ); - let _ = sender.send(Reply::Cancelled); - } + for (task_id, sender) in cancelled { + let _ = write_json_line( + &replaced.writer, + &NodeMessage::Cancel { id: task_id.as_str() }, + ); + let _ = sender.send(Reply::Cancelled); } let _ = replaced.stream.shutdown(Shutdown::Both); } @@ -195,22 +223,26 @@ impl Shared { AgentMessage::Failed { id } => (id, Reply::Failed), AgentMessage::Cancelled { id } => (id, Reply::Cancelled), }; - if let Ok(pending) = pending.lock() - && let Some(sender) = pending.get(&id) + if let Ok(turns) = pending.lock() + && let Some(sender) = turns.open.get(&id) { let _ = sender.send(reply); } } - if let Ok(mut connection) = self.connection.lock() + // Under the `connection` mutex, as in the replace path: a turn + // that took this connection but is not open yet does not start. + // Each sender is dropped, so a turn that waits fails. + let connection = self.connection.lock(); + if let Ok(mut turns) = pending.lock() { + drop(turns.close()); + } + if let Ok(mut connection) = connection && connection .as_ref() .is_some_and(|current| current.generation == generation) { *connection = None; } - if let Ok(mut pending) = pending.lock() { - pending.clear(); - } } } @@ -233,9 +265,9 @@ impl ConnectedAgent { ctx: &TurnContext, events: &mut dyn FnMut(ExecutionEvent), ) -> Result { - let (writer, pending, receiver) = { - // Held until the turn is pending, so that a cancel either finds - // it pending or is kept for this check. + let (writer, pending, receiver, sent) = { + // Held until the turn is open, so that a cancel either finds + // it open or is kept for this check. let mut cancels = self.shared.cancels.lock().map_err(|_| ExecutionError::Unavailable)?; if cancels.take(&ctx.task_id) { @@ -243,26 +275,34 @@ impl ConnectedAgent { } let (writer, pending) = self.connection()?; let (sender, receiver) = mpsc::channel(); - { - let mut pending = + let sent = { + let mut turns = pending.lock().map_err(|_| ExecutionError::Unavailable)?; - if pending.contains_key(&ctx.task_id) { + if turns.closed { + return Err(ExecutionError::Unavailable); + } + if turns.open.contains_key(&ctx.task_id) { return Err(ExecutionError::Protocol); } - pending.insert(ctx.task_id.clone(), sender); - } - drop(cancels); - (writer, pending, receiver) + turns.open.insert(ctx.task_id.clone(), sender); + drop(cancels); + // Written before `turns` is unlocked: a cancel waits for + // this lock, so the agent gets the task first. + let sent = write_json_line( + &writer, + &NodeMessage::Task { + id: &ctx.task_id, + instructions: agent_instructions(&ctx.skill), + text: &ctx.text, + }, + ); + drop(turns); + sent + }; + (writer, pending, receiver, sent) }; let result = (|| { - write_json_line( - &writer, - &NodeMessage::Task { - id: &ctx.task_id, - instructions: agent_instructions(&ctx.skill), - text: &ctx.text, - }, - )?; + sent?; loop { let remaining = ctx .deadline @@ -285,8 +325,8 @@ impl ConnectedAgent { } } })(); - if let Ok(mut pending) = pending.lock() { - pending.remove(&ctx.task_id); + if let Ok(mut turns) = pending.lock() { + turns.open.remove(&ctx.task_id); } if result == Err(ExecutionError::Timeout) { write_json_line(&writer, &NodeMessage::Cancel { id: &ctx.task_id })?; @@ -311,7 +351,7 @@ impl Agent for ConnectedAgent { fn cancel(&self, task_id: &str) { let Ok(mut cancels) = self.shared.cancels.lock() else { return }; if let Ok((writer, pending)) = self.connection() - && pending.lock().is_ok_and(|pending| pending.contains_key(task_id)) + && pending.lock().is_ok_and(|turns| turns.open.contains_key(task_id)) { drop(cancels); let _ = write_json_line(&writer, &NodeMessage::Cancel { id: task_id }); @@ -493,6 +533,13 @@ mod tests { assert!(peer.take().expect("a connection").closed(), "{name}"); } else if step["closes"] == "agent" { peer = None; + // The node sees the close before the next step: an agent + // that attached earlier would replace the connection and + // cancel its turns. + while agent.generation().is_some() { + assert!(Instant::now() < deadline, "{name}: the node must detach"); + std::thread::sleep(Duration::from_millis(1)); + } } } for (id, outcome) in case["outcomes"].as_object().expect("outcomes") { @@ -704,6 +751,92 @@ mod tests { assert_eq!(answer(&mut peer), Ok("answer".to_owned())); } + #[test] + fn a_cancel_never_reaches_the_agent_before_its_task() { + let directory = tempfile::tempdir().expect("directory must create"); + let path = crate::data_dir::DataDir::new(directory.path()).agent_socket(); + let agent = ConnectedAgent::listen(&path).expect("listen"); + let mut peer = + Peer::attach(&agent, &path, &json!({"type": "ready", "protocol": 1})); + peer.stream + .set_read_timeout(Some(Duration::from_secs(5))) + .expect("timeout must set"); + let deadline = + Instant::now().checked_add(Duration::from_secs(5)).expect("deadline"); + for round in 0..100 { + let id = format!("task-{round}"); + let mut runner = agent.clone(); + let ctx = turn_ctx(&id, "hello", deadline); + let turn = std::thread::spawn(move || runner.start_turn(&ctx)); + // The cancels race with the start of the turn. One that comes + // before the start is kept and no task is sent. + let canceller = agent.clone(); + let task = id.clone(); + let cancels = std::thread::spawn(move || { + for _ in 0..20 { + canceller.cancel(&task); + } + }); + cancels.join().expect("cancels join"); + // A marker turn ends the lines of this round. + let mut marker = agent.clone(); + let mark = std::thread::spawn(move || { + marker.start_turn(&turn_ctx("marker", "hello", deadline)) + }); + let mut first = None; + loop { + let line = peer.read(); + if line["id"] == "marker" { + break; + } + first.get_or_insert(line); + } + if let Some(first) = first { + assert_eq!(first["type"], "task", "round {round}"); + peer.write(&json!({"type": "cancelled", "id": id})); + } + peer.write(&json!({"type": "result", "id": "marker", "text": "m"})); + assert_eq!(mark.join().expect("marker joins"), Ok("m".to_owned())); + assert_eq!( + turn.join().expect("turn joins"), + Err(ExecutionError::Cancelled) + ); + } + } + + #[test] + fn a_connection_that_ended_takes_no_turn() { + let directory = tempfile::tempdir().expect("directory must create"); + let path = crate::data_dir::DataDir::new(directory.path()).agent_socket(); + let agent = ConnectedAgent::listen(&path).expect("listen"); + let peer = + Peer::attach(&agent, &path, &json!({"type": "ready", "protocol": 1})); + // What a turn holds between `connection()` and its insert. + let (_, taken) = agent.connection().expect("a connection"); + // The agent closes only its sending side: it still reads. + peer.stream.shutdown(std::net::Shutdown::Write).expect("half close"); + let deadline = + Instant::now().checked_add(Duration::from_secs(5)).expect("deadline"); + while !taken.lock().expect("turns lock").closed { + assert!(Instant::now() < deadline, "the connection must close"); + std::thread::sleep(Duration::from_millis(1)); + } + } + + #[test] + fn a_replaced_connection_takes_no_turn() { + let directory = tempfile::tempdir().expect("directory must create"); + let path = crate::data_dir::DataDir::new(directory.path()).agent_socket(); + let agent = ConnectedAgent::listen(&path).expect("listen"); + let ready = json!({"type": "ready", "protocol": 1}); + let _first = Peer::attach(&agent, &path, &ready); + let (_, taken) = agent.connection().expect("a connection"); + let _second = Peer::attach(&agent, &path, &ready); + // `attach` returns when the new connection is in place; the old + // one was closed for turns before that. + assert!(taken.lock().expect("turns lock").closed); + } + #[test] fn a_file_that_is_not_a_socket_is_kept() { let directory = tempfile::tempdir().expect("directory must create"); diff --git a/crates/aether/src/control_service.rs b/crates/aether/src/control_service.rs index 7a2e436..28ebc90 100644 --- a/crates/aether/src/control_service.rs +++ b/crates/aether/src/control_service.rs @@ -44,6 +44,8 @@ pub enum ControlError { Expired, #[error("record was not found")] NotFound, + #[error("record is not later than a revoked record")] + Revoked, #[error("control store error")] Store(#[from] aether_store::StoreError), #[error("control server error: {0}")] @@ -83,14 +85,23 @@ impl ControlService { Err(aether_store::StoreError::NotFound) => false, Err(error) => return Err(ControlError::Store(error)), }; - store.publish_signed_record( - &wire.signed_store_record().map_err(|_| ControlError::InvalidRecord)?, - if is_renewal { - aether_store::DirectoryEventType::Renewed - } else { - aether_store::DirectoryEventType::Published - }, - )?; + // The request is the signed record alone, and a record is public. + // The store refuses one from before a revocation, which anyone + // could send again. + store + .publish_signed_record( + &wire.signed_store_record().map_err(|_| ControlError::InvalidRecord)?, + &wire.signing_key, + if is_renewal { + aether_store::DirectoryEventType::Renewed + } else { + aether_store::DirectoryEventType::Published + }, + ) + .map_err(|error| match error { + aether_store::StoreError::InvalidState => ControlError::Revoked, + error => ControlError::Store(error), + })?; // Held from the read to the write, so two publishes cannot interleave. drop(store); Ok(is_renewal) @@ -139,7 +150,9 @@ impl ControlService { if decode_record(&existing.record)?.signing_key != wire.signing_key { return Err(ControlError::InvalidRecord); } - store.revoke_signed_record(agent_id).map_err(map_store_error)?; + store + .revoke_signed_record(agent_id, &wire.signing_key) + .map_err(map_store_error)?; // Held from the key check to the revocation. drop(store); Ok(()) @@ -284,6 +297,7 @@ impl IntoResponse for ControlError { Self::Forged => StatusCode::UNAUTHORIZED, Self::Expired => StatusCode::GONE, Self::NotFound => StatusCode::NOT_FOUND, + Self::Revoked => StatusCode::CONFLICT, Self::Store(_) | Self::Server(_) | Self::Io(_) => { StatusCode::INTERNAL_SERVER_ERROR } @@ -523,6 +537,36 @@ mod tests { assert!(matches!(service.changes_after(-1), Err(ControlError::InvalidRecord))); } + #[test] + fn a_revoked_record_cannot_be_published_again() { + let directory = tempfile::tempdir().expect("directory must create"); + let service = + ControlService::open(DataDir::new(directory.path()).control_store()) + .expect("service must open"); + let key = SigningKey::from_bytes(&[7; 32]); + let record = record_for(&key); + + service.publish(&record).expect("record must publish"); + service.revoke("test-agent", &record).expect("record must revoke"); + // The record is public, so this sender need not be its owner. + assert!(matches!(service.publish(&record), Err(ControlError::Revoked))); + assert!(matches!(service.resolve("test-agent"), Err(ControlError::NotFound))); + assert_eq!(service.changes_after(0).expect("changes must load").len(), 2); + + let later = WireRecord::from_record(&signed_record( + &key, + "test-agent".to_owned(), + "endpoint".to_owned(), + vec!["127.0.0.1:9443".to_owned()], + "test-scope".to_owned(), + vec!["test".to_owned()], + SystemTime::now() + Duration::from_secs(7_200), + )); + assert!(!service.publish(&later).expect("a later record must publish")); + assert!(matches!(service.publish(&record), Err(ControlError::Revoked))); + assert_eq!(service.resolve("test-agent").expect("record must resolve"), later); + } + #[test] fn forged_records_are_not_stored() { let directory = tempfile::tempdir().expect("directory must create"); diff --git a/crates/aether/src/directory_client.rs b/crates/aether/src/directory_client.rs index 10c5675..a502809 100644 --- a/crates/aether/src/directory_client.rs +++ b/crates/aether/src/directory_client.rs @@ -9,7 +9,7 @@ use aether_store::DirectoryEventType; use crate::{ discovery::{ - validate_record, + DiscoveryError, validate_record, wire::{self, WireDirectoryEvent, WireRecord}, }, pinned_json::{self, HttpError, PinnedJsonClient}, @@ -30,6 +30,8 @@ pub enum DirectoryClientError { InvalidRecord, #[error("directory record signer is not trusted")] UntrustedRecord, + #[error("directory record has expired")] + ExpiredRecord, } impl From for DirectoryClientError { @@ -84,7 +86,7 @@ impl DirectoryClient { &[StatusCode::OK], ) .await?; - self.validate(&record)?; + self.validate_resolved(agent_id, &record)?; Ok(record) } @@ -121,6 +123,13 @@ impl DirectoryClient { Ok(()) } + /// The events of the directory after `cursor`, in order. + /// + /// The directory keeps each event for ever, and it takes a record of + /// any key for a free agent ID. So an honest directory also sends a + /// record that has expired since, or one that another key signed. Such + /// an event comes back without its record: the caller has nothing to + /// keep, and moves its cursor past the event. pub async fn events_after( &self, cursor: i64, @@ -128,7 +137,7 @@ impl DirectoryClient { if cursor < 0 { return Err(DirectoryClientError::InvalidRecord); } - let events: Vec = pinned_json::json( + let mut events: Vec = pinned_json::json( self.http .client() .get(self.events_url()?) @@ -142,8 +151,10 @@ impl DirectoryClient { ) { return Err(DirectoryClientError::InvalidRecord); } - for event in &events { - self.validate_event(event)?; + for event in &mut events { + if !self.validate_event(event)? { + event.record = None; + } } Ok(events) } @@ -169,13 +180,35 @@ impl DirectoryClient { if record.signing_key != self.trusted_signing_key { return Err(DirectoryClientError::UntrustedRecord); } - validate_record(&record).map_err(|_| DirectoryClientError::InvalidRecord) + validate_record(&record).map_err(|error| match error { + DiscoveryError::Expired => DirectoryClientError::ExpiredRecord, + DiscoveryError::Forged | DiscoveryError::Malformed => { + DirectoryClientError::InvalidRecord + } + }) + } + + /// Checks the answer of the directory to a question about `agent_id`. + /// The directory chooses the record that it sends, so a valid record of + /// another agent is refused here. + fn validate_resolved( + &self, + agent_id: &str, + record: &WireRecord, + ) -> Result<(), DirectoryClientError> { + if record.agent_id != agent_id { + return Err(DirectoryClientError::InvalidRecord); + } + self.validate(record) } + /// Whether the caller can keep the record of `event`. `false` for a + /// record that expired or that another key signed; an event that is + /// malformed, or whose signature does not fit, is an error. fn validate_event( &self, event: &WireDirectoryEvent, - ) -> Result<(), DirectoryClientError> { + ) -> Result { if event.scope_id.is_empty() { return Err(DirectoryClientError::InvalidRecord); } @@ -189,9 +222,16 @@ impl DirectoryClient { { return Err(DirectoryClientError::InvalidRecord); } - self.validate(record) + match self.validate(record) { + Ok(()) => Ok(true), + Err( + DirectoryClientError::UntrustedRecord + | DirectoryClientError::ExpiredRecord, + ) => Ok(false), + Err(error) => Err(error), + } } - DirectoryEventType::Revoked if event.record.is_none() => Ok(()), + DirectoryEventType::Revoked if event.record.is_none() => Ok(true), DirectoryEventType::Revoked => Err(DirectoryClientError::InvalidRecord), } } @@ -262,12 +302,14 @@ pub async fn sync_directory( // `events_after` refuses a page whose cursors do not climb past // `cursor`, and an event whose record does not match its type, so // each change moves the cursor forward and needs no further check. + // It takes the record out of an event that this node cannot use. for change in changes { match change.event { DirectoryEventType::Published | DirectoryEventType::Renewed => { - let record = change.record.as_ref().ok_or(Failed)?; - cache_wire_directory_record(&store, record)?; - records = records.checked_add(1).ok_or(Failed)?; + if let Some(record) = change.record.as_ref() { + cache_wire_directory_record(&store, record)?; + records = records.checked_add(1).ok_or(Failed)?; + } } DirectoryEventType::Revoked => { store.mark_directory_record_stale( @@ -344,12 +386,24 @@ pub async fn request_via_directory( #[cfg(test)] mod tests { - use std::{fs, time::Duration}; + use std::{ + fs, + time::{Duration, SystemTime}, + }; + use aether_store::DirectoryEventType; use axum_server::Handle; - use super::{DirectoryClient, DirectoryClientError}; - use crate::{control_service::serve, discovery::wire::WireRecord}; + use super::{ + DirectoryClient, DirectoryClientError, cached_directory_record, sync_directory, + }; + use crate::{ + control_service::serve, + discovery::{ + signed_record, + wire::{WireDirectoryEvent, WireRecord}, + }, + }; use ed25519_dalek::SigningKey; fn trusted_signing_key() -> [u8; 32] { @@ -435,6 +489,155 @@ mod tests { )); } + fn offline_client() -> DirectoryClient { + DirectoryClient::with_pinned_certificate( + "https://directory.test", + rcgen::generate_simple_self_signed(vec!["directory.test".to_owned()]) + .expect("certificate must generate") + .cert + .der(), + trusted_signing_key(), + ) + .expect("client must build") + } + + fn record_of(key: u8, agent_id: &str, expires_at: SystemTime) -> WireRecord { + WireRecord::from_record(&signed_record( + &SigningKey::from_bytes(&[key; 32]), + agent_id.to_owned(), + "endpoint".to_owned(), + vec!["127.0.0.1:9443".to_owned()], + "test-scope".to_owned(), + vec!["test".to_owned()], + expires_at, + )) + } + + fn published(record: WireRecord) -> WireDirectoryEvent { + WireDirectoryEvent { + cursor: 1, + event: DirectoryEventType::Published, + scope_id: record.scope_id.clone(), + agent_id: record.agent_id.clone(), + record: Some(record), + } + } + + #[test] + fn a_resolved_record_of_another_agent_is_refused() { + let client = offline_client(); + let record = WireRecord::test_record(); + client + .validate_resolved("test-agent", &record) + .expect("the record of the agent must pass"); + // A directory that answers with a valid record of another agent. + assert!(matches!( + client.validate_resolved("other-agent", &record), + Err(DirectoryClientError::InvalidRecord) + )); + } + + #[test] + fn an_event_with_a_record_that_cannot_be_used_is_skipped_not_refused() { + let client = offline_client(); + let soon = SystemTime::now() + Duration::from_secs(60); + let past = SystemTime::now() - Duration::from_secs(60); + assert!(matches!( + client.validate_event(&published(record_of(7, "agent", soon))), + Ok(true) + )); + // The record expired after the directory took it. + assert!(matches!( + client.validate_event(&published(record_of(7, "agent", past))), + Ok(false) + )); + // The directory takes a record of any key for a free agent ID. + assert!(matches!( + client.validate_event(&published(record_of(8, "agent", soon))), + Ok(false) + )); + let mut forged = published(record_of(7, "agent", soon)); + if let Some(record) = forged.record.as_mut() { + record.endpoint_id = "changed".to_owned(); + } + assert!(matches!( + client.validate_event(&forged), + Err(DirectoryClientError::InvalidRecord) + )); + let mut misfiled = published(record_of(7, "agent", soon)); + misfiled.agent_id = "other".to_owned(); + assert!(matches!( + client.validate_event(&misfiled), + Err(DirectoryClientError::InvalidRecord) + )); + } + + #[tokio::test] + async fn a_record_of_another_key_in_the_log_does_not_stop_the_sync() { + let directory = tempfile::tempdir().expect("directory must create"); + let data_dir = directory.path().join("control"); + let node_dir = directory.path().join("node"); + let handle = Handle::new(); + let server = tokio::spawn({ + let handle = handle.clone(); + let data_dir = data_dir.clone(); + async move { serve(&data_dir, 0, handle).await } + }); + let address = tokio::time::timeout(Duration::from_secs(5), handle.listening()) + .await + .expect("server must listen") + .expect("server address must exist"); + let certificate = + fs::read(crate::data_dir::DataDir::new(&data_dir).control_certificate()) + .expect("certificate must exist"); + let url = format!("https://127.0.0.1:{}", address.port()); + let client = DirectoryClient::with_pinned_certificate( + &url, + &certificate, + trusted_signing_key(), + ) + .expect("client must trust the directory"); + let soon = SystemTime::now() + Duration::from_secs(60); + let stranger = DirectoryClient::with_pinned_certificate( + &url, + &certificate, + SigningKey::from_bytes(&[8; 32]).verifying_key().to_bytes(), + ) + .expect("client must build"); + stranger + .publish(&record_of(8, "stranger", soon)) + .await + .expect("the directory takes a record of any key"); + let listed = record_of(7, "listed", soon); + client.publish(&listed).await.expect("record must publish"); + + let (cursor, records) = + sync_directory(&node_dir, &url, trusted_signing_key(), &client) + .await + .expect("the sync must pass the record of the other key"); + assert_eq!((cursor, records), (2, 1)); + assert!( + cached_directory_record( + &node_dir, + "test-scope", + "listed", + trusted_signing_key() + ) + .is_ok() + ); + assert!( + cached_directory_record( + &node_dir, + "test-scope", + "stranger", + trusted_signing_key() + ) + .is_err() + ); + handle.graceful_shutdown(Some(Duration::from_secs(5))); + server.await.expect("server task must finish").expect("server must stop"); + } + #[tokio::test] async fn trusted_client_completes_directory_record_operations() { let directory = tempfile::tempdir().expect("directory must create"); diff --git a/crates/aether/src/invites.rs b/crates/aether/src/invites.rs index 9e996fb..a110904 100644 --- a/crates/aether/src/invites.rs +++ b/crates/aether/src/invites.rs @@ -78,6 +78,13 @@ pub fn sign_direct_invite( ) } +/// One call of [`sign_direct_invite`] at a time in this process. A call +/// reads the group, adds the person, and takes the person out again when +/// it fails. Two calls for one person that interleave would undo each +/// other: the one that fails would take out the person that the other +/// one's invite needs. +static SIGNING: std::sync::Mutex<()> = std::sync::Mutex::new(()); + /// [`crate::direct::encode_invite_after_grant`], which tests replace. type EncodeInvite = fn( &Path, @@ -103,6 +110,7 @@ fn sign_direct_invite_with( let internal = |error: &dyn std::fmt::Display| { InviteError::Internal(std::io::Error::other(error.to_string())) }; + let _signing = SIGNING.lock().unwrap_or_else(std::sync::PoisonError::into_inner); let agent_card = crate::direct::create_card(&signing.data_dir, agent_name) .map_err(|error| internal(&error))?; let (authorization, grant) = crate::direct::sign_invite_access( @@ -242,6 +250,86 @@ mod tests { assert_eq!(members(data_dir, group), ["ana"]); } + #[test] + fn a_failing_invite_does_not_take_out_the_person_of_a_second_invite() { + use std::sync::mpsc::{Receiver, Sender, channel}; + use std::sync::{Mutex, PoisonError}; + use std::time::Duration; + + // The failing call says that it reached the encode step, then + // waits a moment for the second call before it fails. + static REACHED: Mutex>> = Mutex::new(None); + static SECOND_DONE: Mutex>> = Mutex::new(None); + + let directory = tempfile::tempdir().expect("directory must create"); + let data_dir = directory.path(); + let administration = shared_in(data_dir); + let node = Arc::new(FakeNode::default().with_workspace("/start")); + administration.lock().expect("administration must lock").set_live(node); + let signing = DirectInviteSigning::for_data_dir(data_dir); + let group = crate::access_groups::REQUESTS_GROUP; + let endpoint = iroh::SecretKey::generate().public().to_string(); + let (reached, reached_rx) = channel(); + let (second_done, second_done_rx) = channel(); + *REACHED.lock().unwrap_or_else(PoisonError::into_inner) = Some(reached); + *SECOND_DONE.lock().unwrap_or_else(PoisonError::into_inner) = + Some(second_done_rx); + + std::thread::scope(|scope| { + let failing = scope.spawn(|| { + sign_direct_invite_with( + &administration, + &signing, + "law", + "ana", + &endpoint, + 7, + group, + AuditActor::Ui, + |_, _, _, _, _, _| { + let reached = REACHED + .lock() + .unwrap_or_else(PoisonError::into_inner) + .take(); + if let Some(reached) = reached { + let _ = reached.send(()); + } + let done = SECOND_DONE + .lock() + .unwrap_or_else(PoisonError::into_inner) + .take(); + if let Some(done) = done { + let _ = done.recv_timeout(Duration::from_millis(500)); + } + Err(crate::direct::DirectError::Unavailable) + }, + ) + }); + reached_rx.recv().expect("the first call must reach the encode step"); + let second = sign_direct_invite_with( + &administration, + &signing, + "law", + "ana", + &endpoint, + 7, + group, + AuditActor::Ui, + |_, _, _, _, _, _| Ok("line".to_owned()), + ); + let _ = second_done.send(()); + assert!(failing.join().expect("the first call must not panic").is_err()); + let (_, grant_id) = second.expect("the second call must sign"); + let grants = administration + .lock() + .expect("administration must lock") + .grants() + .expect("grants must read"); + assert!(grants.iter().any(|grant| grant.id.as_str() == grant_id)); + }); + assert_eq!(members(data_dir, group), ["ana"]); + } + #[test] fn invite_agent_name_matches_the_host_page() { let directory = tempfile::tempdir().expect("directory must create"); diff --git a/crates/aether/src/mcp/tools/admin.rs b/crates/aether/src/mcp/tools/admin.rs index f61263c..85527c7 100644 --- a/crates/aether/src/mcp/tools/admin.rs +++ b/crates/aether/src/mcp/tools/admin.rs @@ -139,7 +139,7 @@ impl McpServer { #[tool( name = "aether.settings.update_policy", - description = "Validate or save task policy limits and the task folder root. Omitted fields keep their values. Saved changes take effect after a node restart." + description = "Validate or save task policy limits and the task folder root. Omitted fields keep their values. A new task folder root or a higher limit waits for the owner's confirmation in the admin UI. Saved changes take effect after a node restart." )] async fn settings_update_policy( &self, @@ -181,6 +181,14 @@ impl McpServer { }) .to_string(), ), + Ok(Response::Pending) => tool_success( + json!({ + "status": "pending", + "restartRequired": false, + "next": "The owner confirms this change on the Advanced page.", + }) + .to_string(), + ), Ok(Response::Error { code }) => refused("the policy change", &code), _ => tool_error("administration service is unavailable"), } @@ -587,7 +595,8 @@ mod tests { None, ) .expect("first policy must create"); - let server = served(&data_dir, shared_in(&data_dir)); + let administration = shared_in(&data_dir); + let server = served(&data_dir, administration.clone()); let request = PolicyUpdateArguments { workspace: None, max_context_tokens: None, @@ -610,7 +619,7 @@ mod tests { workspace: None, max_context_tokens: None, max_seconds: Some(75), - queue_global: Some(2), + queue_global: None, queue_per_peer: None, dry_run: false, })) @@ -621,7 +630,37 @@ mod tests { .expect("policy must read") .expect("policy must exist"); assert_eq!(settings.max_seconds, 75); - assert_eq!(settings.queue.global, 2); + + // A higher limit or another task folder root waits for the owner. + let other = directory.path().join("other"); + std::fs::create_dir(&other).expect("folder must create"); + let raised = server + .settings_update_policy(Parameters(PolicyUpdateArguments { + workspace: Some(other.display().to_string()), + max_context_tokens: None, + max_seconds: Some(76), + queue_global: Some(2), + queue_per_peer: None, + dry_run: false, + })) + .await; + assert_eq!(raised.is_error, Some(false), "{}", decode_text(&raised)); + assert_eq!(decode(&raised)["status"], "pending"); + let saved = || { + crate::policy::policy_settings(&data_dir) + .expect("policy must read") + .expect("policy must exist") + }; + assert_eq!(saved().max_seconds, 75); + assert_ne!(saved().workspace, other); + administration + .lock() + .expect("administration must lock") + .confirm_ui("policy") + .expect("the owner must confirm the policy"); + assert_eq!(saved().max_seconds, 76); + assert_eq!(saved().queue.global, 2); + assert_eq!(saved().workspace, other); } #[tokio::test] diff --git a/crates/aether/src/node_builder.rs b/crates/aether/src/node_builder.rs index 8e32b66..1140ec1 100644 --- a/crates/aether/src/node_builder.rs +++ b/crates/aether/src/node_builder.rs @@ -412,6 +412,8 @@ mod tests { aether_store::ChangeKind::Limit, aether_core::limits::QueueLimitId::Global.as_str(), "2", + aether_store::AuditActor::Ui, + 1, ) .expect("queue limit must store"); drop(store); @@ -885,6 +887,8 @@ mod tests { aether_store::ChangeKind::Grant, "restored", &encode_grant(&restored_grant).expect("grant must encode"), + aether_store::AuditActor::Ui, + 1, ) .expect("grant must store"); drop(store); diff --git a/crates/aether/src/node_service.rs b/crates/aether/src/node_service.rs index 838fe7d..3810046 100644 --- a/crates/aether/src/node_service.rs +++ b/crates/aether/src/node_service.rs @@ -310,11 +310,21 @@ where } fn apply_workspace(&self, id: &str, path: &str) -> Result<(), AdminError> { + self.check_workspace(id, path)?; + self.service + .apply_workspace(Path::new(path)) + .map_err(|_| AdminError::InvalidField("path")) + } + + fn check_workspace(&self, id: &str, path: &str) -> Result<(), AdminError> { let path = Path::new(path); if !self.service.workspace_change_is_approved(id, path) { return Err(AdminError::InvalidField("id")); } - self.service.apply_workspace(path).map_err(|_| AdminError::InvalidField("path")) + if !path.is_dir() { + return Err(AdminError::InvalidField("path")); + } + Ok(()) } fn workspace(&self) -> Option { diff --git a/crates/aether/src/outbox.rs b/crates/aether/src/outbox.rs index 153ff6d..a5f237b 100644 --- a/crates/aether/src/outbox.rs +++ b/crates/aether/src/outbox.rs @@ -395,12 +395,36 @@ async fn follow( replayed = true; continue; } + // An ended status is not enough to stop: the host cut the page + // before the last event when it says that more events remain. + let more_events = result + .as_ref() + .is_ok_and(|frames| crate::transport::response_more_events_remain(frames)); let outcome = outcome(&task.task_id, result); after = after.max(outcome.last_event_sequence); - if outcome.state != SentState::Working || started.elapsed() >= window { + let working = outcome.state == SentState::Working; + if !working && !more_events { return Ok(Outcome { last_event_sequence: after, ..outcome }); } - tokio::time::sleep(POLL_INTERVAL).await; + if started.elapsed() >= window { + return Ok(still_working(outcome, after)); + } + if working { + tokio::time::sleep(POLL_INTERVAL).await; + } + } +} + +/// The outcome of an attempt whose window closed before the last page of +/// events: the task stays active, and the next attempt reads on from `after`. +fn still_working(outcome: Outcome, after: u64) -> Outcome { + Outcome { + state: SentState::Working, + reason: None, + host_state: outcome.host_state, + answer: None, + last_event_sequence: after, + delay: Some(Delay::Working), } } @@ -833,6 +857,73 @@ mod tests { assert_eq!(kept.answer.as_deref(), Some("done")); } + /// One page of an ended task: the cursor, and whether events remain. + #[expect(clippy::unnecessary_wraps, reason = "a scripted answer is a Result")] + fn page(cursor: i64, more_events: bool) -> Result, TransportError> { + let task = "00000000-0000-4000-8000-000000000001"; + Ok(vec![Frame { + version: 0, + kind: FrameKind::Result, + exchange_id: "e".to_owned(), + scope_id: "direct".to_owned(), + task_id: Some(task.to_owned()), + payload: crate::transport::text_result_payload_with_progress( + task, + A2aTaskStatus::Completed, + "done", + cursor, + more_events, + ), + }]) + } + + #[tokio::test] + async fn an_ended_task_is_read_to_its_last_event() { + let (_host, caller) = caller(); + let task = enqueue(caller.path(), "tudor", "work", now()).expect("enqueue"); + let courier = Scripted::with(vec![page(2, true), page(4, false)]); + let state = + attempt(caller.path(), courier.as_ref(), &task, Duration::from_secs(5)) + .await + .expect("attempt"); + assert_eq!(state, SentState::Answered); + let cursors: Vec> = courier + .requests() + .iter() + .map(|frame| { + serde_json::from_value::(frame.payload.clone()) + .expect("payload") + .last_event_sequence + }) + .collect(); + assert_eq!(cursors, [Some(0), Some(2)]); + let kept = NodeStore::in_dir(caller.path()) + .expect("store") + .sent_task(&task.task_id) + .expect("read") + .expect("the task exists"); + assert_eq!(kept.last_event_sequence, 4); + assert_eq!(kept.answer.as_deref(), Some("done")); + } + + #[tokio::test] + async fn a_closed_window_keeps_a_task_with_more_events_active() { + let (_host, caller) = caller(); + let task = enqueue(caller.path(), "tudor", "work", now()).expect("enqueue"); + let courier = Scripted::with(vec![page(2, true)]); + let state = attempt(caller.path(), courier.as_ref(), &task, Duration::ZERO) + .await + .expect("attempt"); + assert_eq!(state, SentState::Working); + let kept = NodeStore::in_dir(caller.path()) + .expect("store") + .sent_task(&task.task_id) + .expect("read") + .expect("the task exists"); + assert_eq!(kept.last_event_sequence, 2); + assert_eq!(kept.answer, None); + } + #[tokio::test] async fn a_replay_of_an_admitted_frame_asks_again_with_a_new_frame() { let (_host, caller) = caller(); diff --git a/crates/aether/src/policy.rs b/crates/aether/src/policy.rs index f7b17ff..d21152c 100644 --- a/crates/aether/src/policy.rs +++ b/crates/aether/src/policy.rs @@ -320,7 +320,7 @@ pub(crate) fn load_or_create( /// Settings the owner can change on the Advanced page. They take effect at /// the next node start, when the executor and queue are built. -#[derive(Clone)] +#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)] pub struct PolicySettings { pub workspace: PathBuf, pub max_context_tokens: u32, @@ -338,6 +338,14 @@ pub fn policy_settings(data_dir: &Path) -> Result, Policy Ok(stored(&store)?.as_ref().map(PolicyFile::settings)) } +/// The settings of the policy that `store` holds; `None` before the first +/// start. +pub(crate) fn policy_settings_in_store( + store: &NodeStore, +) -> Result, PolicyError> { + Ok(stored(store)?.as_ref().map(PolicyFile::settings)) +} + /// Saves the common policy settings and keeps every other field of the /// stored policy. The running node keeps its current settings until /// restart. diff --git a/crates/aether/src/proof/mod.rs b/crates/aether/src/proof/mod.rs index babb7ef..3f1df76 100644 --- a/crates/aether/src/proof/mod.rs +++ b/crates/aether/src/proof/mod.rs @@ -61,8 +61,12 @@ pub struct SubmissionInput<'a> { pub task: &'a Task, } -pub(crate) const REPLAY_LIMIT: usize = 256; pub(crate) const REPLAY_TTL: Duration = Duration::from_secs(300); +/// The replay entries that the node keeps for one endpoint and scope. An +/// entry stays for `REPLAY_TTL`, and a full table refuses the next frame, so +/// the table has room for every frame that the peer rate limit lets through +/// in that time: its burst and then `PEER_REQUESTS_PER_SECOND` each second. +pub(crate) const REPLAY_LIMIT: usize = 2408; pub(crate) const RESULT_TTL: Duration = Duration::from_hours(24); pub(crate) const LEASE_TTL: Duration = Duration::from_secs(30); pub(crate) const LEASE_RENEWAL_INTERVAL: Duration = Duration::from_secs(10); @@ -467,27 +471,28 @@ where Ok(()) } + /// Cancels the task that `caller_endpoint` sent as `task_id`, and returns + /// the ID that the node keeps it under. pub fn cancel_from( &self, task_id: &str, caller_endpoint: &EndpointId, scope_id: &str, - ) -> Result<(), ProofError> { - let task_id = task_id.to_owned(); - { + ) -> Result { + let task_id = { let _guard = self.dispatch_serial.lock().map_err(|_| ProofError::Internal)?; let caller_endpoint = caller_endpoint.as_str().to_owned(); let scope_id = scope_id.to_owned(); - let stored_task_id = task_id.clone(); + let sent_task_id = task_id.to_owned(); self.store.call(move |store| { - store.cancel_if_owned(&stored_task_id, &caller_endpoint, &scope_id) - })?; - } + store.cancel_if_owned(&sent_task_id, &caller_endpoint, &scope_id) + })? + }; self.canceller.cancel(&task_id); let _ = self.scheduler_wake.try_send(()); - let _ = self.event_sender.send(task_id); - Ok(()) + let _ = self.event_sender.send(task_id.clone()); + Ok(task_id) } } @@ -543,6 +548,13 @@ mod tests { test_support::Trusted, }; + #[test] + fn the_replay_table_holds_every_frame_that_the_rate_limit_lets_through() { + let frames = u64::from(crate::transport::PEER_REQUESTS_PER_SECOND) + * (REPLAY_TTL.as_secs() + 1); + assert!(u64::try_from(REPLAY_LIMIT).expect("limit fits") >= frames); + } + #[derive(Clone)] struct Cancellable { cancelled: Arc, diff --git a/docs/usage.md b/docs/usage.md index d8c6e4d..0b9a04b 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -81,9 +81,10 @@ The same node data directory serves MCP tools for these groups, task policy, relay and hub URLs, your hub name, invites, and direct access. Use `aether.settings.get` to read the saved policy and URLs. Use `aether.settings.update_policy` to edit task limits or the task folder root. -Policy changes need a node restart. `aether.settings.set_relay` changes a -running node at once, and `aether.settings.set_hub` takes effect on the next -hub request. The `aether.name.*`, `aether.invites.*`, `aether.access.list` +A new task folder root or a higher limit waits until you confirm it under +Pending changes on the Advanced page. Policy changes need a node restart. +`aether.settings.set_relay` changes a running node at once, and +`aether.settings.set_hub` takes effect on the next hub request. The `aether.name.*`, `aether.invites.*`, `aether.access.list` and `aether.access.revoke` tools cover the matching actions on the Sharing page. On a node without an agent type, a first `aether.name.set` makes a personal agent: claim a service agent on the page. `aether.access.request` diff --git a/specs/Admission.cfg b/specs/Admission.cfg index 3ab7f1a..8338b12 100644 --- a/specs/Admission.cfg +++ b/specs/Admission.cfg @@ -1,15 +1,17 @@ \* Admission: one wire request on the host. See Admission.tla. \* Two endpoints, and the owner can give the name `alice` to both, so that -\* the shared per-peer limit is in the model. NoTaskIdClash, NoSharedQuota -\* and NoReplayBeforeExpiry are false; the spec explains each one. +\* two endpoints with one name are in the model. The node can make one +\* task ID of its own, for one clash of task IDs. There is one data value: +\* a changed request under a known key has another name or task ID. CONSTANTS Eps = {e1, e2} Names = {alice, mallory} HonestName = alice HonestEp = e1 TaskIds = {t1, t2} + NodeIds = {m1} Keys = {k1, k2} - Data = {d1, d2} + Data = {d1} Nonces = {n1, n2} ReplayLimit = 1 Global = 2 @@ -25,11 +27,15 @@ INVARIANTS AdmittedWasCovered RowOfInvitedPerson OneTaskPerKey + OneTaskPerSentId QueueWithinLimits OnlyGoodFramesChange NoForeignRead OnlyOwnerCancels + NoTaskIdClash + NoSharedQuota PROPERTIES RowsAreStable + NoReplayBeforeExpiry HonestGetsIn diff --git a/specs/Admission.tla b/specs/Admission.tla index d5fbb3e..be6e8f5 100644 --- a/specs/Admission.tla +++ b/specs/Admission.tla @@ -18,7 +18,8 @@ (* verify_grant *) (* crates/aether-store/src/tasks.rs admit_with_replay, *) (* accept_replay_key, admit, *) -(* count, cancel_if_owned *) +(* own_ids, count, *) +(* cancel_if_owned *) (* crates/aether-store/src/access_groups.rs access_group_allows *) (* *) (* Every endpoint is an attacker here: it can send any frame under its own *) @@ -46,11 +47,15 @@ (* frame for another scope has no claim that fits, and `policy_data` *) (* refuses it. Only a cancel frame carries a scope here. The request ID *) (* (`tasks.request_id`, also UNIQUE) is the task ID, as in `direct.rs`. *) +(* An ID that the node makes (`random_id`) is 128 random bits, so no *) +(* caller sends it: NodeIds and TaskIds share nothing. *) (* The replay table has one part for each endpoint and scope; with one *) (* scope it has one part for each endpoint. All replay entries have the *) (* same lifetime (REPLAY_TTL), so the oldest entry expires first, and an *) (* expired entry is the same as no entry: `accept_replay_key` deletes the *) -(* expired entries before it reads. *) +(* expired entries before it reads. REPLAY_LIMIT has room for every frame *) +(* that the peer rate limit lets through in REPLAY_TTL; the model does not *) +(* have the rate limit, so here an endpoint can fill its part. *) (***************************************************************************) EXTENDS Naturals, Sequences, FiniteSets @@ -60,12 +65,13 @@ CONSTANTS HonestName, \* the name of the person that the last properties look at HonestEp, \* and the endpoint of that person TaskIds, \* task IDs (UUIDs that the caller chooses) + NodeIds, \* task IDs that the node makes for a row Keys, \* idempotency keys Data, \* the rest of a request: its fingerprint Nonces, \* `exchangeId:requestNonce` values ReplayLimit, \* REPLAY_LIMIT Global, \* QueueLimits.global - PerPeer, \* QueueLimits.per_peer + PerPeer, \* QueueLimits.per_peer, for one endpoint DirectScope, \* the scope of every task OtherScope \* another scope of the node @@ -87,11 +93,17 @@ AccessStates == {"none", "live", "revoked"} TaskStates == {"queued", "ended"} NoTask == [owner |-> "none"] -\* A `tasks` row. `auth` and `covered` are ghosts: the authenticated -\* endpoint of the frame that made the row, and whether that endpoint had -\* a live grant and a group membership under the name of the row then. +\* The primary keys of `tasks`. +RowIds == TaskIds \cup NodeIds + +\* A `tasks` row. `sent` is the task ID that the caller sent +\* (`caller_task_id`, or `id` when that is NULL). `auth` and `covered` are +\* ghosts: the authenticated endpoint of the frame that made the row, and +\* whether that endpoint had a live grant and a group membership under the +\* name of the row then. TaskRow == [owner : Eps, agent : Names, key : Keys, data : Data, - state : TaskStates, auth : Eps, covered : BOOLEAN] + sent : TaskIds, state : TaskStates, auth : Eps, + covered : BOOLEAN] \* A request frame. `cep` and `agent` are the caller endpoint and name in \* the authorization. `claim` is the person that the claim names; a claim @@ -102,7 +114,7 @@ Frames == [cep : Eps, agent : Names, claim : AllPeople, id : TaskIds, VARIABLES access, \* the claim and the grant of each person members, \* access_group_members, of any group - tasks, \* the `tasks` table, by task ID + tasks, \* the `tasks` table, by `tasks.id` replay, \* replay_entries of each endpoint, oldest first wrongAdmit, \* ghost: a frame that the host must refuse changed something leaked, \* ghost: an answer showed a task of another endpoint @@ -115,7 +127,7 @@ Range(s) == {s[i] : i \in 1..Len(s)} TypeOK == /\ access \in [AllPeople -> AccessStates] /\ members \subseteq People - /\ tasks \in [TaskIds -> TaskRow \cup {NoTask}] + /\ tasks \in [RowIds -> TaskRow \cup {NoTask}] /\ replay \in [Eps -> Seq(Nonces)] /\ \A e \in Eps : Len(replay[e]) <= ReplayLimit /\ wrongAdmit \in BOOLEAN @@ -125,16 +137,19 @@ TypeOK == Init == /\ access = [p \in AllPeople |-> "none"] /\ members = {} - /\ tasks = [id \in TaskIds |-> NoTask] + /\ tasks = [id \in RowIds |-> NoTask] /\ replay = [e \in Eps |-> <<>>] /\ wrongAdmit = FALSE /\ leaked = FALSE /\ badCancel = FALSE -Rows == {id \in TaskIds : tasks[id] # NoTask} +Rows == {id \in RowIds : tasks[id] # NoTask} Queued == {id \in Rows : tasks[id].state = "queued"} -\* `count(tx, Some(peer))`: the queued tasks of one agent NAME. -QueuedOf(name) == {id \in Queued : tasks[id].agent = name} +\* `count(tx, Some(peer))`: the queued tasks of one ENDPOINT. +QueuedOf(ep) == {id \in Queued : tasks[id].owner = ep} +\* The row of `ep` that the caller sent as the task ID `sid`. +OwnSent(ep, sid) == + {id \in Rows : tasks[id].owner = ep /\ tasks[id].sent = sid} ----------------------------------------------------------------------------- (* The owner and the clock. *) @@ -210,8 +225,9 @@ MayChange(ep, f) == /\ Covered(f.agent, ep) /\ f.nonce \notin Range(replay[ep]) -\* `accept_replay_key`: keep the nonce; at the limit the oldest entry goes. -Keep(s, n) == Append(IF Len(s) >= ReplayLimit THEN Tail(s) ELSE s, n) +\* `accept_replay_key`: the part of `ep` has room for one more nonce. A +\* full part refuses the frame; no entry goes before its time. +ReplayRoom(ep) == Len(replay[ep]) < ReplayLimit \* The row of `ep` with this idempotency key \* (`WHERE caller_endpoint_id=?1 AND idempotency_key=?2`). @@ -219,64 +235,80 @@ KeyRows(ep, key) == {id \in Rows : tasks[id].owner = ep /\ tasks[id].key = key} \* `stored == *request && fingerprint == input.request_fingerprint`. SameRequest(id, f) == - /\ id = f.id + /\ tasks[id].sent = f.id /\ tasks[id].agent = f.agent /\ tasks[id].data = f.data \* `admit`: the queue is full for this frame (StoreError::Overloaded). -Full(f) == +Full(ep) == \/ Cardinality(Queued) >= Global - \/ Cardinality(QueuedOf(f.agent)) >= PerPeer + \/ Cardinality(QueuedOf(ep)) >= PerPeer + +\* `own_ids`: the `tasks.id` values that the row of a new frame can get. +\* It is the ID of the frame when no row has it. When a row of another +\* endpoint has it, it is an ID that the node makes. (A row of the same +\* endpoint with this ID refuses the frame before; see Request.) +StoreIds(f) == + IF tasks[f.id] = NoTask THEN {f.id} + ELSE {m \in NodeIds : tasks[m] = NoTask} \* `A2aTransport::handle` -> `ProofNode::admit` -> `enqueue` -> \* `admit_with_replay`, and then `task_progress` of the admitted task. A \* frame that the policy, the group or the replay table refuses changes \* nothing, so it is no step here. An error of the transaction (a changed -\* request under a known key, a full queue, a failed INSERT) rolls back the -\* replay entry too, so it is no step either. +\* request under a known key, a full queue, a task ID that the endpoint +\* used for another key) rolls back the replay entry too, so it is no step +\* either. Request(ep, f) == /\ PolicyAdmits(ep, f) /\ GroupAllows(ep, f) /\ f.nonce \notin Range(replay[ep]) \* else DuplicateConflict - /\ replay' = [replay EXCEPT ![ep] = Keep(@, f.nonce)] + /\ ReplayRoom(ep) \* else Overloaded + /\ replay' = [replay EXCEPT ![ep] = Append(@, f.nonce)] /\ IF KeyRows(ep, f.key) # {} THEN \* TaskAdmission::Existing; else DuplicateConflict. \E id \in KeyRows(ep, f.key) : /\ SameRequest(id, f) /\ leaked' = (leaked \/ tasks[id].owner # ep) /\ wrongAdmit' = (wrongAdmit \/ ~MayChange(ep, f) - \/ id # f.id \/ tasks[id].data # f.data) + \/ tasks[id].sent # f.id + \/ tasks[id].data # f.data) /\ UNCHANGED tasks - ELSE \* TaskAdmission::Accepted; else Overloaded, or the INSERT - \* fails: `tasks.id` is the PRIMARY KEY of the whole table. - /\ ~Full(f) - /\ tasks[f.id] = NoTask - /\ tasks' = [tasks EXCEPT ![f.id] = - [owner |-> ep, agent |-> f.agent, key |-> f.key, - data |-> f.data, state |-> "queued", auth |-> ep, - covered |-> Covered(f.agent, ep)]] + ELSE \* TaskAdmission::Accepted; else Overloaded, or + \* DuplicateConflict for a task ID of another row of `ep`. + /\ ~Full(ep) + /\ OwnSent(ep, f.id) = {} + /\ \E id \in StoreIds(f) : + tasks' = [tasks EXCEPT ![id] = + [owner |-> ep, agent |-> f.agent, key |-> f.key, + data |-> f.data, sent |-> f.id, state |-> "queued", + auth |-> ep, covered |-> Covered(f.agent, ep)]] /\ wrongAdmit' = (wrongAdmit \/ ~MayChange(ep, f)) /\ UNCHANGED leaked /\ UNCHANGED <> \* `A2aTransport::cancel` -> `ProofNode::cancel_from` -> `cancel_if_owned` \* -> `cancel`. It needs no claim and no grant: the authenticated endpoint -\* and the scope must be those of the row. A task that ended stays as it -\* is (`TaskState::allows`), and a cancelled task stays cancelled. -Cancel(ep, id, scope) == - /\ id \in Rows - /\ tasks[id].owner = ep /\ scope = DirectScope \* else Unauthorized - /\ tasks[id].state = "queued" - /\ tasks' = [tasks EXCEPT ![id].state = "ended"] - /\ badCancel' = (badCancel \/ tasks[id].auth # ep \/ scope # DirectScope) - /\ UNCHANGED <> - -\* A first frame of the honest caller: its own name, endpoint and claim, a -\* key that it did not use, and a task ID that no row has. +\* and the scope must be those of the row. `sid` is the task ID that the +\* caller sent; the row is the one of `ep` with it, whatever its +\* `tasks.id`. A task that ended stays as it is (`TaskState::allows`), and +\* a cancelled task stays cancelled. +Cancel(ep, sid, scope) == + \E id \in OwnSent(ep, sid) : \* else NotFound, Unauthorized + /\ scope = DirectScope \* else Unauthorized + /\ tasks[id].state = "queued" + /\ tasks' = [tasks EXCEPT ![id].state = "ended"] + /\ badCancel' = (badCancel \/ tasks[id].auth # ep + \/ scope # DirectScope) + /\ UNCHANGED <> + +\* A first frame of the honest caller: its own name, endpoint and claim, +\* and a key and a task ID that it did not use. Another endpoint can have +\* a row with that task ID. HonestFrame(f) == /\ f.cep = HonestEp /\ f.agent = HonestName /\ f.claim = Honest /\ KeyRows(HonestEp, f.key) = {} - /\ tasks[f.id] = NoTask + /\ OwnSent(HonestEp, f.id) = {} \* The host accepts a first frame of the honest caller. HonestAdmitted == @@ -288,7 +320,7 @@ HonestAdmitted == Next == \/ \E p \in People : Grant(p) \/ Revoke(p) \/ Expire(p) \/ Join(p) \/ Leave(p) \/ \E e \in Eps : ReplayExpires(e) - \/ \E id \in TaskIds : HostRuns(id) + \/ \E id \in RowIds : HostRuns(id) \* Any endpoint sends any frame. The policy reads only the first three \* fields, so they come first: TLC then drops a refused frame early. \/ \E e \in Eps, cep \in Eps, agent \in Names, claim \in AllPeople : @@ -299,10 +331,12 @@ Next == nonce |-> nonce]) \/ \E e \in Eps, id \in TaskIds, s \in Scopes : Cancel(e, id, s) -\* The scheduler keeps working, and the honest caller sends its task again -\* (see Outbox) with a new nonce for as long as it must. +\* The scheduler keeps working, time passes for the replay entries, and +\* the honest caller sends its task again (see Outbox) with a new nonce +\* for as long as it must. Fairness == - /\ \A id \in TaskIds : WF_vars(HostRuns(id)) + /\ \A id \in RowIds : WF_vars(HostRuns(id)) + /\ \A e \in Eps : WF_vars(ReplayExpires(e)) /\ SF_vars(HonestAdmitted) Spec == Init /\ [][Next]_vars /\ Fairness @@ -329,11 +363,17 @@ OneTaskPerKey == \A a, b \in Rows : tasks[a].owner = tasks[b].owner /\ tasks[a].key = tasks[b].key => a = b +\* An endpoint has one row for a task ID that it sent, so a cancel names +\* one task. +OneTaskPerSentId == + \A a, b \in Rows : + tasks[a].owner = tasks[b].owner /\ tasks[a].sent = tasks[b].sent => a = b + \* The queue holds at most `global` tasks, and at most `per_peer` tasks of -\* one agent name. +\* one endpoint. QueueWithinLimits == /\ Cardinality(Queued) <= Global - /\ \A n \in Names : Cardinality(QueuedOf(n)) <= PerPeer + /\ \A e \in Eps : Cardinality(QueuedOf(e)) <= PerPeer \* A frame changes the tasks or the replay table only when the endpoint \* that sent it has a live grant and a membership and the nonce is new. A @@ -348,7 +388,7 @@ NoForeignRead == ~leaked \* Only the owner endpoint, in the scope of the task, cancels a task. OnlyOwnerCancels == ~badCancel -\* A row keeps its owner, name, key and data for ever: the same key with +\* A row keeps its owner, name, key, data and sent ID for ever: the same key with \* changed data never changes the task, and no frame takes a task over. \* Only the state changes, and an ended task does not change. RowsAreStable == @@ -357,53 +397,48 @@ RowsAreStable == /\ [tasks'[id] EXCEPT !.state = "queued"] = [tasks[id] EXCEPT !.state = "queued"] /\ tasks[id].state # "queued" => tasks'[id] = tasks[id]]_vars -(***************************************************************************) -(* Properties that TLC finds false. They are not in Admission.cfg; each *) -(* comment gives the counterexample. *) -(***************************************************************************) +\* The node has no ID left to make. Only this small model has that state. +NodeIdsUsedUp == NodeIds \subseteq Rows -\* A frame of `ep` that has everything it needs (access, a new nonce, a new -\* key, room in the queue) and still fails: another endpoint has a row with -\* its task ID. +\* A frame of `ep` that has everything it needs (access, a new nonce, room +\* in the replay table, a key and a task ID that `ep` did not use, room in +\* the queue) and still fails, because another endpoint has a row with its +\* task ID. ClashRefused(ep, f) == /\ PolicyAdmits(ep, f) /\ GroupAllows(ep, f) - /\ f.nonce \notin Range(replay[ep]) + /\ f.nonce \notin Range(replay[ep]) /\ ReplayRoom(ep) /\ KeyRows(ep, f.key) = {} - /\ ~Full(f) - /\ tasks[f.id] # NoTask /\ tasks[f.id].owner # ep - -\* FALSE: a caller is never refused because of a task ID that another -\* endpoint used. `tasks.id` is the PRIMARY KEY of the table (and -\* `request_id` is UNIQUE), not unique for each endpoint, and `admit` looks -\* only for a row of the same endpoint before the INSERT. Trace: the owner -\* invites two people; the second person sends a task with the ID t1 and -\* the host ends it; the first person sends its own task with the ID t1; -\* the INSERT fails with a constraint error, the caller gets "task store -\* unavailable", and every resend fails the same way, because rows stay. -\* The second person must know the ID. It is a random UUID that only the -\* first person and the host see, so the IDs keep the two apart, not the -\* table. -NoTaskIdClash == \A ep \in Eps, f \in Frames : ~ClashRefused(ep, f) - -\* FALSE: the honest caller is refused as overloaded only for its own -\* queued tasks or a full global queue. `count` uses `caller_agent_id` for -\* the per-peer limit, so two endpoints that the owner invited under one -\* name share one limit. Trace: the owner invites <> and -\* <>; e2 fills the per-peer limit; the first task of e1 gets -\* "overloaded". A caller cannot choose its name: the claim and the grant -\* carry the name that the owner gave to that endpoint (PolicyAdmits). + /\ OwnSent(ep, f.id) = {} + /\ ~Full(ep) + /\ tasks[f.id] # NoTask + /\ StoreIds(f) = {} + +\* A caller is never refused because of a task ID that another endpoint +\* used. `tasks.id` is the PRIMARY KEY of the whole table, so the row of +\* the second caller gets an ID that the node makes, and the answer and a +\* cancel still use the ID that the caller sent. +\* (The policy admits only a frame with the endpoint of the sender and its +\* claim, and the data of a new frame decides nothing, so those fields have +\* one value here.) +NoTaskIdClash == + \/ NodeIdsUsedUp + \/ \A ep \in Eps, agent \in Names, id \in TaskIds, key \in Keys, + nonce \in Nonces, data \in Data : + ~ClashRefused(ep, [cep |-> ep, agent |-> agent, + claim |-> <>, id |-> id, key |-> key, + data |-> data, nonce |-> nonce]) + +\* The honest caller is refused as overloaded only for its own queued +\* tasks or a full global queue: two endpoints that the owner invited +\* under one name do not share a limit. NoSharedQuota == - ~ /\ Covered(HonestName, HonestEp) - /\ Cardinality(Queued) < Global - /\ Cardinality({id \in Queued : tasks[id].owner = HonestEp}) < PerPeer - /\ Cardinality(QueuedOf(HonestName)) >= PerPeer - -\* FALSE: a nonce stays in the replay table until REPLAY_TTL passes. At -\* REPLAY_LIMIT entries `accept_replay_key` removes the oldest entry, so an -\* endpoint that sends REPLAY_LIMIT more frames can send its own old frame -\* again before the time passes. The frame then finds its task by the -\* idempotency key (`Existing`) and makes no second task: OneTaskPerKey. -\* (Only ReplayExpires makes the table of an endpoint shorter.) + Full(HonestEp) => + \/ Cardinality(Queued) >= Global + \/ Cardinality({id \in Queued : tasks[id].auth = HonestEp}) >= PerPeer + +\* A nonce stays in the replay table until REPLAY_TTL passes, so an +\* endpoint cannot send its own old frame again before that. (Only +\* ReplayExpires makes the table of an endpoint shorter.) NoReplayBeforeExpiry == [][\A e \in Eps : Len(replay'[e]) >= Len(replay[e]) @@ -414,13 +449,12 @@ NoReplayBeforeExpiry == HonestCovered == Covered(HonestName, HonestEp) HonestHasTask == \E id \in Rows : tasks[id].owner = HonestEp -\* Every task ID has a row, so this small model has no ID left. -IdsUsedUp == Rows = TaskIds \* An honest caller that keeps its grant and its group membership gets a \* task in, whatever the other endpoints send: the queue gets room again, -\* and no frame of another endpoint uses up its nonces or its keys. +\* and no frame of another endpoint uses up its nonces, its keys or its +\* task IDs. HonestGetsIn == - <>[]HonestCovered => <>(HonestHasTask \/ IdsUsedUp) + <>[]HonestCovered => <>(HonestHasTask \/ NodeIdsUsedUp) ============================================================================= diff --git a/specs/ConnectedAgent.cfg b/specs/ConnectedAgent.cfg index 840a506..faa8c88 100644 --- a/specs/ConnectedAgent.cfg +++ b/specs/ConnectedAgent.cfg @@ -1,9 +1,6 @@ \* ConnectedAgent: the agent socket. See ConnectedAgent.tla. \* One task ID that gets two turns, and two connections (the second -\* replaces the first, or attaches after it closed). Two tasks with one turn -\* each pass the safety properties too, but that run takes 8 minutes. -\* NoStaleCancel, NoLostCancel, TaskOnlyToAttached, AnswerWhileAttached, -\* AnswerAfterSent and NoOrphanWait are false; the spec explains each one. +\* replaces the first, or attaches after it closed). CONSTANTS Tasks = {t1} MaxConns = 2 @@ -17,14 +14,18 @@ INVARIANTS NoProtocolError AnswerFromHolder TurnEndsOnce - HonestNoOrphanWait + NoLostCancel + NoStaleCancel + NoOrphanWait PROPERTIES NoAgentNoTask EarlyCancelHonored LateCancelDropped CancelToldToHolder - HonestAnswerAfterSent + AnswerAfterSent + TaskOnlyToAttached + AnswerWhileAttached TurnEnds LostAgentFailsTurn CancelStopsHonestTurn diff --git a/specs/ConnectedAgent.tla b/specs/ConnectedAgent.tla index a874f15..31da679 100644 --- a/specs/ConnectedAgent.tla +++ b/specs/ConnectedAgent.tla @@ -8,14 +8,15 @@ (* crates/aether/src/agent/connected.rs Shared::serve (attach, the *) (* replace path, the read loop, the end of a connection), *) (* ConnectedAgent::connection, run_turn, start_turn_with_events, *) -(* cancel *) +(* cancel, Turns::close *) (* crates/aether/src/agent.rs EarlyCancels (cancel, take, *) (* end) *) (* protocol/agent-socket/README.md the rules of both sides *) (* integrations/openclaw-plugin/src/task-runner.ts the honest agent *) (* *) (* A connection is a number: the `generation` that `serve` gives it. Each *) -(* connection has its own `pending` map. A turn is one call of *) +(* connection has its own `pending` turns (`Turns`: the open task IDs and *) +(* the `closed` flag). A turn is one call of *) (* `start_turn_with_events`; each task has one thread that can run *) (* MaxTurns turns, one after the other. Turns of different tasks can run *) (* at the same time, which is more than the scheduler does (it runs one *) @@ -35,6 +36,8 @@ (* the 256-entry bound of each EarlyCancels list. A write and its receipt *) (* by the agent are one step, and so are an agent message and its read by *) (* `serve`. `generation.fetch_add` and `connection.replace` are one step. *) +(* `run_turn` holds the `pending` mutex from the insert until the `task` *) +(* message is written, so the insert and the write are one step. *) (* A turn reads only the first final reply in its channel, so the channel *) (* keeps only that one. The variables of a turn are reset when it ends. *) (***************************************************************************) @@ -48,8 +51,8 @@ CONSTANTS Conns == 1..MaxConns NoConn == 0 -Stages == {"unused", "drain", "shut", "live", "eof", "detached", "done"} -Pcs == {"idle", "got", "send", "wait", "remove", "tcancel", "ending"} +Stages == {"unused", "drain", "shut", "live", "eof", "done"} +Pcs == {"idle", "got", "wait", "remove", "tcancel", "ending"} Results == {"none", "answered", "failed", "cancelled", "timeout", "gone", "protocol"} ReplyKinds == {"result", "failed", "cancelled"} @@ -68,7 +71,9 @@ VARIABLES repl, \* the connection that a new connection replaces nodeShut, \* the node called `shutdown` on the connection agentEnd, \* "open", "half" (the agent closed its sending side), "closed" - pending, \* Connection.pending: the open task IDs + pending, \* Connection.pending: the open task IDs (Turns.open) + closed, \* Turns.closed: the connection was replaced or ended + drain, \* the turns that a new connection took from the replaced one open, \* honest agent: its open tasks (TaskRunner #open) cpend, \* honest agent: `cancelled` messages on their way to the node known, \* task IDs that the node ever wrote to an agent @@ -81,16 +86,18 @@ VARIABLES res, \* the result of the turn, until it ends turns, \* how many turns the task started ends, \* ghost: how many turns of the task ended - told \* ghost: the agent got a `cancel` after this turn's `task` + told, \* ghost: the agent got a `cancel` after this turn's `task` + sent \* ghost: the node wrote the `task` message of this turn vars == <> + closed, drain, open, cpend, known, lock, cancelled, ended, pc, tc, + chan, res, turns, ends, told, sent>> connVars == <> agentVars == <> turnVars == <> fixed == <> +ghosts == <> Free == "free" @@ -104,6 +111,8 @@ TypeOK == /\ nodeShut \in [Conns -> BOOLEAN] /\ agentEnd \in [Conns -> {"open", "half", "closed"}] /\ pending \in [Conns -> SUBSET Tasks] + /\ closed \in [Conns -> BOOLEAN] + /\ drain \in [Conns -> SUBSET Tasks] /\ open \in [Conns -> SUBSET Tasks] /\ cpend \in [Conns -> SUBSET Tasks] /\ known \subseteq Tasks @@ -117,6 +126,7 @@ TypeOK == /\ turns \in [Tasks -> 0..MaxTurns] /\ ends \in [Tasks -> 0..MaxTurns] /\ told \in [Tasks -> BOOLEAN] + /\ sent \in [Tasks -> BOOLEAN] Init == /\ honest \in BOOLEAN @@ -128,6 +138,8 @@ Init == /\ nodeShut = [c \in Conns |-> FALSE] /\ agentEnd = [c \in Conns |-> "open"] /\ pending = [c \in Conns |-> {}] + /\ closed = [c \in Conns |-> FALSE] + /\ drain = [c \in Conns |-> {}] /\ open = [c \in Conns |-> {}] /\ cpend = [c \in Conns |-> {}] /\ known = {} @@ -141,6 +153,7 @@ Init == /\ turns = [t \in Tasks |-> 0] /\ ends = [t \in Tasks |-> 0] /\ told = [t \in Tasks |-> FALSE] + /\ sent = [t \in Tasks |-> FALSE] ----------------------------------------------------------------------------- (* Helpers. *) @@ -152,10 +165,6 @@ Writable(c) == ~nodeShut[c] /\ agentEnd[c] # "closed" \* `read_message` in the read loop of `serve` returns None. EofVisible(c) == nodeShut[c] \/ agentEnd[c] # "open" -\* The node wrote the `task` message of the turn of t to the connection -\* that the turn took. -Sent(t) == pc[t] = "wait" \/ (pc[t] = "remove" /\ res[t] = "timeout") - \* The read loop of `serve`: `pending.get(&id)` and `sender.send(reply)`. \* The node ignores an answer for a task that is not open on this \* connection. A later reply is never read, so only the first is kept. @@ -177,7 +186,10 @@ AgentGetsCancel(c, S) == (* Connections: `Shared::serve`. *) \* An agent connects and says `ready`: `serve` takes the next generation -\* and puts the connection in `Shared.connection`. +\* and puts the connection in `Shared.connection`. Under the `connection` +\* mutex it first closes the turns of the connection that it replaces +\* (`Turns::close`): each open turn gets `Reply::Cancelled`, and no turn +\* starts on that connection after this. Attach == /\ gen < MaxConns /\ LET c == gen + 1 IN @@ -185,23 +197,28 @@ Attach == /\ cur' = c /\ repl' = [repl EXCEPT ![c] = cur] /\ st' = [st EXCEPT ![c] = IF cur = NoConn THEN "live" ELSE "drain"] - /\ UNCHANGED <> - -\* `serve`, the replace path, part 1: for each open task of the replaced -\* connection, write `cancel` to it and send `Reply::Cancelled`. + /\ IF cur = NoConn + THEN UNCHANGED <> + ELSE /\ closed' = [closed EXCEPT ![cur] = TRUE] + /\ drain' = [drain EXCEPT ![c] = pending[cur]] + /\ pending' = [pending EXCEPT ![cur] = {}] + /\ chan' = [t \in Tasks |-> + IF t \in pending[cur] /\ chan[t].kind = "none" + THEN [kind |-> "cancelled", from |-> NoConn] + ELSE chan[t]] + /\ UNCHANGED <> + +\* `serve`, the replace path, part 1: write `cancel` to the replaced +\* connection for each turn that was open on it. Drain(c) == /\ st[c] = "drain" - /\ LET r == repl[c] IN - /\ chan' = [t \in Tasks |-> - IF t \in pending[r] /\ chan[t].kind = "none" - THEN [kind |-> "cancelled", from |-> NoConn] - ELSE chan[t]] - /\ IF Writable(r) THEN AgentGetsCancel(r, pending[r]) - ELSE UNCHANGED agentVars + /\ IF Writable(repl[c]) THEN AgentGetsCancel(repl[c], drain[c]) + ELSE UNCHANGED agentVars + /\ drain' = [drain EXCEPT ![c] = {}] /\ st' = [st EXCEPT ![c] = "shut"] - /\ UNCHANGED <> + /\ UNCHANGED <> \* `serve`, the replace path, part 2: `replaced.stream.shutdown`. The read \* loop of the new connection starts. The honest agent of the replaced @@ -212,8 +229,8 @@ ShutOld(c) == /\ open' = [open EXCEPT ![repl[c]] = {}] /\ repl' = [repl EXCEPT ![c] = NoConn] /\ st' = [st EXCEPT ![c] = "live"] - /\ UNCHANGED <> + /\ UNCHANGED <> \* The agent process stops or closes the connection. An agent that does \* not follow the protocol can close only its sending side. The honest @@ -225,8 +242,9 @@ AgentClose(c, how) == /\ how = "half" => ~honest /\ agentEnd' = [agentEnd EXCEPT ![c] = how] /\ open' = [open EXCEPT ![c] = {}] - /\ UNCHANGED <> + /\ UNCHANGED <> \* `serve`: the read loop ends. No later message of the agent is read. SeeEof(c) == @@ -234,29 +252,25 @@ SeeEof(c) == /\ EofVisible(c) /\ st' = [st EXCEPT ![c] = "eof"] /\ cpend' = [cpend EXCEPT ![c] = {}] - /\ UNCHANGED <> - -\* `serve`, after the loop: clear `Shared.connection` when it still holds -\* this generation. + /\ UNCHANGED <> + +\* `serve`, after the loop, under the `connection` mutex: `Turns::close`, +\* then clear `Shared.connection` when it still holds this generation. +\* Each sender is dropped, so a turn that waits gets `Disconnected`, and +\* no turn starts on the connection after this. Detach(c) == /\ st[c] = "eof" - /\ cur' = IF cur = c THEN NoConn ELSE cur - /\ st' = [st EXCEPT ![c] = "detached"] - /\ UNCHANGED <> - -\* `serve`, the last step: `pending.clear()`. Each sender is dropped, so a -\* turn that waits gets `Disconnected`. -Clear(c) == - /\ st[c] = "detached" /\ chan' = [t \in Tasks |-> IF t \in pending[c] /\ chan[t].kind = "none" THEN [NoReply EXCEPT !.kind = "dropped"] ELSE chan[t]] /\ pending' = [pending EXCEPT ![c] = {}] + /\ closed' = [closed EXCEPT ![c] = TRUE] + /\ cur' = IF cur = c THEN NoConn ELSE cur /\ st' = [st EXCEPT ![c] = "done"] - /\ UNCHANGED <> + /\ UNCHANGED <> ----------------------------------------------------------------------------- (* The agent. *) @@ -276,8 +290,8 @@ AgentSays(c, t, kind) == ELSE /\ t \in known /\ UNCHANGED agentVars /\ Deliver(c, t, kind) - /\ UNCHANGED <> + /\ UNCHANGED <> \* The `cancelled` that the honest agent sent for a cancel arrives. CancelledArrives(c, t) == @@ -285,8 +299,8 @@ CancelledArrives(c, t) == /\ t \in cpend[c] /\ cpend' = [cpend EXCEPT ![c] = @ \ {t}] /\ Deliver(c, t, "cancelled") - /\ UNCHANGED <> + /\ UNCHANGED <> ----------------------------------------------------------------------------- (* One turn: `start_turn_with_events` and `run_turn`. *) @@ -312,43 +326,43 @@ Begin(t) == /\ pc' = [pc EXCEPT ![t] = "got"] /\ lock' = t /\ UNCHANGED <> - /\ UNCHANGED <> - -\* `run_turn`: `pending.insert`, then the `cancels` mutex is released. A -\* task ID that is already open is a protocol error. + /\ UNCHANGED <> + +\* `run_turn`, under the `pending` mutex of the connection that the turn +\* took: a closed connection takes no turn, and a task ID that is already +\* open is a protocol error. Otherwise insert the task, release the +\* `cancels` mutex and write the `task` message. The honest agent starts a +\* turn for it, unless a task with this ID is open (TaskRunner #start). Insert(t) == /\ pc[t] = "got" /\ lock' = Free - /\ IF t \in pending[tc[t]] - THEN /\ res' = [res EXCEPT ![t] = "protocol"] - /\ pc' = [pc EXCEPT ![t] = "ending"] - /\ UNCHANGED pending - ELSE /\ pending' = [pending EXCEPT ![tc[t]] = @ \cup {t}] - /\ pc' = [pc EXCEPT ![t] = "send"] - /\ UNCHANGED res - /\ UNCHANGED <> - -\* `run_turn`: write the `task` message. The honest agent starts a turn -\* for it, unless a task with this ID is open (TaskRunner #start). -WriteTask(t) == - /\ pc[t] = "send" /\ LET c == tc[t] IN - IF Writable(c) - THEN /\ known' = known \cup {t} - /\ open' = IF honest /\ agentEnd[c] = "open" - THEN [open EXCEPT ![c] = @ \cup {t}] ELSE open - /\ pc' = [pc EXCEPT ![t] = "wait"] - /\ UNCHANGED res - ELSE /\ res' = [res EXCEPT ![t] = "gone"] - /\ pc' = [pc EXCEPT ![t] = "remove"] - /\ UNCHANGED <> - /\ UNCHANGED < + /\ res' = [res EXCEPT ![t] = "gone"] + /\ pc' = [pc EXCEPT ![t] = "ending"] + /\ UNCHANGED <> + [] ~closed[c] /\ t \in pending[c] -> + /\ res' = [res EXCEPT ![t] = "protocol"] + /\ pc' = [pc EXCEPT ![t] = "ending"] + /\ UNCHANGED <> + [] OTHER -> + /\ pending' = [pending EXCEPT ![c] = @ \cup {t}] + /\ IF Writable(c) + THEN /\ known' = known \cup {t} + /\ open' = IF honest /\ agentEnd[c] = "open" + THEN [open EXCEPT ![c] = @ \cup {t}] ELSE open + /\ sent' = [sent EXCEPT ![t] = TRUE] + /\ pc' = [pc EXCEPT ![t] = "wait"] + /\ UNCHANGED res + ELSE /\ res' = [res EXCEPT ![t] = "gone"] + /\ pc' = [pc EXCEPT ![t] = "remove"] + /\ UNCHANGED <> + /\ UNCHANGED <> \* `run_turn`: `receiver.recv_timeout` gives a final reply, or -\* `Disconnected` after `pending.clear()`. +\* `Disconnected` after `Turns::close` in `Detach`. Receive(t) == /\ pc[t] = "wait" /\ chan[t].kind # "none" @@ -358,8 +372,8 @@ Receive(t) == [] chan[t].kind = "cancelled" -> "cancelled" [] OTHER -> "gone"] /\ pc' = [pc EXCEPT ![t] = "remove"] - /\ UNCHANGED <> + /\ UNCHANGED <> \* `run_turn`: the time limit of the turn ends. Timeout(t) == @@ -367,16 +381,16 @@ Timeout(t) == /\ limit /\ res' = [res EXCEPT ![t] = "timeout"] /\ pc' = [pc EXCEPT ![t] = "remove"] - /\ UNCHANGED <> + /\ UNCHANGED <> \* `run_turn`: `pending.remove`. Remove(t) == /\ pc[t] = "remove" /\ pending' = [pending EXCEPT ![tc[t]] = @ \ {t}] /\ pc' = [pc EXCEPT ![t] = IF res[t] = "timeout" THEN "tcancel" ELSE "ending"] - /\ UNCHANGED <> + /\ UNCHANGED <> \* `run_turn`, after a timeout: write `cancel`. A failed write replaces \* the timeout with `Unavailable`. @@ -386,22 +400,25 @@ TimeoutCancel(t) == THEN AgentGetsCancel(tc[t], {t}) /\ UNCHANGED res ELSE res' = [res EXCEPT ![t] = "gone"] /\ UNCHANGED agentVars /\ pc' = [pc EXCEPT ![t] = "ending"] - /\ UNCHANGED <> + /\ UNCHANGED <> -\* `start_turn_with_events`: `cancels.end`. The turn is over. +\* `start_turn_with_events`: `cancels.end`, which also drops a cancel that +\* was kept while the turn ran. The turn is over. End(t) == /\ pc[t] = "ending" /\ lock = Free /\ ended' = ended \cup {t} + /\ cancelled' = cancelled \ {t} /\ ends' = [ends EXCEPT ![t] = @ + 1] /\ pc' = [pc EXCEPT ![t] = "idle"] /\ tc' = [tc EXCEPT ![t] = NoConn] /\ chan' = [chan EXCEPT ![t] = NoReply] /\ res' = [res EXCEPT ![t] = "none"] /\ told' = [told EXCEPT ![t] = FALSE] - /\ UNCHANGED <> + /\ sent' = [sent EXCEPT ![t] = FALSE] + /\ UNCHANGED <> ----------------------------------------------------------------------------- (* `Agent::cancel`. The node calls it at any time: for a task whose turn *) @@ -409,6 +426,8 @@ End(t) == (* thread, shutdown). *) \* The task is open on the attached connection, so `cancel` writes it. +\* `cancel` reads this under the `pending` mutex, so after the `task` +\* message of the turn was written. CancelWrites(t) == cur # NoConn /\ t \in pending[cur] Cancel(t) == @@ -421,20 +440,21 @@ Cancel(t) == ELSE \* `EarlyCancels::cancel`: keep it, unless the turn ended. /\ cancelled' = IF t \in ended THEN cancelled ELSE cancelled \cup {t} /\ UNCHANGED <> - /\ UNCHANGED <> + /\ UNCHANGED <> ----------------------------------------------------------------------------- Next == \/ Attach \/ \E c \in Conns : - \/ Drain(c) \/ ShutOld(c) \/ SeeEof(c) \/ Detach(c) \/ Clear(c) + \/ Drain(c) \/ ShutOld(c) \/ SeeEof(c) \/ Detach(c) \/ \E how \in {"half", "closed"} : AgentClose(c, how) \/ \E t \in Tasks : \/ CancelledArrives(c, t) \/ \E kind \in ReplyKinds : AgentSays(c, t, kind) \/ \E t \in Tasks : - \/ Begin(t) \/ Insert(t) \/ WriteTask(t) \/ Receive(t) \/ Timeout(t) + \/ Begin(t) \/ Insert(t) \/ Receive(t) \/ Timeout(t) \/ Remove(t) \/ TimeoutCancel(t) \/ End(t) \/ Cancel(t) \* The node's threads keep running, and a message that the agent sent @@ -442,12 +462,12 @@ Next == \* the time limit, and the limit ends only when `limit` is TRUE. Fairness == /\ \A t \in Tasks : - /\ WF_vars(Insert(t)) /\ WF_vars(WriteTask(t)) /\ WF_vars(Receive(t)) + /\ WF_vars(Insert(t)) /\ WF_vars(Receive(t)) /\ WF_vars(Timeout(t)) /\ WF_vars(Remove(t)) /\ WF_vars(TimeoutCancel(t)) /\ WF_vars(End(t)) /\ \A c \in Conns : /\ WF_vars(Drain(c)) /\ WF_vars(ShutOld(c)) /\ WF_vars(SeeEof(c)) - /\ WF_vars(Detach(c)) /\ WF_vars(Clear(c)) + /\ WF_vars(Detach(c)) /\ \A t \in Tasks : WF_vars(CancelledArrives(c, t)) Spec == Init /\ [][Next]_vars /\ Fairness @@ -457,10 +477,11 @@ Spec == Init /\ [][Next]_vars /\ Fairness \* An open task ID belongs to a turn that runs on that connection: no \* sender stays in a `pending` map after its turn, so the protocol error -\* of `Insert` never happens. +\* of `Insert` never happens. A closed connection has no open task. PendingIsOpenTurn == \A c \in Conns, t \in Tasks : - t \in pending[c] => pc[t] \in {"send", "wait", "remove"} /\ tc[t] = c + t \in pending[c] + => pc[t] \in {"wait", "remove"} /\ tc[t] = c /\ ~closed[c] NoProtocolError == \A t \in Tasks : res[t] # "protocol" @@ -471,12 +492,27 @@ AnswerFromHolder == res[t] = "answered" => chan[t].kind = "result" /\ chan[t].from = tc[t] \* A result enters the channel of a turn only after the node sent the -\* turn's task to the connection of that agent. -AnswerAfterSentStep == - \A t \in Tasks : chan[t].kind = "none" /\ chan'[t].kind = "result" => Sent(t) +\* turn's task to the connection of that agent, also when the agent does +\* not follow the protocol and knows the task ID from an earlier turn. +AnswerAfterSent == + [][\A t \in Tasks : + chan[t].kind = "none" /\ chan'[t].kind = "result" => sent[t]]_vars + +\* A `task` goes only to the attached connection: `serve` closes a +\* connection for turns before it replaces it. +TaskOnlyToAttached == + [][\A t \in Tasks : ~sent[t] /\ sent'[t] => cur = tc[t]]_vars + +\* The result of an agent that was replaced never enters the channel of a +\* turn. +AnswerWhileAttached == + [][\A t \in Tasks : chan[t].kind = "none" /\ chan'[t].kind = "result" + => chan'[t].from = cur]_vars -\* With honest agents, the answer came after the node sent the turn. -HonestAnswerAfterSent == [][honest => AnswerAfterSentStep]_vars +\* A `cancel` never reaches the agent before its `task`: when `cancel` +\* finds the task open on the attached connection, the task was written. +NoLostCancel == + \A t \in Tasks : CancelWrites(t) /\ Writable(cur) => sent[t] \* Each turn ends once. TurnEndsOnce == @@ -501,76 +537,22 @@ LateCancelDropped == [][\A t \in Tasks : t \in ended /\ t \notin cancelled => t \notin cancelled']_vars +\* No cancel is kept after a turn of its task ended, so a later turn with +\* the same task ID is not cancelled at its start. +NoStaleCancel == + \A t \in Tasks : pc[t] = "idle" /\ turns[t] > 0 => t \notin cancelled + \* A cancel for a turn that the attached agent has is written to it. CancelToldToHolder == [][\A t \in Tasks : Cancel(t) /\ pc[t] = "wait" /\ tc[t] = cur /\ Writable(cur) => told'[t]]_vars -\* With honest agents, a turn never waits on a connection that is over -\* with nothing in its channel. -OrphanWait(t) == - pc[t] = "wait" /\ st[tc[t]] = "done" /\ chan[t].kind = "none" -HonestNoOrphanWait == \A t \in Tasks : honest => ~OrphanWait(t) - -(***************************************************************************) -(* Properties that TLC finds false. They are not in ConnectedAgent.cfg; *) -(* each comment gives the counterexample. *) -(***************************************************************************) - -\* FALSE (a race, and only with a task ID that gets a second turn): a -\* cancel is not kept after a turn of its task ended. `cancel` keeps it -\* when the task is not open on the attached connection and `cancels.end` -\* did not run yet: Attach, Begin, Insert, WriteTask, AgentSays(result), -\* Receive, Remove, Cancel (not in `pending`, not in `ended`: kept), End. -\* A second turn with this task ID is then cancelled at its start. The -\* node starts one turn for a task ID (ExecutionLease, AtMostOneStart), so -\* the kept cancel only stays in the list. -NoStaleCancel == - \A t \in Tasks : pc[t] = "idle" /\ turns[t] > 0 => t \notin cancelled - -\* FALSE (a race): a `cancel` never reaches the agent before its `task`. -\* `run_turn` inserts the task into `pending` and releases the `cancels` -\* mutex before it writes `task`: Attach, Begin, Insert, Cancel (open on -\* the attached connection: `cancel` is written), WriteTask. The honest -\* agent ignores a cancel for a task that it does not have, then runs the -\* turn. A cancel deletes the lease, so the lease renewal thread calls -\* `cancel` once more within 10 s; that second signal stops the turn. -\* The property says that no state is in this window, in which `Cancel` -\* writes `cancel` and changes nothing else. -NoLostCancel == - \A t \in Tasks : ~(CancelWrites(t) /\ Writable(cur) /\ pc[t] = "send") - -\* FALSE (a race): a `task` goes only to the attached connection. -\* `run_turn` takes the connection, and `serve` replaces it before the -\* write: Attach, Begin, Attach, Insert, WriteTask. The replaced -\* connection is still open until ShutOld. The turn then fails. -TaskOnlyToAttached == - [][\A t \in Tasks : pc[t] = "send" /\ pc'[t] = "wait" => cur = tc[t]]_vars - -\* FALSE (the same race): the result of an agent that was replaced never -\* enters the channel of a turn. Attach, Begin, Insert, WriteTask, Attach, -\* AgentSays(result) by the first agent before Drain: the answer of the -\* agent that got the task is taken. Also Attach, Begin, Attach, Drain -\* (nothing open yet), Insert, WriteTask, AgentSays(result), before ShutOld. -AnswerWhileAttached == - [][\A t \in Tasks : chan[t].kind = "none" /\ chan'[t].kind = "result" - => chan'[t].from = cur]_vars - -\* FALSE (an agent that does not follow the protocol, and a task ID that -\* gets a second turn): the answer came after the node sent the turn. An -\* agent that knows the ID from the first turn answers the second turn -\* between Insert and WriteTask. It holds with MaxTurns = 1. The agent is a -\* process of the node owner, and the node starts one turn for a task ID. -AnswerAfterSent == [][AnswerAfterSentStep]_vars - -\* FALSE (a race, with an agent that closes only its sending side): a -\* turn never waits on a connection that is over with nothing in its -\* channel. Attach, Begin (takes the connection), AgentClose(half), SeeEof, -\* Detach, Clear (`pending` is still empty), Insert, WriteTask (the agent -\* still reads, so the write succeeds). No one drops the sender, so the -\* turn waits until its time limit instead of failing at once. -NoOrphanWait == \A t \in Tasks : ~OrphanWait(t) +\* A turn never waits on a connection that is over with nothing in its +\* channel, also when the agent closed only its sending side. +NoOrphanWait == + \A t \in Tasks : + ~(pc[t] = "wait" /\ st[tc[t]] = "done" /\ chan[t].kind = "none") ----------------------------------------------------------------------------- (* Liveness. *) @@ -579,11 +561,10 @@ NoOrphanWait == \A t \in Tasks : ~OrphanWait(t) TurnEnds == \A t \in Tasks : (limit /\ pc[t] # "idle") ~> pc[t] = "idle" \* Without the time limit: when the connection of a turn is closed (the -\* node replaced it, or the agent closed it), the turn stops waiting. The -\* turn of NoOrphanWait is left out: it waits for the time limit. +\* node replaced it, or the agent closed it), the turn stops waiting. LostAgentFailsTurn == \A t \in Tasks, c \in Conns : - (~limit /\ pc[t] = "wait" /\ tc[t] = c /\ ~OrphanWait(t) + (~limit /\ pc[t] = "wait" /\ tc[t] = c /\ (nodeShut[c] \/ agentEnd[c] = "closed")) ~> pc[t] # "wait" diff --git a/specs/DirectInvite.cfg b/specs/DirectInvite.cfg index d92916a..927a16d 100644 --- a/specs/DirectInvite.cfg +++ b/specs/DirectInvite.cfg @@ -1,6 +1,5 @@ -\* Two calls of sign_direct_invite that can interleave, one caller, one -\* attacker endpoint, two contact names. ReturnedLineWorks and NoStrayMember -\* are false (see DirectInvite.tla) and are not checked here. +\* Two calls of sign_direct_invite, one caller, one attacker endpoint, two +\* contact names. CONSTANTS Invites = {i1, i2} CallerName = caller @@ -20,6 +19,8 @@ INVARIANTS AdmitOnlyInvited KeptAuthIsOwn OneNamePerEndpoint + NoStrayMember + ReturnedLineWorks PROPERTIES NameKeepsEndpoint diff --git a/specs/DirectInvite.tla b/specs/DirectInvite.tla index 314b248..ed38851 100644 --- a/specs/DirectInvite.tla +++ b/specs/DirectInvite.tla @@ -16,10 +16,13 @@ (* crates/aether/src/proof/admission.rs admit, check_group *) (* crates/aether-core/src/lib.rs PolicyEngine::admit, match_grant *) (* *) -(* sign_direct_invite has three callers that share no lock for the whole *) -(* call: the host page (admin_ui/host.rs create_invite), the admin socket *) -(* (admin_socket.rs create_invite_response, for an MCP client), and the *) -(* hub worker (hub_workers.rs sign_and_pin). So two calls can interleave; *) +(* sign_direct_invite has three callers: the host page (admin_ui/host.rs *) +(* create_invite), the admin socket (admin_socket.rs *) +(* create_invite_response, for an MCP client), and the hub worker *) +(* (hub_workers.rs sign_and_pin). All three run in the node process, and *) +(* sign_direct_invite_with holds the SIGNING lock of invites.rs for the *) +(* whole call, so one call runs at a time. The owner's other actions (a *) +(* revoke, a group change) and every request still interleave with a call; *) (* each store call and each Administration call is one atomic step. *) (* *) (* An invite line holds two separate signed things: the invitation (agent *) @@ -113,10 +116,14 @@ Init == ----------------------------------------------------------------------------- (* The host: one call of sign_direct_invite_with. *) -\* create_card, sign_invite_access, and the first is_member read -\* (`was_member` of sign_direct_invite_with). +\* A call holds the SIGNING lock from its start to its end. +Signing(i) == inv[i].pc \in {"signed", "joined", "applied"} + +\* SIGNING.lock, then create_card, sign_invite_access, and the first +\* is_member read (`was_member` of sign_direct_invite_with). Start(i, p) == /\ inv[i].pc = "idle" + /\ \A j \in Invites : ~Signing(j) /\ inv' = [inv EXCEPT ![i] = [pc |-> "signed", who |-> p, was1 |-> p \in members, was2 |-> FALSE]] /\ invited' = invited \cup {p} @@ -303,37 +310,17 @@ NameKeepsEndpoint == (Valid(n) /\ contacts'[n].ep # None) => contacts'[n].ep = contacts[n].ep ]_vars -(***************************************************************************) -(* Properties that TLC finds false. They are not in DirectInvite.cfg. *) -(***************************************************************************) - -\* FALSE: a person is in the group only through a call that reached the -\* join and did not fail, so failed calls alone leave nobody in the group. -\* -\* TLC, with two calls for one person: Start(i1) (was1 = FALSE), Join(i1), -\* Start(i2) (was1 = TRUE), Apply(i1) fails and takes the person out, -\* Join(i2) (was2 = FALSE) puts the person back, Apply(i2), Encode(i2) -\* fails. Encode uses the read of Start (was1 = TRUE), so it leaves the -\* person in the group. Both calls failed and no grant is live, but the -\* person stays a member. A member without a grant gets no task admitted -\* (AdmitOnlyInvited holds), so this is a leftover row, not an access. +\* A person is in the group only through a call that reached the join and +\* did not fail, so failed calls alone leave nobody in the group. NoStrayMember == \A p \in members : \E i \in Invites : inv[i].who = p /\ inv[i].pc \in {"joined", "applied", "done"} -\* FALSE: a line that the host returned works. When no call for the person -\* still runs, the grant is live, and the owner did not take the person out -\* of the group, the person is in the group, so check_group admits them. -\* -\* TLC, with two calls for one person (for example the host page and an -\* MCP client, or a double click): Start(i1), Join(i1) (was2 = FALSE), -\* Start(i2) (was1 = TRUE), Join(i2) (was2 = TRUE), Apply(i1) fails and -\* takes the person out of the group, Apply(i2), Encode(i2). The line of i2 -\* is returned and its grant is live, but the person is in no group, and -\* every request with it is refused (ProofError::GroupDenied). The same -\* happens when Encode(i1) fails after Start(i1) read was1 = FALSE. -\* Each call decides "I added this person" from its own read and no lock -\* covers the read and the later removal. +\* A line that the host returned works. When no call for the person still +\* runs, the grant is live, and the owner did not take the person out of +\* the group, the person is in the group, so check_group admits them. +\* Without the SIGNING lock a second call for the same person that fails +\* takes the person out of the group under the first call's line. ReturnedLineWorks == \A i \in lines : (/\ i \in live diff --git a/specs/EventPaging.cfg b/specs/EventPaging.cfg index 1cfd874..0af5d0b 100644 --- a/specs/EventPaging.cfg +++ b/specs/EventPaging.cfg @@ -1,8 +1,7 @@ \* EventPaging: the event journal, one poll page, and the polling loops. \* A page has at most two events and a byte budget of 3; a progress event \* has size 1 or 2, so two events do not always fit. See EventPaging.tla. -\* OutboxReadsToEnd is false (`follow` stops on the status alone); the spec -\* explains it. PageProgress needs Sizes within 1..Budget. +\* PageProgress needs Sizes within 1..Budget. CONSTANTS MaxEvents = 6 PageLimit = 2 @@ -22,6 +21,7 @@ INVARIANTS CursorInJournal CliInOrder CliComplete + OutboxReadsToEnd PROPERTIES JournalNeverChanges diff --git a/specs/EventPaging.tla b/specs/EventPaging.tla index ef70bc5..8312b49 100644 --- a/specs/EventPaging.tla +++ b/specs/EventPaging.tla @@ -27,7 +27,9 @@ (* One task and one caller. `mode` is chosen in Init and does not change, *) (* so one TLC run checks both polling loops: "cli" is *) (* `request_with_polling_on`, which keeps every event frame; "outbox" is *) -(* `follow`, which keeps only the cursor and the answer. *) +(* `follow`, which keeps only the cursor and the answer. A `follow` whose *) +(* window closes keeps the cursor in `sent_tasks`, and the next attempt *) +(* polls on from it, so the attempts of one task are one loop here. *) (* *) (* `task_progress` reads the state and the page in one store call, so the *) (* host read is one step. At most one exchange is in flight: each loop *) @@ -247,16 +249,17 @@ CliReceive == /\ rep' = None /\ UNCHANGED <> -\* `follow` with `outcome`: stop when the state is not Working. It does not -\* read `aetherMoreEvents`, and it keeps no event frames. +\* `follow` with `outcome`: stop on an error, or on a state that is not +\* Working whose page has no `aetherMoreEvents`. It keeps no event frames. +\* When the window closes first, `still_working` keeps the task active. OutboxReceive == /\ mode = "outbox" /\ c.phase = "sent" /\ rep # None /\ IF rep.kind = "error" THEN c' = [c EXCEPT !.phase = "error"] - ELSE c' = [c EXCEPT !.phase = IF rep.status = "working" - THEN "idle" ELSE "done", + ELSE c' = [c EXCEPT !.phase = IF Ended(rep.status) /\ ~rep.more + THEN "done" ELSE "idle", !.cursor = Max(c.cursor, rep.cursor)] /\ rep' = None /\ UNCHANGED <> @@ -362,27 +365,16 @@ CliInOrder == CliComplete == mode = "cli" /\ c.phase = "done" => termSeq > 0 /\ c.cursor >= termSeq +\* The cursor that the outbox keeps for an ended task covers the event +\* that ended it: `follow` polls on while a page has `aetherMoreEvents`, +\* as the wire profile asks, also when the status looks terminal. +OutboxReadsToEnd == + mode = "outbox" /\ c.phase = "done" => termSeq > 0 /\ c.cursor >= termSeq + \* An ended task lets the caller stop: with its last page, with an error \* frame, or (cli) with a lost exchange or the poll deadline. EndedTaskStops == (state \in Terminal \cup {"unknown_result"}) ~> (c.phase \in {"done", "error", "aborted"} \/ lost = MaxLost) -(***************************************************************************) -(* A property that TLC finds false. It is not in EventPaging.cfg. *) -(***************************************************************************) - -\* FALSE: the cursor that the outbox keeps for an ended task covers the -\* event that ended it. `follow` stops as soon as `outcome` gives a state -\* that is not Working, and neither reads `aetherMoreEvents` -\* (outbox.rs `follow`, `outcome`). The wire profile says that a caller -\* polls on while `aetherMoreEvents` is true, also when the status looks -\* terminal. With PageLimit = 2 TLC finds: Start, Progress, Finish (4 -\* events), Poll, HostRead (events 1 and 2, status completed, more = TRUE), -\* OutboxReceive: the task is answered with the cursor at 2. -\* The outbox keeps only the answer, which is in every page of a succeeded -\* task, so it loses no answer; the cursor in `sent_tasks` is short. -OutboxReadsToEnd == - mode = "outbox" /\ c.phase = "done" => c.cursor >= termSeq - ============================================================================= diff --git a/specs/ExecutionLease.tla b/specs/ExecutionLease.tla index 7558222..48ca862 100644 --- a/specs/ExecutionLease.tla +++ b/specs/ExecutionLease.tla @@ -346,7 +346,8 @@ TurnEnds == /\ w.phase = "turn" /\ \E o \in IF turn.interrupted THEN {"cancelled"} ELSE {"ok", "err"} : w' = [w EXCEPT !.phase = "finish", !.outcome = o] - /\ turn' = TurnOver(turn.early, turn.ended \cup {w.task}, turn.spurious) + /\ turn' = TurnOver(turn.early \ {w.task}, turn.ended \cup {w.task}, + turn.spurious) /\ UNCHANGED <> diff --git a/specs/ManagedRoster.cfg b/specs/ManagedRoster.cfg index 63053d5..a276c43 100644 --- a/specs/ManagedRoster.cfg +++ b/specs/ManagedRoster.cfg @@ -1,9 +1,11 @@ \* ManagedRoster: the managed roster and the directory records. See \* ManagedRoster.tla. Two agents, two tokens, two spellings of the control -\* URL, two sync processes, pages of two events. RevokeStays, -\* NoAdmitAfterServiceRevoke, ResolveIsForAgent, RevokedStaysOut, -\* EveryKeyCatchesUp and DirSyncCatchesUp are false; the spec explains -\* each one. +\* URL, two sync processes, pages of two events. +\* NoAdmitAfterServiceRevoke is false by design; the spec explains it. +\* Three directory events keep the run short. The case where the owner +\* publishes an older record over a newer one and a revoke follows needs +\* four: RevokedStaysOut also holds with MaxDirLog = 4 (run it without the +\* PROPERTIES, which takes about 20 s). CONSTANTS Agents = {a1, a2} Eps = {e1, e2} @@ -22,13 +24,15 @@ INVARIANTS RosterFromLog AdmitIsMember OneKeyExact - OneKeyRevokeStays + RevokeStays UsedRecordIsTrusted - HonestResolveIsForAgent + ResolveIsForAgent + RevokedStaysOut CacheIsSigned PROPERTIES CursorForward DirCursorForward RevokeReaches - DirSyncUnlessPoisoned + EveryKeyCatchesUp + DirSyncCatchesUp diff --git a/specs/ManagedRoster.tla b/specs/ManagedRoster.tla index cc36ab2..bafad15 100644 --- a/specs/ManagedRoster.tla +++ b/specs/ManagedRoster.tla @@ -39,7 +39,9 @@ (* A node keeps one roster for a scope, but one cursor for each pair of *) (* control URL and scope (`cursor_key`). `Keys` are the spellings of the *) (* control URL that the owner passes to `--managed-control` or to *) -(* `aether managed sync`. `OneKey` says that the node used one only. *) +(* `aether managed sync`. Each cursor reads the events from the start, so *) +(* a row of the roster only moves from absent to active to revoked. *) +(* `OneKey` says that the node used one spelling only. *) (* *) (* Abstracted away: the creation and the expiry of a token (each token *) (* exists in Init), the expiry of a member (an expired member only loses *) @@ -49,9 +51,12 @@ (* endpoint has a valid claim of the trusted issuer, the worst case), the *) (* grant, addresses and capabilities of a record, `search`, the renewal *) (* worker, and wall-clock time (each expiry is a flag that an `Expire*` *) -(* action sets at any moment). A directory page holds one event here; the *) -(* real page holds up to 128 (`EVENT_PAGE`), and one bad event refuses the *) -(* whole page. The directory cursor has one key here. *) +(* action sets at any moment). The expiry of a directory record is its *) +(* serial: a record that the trusted key signed later expires later, and *) +(* each record of the attacker expires at one time. A directory page holds *) +(* one event here; the real page holds up to 128 (`EVENT_PAGE`), and one *) +(* malformed event refuses the whole page. The directory cursor has one *) +(* key here. *) (***************************************************************************) EXTENDS Naturals, Sequences, FiniteSets @@ -103,6 +108,8 @@ VARIABLES rexp, \* serials whose expires_at passed dstore, \* signed_records of the directory, by agent dlog, \* directory_events, in order + high, \* directory_record_marks.latest_expires_at, by agent and key + tomb, \* directory_record_marks.revoked_through, by agent and key revoked, \* ghost: records that a revoke removed from the directory cache, \* the node's cached directory records, by scope and agent dcur, \* the node's directory cursor @@ -110,11 +117,14 @@ VARIABLES badUse \* ghost: which wrong uses of a record happened mvars == <> -dvars == <> +dvars == <> vars == <> Idle(k) == [key |-> k, lo |-> 0, hi |-> 0] +SignKeys == {"trusted", "other"} +\* The expiry of a record as a mark: 0 is "no mark". +Exp(r) == r.n + 1 NoEntry == [rec |-> NoRec, stale |-> FALSE] TypeOK == @@ -132,6 +142,8 @@ TypeOK == /\ rexp \subseteq 1..MaxRec /\ dstore \in [Agents -> Rec \cup {NoRec}] /\ dlog \in Seq(DirEvents) /\ Len(dlog) <= MaxDirLog + /\ high \in [Agents -> [SignKeys -> 0..(MaxRec + 1)]] + /\ tomb \in [Agents -> [SignKeys -> 0..(MaxRec + 1)]] /\ revoked \subseteq Rec /\ cache \in [Scopes -> [Agents -> [rec : Rec \cup {NoRec}, stale : BOOLEAN]]] /\ dcur \in 0..MaxDirLog @@ -153,6 +165,8 @@ Init == /\ rexp = {} /\ dstore = [a \in Agents |-> NoRec] /\ dlog = <<>> + /\ high = [a \in Agents |-> [k \in SignKeys |-> 0]] + /\ tomb = [a \in Agents |-> [k \in SignKeys |-> 0]] /\ revoked = {} /\ cache = [s \in Scopes |-> [a \in Agents |-> NoEntry]] /\ dcur = 0 @@ -206,10 +220,11 @@ Fetch(p) == \* One event of the page: apply_managed_member or revoke_managed_member. \* The cursor and the row change in one transaction. `advance_cursor` -\* refuses a cursor that does not move forward. A join replaces the row of -\* its agent and clears revoked_at (ON CONFLICT DO UPDATE); it fails when -\* another agent has the endpoint (UNIQUE). A revoke fails with NotFound -\* when no row of the agent is active. A failure ends the sync. +\* refuses a cursor that does not move forward. A join writes the row of +\* its agent unless the row is revoked (ON CONFLICT DO UPDATE ... WHERE +\* revoked_at IS NULL); it fails when another agent has the endpoint +\* (UNIQUE). A revoke keeps the revoked_at of a row that is revoked, and +\* fails with NotFound when the agent has no row. A failure ends the sync. Apply(p) == /\ mode = "managed" /\ proc[p].lo < proc[p].hi @@ -220,14 +235,15 @@ Apply(p) == ok == /\ i > cur[k] /\ IF ev.type = "joined" THEN \A b \in Agents \ {a} : roster[b].ep # ev.ep - ELSE roster[a].st = "active" + ELSE roster[a] # NoRow IN IF ok THEN /\ cur' = [cur EXCEPT ![k] = i] /\ proc' = [proc EXCEPT ![p].lo = i] /\ roster' = [roster EXCEPT ![a] = - IF ev.type = "joined" - THEN [st |-> "active", ep |-> ev.ep] - ELSE [@ EXCEPT !.st = "revoked"]] + IF ev.type = "revoked" + THEN [@ EXCEPT !.st = "revoked"] + ELSE IF @.st = "revoked" THEN @ + ELSE [st |-> "active", ep |-> ev.ep]] /\ revApplied' = IF ev.type = "revoked" THEN revApplied \cup {a} ELSE revApplied ELSE /\ proc' = [proc EXCEPT ![p].lo = proc[p].hi] @@ -243,7 +259,8 @@ Lose(p) == dvars>> \* The owner starts the node, or runs `aether managed sync`, with another -\* spelling of the control URL. The roster stays; the cursor is another one. +\* spelling of the control URL. The roster stays; the cursor is another +\* one, and it starts before the first event. Rekey(p, k) == /\ mode = "managed" /\ proc[p].lo = proc[p].hi @@ -271,39 +288,54 @@ Sign(a, s) == /\ Cardinality(signed) < MaxRec /\ signed' = signed \cup {[agent |-> a, scope |-> s, key |-> "trusted", sig |-> "good", n |-> Cardinality(signed) + 1]} - /\ UNCHANGED <> + /\ UNCHANGED <> \* Time passes the record's expires_at. ExpireRec(n) == /\ mode = "directory" /\ n \in Serials \ rexp /\ rexp' = rexp \cup {n} - /\ UNCHANGED <> + /\ UNCHANGED <> \* `validate_record` in the service: the signature fits the record's own \* key, and the record has not expired. It does not know a trusted key. ServiceAccepts(r) == r.sig = "good" /\ r.n \notin rexp -\* ControlService::publish. The request is the record alone, so anyone who -\* holds a record can send it: its owner, or a reader of the directory. -\* The service takes a record of any key for an agent id that has no -\* record, and only the same key for an agent id that has one. +\* ControlService::publish -> ControlStore::publish_signed_record. The +\* request is the record alone, so anyone who holds a record can send it: +\* its owner, or a reader of the directory. The service takes a record of +\* any key for an agent id that has no record, and only the same key for +\* an agent id that has one. It refuses a record that does not expire +\* after the last revoke of its agent id and key (`revoked_through`): each +\* record that was public before the revoke is such a record. DirPublish(r) == /\ mode = "directory" /\ dirHonest /\ r \in signed \cup Evil /\ ServiceAccepts(r) /\ dstore[r.agent] = NoRec \/ dstore[r.agent].key = r.key + /\ Exp(r) > tomb[r.agent][r.key] /\ Len(dlog) < MaxDirLog /\ dstore' = [dstore EXCEPT ![r.agent] = r] /\ dlog' = Append(dlog, [type |-> "put", agent |-> r.agent, scope |-> r.scope, rec |-> r]) - /\ UNCHANGED <> + /\ high' = [high EXCEPT ![r.agent][r.key] = + IF Exp(r) > @ THEN Exp(r) ELSE @] + /\ UNCHANGED <> -\* ControlService::revoke. The request is a record of the same agent and -\* key that `validate_record` accepts; the stored record itself is one. +\* The records of the key of agent `a`'s stored record that the directory +\* took for `a`: what a reader of the directory can hold. +Public(a) == + {dlog[i].rec : i \in {j \in 1..Len(dlog) : + /\ dlog[j].type = "put" /\ dlog[j].agent = a + /\ dlog[j].rec.key = dstore[a].key}} + +\* ControlService::revoke -> ControlStore::revoke_signed_record. The +\* request is a record of the same agent and key that `validate_record` +\* accepts; the stored record itself is one, so anyone who read a record +\* can revoke it. `revoked_through` becomes `latest_expires_at`. DirRevoke(a) == /\ mode = "directory" /\ dirHonest /\ dstore[a] # NoRec @@ -313,9 +345,10 @@ DirRevoke(a) == /\ dstore' = [dstore EXCEPT ![a] = NoRec] /\ dlog' = Append(dlog, [type |-> "revoke", agent |-> a, scope |-> dstore[a].scope, rec |-> NoRec]) - /\ revoked' = revoked \cup {dstore[a]} - /\ UNCHANGED <> + /\ tomb' = [tomb EXCEPT ![a][dstore[a].key] = high[a][dstore[a].key]] + /\ revoked' = revoked \cup Public(a) + /\ UNCHANGED <> \* DirectoryClient::validate: the trusted key, a signature that fits, and \* not expired. @@ -333,29 +366,39 @@ NextDirEvents == rec : signed \cup Evil \cup {NoRec}] ELSE {}) -\* DirectoryClient::validate_event. -EventOk(ev) == +\* DirectoryClient::validate_event: the names of the event and of its +\* record agree. Else events_after refuses the page. +EventShape(ev) == IF ev.type = "put" - THEN /\ ev.rec # NoRec - /\ ev.rec.agent = ev.agent /\ ev.rec.scope = ev.scope - /\ ClientAccepts(ev.rec) + THEN ev.rec # NoRec /\ ev.rec.agent = ev.agent /\ ev.rec.scope = ev.scope ELSE ev.rec = NoRec +\* A record that the node does not keep and does not refuse: another key +\* signed it, or it expired (DirectoryClient::validate checks the key, +\* then validate_record checks the expiry before the signature). +\* events_after takes such a record out of its event. +Unusable(r) == r.key # "trusted" \/ r.n \in rexp + \* sync_directory, first half: events_after refuses a page with an event -\* that validate_event refuses, and then nothing changes. Else -\* cache_directory_record or mark_directory_record_stale. +\* of a wrong shape or with a signature that does not fit, and then +\* nothing changes. Else cache_directory_record for a record that the node +\* can use, mark_directory_record_stale for a revoke, and nothing for a +\* record that the node cannot use. DirApply == /\ mode = "directory" /\ dpc = "idle" /\ \E ev \in NextDirEvents : - /\ EventOk(ev) + /\ EventShape(ev) + /\ ev.type = "put" => Unusable(ev.rec) \/ ClientAccepts(ev.rec) /\ cache' = [cache EXCEPT ![ev.scope][ev.agent] = - IF ev.type = "put" THEN [rec |-> ev.rec, stale |-> FALSE] + IF ev.type = "put" + THEN (IF Unusable(ev.rec) THEN @ + ELSE [rec |-> ev.rec, stale |-> FALSE]) ELSE IF @.rec = NoRec THEN @ ELSE [@ EXCEPT !.stale = TRUE]] /\ dpc' = "advance" - /\ UNCHANGED <> + /\ UNCHANGED <> \* sync_directory, second half: advance_directory_cursor. It is another \* statement than the cache write, not the same transaction. @@ -364,8 +407,8 @@ DirAdvance == /\ dpc = "advance" /\ dcur' = dcur + 1 /\ dpc' = "idle" - /\ UNCHANGED <> + /\ UNCHANGED <> \* The process stops between the two halves. The next sync reads the same \* event again. @@ -373,8 +416,8 @@ DirCrash == /\ mode = "directory" /\ dpc = "advance" /\ dpc' = "idle" - /\ UNCHANGED <> + /\ UNCHANGED <> \* What `resolve` answers for the agent id `want`. ControlService::resolve \* answers 410 for an expired record. @@ -385,13 +428,13 @@ Resolved(want) == ELSE signed \cup Evil \* request_via_directory, when the directory answers: DirectoryClient:: -\* resolve checks the key, the signature and the expiry, and the caller -\* checks the scope. Nothing compares the record's agent id with `want`. -\* The caller caches the record under the record's own names and sends -\* the task to the record's endpoint. +\* resolve checks the agent id (validate_resolved), the key, the signature +\* and the expiry, and the caller checks the scope. The caller caches the +\* record and sends the task to the record's endpoint. Resolve(want) == /\ mode = "directory" /\ \E r \in Resolved(want) : + /\ r.agent = want /\ ClientAccepts(r) /\ r.scope = "dir" /\ cache' = [cache EXCEPT ![r.scope][r.agent] = @@ -399,8 +442,8 @@ Resolve(want) == /\ badUse' = badUse \cup (IF Trusted(r) /\ r.scope = "dir" THEN {} ELSE {"untrusted"}) \cup (IF r.agent = want THEN {} ELSE {"resolved_other_agent"}) - /\ UNCHANGED <> + /\ UNCHANGED <> \* request_via_directory, when the directory cannot be reached: \* cached_directory_record checks the names, the expiry (a stale record @@ -414,8 +457,8 @@ UseCached(want) == /\ badUse' = badUse \cup (IF Trusted(c.rec) /\ c.rec.scope = "dir" THEN {} ELSE {"untrusted"}) - /\ UNCHANGED <> + /\ UNCHANGED <> ----------------------------------------------------------------------------- @@ -477,36 +520,23 @@ RosterAt(n) == OneKeyExact == OneKey => \A k \in Keys : cur[k] > 0 => roster = RosterAt(cur[k]) -\* With one control URL a revoke that the node applied stays, and no claim -\* of that member admits work again. -OneKeyRevokeStays == - OneKey => \A a \in revApplied : - /\ roster[a].st = "revoked" - /\ \A e \in Eps : ~Admits(a, e) +\* A revoke that the node applied stays, and no claim of that member admits +\* work again, whatever the spellings of the control URL that the node +\* used: a second cursor reads the old join again and changes nothing. +RevokeStays == + \A a \in revApplied : + /\ roster[a].st = "revoked" + /\ \A e \in Eps : ~Admits(a, e) \* A cursor moves forward by one event, or not at all. CursorForward == [][\A k \in Keys : cur'[k] = cur[k] \/ cur'[k] = cur[k] + 1]_vars (***************************************************************************) -(* Managed properties that TLC finds false. They are not in *) -(* ManagedRoster.cfg; each comment gives the counterexample. *) +(* A managed property that TLC finds false. It is not in *) +(* ManagedRoster.cfg; the comment gives the counterexample. *) (***************************************************************************) -\* FALSE: a revoke that the node applied stays, and no claim of that member -\* admits work again. The cursor has the control URL in its key -\* (managed.rs cursor_key), the roster does not, and a join event clears -\* revoked_at (apply_managed_member, ON CONFLICT DO UPDATE). Trace: -\* Redeem(a), RevokeMember(a); the node syncs both events under URL k1 -\* (a is revoked); a sync under another spelling k2 starts at cursor 0 and -\* applies the join again (a is active); the process stops or loses the -\* next reply before the revoke; the claim of a admits work. A later sync under k1 reads -\* nothing new, so the member stays active for a node that runs under k1. -RevokeStays == - \A a \in revApplied : - /\ roster[a].st = "revoked" - /\ \A e \in Eps : ~Admits(a, e) - \* FALSE, by design: no claim admits work after the service revoked the \* member. The node learns of a revoke at its next sync (every 30 s), so \* after Redeem(a), a sync and RevokeMember(a), the claim of a admits work @@ -521,9 +551,9 @@ NoAdmitAfterServiceRevoke == \* expired, and that is for the scope that the caller asked for. UsedRecordIsTrusted == "untrusted" \notin badUse -\* An honest directory answers with the record of the agent that the -\* caller asked for. -HonestResolveIsForAgent == dirHonest => "resolved_other_agent" \notin badUse +\* The caller sends its task to the agent that it asked for, also when +\* the directory answers with a valid record of another agent. +ResolveIsForAgent == "resolved_other_agent" \notin badUse \* The cache holds only records that the trusted key signed, each under \* its own scope and agent id, so a record from the cache is the record of @@ -536,66 +566,27 @@ CacheIsSigned == DirCursorForward == [][dcur' = dcur \/ dcur' = dcur + 1]_vars -(***************************************************************************) -(* Directory properties that TLC finds false. They are not in *) -(* ManagedRoster.cfg. *) -(***************************************************************************) - -\* FALSE: the caller sends its task to the agent that it asked for. -\* request_via_directory checks the scope of the resolved record but not -\* its agent id, and DirectoryClient::resolve checks only the key, the -\* signature and the expiry. Trace with an attacker directory: Sign(b), -\* Resolve(a) answers with the record of b; the caller caches it and -\* sends the task for a to the endpoint of b. cached_directory_record -\* does check the agent id. -ResolveIsForAgent == "resolved_other_agent" \notin badUse - -\* FALSE: a record that a revoke removed does not come back. A publish -\* request is the signed record alone, so anyone who read the record can -\* send it again while it has not expired. Trace with an honest directory: -\* Sign(a), DirPublish(r), DirRevoke(a), DirPublish(r). In the same way -\* anyone who read a record can revoke it. +\* No record that was public before a revoke comes back. A publish +\* request is the signed record alone, so anyone who read such a record +\* can send it again while it has not expired. RevokedStaysOut == \A a \in Agents : dstore[a] \notin revoked ----------------------------------------------------------------------------- (* Liveness. *) -\* A revoke of the service reaches a node that keeps syncing under one -\* control URL. +\* A revoke of the service reaches a node that keeps syncing. RevokeReaches == - \A a \in Agents : - cm[a].st = "revoked" ~> (roster[a].st = "revoked" \/ ~OneKey) - -\* FALSE: the same without "one control URL". Trace: Redeem(a), -\* RevokeMember(a); a sync under k1 applies the join, a sync under k2 -\* applies the join, the sync under k1 applies the revoke; the sync under -\* k2 then fails at the revoke with NotFound (no active row) every time, -\* so the cursor of k2 stays at 1 and `aether node serve` with that URL -\* stops with "managed roster synchronization failed". Here the member is -\* revoked; with a later join and revoke of another member the node under -\* k2 never learns of them. + \A a \in Agents : cm[a].st = "revoked" ~> roster[a].st = "revoked" + +\* A node that stays with one spelling of the control URL reads every +\* event, whatever its other cursors applied before: no process stays +\* for ever with a cursor that is behind. EveryKeyCatchesUp == \A k \in Keys, p \in Procs : - <>[](proc[p].key = k /\ cur[k] > 0) => <>[](cur[k] = Len(log)) - -\* An event of the directory log is one that validate_event refuses for -\* ever: a record of another key, or a record that expired. -Poisoned == - \E j \in 1..Len(dlog) : dlog[j].type = "put" /\ ~ClientAccepts(dlog[j].rec) - -\* An honest directory's events reach a node that keeps syncing, unless -\* the log is poisoned. -DirSyncUnlessPoisoned == - dirHonest => \A i \in 1..MaxDirLog : - (Len(dlog) >= i) ~> (dcur >= i \/ Poisoned) - -\* FALSE: an honest directory's events reach a node that keeps syncing. -\* changes_after serves the stored event with its record whatever the -\* expiry, and validate_event refuses an expired record, so events_after -\* fails for the whole page. Trace: Sign(a), DirPublish(r), ExpireRec(r); -\* the node's cursor stays at 0 for ever, and a later DirRevoke never -\* reaches its cache. The same happens after DirPublish of a record of -\* another key, which the service accepts for a free agent id. + []<>(proc[p].key # k \/ cur[k] = Len(log)) + +\* An honest directory's events reach a node that keeps syncing, also +\* when the log has a record that expired or that another key signed. DirSyncCatchesUp == dirHonest => \A i \in 1..MaxDirLog : (Len(dlog) >= i) ~> (dcur >= i) diff --git a/specs/PendingChange.cfg b/specs/PendingChange.cfg index 92385ff..c0c7289 100644 --- a/specs/PendingChange.cfg +++ b/specs/PendingChange.cfg @@ -1,8 +1,8 @@ \* PendingChange: local administration. See PendingChange.tla. \* One change id, which is also the id of a grant in the policy file. Three \* requests, one process stop, and store writes that can fail. -\* LiveFromUi, StaleRefused, StaleSeesRevoke, NoMcpRevival, -\* LiveMatchesStoreAlways and Audited are false; the spec explains each one. +\* StaleSeesRevoke and NoMcpRevival are false by design; the spec explains +\* each one. CONSTANTS Ids = {i1} FileIds = {i1} @@ -16,13 +16,13 @@ INVARIANTS TypeOK HighRiskGrantNeedsUi CapabilityNeedsUi - ChangeNeedsUi - LiveFromUiOrPolicy + StoredFromUi + LiveFromUi LiveMatchesStore RevokedStaysOut - StaleRefusedWhileRecorded - AuditedWhileRecorded + StaleRefused + Audited + ExpiredNeverApplies PROPERTIES - ExpiredRowStays RequestEnds diff --git a/specs/PendingChange.tla b/specs/PendingChange.tla index a3ad901..dadbc77 100644 --- a/specs/PendingChange.tla +++ b/specs/PendingChange.tla @@ -7,14 +7,15 @@ (* *) (* Code that this spec models: *) (* crates/aether/src/admin.rs Administration::submit, apply, *) -(* queue_pending, apply_now, finish_live, apply_live, *) -(* apply_live_inner, change_requires_confirmation, confirm_ui, *) -(* confirm_pending, check_not_stale, revoke, revoke_inner, *) -(* save_policy_settings, with_store; Change::is_high_risk *) -(* crates/aether-store/src/admin.rs apply_change, queue_change, *) -(* pending_revision, record_applied_change, admin_revision, *) +(* settle, queue_pending, apply_now, check_live, finish_live, *) +(* apply_live, change_requires_confirmation, policy_is_wider, *) +(* confirm_ui, confirm_pending, check_not_stale, revoke, *) +(* revoke_inner, save_policy_settings, with_store; *) +(* Change::is_high_risk *) +(* crates/aether-store/src/admin.rs apply_change, keep_change, *) +(* queue_change, delete_expired, pending_revision, admin_revision, *) (* revert_change, confirm_pending_change, revoke_applied_grant, *) -(* set_current_workspace, grant_revoked *) +(* record_change, fail_change, grant_revoked *) (* crates/aether/src/admin_socket.rs handle: Change, RevokeGrant and *) (* UpdatePolicy always get AuditActor::Mcp; the socket has no *) (* confirm request *) @@ -33,6 +34,12 @@ (* `aether node admin` (mode "admin", no live node). It can stop at any *) (* step and start again. A store call can fail (StoreFaults). *) (* *) +(* A change is one store transaction (the value, the current workspace of *) +(* a workspace change, the new revision and the audit record) and then *) +(* the node call. When the node refuses, a second transaction puts the *) +(* old value back. When that fails, the Administration keeps the undo and *) +(* runs no request before it worked (pc "undo"). *) +(* *) (* The MCP client is hostile inside its interface: it sends any socket *) (* request in any order. It cannot sign a grant, but it can send again a *) (* signed grant that it saw before. *) @@ -41,12 +48,12 @@ (* clock (a pending change expires at any moment), the audit records *) (* other than `applied` (an audit record has no value column, so it holds *) (* no secret by its type), grant expiry and a stored grant that no longer *) -(* verifies at start, the approved-workspace set (a refusal is one *) -(* nondeterministic step), the two limit ids (one limit here), the *) -(* `admin..` values of workspace, capability and directory *) -(* changes (nothing reads them at start), set_relay, cancel_task, access *) -(* groups, and the two store writes of save_policy_settings_in_store, *) -(* which are one step here. A live revoke does not fail. *) +(* verifies at start, the two limit ids and the two task limits of the *) +(* policy (one limit here), the `admin..` values of workspace, *) +(* capability, directory and policy changes (nothing reads them at *) +(* start), set_relay, cancel_task, access groups, and the store writes of *) +(* save_policy_settings_in_store, which are one step here. A live revoke *) +(* does not fail. *) (***************************************************************************) EXTENDS Naturals, FiniteSets @@ -59,7 +66,9 @@ CONSTANTS None == "none" Actors == {"mcp", "ui"} -Kinds == {"grant", "workspace", "limit", "capability", "directory"} +\* "policy": the settings of UpdatePolicy, which wait as a pending change +\* when they come from MCP and are wider than the stored policy. +Kinds == {"grant", "workspace", "limit", "capability", "directory", "policy"} \* "lo": a direct invite grant (direct::grant_is_low_risk_invite). "hi": \* every other grant. GVals == {"lo", "hi"} @@ -69,11 +78,13 @@ InitLimit == 2 InitWs == "w1" \* The value of a change: `val` for a grant or a workspace, `num` for a -\* limit. Capability and directory changes have one value. +\* limit, both for the policy settings. Capability and directory changes +\* have one value. ValsOf(kind) == CASE kind = "grant" -> [val : GVals, num : {0}] [] kind = "workspace" -> [val : WVals, num : {0}] [] kind = "limit" -> [val : {None}, num : Limits] + [] kind = "policy" -> [val : WVals, num : Limits] [] OTHER -> [val : {None}, num : {0}] \* Change::is_high_risk. @@ -81,7 +92,7 @@ HighRisk(kind, v) == \/ kind = "grant" /\ v.val = "hi" \/ kind \in {"workspace", "capability"} -Pcs == {"idle", "live", "ws_cur", "record", "revert", "rv_live", "rv_record"} +Pcs == {"idle", "live", "revert", "undo", "rv_live"} VARIABLES mode, \* "serve": a node runs in the process; "admin": none @@ -105,21 +116,17 @@ VARIABLES wsOk, \* workspaces that a UI action asked for or confirmed limOk, \* the highest limit that a UI action asked for capOk, \* a UI action confirmed a capability - wsPol, \* workspaces that MCP saved with UpdatePolicy - limPol, \* the highest limit that MCP saved with UpdatePolicy dead, \* grants revoked, with no new apply of the id since - applies, \* changes and revokes that reached the node - lost, \* a live apply whose revision was not recorded - auditLost, \* an apply or revoke whose audit record was not written - faulted, \* a store write failed since the process started + applies, \* changes, revokes and policy saves that took effect mcpRevived, \* MCP applied a grant id that the owner had revoked staleConfirmed, \* a confirm passed although a change landed after the queue - otherConfirmed \* the same, for a revoke or a policy save + otherConfirmed, \* the same, for a revoke or a policy save + expiredApplied \* a confirm applied an expired change store == <> node == <> -approvals == <> -flags == <> +approvals == <> +flags == <> vars == <> @@ -127,7 +134,7 @@ NoPending == [kind |-> None, val |-> None, num |-> 0, base |-> 0, expired |-> FALSE, landed |-> "no"] Idle == [pc |-> "idle", actor |-> "ui", kind |-> "grant", id |-> CHOOSE i \in Ids : TRUE, val |-> None, num |-> 0, - prevVal |-> None, prevNum |-> 0] + prevVal |-> None, prevNum |-> 0, prevCur |-> None] Max(a, b) == IF a >= b THEN a ELSE b @@ -135,7 +142,8 @@ TypeOK == /\ mode \in {"serve", "admin"} /\ op \in [pc : Pcs, actor : Actors, kind : Kinds, id : Ids, val : GVals \cup WVals \cup {None}, num : 0..3, - prevVal : GVals \cup {None}, prevNum : 0..3] + prevVal : GVals \cup {None}, prevNum : 0..3, + prevCur : WVals \cup {None}] /\ durGrant \in [Ids -> GVals \cup {None}] /\ durLimit \in 0..3 /\ curWs \in WVals \cup {None} @@ -153,13 +161,12 @@ TypeOK == /\ audits \in 0..MaxOps /\ applies \in 0..MaxOps /\ nOps \in 0..MaxOps /\ restarts \in 0..MaxRestarts /\ grOk \subseteq Ids \X GVals - /\ wsOk \subseteq WVals /\ wsPol \subseteq WVals - /\ limOk \in Limits /\ limPol \in 0..3 + /\ wsOk \subseteq WVals + /\ limOk \in Limits /\ capOk \in BOOLEAN /\ dead \subseteq Ids - /\ lost \in BOOLEAN /\ auditLost \in BOOLEAN /\ faulted \in BOOLEAN /\ mcpRevived \in BOOLEAN /\ staleConfirmed \in BOOLEAN - /\ otherConfirmed \in BOOLEAN + /\ otherConfirmed \in BOOLEAN /\ expiredApplied \in BOOLEAN \* node_builder: the grants that a node start makes live. The policy file \* grants without the revoked ones, then each stored grant, which replaces @@ -185,12 +192,12 @@ Init == /\ liveCap = FALSE /\ audits = 0 /\ applies = 0 /\ nOps = 0 /\ restarts = 0 /\ grOk = FileIds \X {"hi"} - /\ wsOk = {InitWs} /\ wsPol = {} - /\ limOk = InitLimit /\ limPol = 0 + /\ wsOk = {InitWs} + /\ limOk = InitLimit /\ capOk = FALSE /\ dead = {} - /\ lost = FALSE /\ auditLost = FALSE /\ faulted = FALSE - /\ mcpRevived = FALSE /\ staleConfirmed = FALSE /\ otherConfirmed = FALSE + /\ mcpRevived = FALSE /\ staleConfirmed = FALSE + /\ otherConfirmed = FALSE /\ expiredApplied = FALSE Fault == StoreFaults @@ -203,30 +210,35 @@ Landed(p, what) == \* What a UI action approves (ghost). Approve(kind, id, v) == /\ grOk' = IF kind = "grant" THEN grOk \cup {<>} ELSE grOk - /\ wsOk' = IF kind = "workspace" THEN wsOk \cup {v.val} ELSE wsOk - /\ limOk' = IF kind = "limit" THEN Max(limOk, v.num) ELSE limOk + /\ wsOk' = IF kind \in {"workspace", "policy"} THEN wsOk \cup {v.val} + ELSE wsOk + /\ limOk' = IF kind \in {"limit", "policy"} THEN Max(limOk, v.num) + ELSE limOk /\ capOk' = (capOk \/ kind = "capability") - /\ UNCHANGED <> ----------------------------------------------------------------------------- -(* A change request: the socket's `Change` (MCP), or a UI action that *) -(* applies a change (the invite page, the consent page, the hub workers). *) +(* A change request: the socket's `Change` and `UpdatePolicy` (MCP), or a *) +(* UI action that applies a change (the invite page, the consent page, *) +(* the hub workers, the policy form). *) \* change_requires_confirmation. A limit from MCP is free only when the -\* live node reads a limit that is not lower. +\* live node reads a limit that is not lower. Policy settings from MCP are +\* free only when they keep the workspace and raise no limit +\* (policy_is_wider). NeedsConfirmation(actor, kind, v) == /\ actor = "mcp" - /\ IF kind = "limit" - THEN ~(mode = "serve" /\ v.num <= liveLimit) - ELSE HighRisk(kind, v) + /\ CASE kind = "limit" -> ~(mode = "serve" /\ v.num <= liveLimit) + [] kind = "policy" -> v.val # pol.ws \/ v.num > pol.limit + [] OTHER -> HighRisk(kind, v) -\* Administration::apply -> queue_pending -> queue_change. The row's key is -\* the id alone, so a second row for the id is a store error. +\* Administration::apply or save_policy_settings -> queue_pending -> +\* queue_change. The row's key is the id alone, so a second row for the id +\* is a store error; delete_expired first removes a row that expired. Queue(actor, kind, id, v) == /\ op.pc = "idle" /\ nOps < MaxOps /\ NeedsConfirmation(actor, kind, v) /\ nOps' = nOps + 1 - /\ IF pending[id].kind = None + /\ IF pending[id].kind = None \/ pending[id].expired THEN \/ pending' = [pending EXCEPT ![id] = [kind |-> kind, val |-> v.val, num |-> v.num, base |-> mrev, expired |-> FALSE, landed |-> "no"]] @@ -235,161 +247,169 @@ Queue(actor, kind, id, v) == /\ UNCHANGED <> -\* Administration::apply -> apply_now, first half: apply_change keeps the -\* value in the store and returns the value that it replaced. +\* apply_change and confirm_pending_change -> keep_change: one transaction +\* keeps the value, the current workspace of a workspace change, the new +\* revision and the audit record. The revision in memory follows at once. +\* `p` is the pending table without the row that a confirm removes. +Keep(actor, kind, id, v, p) == + /\ op' = [pc |-> "live", actor |-> actor, kind |-> kind, id |-> id, + val |-> v.val, num |-> v.num, + prevVal |-> IF kind = "grant" THEN durGrant[id] ELSE None, + prevNum |-> IF kind = "limit" THEN durLimit ELSE 0, + prevCur |-> curWs] + /\ durGrant' = IF kind = "grant" THEN [durGrant EXCEPT ![id] = v.val] + ELSE durGrant + /\ durLimit' = IF kind = "limit" THEN v.num ELSE durLimit + /\ curWs' = IF kind = "workspace" THEN v.val ELSE curWs + /\ drev' = mrev + 1 /\ mrev' = mrev + 1 + /\ audits' = audits + 1 + /\ pending' = Landed(p, "change") + /\ dead' = IF kind = "grant" THEN dead \ {id} ELSE dead + +\* check_live: the running node refuses a workspace (not approved, or not +\* a folder) before the store has it. +WorkspaceRefused(kind) == kind = "workspace" /\ mode = "serve" + +\* Administration::apply -> apply_now, up to the store transaction. Policy +\* settings that need no confirmation go to SavePolicy. ApplyNow(actor, kind, id, v) == /\ op.pc = "idle" /\ nOps < MaxOps + /\ kind # "policy" /\ ~NeedsConfirmation(actor, kind, v) /\ nOps' = nOps + 1 - /\ \/ /\ op' = [pc |-> "live", actor |-> actor, kind |-> kind, id |-> id, - val |-> v.val, num |-> v.num, - prevVal |-> IF kind = "grant" THEN durGrant[id] ELSE None, - prevNum |-> IF kind = "limit" THEN durLimit ELSE 0] - /\ durGrant' = IF kind = "grant" THEN [durGrant EXCEPT ![id] = v.val] - ELSE durGrant - /\ durLimit' = IF kind = "limit" THEN v.num ELSE durLimit - /\ dead' = IF kind = "grant" THEN dead \ {id} ELSE dead + /\ \/ /\ Keep(actor, kind, id, v, pending) /\ mcpRevived' = (mcpRevived \/ (actor = "mcp" /\ kind = "grant" /\ id \in revoked)) /\ IF actor = "ui" THEN Approve(kind, id, v) ELSE UNCHANGED approvals - \/ /\ Fault - /\ UNCHANGED <> - /\ UNCHANGED <> + \/ /\ Fault \/ WorkspaceRefused(kind) + /\ UNCHANGED <> + /\ UNCHANGED <> \* Administration::confirm_ui -> confirm_pending: only the UI calls it. \* check_not_stale compares the revision of the queue with the revision in -\* memory. confirm_pending_change refuses an expired row; else it keeps -\* the value and deletes the row in one transaction. +\* memory. confirm_pending_change refuses an expired row and removes it; +\* else it keeps the value and deletes the row in one transaction. Confirm(id) == /\ op.pc = "idle" /\ nOps < MaxOps /\ pending[id].kind # None /\ nOps' = nOps + 1 /\ LET p == pending[id] v == [val |-> p.val, num |-> p.num] - IN IF p.base # mrev \/ p.expired - THEN UNCHANGED <> - ELSE \/ /\ op' = [pc |-> "live", actor |-> "ui", kind |-> p.kind, - id |-> id, val |-> p.val, num |-> p.num, - prevVal |-> IF p.kind = "grant" THEN durGrant[id] - ELSE None, - prevNum |-> IF p.kind = "limit" THEN durLimit ELSE 0] - /\ durGrant' = IF p.kind = "grant" - THEN [durGrant EXCEPT ![id] = p.val] ELSE durGrant - /\ durLimit' = IF p.kind = "limit" THEN p.num ELSE durLimit + nothing == UNCHANGED <> + IN IF p.base # mrev + THEN nothing + ELSE IF p.expired + THEN \/ nothing + \/ /\ ~WorkspaceRefused(p.kind) /\ pending' = [pending EXCEPT ![id] = NoPending] - /\ dead' = IF p.kind = "grant" THEN dead \ {id} ELSE dead + /\ UNCHANGED <> + ELSE \/ /\ Keep("ui", p.kind, id, v, + [pending EXCEPT ![id] = NoPending]) /\ Approve(p.kind, id, v) /\ staleConfirmed' = (staleConfirmed \/ p.landed = "change") /\ otherConfirmed' = (otherConfirmed \/ p.landed = "other") - \/ /\ Fault - /\ UNCHANGED <> - /\ UNCHANGED <> - -\* The live value is in the node: apply_live adds one to the revision in -\* memory. + /\ expiredApplied' = (expiredApplied \/ p.expired) + \/ (Fault \/ WorkspaceRefused(p.kind)) /\ nothing + /\ UNCHANGED <> + +\* The node, or the stored policy, has the change. LiveDone == - /\ mrev' = mrev + 1 /\ applies' = applies + 1 - /\ pending' = Landed(pending, "change") - /\ op' = [op EXCEPT !.pc = "record"] + /\ op' = Idle -\* finish_live -> apply_live -> apply_live_inner. Without a live node, a -\* grant, a limit and a workspace count as applied; a directory and a -\* capability change are unsupported. The node can refuse a grant (it does -\* not verify), a workspace (not approved), a directory and a capability. +\* finish_live -> apply_live. Without a live node, a grant, a limit and a +\* workspace count as applied; a directory and a capability change are +\* unsupported. The node can refuse a grant (it does not verify), a +\* workspace (the folder went away after check_live), a directory and a +\* capability. Policy settings go to the stored policy +\* (save_policy_settings_in_store), which also removes the stored limit; +\* the running node keeps its settings until it starts again. ApplyLive == /\ op.pc = "live" /\ LET refuse == /\ op' = [op EXCEPT !.pc = "revert"] - /\ UNCHANGED <> + /\ UNCHANGED <> IN CASE op.kind = "grant" -> \/ /\ LiveDone /\ liveGrant' = IF mode = "serve" THEN [liveGrant EXCEPT ![op.id] = op.val] ELSE liveGrant - /\ UNCHANGED <> + /\ UNCHANGED <> \/ mode = "serve" /\ refuse [] op.kind = "limit" -> /\ LiveDone /\ liveLimit' = IF mode = "serve" THEN op.num ELSE liveLimit - /\ UNCHANGED <> + /\ UNCHANGED <> [] op.kind = "workspace" -> - \/ /\ liveWs' = IF mode = "serve" THEN op.val ELSE liveWs - /\ op' = [op EXCEPT !.pc = "ws_cur"] - /\ UNCHANGED <> + \/ /\ LiveDone + /\ liveWs' = IF mode = "serve" THEN op.val ELSE liveWs + /\ UNCHANGED <> \/ mode = "serve" /\ refuse [] op.kind = "capability" -> \/ /\ mode = "serve" /\ LiveDone /\ liveCap' = TRUE - /\ UNCHANGED <> + /\ UNCHANGED <> \/ refuse + [] op.kind = "policy" -> + \/ /\ LiveDone + /\ pol' = [ws |-> op.val, limit |-> op.num] + /\ durLimit' = 0 + /\ UNCHANGED node + \/ Fault /\ refuse [] OTHER -> - \/ mode = "serve" /\ LiveDone /\ UNCHANGED node + \/ mode = "serve" /\ LiveDone /\ UNCHANGED <> \/ refuse - /\ UNCHANGED <> -\* apply_live_inner, the workspace branch after the node moved: -\* set_current_workspace. When it fails, finish_live reverts the store -\* value, but the node keeps the new workspace. -SetCurrentWorkspace == - /\ op.pc = "ws_cur" - /\ \/ /\ curWs' = op.val - /\ LiveDone - /\ UNCHANGED faulted - \/ /\ Fault - /\ faulted' = TRUE - /\ op' = [op EXCEPT !.pc = "revert"] - /\ UNCHANGED <> - /\ UNCHANGED <> - -\* finish_live, the success branch: record_applied_change writes the new -\* revision and the audit record in one transaction. -Record == - /\ op.pc = "record" +\* revert_change: one transaction puts back the value and the current +\* workspace that the change replaced and marks the audit record as +\* failed. The revision stays. +PutBack == + /\ durGrant' = IF op.kind = "grant" + THEN [durGrant EXCEPT ![op.id] = op.prevVal] + ELSE durGrant + /\ durLimit' = IF op.kind = "limit" THEN op.prevNum ELSE durLimit + /\ curWs' = IF op.kind = "workspace" THEN op.prevCur ELSE curWs + /\ audits' = audits - 1 /\ op' = Idle - /\ \/ /\ drev' = mrev - /\ audits' = audits + 1 - /\ UNCHANGED <> - \/ /\ Fault - /\ lost' = TRUE /\ auditLost' = TRUE /\ faulted' = TRUE - /\ UNCHANGED <> - /\ UNCHANGED <> - -\* finish_live, the failure branch: revert_change puts back the value that -\* the change replaced. + +\* finish_live, the failure branch. When the store fails, the +\* Administration keeps the undo. Revert == /\ op.pc = "revert" - /\ op' = Idle - /\ \/ /\ durGrant' = IF op.kind = "grant" - THEN [durGrant EXCEPT ![op.id] = op.prevVal] - ELSE durGrant - /\ durLimit' = IF op.kind = "limit" THEN op.prevNum ELSE durLimit - /\ UNCHANGED faulted + /\ \/ PutBack \/ /\ Fault - /\ faulted' = TRUE - /\ UNCHANGED <> - /\ UNCHANGED <> + /\ op' = [op EXCEPT !.pc = "undo"] + /\ UNCHANGED <> + /\ UNCHANGED <> + +\* Administration::settle: the next request, of any kind, first tries the +\* undo again, and is refused when the store fails again. +Settle == + /\ op.pc = "undo" /\ nOps < MaxOps + /\ nOps' = nOps + 1 + /\ \/ PutBack + \/ Fault /\ UNCHANGED <> + /\ UNCHANGED <> ----------------------------------------------------------------------------- (* Revoke and the policy settings. *) \* Administration::revoke -> revoke_inner, first half: -\* revoke_applied_grant removes the stored grant and keeps the mark. A -\* process without a node refuses. The socket's RevokeGrant (MCP) asks -\* first that the live policy has the grant. +\* revoke_applied_grant removes the stored grant, keeps the mark and writes +\* the audit record in one transaction. A process without a node refuses. +\* The socket's RevokeGrant (MCP) asks first that the live policy has the +\* grant. Revoke(actor, id) == /\ op.pc = "idle" /\ nOps < MaxOps /\ mode = "serve" @@ -397,9 +417,10 @@ Revoke(actor, id) == /\ nOps' = nOps + 1 /\ \/ /\ revoked' = revoked \cup {id} /\ durGrant' = [durGrant EXCEPT ![id] = None] + /\ audits' = audits + 1 /\ op' = [Idle EXCEPT !.pc = "rv_live", !.actor = actor, !.id = id] - \/ Fault /\ UNCHANGED <> - /\ UNCHANGED <> + /\ UNCHANGED <> \* revoke_inner: LiveNode::revoke_grant. It does not change the revision. @@ -409,52 +430,40 @@ RevokeLive == /\ dead' = dead \cup {op.id} /\ applies' = applies + 1 /\ pending' = Landed(pending, "other") - /\ op' = [op EXCEPT !.pc = "rv_record"] + /\ op' = Idle /\ UNCHANGED <> -\* revoke_inner: record_change. -RevokeRecord == - /\ op.pc = "rv_record" - /\ op' = Idle - /\ \/ audits' = audits + 1 /\ UNCHANGED <> - \/ Fault /\ auditLost' = TRUE /\ faulted' = TRUE /\ UNCHANGED audits - /\ UNCHANGED <> - -\* The socket's UpdatePolicy (MCP, the tool aether.settings.update_policy) -\* and the UI's policy form -> Administration::save_policy_settings -> -\* save_policy_settings_in_store. It keeps the workspace and the limit in -\* the stored policy and removes the stored limit of `aether.change`. No -\* actor needs a confirmation. The running node keeps its settings until -\* it starts again. -UpdatePolicy(actor, w, l) == +\* The UI's policy form, or the socket's UpdatePolicy (MCP, the tool +\* aether.settings.update_policy) with settings that are not wider -> +\* Administration::save_policy_settings -> save_policy_settings_in_store. +\* The audit record is written first (record_change); when the save fails, +\* fail_change marks it, and when that fails too the record stays. The +\* save keeps the workspace and the limit in the stored policy and removes +\* the stored limit of `aether.change`. The running node keeps its +\* settings until it starts again. +SavePolicy(actor, v) == /\ op.pc = "idle" /\ nOps < MaxOps + /\ ~NeedsConfirmation(actor, "policy", v) /\ nOps' = nOps + 1 - /\ \/ /\ pol' = [ws |-> w, limit |-> l] + /\ \/ /\ pol' = [ws |-> v.val, limit |-> v.num] /\ durLimit' = 0 + /\ audits' = audits + 1 /\ applies' = applies + 1 /\ pending' = Landed(pending, "other") - /\ IF actor = "ui" - THEN /\ wsOk' = wsOk \cup {w} /\ limOk' = Max(limOk, l) - /\ UNCHANGED <> - ELSE /\ wsPol' = wsPol \cup {w} /\ limPol' = Max(limPol, l) - /\ UNCHANGED <> - /\ \/ audits' = audits + 1 /\ UNCHANGED <> - \/ Fault /\ auditLost' = TRUE /\ faulted' = TRUE /\ UNCHANGED audits + /\ IF actor = "ui" THEN Approve("policy", op.id, v) + ELSE UNCHANGED approvals \/ /\ Fault - /\ UNCHANGED <> + /\ audits' \in {audits, audits + 1} + /\ UNCHANGED <> /\ UNCHANGED <> + restarts, dead, flags>> ----------------------------------------------------------------------------- (* The environment. *) -\* 300 s pass after the queue. No function deletes an expired row. +\* 300 s pass after the queue. Expire(id) == /\ pending[id].kind # None /\ ~pending[id].expired /\ pending' = [pending EXCEPT ![id].expired = TRUE] @@ -464,39 +473,32 @@ Expire(id) == \* The process stops at any step and starts again, with or without a \* node. Administration::with_store reads the stored revision. A node -\* start replays the store (node_builder). A stop between the live apply -\* and record_applied_change loses the new revision and the audit record. +\* start replays the store (node_builder), so it has a change that was +\* stored and not yet live, and an undo that was not done. Restart(m) == /\ restarts < MaxRestarts /\ restarts' = restarts + 1 /\ mode' = m /\ op' = Idle /\ mrev' = drev - /\ lost' = (lost \/ op.pc = "record") - /\ auditLost' = (auditLost \/ op.pc \in {"record", "rv_record"}) - /\ faulted' = FALSE /\ liveGrant' = [id \in Ids |-> IF m = "serve" THEN StartGrant(id) ELSE None] /\ liveLimit' = IF durLimit # 0 THEN durLimit ELSE pol.limit /\ liveWs' = IF curWs # None THEN curWs ELSE pol.ws /\ liveCap' = FALSE - /\ UNCHANGED <> + /\ UNCHANGED <> Next == \/ \E actor \in Actors, kind \in Kinds, id \in Ids : \E v \in ValsOf(kind) : Queue(actor, kind, id, v) \/ ApplyNow(actor, kind, id, v) + \/ \E actor \in Actors : \E v \in ValsOf("policy") : SavePolicy(actor, v) \/ \E id \in Ids : Confirm(id) \/ Expire(id) \/ \E actor \in Actors, id \in Ids : Revoke(actor, id) - \/ \E actor \in Actors, w \in WVals, l \in Limits : UpdatePolicy(actor, w, l) - \/ ApplyLive \/ SetCurrentWorkspace \/ Record \/ Revert - \/ RevokeLive \/ RevokeRecord + \/ ApplyLive \/ Revert \/ Settle \/ RevokeLive \/ \E m \in {"serve", "admin"} : Restart(m) \* A request that started goes on to its end. -Fairness == - /\ WF_vars(ApplyLive) /\ WF_vars(SetCurrentWorkspace) /\ WF_vars(Record) - /\ WF_vars(Revert) /\ WF_vars(RevokeLive) /\ WF_vars(RevokeRecord) +Fairness == WF_vars(ApplyLive) /\ WF_vars(Revert) /\ WF_vars(RevokeLive) Spec == Init /\ [][Next]_vars /\ Fairness @@ -515,76 +517,52 @@ HighRiskGrantNeedsUi == CapabilityNeedsUi == liveCap => capOk \* A pending change is not in force: its value reaches the store and the -\* node only through Confirm. The workspace that a change made live, and -\* the stored limit, come from a UI action, or the limit is not higher -\* than a limit that the node already had. -ChangeNeedsUi == +\* node only through Confirm. The stored workspace, the stored limit and +\* the stored policy come from a UI action, or the limit is not higher +\* than a limit that a UI action asked for. +StoredFromUi == /\ curWs # None => curWs \in wsOk - /\ durLimit <= Max(limOk, limPol) + /\ durLimit <= limOk + /\ pol.ws \in wsOk /\ pol.limit <= limOk -\* The live workspace and limit come from a UI action or from a saved -\* policy (UpdatePolicy), from the UI or from MCP. -LiveFromUiOrPolicy == - /\ liveWs \in wsOk \cup wsPol - /\ liveLimit <= Max(limOk, limPol) +\* The live workspace and limit come from a UI action only. An MCP client +\* moves the workspace or raises the limit neither with a change nor with +\* UpdatePolicy and a node start. +LiveFromUi == + /\ liveWs \in wsOk + /\ liveLimit <= limOk -\* After each complete request, the node and the store agree, unless a -\* store write failed since the process started. +\* When no request runs and no undo waits, the node and the store agree, +\* also after a store write failed. Agree == /\ \A id \in Ids : liveGrant[id] = StartGrant(id) /\ curWs # None => liveWs = curWs /\ durLimit # 0 => liveLimit = durLimit -LiveMatchesStore == - (mode = "serve" /\ op.pc = "idle" /\ ~faulted) => Agree +LiveMatchesStore == (mode = "serve" /\ op.pc = "idle") => Agree \* A revoked grant is not live and not in the store, and a node start does \* not bring it back, until someone applies a grant with that id again. RevokedStaysOut == \A id \in dead : liveGrant[id] = None /\ durGrant[id] = None -\* A confirmation is refused when another change was applied after the -\* queue, as long as each applied change recorded its revision. -StaleRefusedWhileRecorded == staleConfirmed => lost - -\* Each change that reached the node has one `applied` audit record, as -\* long as each record was written. -AuditedWhileRecorded == - /\ audits <= applies - /\ (op.pc = "idle" /\ ~auditLost) => audits = applies - -\* A pending row that expired never changes (but for the ghost `landed`) -\* and never leaves the table: -\* only confirm_pending_change deletes a row, and it refuses this one. The -\* row's key is the id, so no change with this id can be queued again (see -\* Queue). -ExpiredRowStays == - [][\A id \in Ids : - (pending[id].kind # None /\ pending[id].expired) - => [pending'[id] EXCEPT !.landed = "no"] - = [pending[id] EXCEPT !.landed = "no"]]_vars +\* A confirmation is refused when another change was stored after the +\* queue, also when the process stopped before the node had that change. +StaleRefused == ~staleConfirmed + +\* Each change, revoke and policy save that took effect has an `applied` +\* audit record, which the store had no later than the change. +Audited == applies <= audits + +\* A confirmation never applies an expired change. An expired row leaves +\* at the next confirm of its id or at the next queue (see Queue and +\* Confirm), so its id is free again. +ExpiredNeverApplies == ~expiredApplied (***************************************************************************) (* Properties that TLC finds false. They are not in PendingChange.cfg; *) (* each comment gives the counterexample. *) (***************************************************************************) -\* FALSE: the live workspace and limit come from a UI action only. -\* UpdatePolicy("mcp", w2, 3), Restart("serve"): the node starts in w2 -\* with the limit 3. admin_socket.rs gives UpdatePolicy to -\* save_policy_settings with no confirmation, and node_builder reads the -\* stored policy at start. An `aether.change` for the same workspace or -\* limit waits for the UI. -LiveFromUi == - /\ liveWs \in wsOk - /\ liveLimit <= limOk - -\* FALSE: a stale confirmation is always refused. MCP queues a change at -\* revision 0; the UI applies another change; the process stops after -\* apply_live and before record_applied_change; it starts again with the -\* stored revision 0, and Confirm passes. The store value of the other -\* change was written first, so a node start makes it live. -StaleRefused == ~staleConfirmed - \* FALSE (by design): a revoke or a policy save after the queue makes the \* confirmation stale. Neither changes the revision. StaleSeesRevoke == ~otherConfirmed @@ -595,23 +573,13 @@ StaleSeesRevoke == ~otherConfirmed \* The revoked mark only stops a grant of the policy file. NoMcpRevival == ~mcpRevived -\* FALSE with a store fault: the node and the store agree after each -\* complete request. (1) A workspace change moves the node, then -\* set_current_workspace fails, and revert_change restores the store only. -\* (2) The node refuses a grant and revert_change fails: the store keeps -\* the grant, the caller reads an error, and the next start makes it live. -LiveMatchesStoreAlways == (mode = "serve" /\ op.pc = "idle") => Agree - -\* FALSE with a store fault or a stop: each applied change has an audit -\* record. record_applied_change runs after the node has the change. -Audited == op.pc = "idle" => audits = applies - (***************************************************************************) (* Liveness. *) (***************************************************************************) -\* A request that holds the mutex ends: it is recorded or reverted, or the -\* process stops. -RequestEnds == (op.pc # "idle") ~> (op.pc = "idle") +\* A request that holds the mutex ends: its change is in the node, or its +\* value is put back or waits as an undo, or the process stops. +RequestEnds == + (op.pc \notin {"idle", "undo"}) ~> (op.pc \in {"idle", "undo"}) ============================================================================= diff --git a/specs/README.md b/specs/README.md index faea214..dcefbd6 100644 --- a/specs/README.md +++ b/specs/README.md @@ -8,49 +8,28 @@ change the model in the same commit. | Model | Code | Checked properties | |---|---|---| -| `DirectInvite` | `invites.rs`, `join_and_apply` in `access_groups.rs`, `import_bundle` and the contact functions in `direct.rs`, `PolicyEngine::admit`, `check_group` | A call that failed leaves no grant; the host admits a request only from an endpoint that the owner invited, with a claim signed for that endpoint, so a copied line gives nothing; the caller keeps only an authorization for its own endpoint; one contact name for one endpoint; a valid contact's name stays with its endpoint; each invite call ends (liveness) | -| `Admission` | `a2a_transport.rs`, `proof/admission.rs`, `PolicyEngine::admit`, `admit_with_replay` and `cancel_if_owned` in `aether-store/src/tasks.rs` | A task's owner is the authenticated endpoint, which had a live grant and a group membership; one task for each endpoint and idempotency key; a refused, replayed or changed frame changes nothing; the queue stays within its limits; no answer shows another endpoint's task; only the owner cancels; an honest caller with access gets its task in (liveness) | +| `DirectInvite` | `invites.rs`, `join_and_apply` in `access_groups.rs`, `import_bundle` and the contact functions in `direct.rs`, `PolicyEngine::admit`, `check_group` | A call that failed leaves no grant; one `sign_direct_invite` call runs at a time, so failed calls leave nobody in the group; a returned line whose grant is live admits its person unless the owner took them out of the group; the host admits a request only from an endpoint that the owner invited, with a claim signed for that endpoint, so a copied line gives nothing; the caller keeps only an authorization for its own endpoint; one contact name for one endpoint; a valid contact's name stays with its endpoint; each invite call ends (liveness) | +| `Admission` | `a2a_transport.rs`, `proof/admission.rs`, `PolicyEngine::admit`, `admit_with_replay`, `own_ids` and `cancel_if_owned` in `aether-store/src/tasks.rs` | A task's owner is the authenticated endpoint, which had a live grant and a group membership; one task for each endpoint and idempotency key; a refused, replayed or changed frame changes nothing; a nonce stays in the replay table until it expires; the queue stays within its limits, with one per-peer limit for each endpoint, so two endpoints under one name share nothing; a task ID that another endpoint used does not refuse a caller, and one endpoint has one task for a task ID that it sent; no answer shows another endpoint's task; only the owner cancels; an honest caller with access gets its task in (liveness) | | `ExecutionLease` | `NodeStore` lease functions, `SchedulerContext` in `proof/scheduler.rs`, `Agent::cancel` and `EarlyCancels` in `agent.rs` | A lease row exists only while a task is leased or running; a turn starts at most once for a task; a live turn's task is running, cancelled, or `unknown_result`; a cancel that an earlier run left does not stop a turn; every cancel reaches the turn (liveness) | -| `ConnectedAgent` | `agent/connected.rs`, `EarlyCancels` in `agent.rs`, `protocol/agent-socket` | An open task ID belongs to a running turn on that connection; an answer comes only from the agent of the turn's connection; a turn ends once; no agent, no task sent; a cancel before the start cancels the turn, and a cancel after the end is not kept; every turn ends with its time limit, and a turn on a closed or replaced connection or with a cancelled honest agent stops (liveness) | -| `EventPaging` | `events_page`, `task_progress` and the event writers in `aether-store/src/tasks.rs`, `A2aTransport::handle`, `request_with_polling_on`, `follow` in `outbox.rs` | Event sequences have no gap and never change; a page is the ordered run after the caller's cursor; a page says "no more events" only at the end of the journal; the state and the page are from one instant; the cursor never moves back; a `node request` that stops with an answer has every event up to the one that ended the task; an ended task lets the caller stop (liveness) | +| `ConnectedAgent` | `agent/connected.rs`, `EarlyCancels` in `agent.rs`, `protocol/agent-socket` | An open task ID belongs to a running turn on that connection; a task goes only to the attached connection, and only its agent's answer is taken; an answer comes only after the task was sent; a turn ends once; no agent, no task sent; a cancel never reaches the agent before its task; a cancel before the start cancels the turn, and no cancel is kept after its turn ended; no turn waits on a connection that is over; every turn ends with its time limit, and a turn with a cancelled honest agent stops (liveness) | +| `EventPaging` | `events_page`, `task_progress` and the event writers in `aether-store/src/tasks.rs`, `A2aTransport::handle`, `request_with_polling_on`, `follow` in `outbox.rs` | Event sequences have no gap and never change; a page is the ordered run after the caller's cursor; a page says "no more events" only at the end of the journal; the state and the page are from one instant; the cursor never moves back; a `node request` or an outbox attempt that stops with an answer has every event up to the one that ended the task; an ended task lets the caller stop (liveness) | | `Outbox` | `outbox.rs`, `sent_tasks` store functions, host admission | The host keeps one task for each sent task; an answer comes only from the host; a task that the host runs never shows as failed after a replay; an attempt whose lease another process claimed records nothing; an ended task does not change; each task ends (liveness) | | `HubInvite` | `hub_sync.rs`, `hub_membership.rs`, `admin_ui/hub.rs` workers, `server/lib/aether_hub` | A grant only for an approved row and its first endpoint; no grant for a blocked endpoint; one live grant for each approval, also when the store fails; a kept line belongs to the approval it was signed for; the caller keeps only lines that it accepted; an honest hub delivers an accepted invite (liveness) | -| `ManagedRoster` | `managed_client.rs`, `directory_client.rs`, `control_service.rs`, `aether-store/src/{managed,directory,control}.rs`, `RosterClaims::verify` in `identity.rs` | A token makes one member; a roster row comes from a join event; a claim admits work only for a member that joined; with one control URL the roster is exactly the events up to the cursor and a revoke stays; a cursor never moves back or skips; the caller uses only an unexpired record of the trusted key and its scope, also with an attacker directory; a revoke reaches a node that keeps syncing, and directory events reach it unless the log is poisoned (liveness) | -| `PendingChange` | `admin.rs` (`Administration`), `aether-store/src/admin.rs`, `admin_socket.rs`, the start replay in `node_builder.rs` | A high-risk grant or a capability is live or stored only after a UI action for that id and value; a workspace or limit is live only from a UI action or a saved policy; the node and the store agree after each request unless a store write failed; a revoked grant stays out, also after a restart; a stale confirmation is refused while each revision was recorded; an expired pending row never leaves; each request ends (liveness) | +| `ManagedRoster` | `managed_client.rs`, `directory_client.rs`, `control_service.rs`, `aether-store/src/{managed,directory,control}.rs`, `RosterClaims::verify` in `identity.rs` | A token makes one member; a roster row comes from a join event; a claim admits work only for a member that joined; with one control URL the roster is exactly the events up to the cursor; a revoke that the node applied stays, whatever spellings of the control URL it used; a cursor never moves back or skips; the caller uses only an unexpired record of the trusted key, its scope and the agent it asked for, also with an attacker directory; a record that was public before a revoke cannot be published again; a revoke reaches a node that keeps syncing, each cursor catches up, and directory events reach the node also past an expired or other-key record (liveness) | +| `PendingChange` | `admin.rs` (`Administration`, `check_live`, `settle`), `aether-store/src/admin.rs`, `admin_socket.rs`, the start replay in `node_builder.rs` | A high-risk grant or a capability is live or stored only after a UI action for that id and value; a workspace, a limit and the stored policy come only from a UI action, also through `UpdatePolicy` and a node start; when no request runs and no undo waits, the node and the store agree, also after a store write failed; a revoked grant stays out, also after a restart; a stale confirmation is refused, also when the process stopped before the node had the other change; each change that took effect has an `applied` audit record written no later than the change; an expired pending change never applies; each request ends (liveness) | | `PactConsent` | `pact/`, `aether-store/src/pact.rs`, the dispatch recheck in `proof.rs` | One token for each device code; no token from a denied code; no task without a token; a failed approval leaves no grant; no task starts after its grant is revoked; an approved flow gets a token, and an admitted task ends (liveness) | ## Properties that are not checked -These properties are in the models but not in the `.cfg` files, because -TLC finds them false. The comment above each one gives the trace. "By -design" marks a property that the code does not intend to keep. The others -describe what the code does today. +These properties are in the models but not in the `.cfg` files. The +comment above each one says why. | Model | Property | Why | |---|---|---| -| `DirectInvite` | `ReturnedLineWorks` | Two calls of `sign_direct_invite` for one person share no lock: one fails and takes the person out of the group, the other returns its line. The grant is live but `check_group` refuses every request. | -| `DirectInvite` | `NoStrayMember` | In the same race, two failed calls can leave the person in the group. Without a grant the person gets no task in. | -| `Admission` | `NoTaskIdClash` | `tasks.id` is unique for the whole table, so a caller that reuses another endpoint's task ID blocks it. The random UUID keeps callers apart. | -| `Admission` | `NoSharedQuota` | The per-peer limit counts by agent name, so two endpoints that the owner invited under one name share it. | -| `Admission` | `NoReplayBeforeExpiry` | At `REPLAY_LIMIT` the oldest replay entry goes before its TTL. The idempotency key still gives one task. | -| `ConnectedAgent` | `NoLostCancel` | `run_turn` puts the task in `pending` before it writes `task`, so a cancel can reach the agent first. The second cancel from the lease renewal stops the turn. | -| `ConnectedAgent` | `NoOrphanWait` | An agent that closes only its sending side, in a race with the start of a turn, leaves the turn waiting until its time limit. | -| `ConnectedAgent` | `NoStaleCancel` | A cancel between `pending.remove` and `cancels.end` is kept. The node starts one turn for a task ID. | -| `ConnectedAgent` | `TaskOnlyToAttached`, `AnswerWhileAttached` | `serve` can replace the connection after a turn took it. The answer is still from the agent that got the task. | -| `ConnectedAgent` | `AnswerAfterSent` | By design, the agent is a process of the owner. It holds when a task ID gets one turn. | -| `EventPaging` | `OutboxReadsToEnd` | `follow` stops on the task status and does not read `aetherMoreEvents`. The outbox keeps only the answer, so only its stored cursor is short. | | `HubInvite` | `GrantToTypedName` | By design, the hub resolves the invite name, so an attacker hub chooses it. | | `HubInvite` | `KeptLineFromNamedHost` | By design, for an invite the caller takes the sender endpoint from the hub. A request checks the listing key. | -| `ManagedRoster` | `RevokeStays`, `EveryKeyCatchesUp` | The roster cursor is keyed by control URL but the roster is not: a second spelling of the URL replays the join over a revoke, or stops at the revoke for ever. | | `ManagedRoster` | `NoAdmitAfterServiceRevoke` | By design, a revoke reaches the node at its next sync. | -| `ManagedRoster` | `ResolveIsForAgent` | `request_via_directory` does not compare the resolved record's agent ID with the one asked for. | -| `ManagedRoster` | `RevokedStaysOut` | Publish and revoke need only the signed record, which is public. | -| `ManagedRoster` | `DirSyncCatchesUp` | An expired or other-key record in the event log fails every later page. | | `Outbox` | `OneAttempt` | Two processes can work on one task when an attempt takes longer than the 90 s `LEASE`. `NoStaleRecord` checks that the late attempt changes nothing. | | `PactConsent` | `StartCovered` | A grant can expire between the dispatch recheck and `mark_running`. Expiry has no lock; `StartNotRevoked` checks revocation. | -| `PendingChange` | `LiveFromUi` | The MCP `UpdatePolicy` request saves a workspace and a higher limit with no confirmation; they apply at the next start. | -| `PendingChange` | `StaleRefused` | A stop between `apply_live` and `record_applied_change` loses the revision. | | `PendingChange` | `StaleSeesRevoke` | By design, a revoke and a policy save do not change the revision. | | `PendingChange` | `NoMcpRevival` | By design, a low-risk grant applies without confirmation, also for a revoked ID. | -| `PendingChange` | `LiveMatchesStoreAlways` | A failed `set_current_workspace` or `revert_change` leaves the node and the store different. | -| `PendingChange` | `Audited` | The audit record is written after the node has the change. |