aegis-runtime-mv
Native Rust agent runtime: Axum WebSocket/SSE/REST gateway, heartbeat scheduler, dependency-aware task workflow, SQLite storage. Attachment of AienOS. Pre-alpha.
Brought by drakestapleton
aegis-runtime-mv / tests / workflow_grant_gate_tests.rs
| 1 | //! G6 (#59): an effectful task starts only under a desk grant bound to its |
| 2 | //! objective and cause, checked again right before the effect. Fake desk; |
| 3 | //! no sovereign-core client. |
| 4 | |
| 5 | use aegis::orchestration::grant_gate::{ |
| 6 | check, DeskGrant, EffectBody, GrantBinding, GrantDesk, GrantGate, GrantRefusal, |
| 7 | }; |
| 8 | use aegis::orchestration::recovery::{GrantId, GrantStatus, LookupError}; |
| 9 | use aegis::orchestration::workflow::{TaskContext, TaskOutcome, WorkflowBuilder}; |
| 10 | use aegis::{ |
| 11 | CancelToken, EffectCertainty, FailureClass, RunId, SessionId, TaskId, TaskRunner, TaskState, |
| 12 | WorkflowConfig, WorkflowExecutor, |
| 13 | }; |
| 14 | use async_trait::async_trait; |
| 15 | use std::collections::HashMap; |
| 16 | use std::sync::atomic::{AtomicUsize, Ordering}; |
| 17 | use std::sync::{Arc, Mutex}; |
| 18 | |
| 19 | const OBJECTIVE: &str = "sha256:objective_mine"; |
| 20 | const CAUSE: &str = "cause_mine"; |
| 21 | |
| 22 | fn gid(s: &str) -> GrantId { |
| 23 | GrantId::new(s) |
| 24 | } |
| 25 | |
| 26 | #[derive(Default)] |
| 27 | struct FakeDesk { |
| 28 | grants: Mutex<HashMap<GrantId, DeskGrant>>, |
| 29 | down: Mutex<bool>, |
| 30 | } |
| 31 | |
| 32 | impl FakeDesk { |
| 33 | fn with(id: &str, status: GrantStatus, objective: &str, cause: &str) -> Arc<Self> { |
| 34 | let d = Arc::new(Self::default()); |
| 35 | d.put(id, status, objective, cause); |
| 36 | d |
| 37 | } |
| 38 | |
| 39 | fn put(&self, id: &str, status: GrantStatus, objective: &str, cause: &str) { |
| 40 | self.grants.lock().unwrap().insert( |
| 41 | gid(id), |
| 42 | DeskGrant { |
| 43 | status, |
| 44 | objective_id: objective.into(), |
| 45 | cause_id: cause.into(), |
| 46 | }, |
| 47 | ); |
| 48 | } |
| 49 | |
| 50 | fn set_status(&self, id: &str, status: GrantStatus) { |
| 51 | self.grants |
| 52 | .lock() |
| 53 | .unwrap() |
| 54 | .get_mut(&gid(id)) |
| 55 | .unwrap() |
| 56 | .status = status; |
| 57 | } |
| 58 | } |
| 59 | |
| 60 | #[async_trait] |
| 61 | impl GrantDesk for FakeDesk { |
| 62 | async fn grant(&self, id: &GrantId) -> Result<Option<DeskGrant>, LookupError> { |
| 63 | if *self.down.lock().unwrap() { |
| 64 | return Err(LookupError::new("desk unreachable")); |
| 65 | } |
| 66 | Ok(self.grants.lock().unwrap().get(id).cloned()) |
| 67 | } |
| 68 | } |
| 69 | |
| 70 | /// Counts preparation and effects. `during_prepare` runs inside prepare, |
| 71 | /// so a test can change the desk between the two checks. |
| 72 | #[derive(Default)] |
| 73 | struct Body { |
| 74 | prepared: AtomicUsize, |
| 75 | applied: AtomicUsize, |
| 76 | applied_with: Mutex<Vec<GrantId>>, |
| 77 | during_prepare: Mutex<Option<Box<dyn Fn() + Send>>>, |
| 78 | } |
| 79 | |
| 80 | #[async_trait] |
| 81 | impl EffectBody for Body { |
| 82 | async fn prepare(&self, _ctx: &TaskContext) -> Result<(), TaskOutcome> { |
| 83 | self.prepared.fetch_add(1, Ordering::SeqCst); |
| 84 | if let Some(f) = self.during_prepare.lock().unwrap().as_ref() { |
| 85 | f(); |
| 86 | } |
| 87 | Ok(()) |
| 88 | } |
| 89 | |
| 90 | async fn apply(&self, _ctx: TaskContext, grant: GrantId) -> TaskOutcome { |
| 91 | self.applied.fetch_add(1, Ordering::SeqCst); |
| 92 | self.applied_with.lock().unwrap().push(grant); |
| 93 | TaskOutcome::Completed(serde_json::json!({ "written": true })) |
| 94 | } |
| 95 | } |
| 96 | |
| 97 | fn binding(grant: Option<&str>) -> GrantBinding { |
| 98 | GrantBinding { |
| 99 | objective_id: OBJECTIVE.into(), |
| 100 | cause_id: CAUSE.into(), |
| 101 | grant: grant.map(gid), |
| 102 | } |
| 103 | } |
| 104 | |
| 105 | fn ctx() -> TaskContext { |
| 106 | TaskContext { |
| 107 | task_id: TaskId::new("write"), |
| 108 | run_id: RunId::from_string("run_g6"), |
| 109 | session_id: SessionId::from_string("sess_g6"), |
| 110 | cancel: CancelToken::new(), |
| 111 | } |
| 112 | } |
| 113 | |
| 114 | async fn gate(desk: Arc<FakeDesk>, b: GrantBinding) -> (TaskOutcome, Arc<Body>) { |
| 115 | let body = Arc::new(Body::default()); |
| 116 | let out = GrantGate::new(desk, b, body.clone()).run(ctx()).await; |
| 117 | (out, body) |
| 118 | } |
| 119 | |
| 120 | /// A refusal is a Rejected, no-effect failure carrying the refusal name. |
| 121 | fn assert_refused(out: &TaskOutcome, body: &Body, name: &str) { |
| 122 | match out { |
| 123 | TaskOutcome::Failed(f) => { |
| 124 | assert!(f.message.starts_with(name), "{}", f.message); |
| 125 | assert_eq!(f.certainty, EffectCertainty::NoEffect); |
| 126 | } |
| 127 | other => panic!("expected refusal {name}, got {other:?}"), |
| 128 | } |
| 129 | assert_eq!(body.applied.load(Ordering::SeqCst), 0, "{name}: effect ran"); |
| 130 | } |
| 131 | |
| 132 | /// Negative control: a good grant runs the effect once, under that grant. |
| 133 | #[tokio::test] |
| 134 | async fn g6_bound_available_grant_runs_the_effect_once() { |
| 135 | let desk = FakeDesk::with("g1", GrantStatus::Available, OBJECTIVE, CAUSE); |
| 136 | let (out, body) = gate(desk, binding(Some("g1"))).await; |
| 137 | assert!(matches!(out, TaskOutcome::Completed(_)), "{out:?}"); |
| 138 | assert_eq!(body.applied.load(Ordering::SeqCst), 1); |
| 139 | assert_eq!(*body.applied_with.lock().unwrap(), vec![gid("g1")]); |
| 140 | } |
| 141 | |
| 142 | /// Refusal 1: no grant. The task asks for approval and nothing runs. |
| 143 | #[tokio::test] |
| 144 | async fn g6_no_grant_waits_for_approval_and_runs_nothing() { |
| 145 | let desk = Arc::new(FakeDesk::default()); |
| 146 | let (out, body) = gate(desk.clone(), binding(None)).await; |
| 147 | assert!(matches!(out, TaskOutcome::ApprovalPending), "{out:?}"); |
| 148 | assert_eq!(body.prepared.load(Ordering::SeqCst), 0); |
| 149 | assert_eq!(body.applied.load(Ordering::SeqCst), 0); |
| 150 | assert_eq!( |
| 151 | check(desk.as_ref(), &binding(None)).await, |
| 152 | Err(GrantRefusal::NoGrant) |
| 153 | ); |
| 154 | } |
| 155 | |
| 156 | /// Refusal 2: stale grant (spent, expired or revoked). |
| 157 | #[tokio::test] |
| 158 | async fn g6_stale_grant_is_refused() { |
| 159 | for status in [ |
| 160 | GrantStatus::Spent, |
| 161 | GrantStatus::Expired, |
| 162 | GrantStatus::Revoked, |
| 163 | ] { |
| 164 | let desk = FakeDesk::with("g1", status, OBJECTIVE, CAUSE); |
| 165 | let (out, body) = gate(desk, binding(Some("g1"))).await; |
| 166 | assert_refused(&out, &body, "GRANT_GATE_STALE"); |
| 167 | assert_eq!(body.prepared.load(Ordering::SeqCst), 0); |
| 168 | } |
| 169 | } |
| 170 | |
| 171 | /// Refusal 3: a grant for another objective. |
| 172 | #[tokio::test] |
| 173 | async fn g6_foreign_objective_grant_is_refused() { |
| 174 | let desk = FakeDesk::with( |
| 175 | "g1", |
| 176 | GrantStatus::Available, |
| 177 | "sha256:objective_other", |
| 178 | CAUSE, |
| 179 | ); |
| 180 | let (out, body) = gate(desk, binding(Some("g1"))).await; |
| 181 | assert_refused(&out, &body, "GRANT_GATE_FOREIGN_OBJECTIVE"); |
| 182 | } |
| 183 | |
| 184 | /// Refusal 4: an id the desk never issued. |
| 185 | #[tokio::test] |
| 186 | async fn g6_forged_grant_id_is_refused() { |
| 187 | let desk = FakeDesk::with("g1", GrantStatus::Available, OBJECTIVE, CAUSE); |
| 188 | let (out, body) = gate(desk, binding(Some("g1-forged"))).await; |
| 189 | assert_refused(&out, &body, "GRANT_GATE_FORGED"); |
| 190 | } |
| 191 | |
| 192 | #[tokio::test] |
| 193 | async fn g6_foreign_cause_grant_is_refused() { |
| 194 | let desk = FakeDesk::with("g1", GrantStatus::Available, OBJECTIVE, "cause_other"); |
| 195 | let (out, body) = gate(desk, binding(Some("g1"))).await; |
| 196 | assert_refused(&out, &body, "GRANT_GATE_FOREIGN_CAUSE"); |
| 197 | } |
| 198 | |
| 199 | #[tokio::test] |
| 200 | async fn g6_unbound_binding_is_refused_even_if_the_desk_matches() { |
| 201 | let desk = FakeDesk::with("g1", GrantStatus::Available, "", CAUSE); |
| 202 | let mut b = binding(Some("g1")); |
| 203 | b.objective_id.clear(); |
| 204 | let (out, body) = gate(desk, b).await; |
| 205 | assert_refused(&out, &body, "GRANT_GATE_UNBOUND"); |
| 206 | } |
| 207 | |
| 208 | #[tokio::test] |
| 209 | async fn g6_unreachable_desk_is_unavailable_with_no_effect() { |
| 210 | let desk = FakeDesk::with("g1", GrantStatus::Available, OBJECTIVE, CAUSE); |
| 211 | *desk.down.lock().unwrap() = true; |
| 212 | let (out, body) = gate(desk, binding(Some("g1"))).await; |
| 213 | match &out { |
| 214 | TaskOutcome::Failed(f) => { |
| 215 | assert_eq!(f.class, FailureClass::Unavailable); |
| 216 | assert_eq!(f.certainty, EffectCertainty::NoEffect); |
| 217 | assert!(f.message.starts_with("GRANT_GATE_DESK_UNAVAILABLE")); |
| 218 | } |
| 219 | other => panic!("{other:?}"), |
| 220 | } |
| 221 | assert_eq!(body.applied.load(Ordering::SeqCst), 0); |
| 222 | } |
| 223 | |
| 224 | /// DoD item 2: the grant is checked again right before the effect. The |
| 225 | /// desk revokes it while the body prepares; the effect must not run. |
| 226 | #[tokio::test] |
| 227 | async fn g6_grant_revoked_during_prepare_stops_the_effect() { |
| 228 | let desk = FakeDesk::with("g1", GrantStatus::Available, OBJECTIVE, CAUSE); |
| 229 | let body = Arc::new(Body::default()); |
| 230 | let d = desk.clone(); |
| 231 | *body.during_prepare.lock().unwrap() = |
| 232 | Some(Box::new(move || d.set_status("g1", GrantStatus::Revoked))); |
| 233 | let out = GrantGate::new(desk, binding(Some("g1")), body.clone()) |
| 234 | .run(ctx()) |
| 235 | .await; |
| 236 | assert_eq!(body.prepared.load(Ordering::SeqCst), 1); |
| 237 | assert_refused(&out, &body, "GRANT_GATE_STALE"); |
| 238 | } |
| 239 | |
| 240 | /// Through the DAG: no grant leaves the task waiting for approval and its |
| 241 | /// dependent untouched; a forged grant fails it and skips the dependent. |
| 242 | #[tokio::test] |
| 243 | async fn g6_gate_inside_a_workflow() { |
| 244 | let run = |b: GrantBinding| async move { |
| 245 | let desk = FakeDesk::with("g1", GrantStatus::Available, OBJECTIVE, CAUSE); |
| 246 | let body = Arc::new(Body::default()); |
| 247 | let spec = WorkflowBuilder::default() |
| 248 | .add_task("write", &[], GrantGate::new(desk, b, body.clone())) |
| 249 | .unwrap() |
| 250 | .add_task( |
| 251 | "report", |
| 252 | &["write"], |
| 253 | GrantGate::new( |
| 254 | Arc::new(FakeDesk::default()), |
| 255 | binding(None), |
| 256 | Arc::new(Body::default()), |
| 257 | ), |
| 258 | ) |
| 259 | .unwrap() |
| 260 | .build() |
| 261 | .unwrap(); |
| 262 | let cfg = WorkflowConfig::new( |
| 263 | RunId::from_string("run_g6"), |
| 264 | SessionId::from_string("sess_g6"), |
| 265 | 1, |
| 266 | ); |
| 267 | let r = WorkflowExecutor::new(cfg).unwrap().run(spec).await; |
| 268 | (r, body.applied.load(Ordering::SeqCst)) |
| 269 | }; |
| 270 | let (r, n) = run(binding(None)).await; |
| 271 | assert_eq!( |
| 272 | r.snapshot.states[&TaskId::new("write")], |
| 273 | TaskState::WaitingForApproval |
| 274 | ); |
| 275 | assert_eq!( |
| 276 | r.snapshot.states[&TaskId::new("report")], |
| 277 | TaskState::Pending |
| 278 | ); |
| 279 | assert_eq!(n, 0); |
| 280 | |
| 281 | let (r, n) = run(binding(Some("forged"))).await; |
| 282 | assert!(matches!( |
| 283 | r.snapshot.states[&TaskId::new("write")], |
| 284 | TaskState::Failed(_) |
| 285 | )); |
| 286 | assert!(matches!( |
| 287 | r.snapshot.states[&TaskId::new("report")], |
| 288 | TaskState::Skipped { .. } |
| 289 | )); |
| 290 | assert_eq!(n, 0); |
| 291 | } |
| 292 | |
| 293 | #[test] |
| 294 | fn g6_refusal_names() { |
| 295 | let g = gid("g"); |
| 296 | let all = [ |
| 297 | (GrantRefusal::Unbound, "GRANT_GATE_UNBOUND"), |
| 298 | (GrantRefusal::NoGrant, "GRANT_GATE_NO_GRANT"), |
| 299 | ( |
| 300 | GrantRefusal::Forged { grant: g.clone() }, |
| 301 | "GRANT_GATE_FORGED", |
| 302 | ), |
| 303 | ( |
| 304 | GrantRefusal::Stale { |
| 305 | grant: g.clone(), |
| 306 | status: GrantStatus::Spent, |
| 307 | }, |
| 308 | "GRANT_GATE_STALE", |
| 309 | ), |
| 310 | ( |
| 311 | GrantRefusal::ForeignObjective { grant: g.clone() }, |
| 312 | "GRANT_GATE_FOREIGN_OBJECTIVE", |
| 313 | ), |
| 314 | ( |
| 315 | GrantRefusal::ForeignCause { grant: g }, |
| 316 | "GRANT_GATE_FOREIGN_CAUSE", |
| 317 | ), |
| 318 | ( |
| 319 | GrantRefusal::DeskUnavailable { detail: "x".into() }, |
| 320 | "GRANT_GATE_DESK_UNAVAILABLE", |
| 321 | ), |
| 322 | ]; |
| 323 | for (r, n) in all { |
| 324 | assert_eq!(r.name(), n); |
| 325 | } |
| 326 | } |