-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Expand file tree
/
Copy pathcapability_port.rs
More file actions
1610 lines (1477 loc) · 58.1 KB
/
Copy pathcapability_port.rs
File metadata and controls
1610 lines (1477 loc) · 58.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use super::*;
use crate::dispatch::BeforeCapabilityHookImpl;
use crate::identity::{ExtensionId, HookId, HookLocalId, HookVersion};
use crate::middleware::gate_ref::UuidHookGateRefFactory;
use crate::ordering::HookPhase;
use crate::ordering::HookPriority;
use crate::registry::{HookBinding, HookBindingScope, HookPointSpec, HookRegistry};
use crate::sink::{RestrictedBeforeCapabilityHook, RestrictedGateSink};
use crate::trust::HookTrustClass;
use async_trait::async_trait;
use ironclaw_host_api::{CapabilityId, RuntimeKind};
use ironclaw_turns::LoopResultRef;
use ironclaw_turns::run_profile::{
CapabilityDescriptorView, CapabilityInputRef, CapabilityResultMessage, CapabilitySurfaceVersion,
};
use std::sync::Mutex;
fn tenant() -> TenantId {
TenantId::new("alpha").expect("ok")
}
struct AlwaysCompletedPort {
calls: Mutex<Vec<CapabilityId>>,
/// Number of times `invoke_capability_batch` was called on the inner
/// port. Distinct from `calls.len()`, which counts the per-entry
/// `invoke_capability` invocations the batch impl makes underneath.
batch_calls: Mutex<Vec<Vec<CapabilityId>>>,
}
impl AlwaysCompletedPort {
fn new() -> Self {
Self {
calls: Mutex::new(Vec::new()),
batch_calls: Mutex::new(Vec::new()),
}
}
fn calls(&self) -> Vec<CapabilityId> {
self.calls.lock().expect("not poisoned").clone()
}
fn batch_calls(&self) -> Vec<Vec<CapabilityId>> {
self.batch_calls.lock().expect("not poisoned").clone()
}
}
#[async_trait]
impl LoopCapabilityPort for AlwaysCompletedPort {
async fn visible_capabilities(
&self,
_request: VisibleCapabilityRequest,
) -> Result<VisibleCapabilitySurface, AgentLoopHostError> {
Ok(VisibleCapabilitySurface {
callable_capability_ids: Vec::new(),
version: CapabilitySurfaceVersion::new("v1").expect("ok"),
descriptors: vec![CapabilityDescriptorView {
capability_id: CapabilityId::new("cap.x").expect("ok"),
provider: None,
runtime: RuntimeKind::Wasm,
safe_name: "cap.x".to_string(),
safe_description: "test capability".to_string(),
concurrency_hint: ironclaw_turns::run_profile::ConcurrencyHint::Exclusive,
parameters_schema: serde_json::Value::Null,
}],
})
}
async fn invoke_capability(
&self,
request: CapabilityInvocation,
) -> Result<CapabilityOutcome, AgentLoopHostError> {
self.calls
.lock()
.expect("not poisoned")
.push(request.capability_id.clone());
Ok(CapabilityOutcome::Completed(CapabilityResultMessage {
result_ref: LoopResultRef::new(format!("result:{}", request.capability_id))
.expect("ok"),
safe_summary: format!("ran {}", request.capability_id),
terminate_hint: false,
byte_len: 0,
output_digest: None,
}))
}
async fn invoke_capability_batch(
&self,
request: CapabilityBatchInvocation,
) -> Result<CapabilityBatchOutcome, AgentLoopHostError> {
self.batch_calls.lock().expect("not poisoned").push(
request
.invocations
.iter()
.map(|i| i.capability_id.clone())
.collect(),
);
let mut outcomes = Vec::with_capacity(request.invocations.len());
for invocation in request.invocations {
outcomes.push(self.invoke_capability(invocation).await?);
}
Ok(CapabilityBatchOutcome {
outcomes,
stopped_on_suspension: false,
})
}
}
struct DenyingHook;
#[async_trait]
impl RestrictedBeforeCapabilityHook for DenyingHook {
async fn evaluate(
&self,
_ctx: &BeforeCapabilityHookContext,
sink: &mut dyn RestrictedGateSink,
) {
sink.deny("blocked by extension policy");
}
}
struct PauseApprovalHook;
#[async_trait]
impl RestrictedBeforeCapabilityHook for PauseApprovalHook {
async fn evaluate(
&self,
_ctx: &BeforeCapabilityHookContext,
sink: &mut dyn RestrictedGateSink,
) {
sink.pause_approval("needs approval for this capability");
}
}
struct PauseAuthHook;
#[async_trait]
impl RestrictedBeforeCapabilityHook for PauseAuthHook {
async fn evaluate(
&self,
_ctx: &BeforeCapabilityHookContext,
sink: &mut dyn RestrictedGateSink,
) {
sink.pause_auth("needs auth for this capability");
}
}
/// Records the digest a real `BeforeCapability` hook receives, then passes.
#[derive(Clone)]
struct CapturingBeforeCapabilityHook {
captured: Arc<Mutex<Vec<[u8; 32]>>>,
}
impl CapturingBeforeCapabilityHook {
fn new() -> Self {
Self {
captured: Arc::new(Mutex::new(Vec::new())),
}
}
fn captured(&self) -> Vec<[u8; 32]> {
self.captured.lock().expect("not poisoned").clone()
}
}
#[async_trait]
impl RestrictedBeforeCapabilityHook for CapturingBeforeCapabilityHook {
async fn evaluate(&self, ctx: &BeforeCapabilityHookContext, sink: &mut dyn RestrictedGateSink) {
self.captured
.lock()
.expect("not poisoned")
.push(ctx.arguments_digest);
// Restricted hooks must make an explicit decision; no-op would fail closed.
sink.pass();
}
}
fn dispatcher_with_restricted_hook(
local: &str,
hook: Box<dyn RestrictedBeforeCapabilityHook>,
) -> (Arc<HookDispatcher>, HookId) {
let hook_id = HookId::derive(
&ExtensionId::new("ext").expect("valid ExtensionId in test"),
"1.0",
&HookLocalId::new(local).expect("valid HookLocalId in test"),
HookVersion::ONE,
);
let binding = HookBinding {
hook_id,
hook_version: HookVersion::ONE,
trust_class: HookTrustClass::Installed,
phase: HookPhase::Policy,
priority: HookPriority::DEFAULT,
point: HookPointSpec::BeforeCapability,
event_kind_filter: None,
owning_extension: None,
scope: HookBindingScope::Global,
poisoned: false,
};
let mut registry = HookRegistry::new();
registry.insert(binding).expect("ok");
let mut dispatcher = HookDispatcher::new(registry);
dispatcher.install_before_capability(hook_id, BeforeCapabilityHookImpl::Restricted(hook));
(Arc::new(dispatcher), hook_id)
}
/// Test-only gate-ref factory that always errors. Used to exercise the
/// fail-closed path when the host's gate-router refuses to mint a ref.
struct FailingGateRefFactory;
#[async_trait]
impl crate::middleware::gate_ref::HookGateRefFactory for FailingGateRefFactory {
async fn mint_approval_ref(
&self,
_reason: &str,
) -> Result<ironclaw_turns::LoopGateRef, AgentLoopHostError> {
Err(AgentLoopHostError::new(
ironclaw_turns::run_profile::AgentLoopHostErrorKind::Internal,
"no router",
))
}
async fn mint_auth_ref(
&self,
_reason: &str,
) -> Result<ironclaw_turns::LoopGateRef, AgentLoopHostError> {
Err(AgentLoopHostError::new(
ironclaw_turns::run_profile::AgentLoopHostErrorKind::Internal,
"no router",
))
}
}
// Canonical digest fixture shared by helper-level and caller-driven pins.
// If the hex changes, audit every caller that keys on `arguments_digest`.
const SNAPSHOT_FIXTURE_DIGEST_HEX: &str =
"4d0ab78e009b32615c2766bd1c26921bd59ef81b5741a75387707f82f0344315";
fn snapshot_fixture_invocation() -> CapabilityInvocation {
CapabilityInvocation {
surface_version: ironclaw_turns::run_profile::CapabilitySurfaceVersion::new("snapshot:v1")
.expect("surface version literal is valid"),
capability_id: CapabilityId::new("cap.snapshot.fixture")
.expect("capability id literal is valid"),
input_ref: ironclaw_turns::run_profile::CapabilityInputRef::new(
"input:cap.snapshot.fixture",
)
.expect("input ref literal is valid"),
approval_resume: None,
}
}
fn digest_hex(digest: &[u8; 32]) -> String {
digest.iter().map(|b| format!("{b:02x}")).collect()
}
fn dispatcher_with_capturing_hook(hook: CapturingBeforeCapabilityHook) -> Arc<HookDispatcher> {
let (dispatcher, _) = dispatcher_with_restricted_hook("capture-digest", Box::new(hook));
dispatcher
}
fn assert_hook_observed_snapshot_digest(hook: &CapturingBeforeCapabilityHook, path: &str) {
let captured = hook.captured();
assert_eq!(
captured.len(),
1,
"hook must observe exactly one BeforeCapability context"
);
assert_eq!(
digest_hex(&captured[0]),
SNAPSHOT_FIXTURE_DIGEST_HEX,
"arguments_digest observed through {path} shifted; this is a \
hook-visible wire-contract break"
);
}
#[test]
fn invocation_arguments_digest_is_stable_for_known_inputs() {
let invocation = snapshot_fixture_invocation();
let digest = invocation_arguments_digest(&invocation);
assert_eq!(
digest_hex(&digest),
SNAPSHOT_FIXTURE_DIGEST_HEX,
"invocation_arguments_digest shifted for a fixed input — \
this is a wire-contract break. See the stability-contract \
rustdoc on `invocation_arguments_digest`."
);
}
/// Caller-driven regression pin for the digest hook authors observe.
#[tokio::test]
async fn invoke_capability_arguments_digest_is_stable_at_middleware_boundary() {
let inner = Arc::new(AlwaysCompletedPort::new());
let hook = CapturingBeforeCapabilityHook::new();
let dispatcher = dispatcher_with_capturing_hook(hook.clone());
let wrapped = HookedLoopCapabilityPort::new(inner.clone(), dispatcher, tenant());
let outcome = wrapped
.invoke_capability(snapshot_fixture_invocation())
.await
.expect("ok");
// The capturing hook allows, so the invocation reaches the inner port.
assert!(matches!(outcome, CapabilityOutcome::Completed(_)));
assert_eq!(
inner.calls().len(),
1,
"allowed invocation must reach inner"
);
assert_hook_observed_snapshot_digest(&hook, "invoke_capability");
}
/// Batch-path variant of the caller-driven digest pin.
#[tokio::test]
async fn invoke_capability_batch_arguments_digest_is_stable_at_middleware_boundary() {
let inner = Arc::new(AlwaysCompletedPort::new());
let hook = CapturingBeforeCapabilityHook::new();
let dispatcher = dispatcher_with_capturing_hook(hook.clone());
let wrapped = HookedLoopCapabilityPort::new(inner.clone(), dispatcher, tenant());
// Two entries of the same fixture: exercises the merged-batch preflight
// per-entry digest computation while also pinning the O(1)-batch
// property — the inner port must see exactly one batched call.
let batch = CapabilityBatchInvocation {
invocations: vec![snapshot_fixture_invocation(), snapshot_fixture_invocation()],
stop_on_first_suspension: false,
};
let outcome = wrapped.invoke_capability_batch(batch).await.expect("ok");
assert_eq!(outcome.outcomes.len(), 2);
assert!(
outcome
.outcomes
.iter()
.all(|o| matches!(o, CapabilityOutcome::Completed(_)))
);
// The hook runs once per entry, so both entries must be digested and
// each must match the pinned snapshot — a batch-only digest regression
// (e.g. dropping/swapping per-entry fields) would shift one of these.
let captured = hook.captured();
assert_eq!(
captured.len(),
2,
"hook must observe one BeforeCapability context per batch entry"
);
for digest in &captured {
assert_eq!(
digest_hex(digest),
SNAPSHOT_FIXTURE_DIGEST_HEX,
"arguments_digest observed through invoke_capability_batch shifted; \
this is a hook-visible wire-contract break"
);
}
// The allowed batch must reach the inner port as a single batched call,
// not degrade into N sequential invocations.
let batch_calls = inner.batch_calls();
assert_eq!(
batch_calls.len(),
1,
"allowed batch must reach inner as exactly one batched call"
);
assert_eq!(batch_calls[0].len(), 2, "both entries batched together");
}
/// Distinct inputs must produce distinct digests (sanity check; the
/// snapshot test pins one specific point in input space, this widens
/// coverage to the structural property).
#[test]
fn invocation_arguments_digest_differs_for_different_input_refs() {
let cap_id = CapabilityId::new("cap.x").expect("ok");
let surface = ironclaw_turns::run_profile::CapabilitySurfaceVersion::new("v").expect("ok");
let a = CapabilityInvocation {
surface_version: surface.clone(),
capability_id: cap_id.clone(),
input_ref: ironclaw_turns::run_profile::CapabilityInputRef::new("input:a").expect("ok"),
approval_resume: None,
};
let b = CapabilityInvocation {
surface_version: surface,
capability_id: cap_id,
input_ref: ironclaw_turns::run_profile::CapabilityInputRef::new("input:b").expect("ok"),
approval_resume: None,
};
assert_ne!(
invocation_arguments_digest(&a),
invocation_arguments_digest(&b)
);
}
/// A shared input ref must still hash differently per capability id.
#[test]
fn invocation_arguments_digest_differs_for_different_capability_ids() {
let surface = ironclaw_turns::run_profile::CapabilitySurfaceVersion::new("v").expect("ok");
let input_ref =
ironclaw_turns::run_profile::CapabilityInputRef::new("input:shared").expect("ok");
let a = CapabilityInvocation {
surface_version: surface.clone(),
capability_id: CapabilityId::new("cap.alpha").expect("ok"),
input_ref: input_ref.clone(),
approval_resume: None,
};
let b = CapabilityInvocation {
surface_version: surface,
capability_id: CapabilityId::new("cap.beta").expect("ok"),
input_ref,
approval_resume: None,
};
assert_ne!(
invocation_arguments_digest(&a),
invocation_arguments_digest(&b),
"same input_ref with different capability_id must yield \
distinct digests — the digest keys on the (capability_id, \
input_ref) tuple, not input_ref alone."
);
}
fn invocation(capability: &str) -> CapabilityInvocation {
CapabilityInvocation {
surface_version: CapabilitySurfaceVersion::new("v1").expect("ok"),
capability_id: CapabilityId::new(capability).expect("ok"),
input_ref: CapabilityInputRef::new(format!("input:{capability}")).expect("ok"),
approval_resume: None,
}
}
fn dispatcher_with_deny_hook() -> (Arc<HookDispatcher>, HookId) {
let hook_id = HookId::derive(
&ExtensionId::new("ext").expect("valid ExtensionId in test"),
"1.0",
&HookLocalId::new("deny").expect("valid HookLocalId in test"),
HookVersion::ONE,
);
let binding = HookBinding {
hook_id,
hook_version: HookVersion::ONE,
trust_class: HookTrustClass::Installed,
phase: HookPhase::Policy,
priority: HookPriority::DEFAULT,
point: HookPointSpec::BeforeCapability,
event_kind_filter: None,
owning_extension: None,
scope: HookBindingScope::Global,
poisoned: false,
};
let mut registry = HookRegistry::new();
registry.insert(binding).expect("ok");
let mut dispatcher = HookDispatcher::new(registry);
dispatcher.install_before_capability(
hook_id,
BeforeCapabilityHookImpl::Restricted(Box::new(DenyingHook)),
);
(Arc::new(dispatcher), hook_id)
}
#[tokio::test]
async fn deny_hook_short_circuits_invocation() {
let inner = Arc::new(AlwaysCompletedPort::new());
let (dispatcher, _) = dispatcher_with_deny_hook();
let wrapped = HookedLoopCapabilityPort::new(inner.clone(), dispatcher, tenant());
let outcome = wrapped
.invoke_capability(invocation("cap.x"))
.await
.expect("ok");
assert!(matches!(outcome, CapabilityOutcome::Denied(_)));
assert!(
inner.calls().is_empty(),
"inner port must not be invoked when a hook denies"
);
}
#[tokio::test]
async fn no_hooks_passes_through_to_inner() {
let inner = Arc::new(AlwaysCompletedPort::new());
let dispatcher = Arc::new(HookDispatcher::new(HookRegistry::new()));
let wrapped = HookedLoopCapabilityPort::new(inner.clone(), dispatcher, tenant());
let outcome = wrapped
.invoke_capability(invocation("cap.x"))
.await
.expect("ok");
assert!(matches!(outcome, CapabilityOutcome::Completed(_)));
assert_eq!(inner.calls().len(), 1);
}
#[tokio::test]
async fn batch_fires_dispatch_per_invocation() {
// With the always-deny hook installed, every invocation in the batch
// gets denied by hook dispatch and the inner port is never reached.
// This verifies the wrapper's per-invocation dispatch loop, not just
// the single-invocation path.
let inner = Arc::new(AlwaysCompletedPort::new());
let (dispatcher, _) = dispatcher_with_deny_hook();
let wrapped = HookedLoopCapabilityPort::new(inner.clone(), dispatcher, tenant());
let batch = CapabilityBatchInvocation {
invocations: vec![invocation("cap.alpha"), invocation("cap.beta")],
stop_on_first_suspension: false,
};
let outcome = wrapped.invoke_capability_batch(batch).await.expect("ok");
assert_eq!(outcome.outcomes.len(), 2);
assert!(inner.calls().is_empty(), "inner must not be invoked");
for entry in &outcome.outcomes {
assert!(matches!(entry, CapabilityOutcome::Denied(_)));
}
}
#[tokio::test]
async fn pause_approval_decision_surfaces_as_approval_required() {
let inner = Arc::new(AlwaysCompletedPort::new());
let (dispatcher, _) =
dispatcher_with_restricted_hook("pause-approval", Box::new(PauseApprovalHook));
// Explicitly opt into the dev-only UUID gate-ref factory; the
// middleware default is fail-closed (Critical #3).
let wrapped = HookedLoopCapabilityPort::new(inner.clone(), dispatcher, tenant())
.with_gate_ref_factory(Arc::new(UuidHookGateRefFactory));
let outcome = wrapped
.invoke_capability(invocation("cap.x"))
.await
.expect("ok");
match outcome {
CapabilityOutcome::ApprovalRequired {
gate_ref,
safe_summary,
..
} => {
assert!(gate_ref.as_str().starts_with("gate:hook-approval-"));
assert_eq!(safe_summary, "needs approval for this capability");
}
other => panic!("expected ApprovalRequired, got {other:?}"),
}
assert!(inner.calls().is_empty(), "inner must not be invoked");
}
#[tokio::test]
async fn pause_auth_decision_surfaces_as_auth_required() {
let inner = Arc::new(AlwaysCompletedPort::new());
let (dispatcher, _) = dispatcher_with_restricted_hook("pause-auth", Box::new(PauseAuthHook));
let wrapped = HookedLoopCapabilityPort::new(inner.clone(), dispatcher, tenant())
.with_gate_ref_factory(Arc::new(UuidHookGateRefFactory));
let outcome = wrapped
.invoke_capability(invocation("cap.x"))
.await
.expect("ok");
match outcome {
CapabilityOutcome::AuthRequired {
gate_ref,
safe_summary,
..
} => {
assert!(gate_ref.as_str().starts_with("gate:hook-auth-"));
assert_eq!(safe_summary, "needs auth for this capability");
}
other => panic!("expected AuthRequired, got {other:?}"),
}
assert!(inner.calls().is_empty(), "inner must not be invoked");
}
#[tokio::test]
async fn gate_ref_factory_failure_falls_back_to_denied() {
let inner = Arc::new(AlwaysCompletedPort::new());
let (dispatcher, _) =
dispatcher_with_restricted_hook("pause-approval-fail", Box::new(PauseApprovalHook));
let wrapped = HookedLoopCapabilityPort::new(inner.clone(), dispatcher, tenant())
.with_gate_ref_factory(Arc::new(FailingGateRefFactory));
let outcome = wrapped
.invoke_capability(invocation("cap.x"))
.await
.expect("ok");
match outcome {
CapabilityOutcome::Denied(denied) => {
assert_eq!(
denied.reason_kind,
CapabilityDeniedReasonKind::unknown("hook_gate_ref_unavailable").expect("ok"),
);
// Sanitized hook reason is preserved; underlying error text
// ("no router") must not leak.
assert_eq!(denied.safe_summary, "needs approval for this capability");
}
other => panic!("expected Denied fallback, got {other:?}"),
}
assert!(inner.calls().is_empty(), "inner must not be invoked");
}
/// Companion to `gate_ref_factory_failure_falls_back_to_denied` covering
/// the `PauseAuth` arm. Deferred from the PR #3573 round-3 review.
/// When the gate-ref factory's `mint_auth_ref` errors, the middleware
/// must fail closed: surface `Denied` with the `hook_gate_ref_unavailable`
/// reason_kind, preserve the hook's sanitized summary, and never reach
/// the inner port.
#[tokio::test]
async fn gate_ref_factory_failure_for_pause_auth_falls_back_to_denied() {
let inner = Arc::new(AlwaysCompletedPort::new());
let (dispatcher, _) =
dispatcher_with_restricted_hook("pause-auth-fail", Box::new(PauseAuthHook));
let wrapped = HookedLoopCapabilityPort::new(inner.clone(), dispatcher, tenant())
.with_gate_ref_factory(Arc::new(FailingGateRefFactory));
let outcome = wrapped
.invoke_capability(invocation("cap.x"))
.await
.expect("ok");
match outcome {
CapabilityOutcome::Denied(denied) => {
assert_eq!(
denied.reason_kind,
CapabilityDeniedReasonKind::unknown("hook_gate_ref_unavailable").expect("ok"),
);
// Sanitized hook reason is preserved; underlying error text
// ("no router") must not leak.
assert_eq!(denied.safe_summary, "needs auth for this capability");
}
other => panic!("expected Denied fallback, got {other:?}"),
}
assert!(inner.calls().is_empty(), "inner must not be invoked");
}
/// serrrfirat P2 #3 on PR #3573: when an inner-port `invoke_capability`
/// in the batch loop returns `Err`, the previous implementation
/// propagated the error before dispatching `AfterCapability` observers.
/// This dropped failed batch entries from observer telemetry, in
/// contrast with the single-invocation path which dispatches observers
/// regardless. Pin the fixed behavior: the observer fires for the
/// failing entry, and the error still propagates.
#[tokio::test]
async fn batch_dispatches_after_capability_observers_on_inner_error() {
use crate::points::ObserverHookContext;
use crate::sink::{ObserverHook, ObserverSink};
struct FailingPort;
#[async_trait]
impl LoopCapabilityPort for FailingPort {
async fn visible_capabilities(
&self,
_request: VisibleCapabilityRequest,
) -> Result<VisibleCapabilitySurface, AgentLoopHostError> {
unreachable!()
}
async fn invoke_capability(
&self,
_request: CapabilityInvocation,
) -> Result<CapabilityOutcome, AgentLoopHostError> {
Err(AgentLoopHostError::new(
ironclaw_turns::run_profile::AgentLoopHostErrorKind::Unavailable,
"inner port failed",
))
}
async fn invoke_capability_batch(
&self,
_request: CapabilityBatchInvocation,
) -> Result<CapabilityBatchOutcome, AgentLoopHostError> {
// After the batched-dispatch refactor, the wrapper forwards
// hook-allowed invocations as a single batched call. Surface
// the same Unavailable error here so the observer-on-error
// contract from PR #3573 still has coverage.
Err(AgentLoopHostError::new(
ironclaw_turns::run_profile::AgentLoopHostErrorKind::Unavailable,
"inner port failed",
))
}
}
struct CountingObserver {
seen: Arc<Mutex<u32>>,
}
#[async_trait]
impl ObserverHook for CountingObserver {
async fn observe(&self, _ctx: &ObserverHookContext, _sink: &mut dyn ObserverSink) {
*self.seen.lock().expect("not poisoned") += 1;
}
}
// Dispatcher with only an AfterCapability observer (no before-cap
// gate → hooks allow → inner runs and fails).
let seen = Arc::new(Mutex::new(0u32));
let observer_id = HookId::for_builtin("test::after_cap_obs", HookVersion::ONE);
let mut registry = HookRegistry::new();
registry
.insert(HookBinding {
hook_id: observer_id,
hook_version: HookVersion::ONE,
trust_class: HookTrustClass::Builtin,
phase: HookPhase::Telemetry,
priority: HookPriority::DEFAULT,
point: HookPointSpec::AfterCapability,
event_kind_filter: None,
owning_extension: None,
scope: HookBindingScope::Global,
poisoned: false,
})
.expect("ok");
let mut dispatcher = HookDispatcher::new(registry);
dispatcher.install_observer_impl(
observer_id,
crate::dispatch::ObserverHookImpl::Any(Box::new(CountingObserver { seen: seen.clone() })),
);
let wrapped =
HookedLoopCapabilityPort::new(Arc::new(FailingPort), Arc::new(dispatcher), tenant());
let batch = CapabilityBatchInvocation {
invocations: vec![invocation("cap.x")],
stop_on_first_suspension: false,
};
let err = wrapped
.invoke_capability_batch(batch)
.await
.expect_err("inner err propagates");
assert_eq!(
err.kind,
ironclaw_turns::run_profile::AgentLoopHostErrorKind::Unavailable
);
assert_eq!(
*seen.lock().expect("not poisoned"),
1,
"AfterCapability observer must fire even when inner port errors \
so failed batch entries are visible to telemetry"
);
}
#[tokio::test]
async fn batch_passes_through_when_no_hooks() {
let inner = Arc::new(AlwaysCompletedPort::new());
let dispatcher = Arc::new(HookDispatcher::new(HookRegistry::new()));
let wrapped = HookedLoopCapabilityPort::new(inner.clone(), dispatcher, tenant());
let batch = CapabilityBatchInvocation {
invocations: vec![invocation("cap.alpha"), invocation("cap.beta")],
stop_on_first_suspension: false,
};
let outcome = wrapped.invoke_capability_batch(batch).await.expect("ok");
assert_eq!(outcome.outcomes.len(), 2);
assert_eq!(inner.calls().len(), 2);
for entry in &outcome.outcomes {
assert!(matches!(entry, CapabilityOutcome::Completed(_)));
}
}
// ── Batched-dispatch regression coverage ───────────────────────────────
//
// The middleware previously degraded `invoke_capability_batch` into N
// sequential `invoke_capability` calls whenever any hook was registered,
// wiping out the O(1)-batch property that the inner port relies on for
// bulk-dispatch performance. The tests below pin the restored behavior
// (PR #3573 deferred refactor).
/// When NO hook denies, the wrapper must call the inner port's
/// `invoke_capability_batch` exactly once, with every invocation in a
/// single payload — not N times via `invoke_capability`.
#[tokio::test]
async fn batch_invocation_remains_batched_when_no_hooks_deny() {
struct AllowingHook;
#[async_trait]
impl RestrictedBeforeCapabilityHook for AllowingHook {
async fn evaluate(
&self,
_ctx: &BeforeCapabilityHookContext,
sink: &mut dyn RestrictedGateSink,
) {
sink.pass();
}
}
let inner = Arc::new(AlwaysCompletedPort::new());
let (dispatcher, _) = dispatcher_with_restricted_hook("allowing", Box::new(AllowingHook));
let wrapped = HookedLoopCapabilityPort::new(inner.clone(), dispatcher, tenant());
let batch = CapabilityBatchInvocation {
invocations: vec![
invocation("cap.alpha"),
invocation("cap.beta"),
invocation("cap.gamma"),
],
stop_on_first_suspension: false,
};
let outcome = wrapped.invoke_capability_batch(batch).await.expect("ok");
assert_eq!(outcome.outcomes.len(), 3);
// The critical perf invariant: ONE batched call, not three sequential.
let batch_calls = inner.batch_calls();
assert_eq!(
batch_calls.len(),
1,
"inner port must see exactly one batched call when hooks allow all entries; \
saw {} batched calls (sequential degradation)",
batch_calls.len()
);
assert_eq!(
batch_calls[0].len(),
3,
"all three entries batched together"
);
}
/// Partial denial: a hook denies some entries; the surviving entries
/// must still be forwarded as a SINGLE batched call to the inner port,
/// and the merged outcomes must be in original index order.
#[tokio::test]
async fn batch_invocation_filters_denied_entries_and_preserves_index_mapping() {
/// Denies only the capability whose name matches `target`.
struct SelectiveDenyHook {
target: &'static str,
}
#[async_trait]
impl RestrictedBeforeCapabilityHook for SelectiveDenyHook {
async fn evaluate(
&self,
ctx: &BeforeCapabilityHookContext,
sink: &mut dyn RestrictedGateSink,
) {
if ctx.capability_name == self.target {
sink.deny("selective deny");
} else {
sink.pass();
}
}
}
let inner = Arc::new(AlwaysCompletedPort::new());
let (dispatcher, _) = dispatcher_with_restricted_hook(
"selective",
Box::new(SelectiveDenyHook { target: "cap.beta" }),
);
let wrapped = HookedLoopCapabilityPort::new(inner.clone(), dispatcher, tenant());
let batch = CapabilityBatchInvocation {
invocations: vec![
invocation("cap.alpha"),
invocation("cap.beta"),
invocation("cap.gamma"),
],
stop_on_first_suspension: false,
};
let outcome = wrapped.invoke_capability_batch(batch).await.expect("ok");
assert_eq!(outcome.outcomes.len(), 3);
// Index 0 and 2 forwarded to inner; index 1 short-circuited to Denied.
assert!(matches!(
outcome.outcomes[0],
CapabilityOutcome::Completed(_)
));
assert!(matches!(outcome.outcomes[1], CapabilityOutcome::Denied(_)));
assert!(matches!(
outcome.outcomes[2],
CapabilityOutcome::Completed(_)
));
let batch_calls = inner.batch_calls();
assert_eq!(
batch_calls.len(),
1,
"remaining entries must be forwarded in a single batched call"
);
assert_eq!(
batch_calls[0].len(),
2,
"only the two non-denied entries reach the inner port"
);
// Order must match the original (allowed) order: alpha then gamma.
assert_eq!(batch_calls[0][0].as_str(), "cap.alpha");
assert_eq!(batch_calls[0][1].as_str(), "cap.gamma");
}
/// Even though the inner port is called only ONCE, `AfterCapability`
/// observers must fire per-entry against the merged outcome vec — the
/// per-entry telemetry contract from PR #3573 (serrrfirat finding #3)
/// is independent of the inner-port call topology.
#[tokio::test]
async fn batch_invocation_dispatches_after_capability_observer_per_entry() {
use crate::points::ObserverHookContext;
use crate::sink::{ObserverHook, ObserverSink};
struct CountingObserver {
seen: Arc<Mutex<u32>>,
}
#[async_trait]
impl ObserverHook for CountingObserver {
async fn observe(&self, _ctx: &ObserverHookContext, _sink: &mut dyn ObserverSink) {
*self.seen.lock().expect("not poisoned") += 1;
}
}
let seen = Arc::new(Mutex::new(0u32));
let observer_id = HookId::for_builtin("test::after_cap_per_entry", HookVersion::ONE);
let mut registry = HookRegistry::new();
registry
.insert(HookBinding {
hook_id: observer_id,
hook_version: HookVersion::ONE,
trust_class: HookTrustClass::Builtin,
phase: HookPhase::Telemetry,
priority: HookPriority::DEFAULT,
point: HookPointSpec::AfterCapability,
owning_extension: None,
scope: HookBindingScope::Global,
event_kind_filter: None,
poisoned: false,
})
.expect("ok");
let mut dispatcher = HookDispatcher::new(registry);
dispatcher.install_observer_impl(
observer_id,
crate::dispatch::ObserverHookImpl::Any(Box::new(CountingObserver { seen: seen.clone() })),
);
let inner = Arc::new(AlwaysCompletedPort::new());
let wrapped = HookedLoopCapabilityPort::new(inner.clone(), Arc::new(dispatcher), tenant());
let batch = CapabilityBatchInvocation {
invocations: vec![
invocation("cap.alpha"),
invocation("cap.beta"),
invocation("cap.gamma"),
],
stop_on_first_suspension: false,
};
let outcome = wrapped.invoke_capability_batch(batch).await.expect("ok");
assert_eq!(outcome.outcomes.len(), 3);
assert_eq!(
inner.batch_calls().len(),
1,
"inner port called exactly once (batched)"
);
assert_eq!(
*seen.lock().expect("not poisoned"),
3,
"AfterCapability observer must fire per merged entry (3 entries) \
even though the inner port was batched into a single call"
);
}
// ── C3 regression: provider resolver populates hook context ────────────
use crate::middleware::resolver::CapabilityProviderResolver;
use crate::points::BeforeCapabilityHookContext as HookCtxForTest;
use ironclaw_host_api::ExtensionId as HostExtensionId;
/// Resolver that records every capability_id it was queried for and
/// returns a fixed provider for each call.
struct RecordingProviderResolver {
provider: HostExtensionId,
queried: Mutex<Vec<String>>,
}
#[async_trait]
impl CapabilityProviderResolver for RecordingProviderResolver {
async fn provider_for(&self, capability_id: &str) -> Option<HostExtensionId> {
self.queried
.lock()
.expect("recording resolver not poisoned")
.push(capability_id.to_string());
Some(self.provider.clone())
}
}
/// Hook that records the provider observed in `ctx.provider`. Always
/// passes (no opinion) so the inner port still runs.
struct ProviderRecordingHook {
observed: Arc<Mutex<Option<Option<HostExtensionId>>>>,
}
#[async_trait]
impl RestrictedBeforeCapabilityHook for ProviderRecordingHook {
async fn evaluate(&self, ctx: &HookCtxForTest, sink: &mut dyn RestrictedGateSink) {
*self.observed.lock().expect("observed mutex ok") = Some(ctx.provider.clone());
sink.pass();
}
}
#[tokio::test]
async fn provider_resolver_populates_hook_context() {
let provider = HostExtensionId::new("ext-resolver-test").expect("valid ext id");
let resolver = Arc::new(RecordingProviderResolver {
provider: provider.clone(),
queried: Mutex::new(Vec::new()),
});
// Use Global scope so the hook fires; we're testing the *context*,
// not the scope filter.
let hook_id = HookId::derive(
&ExtensionId::new("ext").expect("valid ExtensionId in test"),
"1.0",
&HookLocalId::new("recording").expect("valid HookLocalId in test"),
HookVersion::ONE,
);
let observed = Arc::new(Mutex::new(None));
let hook = ProviderRecordingHook {
observed: Arc::clone(&observed),
};
let mut dispatcher = HookDispatcher::new(HookRegistry::new());
dispatcher
.install_installed_before_capability(
hook_id,
HookPhase::Policy,
HostExtensionId::new("ext-resolver-test").expect("valid"),
crate::registry::HookBindingScope::Global,