-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Expand file tree
/
Copy pathcapability_port.rs
More file actions
2283 lines (2125 loc) · 93.5 KB
/
Copy pathcapability_port.rs
File metadata and controls
2283 lines (2125 loc) · 93.5 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
//! Capability-port middleware that runs `dispatch_before_capability` ahead of
//! every invocation and translates hook decisions into the existing
//! `CapabilityOutcome` vocabulary.
//!
//! Translation:
//!
//! - `GateDecisionInner::Allow` → forward to inner port unchanged.
//! - `GateDecisionInner::Deny` → return `CapabilityOutcome::Denied` with
//! `CapabilityDeniedReasonKind::Unknown("hook_denied")` and the sanitized
//! reason as `safe_summary`.
//! - `GateDecisionInner::PauseApproval` → mint an approval gate ref via the
//! configured [`HookGateRefFactory`] and return
//! `CapabilityOutcome::ApprovalRequired { gate_ref, safe_summary }`.
//! - `GateDecisionInner::PauseAuth` → mint an auth gate ref via the factory
//! and return `CapabilityOutcome::AuthRequired { gate_ref, safe_summary }`.
//!
//! If the factory itself fails (e.g. the host's gate-router rejected the
//! mint), the middleware fails closed and surfaces the call as
//! `CapabilityOutcome::Denied` with a sanitized `hook_gate_ref_unavailable`
//! reason kind — better to refuse the call than route the loop through an
//! unresolvable suspension.
//!
//! Failure cases from the dispatcher (panic, timeout, missing impl) also map
//! to `Denied` per the [`crate::failure_policy`] rules.
use std::sync::Arc;
use async_trait::async_trait;
use ironclaw_host_api::TenantId;
use ironclaw_turns::run_profile::{
AgentLoopHostError, CapabilityBatchInvocation, CapabilityBatchOutcome, CapabilityDenied,
CapabilityDeniedReasonKind, CapabilityInvocation, CapabilityOutcome, LoopCapabilityPort,
VisibleCapabilityRequest, VisibleCapabilitySurface,
};
use crate::dispatch::{BeforeCapabilityDispatchOutcome, HookDispatcher};
use crate::kinds::gate::GateDecisionInner;
use crate::middleware::gate_ref::{FailClosedHookGateRefFactory, HookGateRefFactory};
use crate::middleware::resolver::{
CapabilityInputResolver, CapabilityProviderResolver, NullCapabilityInputResolver,
NullCapabilityProviderResolver,
};
use crate::points::{BeforeCapabilityHookContext, SanitizedArguments};
/// Maximum byte length of a capability input that the middleware will
/// hand to predicate evaluation. When [`CapabilityInputResolver::size_hint`]
/// reports a value larger than this, the middleware fails closed (treats
/// the input as unresolved) without calling
/// [`CapabilityInputResolver::resolve`]. A post-materialization check
/// against the serialized JSON length acts as a defense-in-depth backstop
/// when the size hint is unavailable.
///
/// This cap is deliberately conservative — its purpose is to prevent
/// accidental fatality (a multi-gigabyte file blob fed to a predicate
/// that scans for a numeric field) rather than to express a tight
/// production limit. Production deployments that need to evaluate
/// predicates against larger inputs should raise the cap once the
/// streaming-extraction story exists; today the predicate evaluator only
/// reads small numeric fields and 1 MiB is well above any realistic
/// `NumericSum` payload while being orders of magnitude below the cost
/// that would matter to a host.
pub const MAX_PREDICATE_INPUT_BYTES: u64 = 1024 * 1024;
/// Wraps an inner `LoopCapabilityPort`, fires `before_capability` hooks ahead
/// of each invocation, and translates the dispatcher's composed decision into
/// the `CapabilityOutcome` vocabulary the loop driver already speaks.
pub struct HookedLoopCapabilityPort {
inner: Arc<dyn LoopCapabilityPort>,
dispatcher: Arc<HookDispatcher>,
tenant_id: TenantId,
resolver: Arc<dyn CapabilityInputResolver>,
provider_resolver: Arc<dyn CapabilityProviderResolver>,
gate_ref_factory: Arc<dyn HookGateRefFactory>,
}
impl HookedLoopCapabilityPort {
/// Construct a middleware with the bundled
/// [`NullCapabilityInputResolver`]. Predicate evaluators that depend on
/// argument contents (e.g., `ValueOrRateBound::NumericSum`) will fail
/// closed; use [`Self::with_resolver`] to wire in a production resolver.
pub fn new(
inner: Arc<dyn LoopCapabilityPort>,
dispatcher: Arc<HookDispatcher>,
tenant_id: TenantId,
) -> Self {
Self {
inner,
dispatcher,
tenant_id,
resolver: Arc::new(NullCapabilityInputResolver),
provider_resolver: Arc::new(NullCapabilityProviderResolver),
// Default to fail-closed: minting a syntactically-valid but
// router-unregistered ref is worse than refusing the suspension.
// Callers must explicitly opt into UuidHookGateRefFactory for
// tests/dev, or install a router-backed factory for production
// (henrypark133 review Critical #3).
gate_ref_factory: Arc::new(FailClosedHookGateRefFactory),
}
}
/// Override the resolver used to surface sanitized arguments to hook
/// predicates. Returns `self` so callers can chain after `new`.
#[must_use]
pub fn with_resolver(mut self, resolver: Arc<dyn CapabilityInputResolver>) -> Self {
self.resolver = resolver;
self
}
/// Override the resolver used to populate
/// [`crate::points::BeforeCapabilityHookContext::provider`] with the
/// extension that owns the invoked capability. Required for
/// `OwnCapabilities`-scoped Installed hooks to fire — without a
/// production resolver the bundled [`NullCapabilityProviderResolver`]
/// returns `None` and those hooks never see their own capabilities.
#[must_use]
pub fn with_provider_resolver(
mut self,
provider_resolver: Arc<dyn CapabilityProviderResolver>,
) -> Self {
self.provider_resolver = provider_resolver;
self
}
/// Override the gate-ref factory. Production code wires a factory that
/// is bound to the current `LoopRunContext` and the host's approval-
/// router so the resulting `ApprovalRequired` / `AuthRequired` outcomes
/// resolve correctly. Tests and the foundation slice can rely on the
/// default [`UuidHookGateRefFactory`].
#[must_use]
pub fn with_gate_ref_factory(mut self, factory: Arc<dyn HookGateRefFactory>) -> Self {
self.gate_ref_factory = factory;
self
}
pub(crate) async fn hook_context(
&self,
invocation: &CapabilityInvocation,
provider: Option<ironclaw_host_api::ExtensionId>,
) -> BeforeCapabilityHookContext {
// Lazy input resolution probe (PR #3573 follow-up): when no
// active hook would actually read the capability arguments, we
// skip both the size hint and the materializing `resolve` call.
// Eager resolution was a HIGH-priority cost finding because file/
// blob-shaped inputs can be expensive — or fatal — to materialize
// even when no predicate needs them.
let arguments = if self
.dispatcher
.before_capability_needs_input(provider.as_ref())
{
self.resolve_arguments(invocation).await
} else {
SanitizedArguments::unresolved()
};
BeforeCapabilityHookContext::new(
self.tenant_id.clone(),
invocation.capability_id.to_string(),
invocation_arguments_digest(invocation),
arguments,
provider,
)
}
/// Resolve capability arguments with a streaming size pre-check.
///
/// Order of operations:
///
/// 1. Ask the resolver for a [`CapabilityInputResolver::size_hint`].
/// If the hint is `Some(n) > MAX_PREDICATE_INPUT_BYTES`, return
/// `Unresolved` immediately — predicates that need input fail
/// closed via the evaluator's existing unresolved-path policy.
/// 2. Call [`CapabilityInputResolver::resolve`]. If it returns
/// `None`, return `Unresolved`.
/// 3. Re-check the serialized JSON length against
/// `MAX_PREDICATE_INPUT_BYTES`. This is a defense-in-depth
/// backstop for resolvers whose `size_hint` returns `None`
/// (default-impl, or sources that don't know the size up
/// front).
async fn resolve_arguments(&self, invocation: &CapabilityInvocation) -> SanitizedArguments {
if let Some(size) = self.resolver.size_hint(invocation).await
&& size > MAX_PREDICATE_INPUT_BYTES
{
tracing::debug!(
capability = %invocation.capability_id,
size_bytes = size,
cap_bytes = MAX_PREDICATE_INPUT_BYTES,
"capability input exceeds MAX_PREDICATE_INPUT_BYTES; failing closed before resolve"
);
return SanitizedArguments::unresolved();
}
let Some(value) = self.resolver.resolve(invocation).await else {
return SanitizedArguments::unresolved();
};
// Defense-in-depth: even when the resolver's `size_hint`
// returned `None`, refuse to expose payloads larger than the cap
// to predicate evaluation. We measure the serialized byte cost
// by streaming into a counting writer rather than calling
// `serde_json::to_vec` and discarding the buffer — avoids one
// `Vec<u8>` allocation per resolved invocation on the happy
// path (henrypark133 review L1 on PR #3913). `SanitizedArguments::from_json`
// sanitizes the in-memory `serde_json::Value` directly; it does
// not re-serialize, so handing it the unmodified `value` is the
// cheapest path.
match serialized_len(&value) {
Ok(bytes) if bytes > MAX_PREDICATE_INPUT_BYTES => {
tracing::debug!(
capability = %invocation.capability_id,
size_bytes = bytes,
cap_bytes = MAX_PREDICATE_INPUT_BYTES,
"materialized capability input exceeds MAX_PREDICATE_INPUT_BYTES; failing closed"
);
SanitizedArguments::unresolved()
}
// Serialization failure means the resolver produced a value
// we can't measure or surface safely; fail closed.
Err(_) => SanitizedArguments::unresolved(),
Ok(_) => SanitizedArguments::from_json(value),
}
}
async fn run_dispatch(
&self,
invocation: &CapabilityInvocation,
provider: Option<ironclaw_host_api::ExtensionId>,
) -> BeforeCapabilityDispatchOutcome {
let ctx = self.hook_context(invocation, provider).await;
self.dispatcher.dispatch_before_capability(&ctx).await
}
}
#[async_trait]
impl LoopCapabilityPort for HookedLoopCapabilityPort {
async fn visible_capabilities(
&self,
request: VisibleCapabilityRequest,
) -> Result<VisibleCapabilitySurface, AgentLoopHostError> {
// Visible-surface queries don't go through hooks (the surface itself
// is owned by profile-scoped filtering; hooks gate invocation, not
// listing).
self.inner.visible_capabilities(request).await
}
async fn invoke_capability(
&self,
request: CapabilityInvocation,
) -> Result<CapabilityOutcome, AgentLoopHostError> {
let provider = self
.provider_resolver
.provider_for(&request.capability_id.to_string())
.await;
let outcome = self.run_dispatch(&request, provider.clone()).await;
let result = match self.decision_to_outcome(&outcome).await {
Some(translated) => Ok(translated),
None => self.inner.invoke_capability(request).await,
};
// Fire AfterCapability observers regardless of whether the hook
// short-circuited or the inner port ran. Observer-only point — no
// gate decisions composed here. Telemetry must reflect both denied
// and allowed invocations. The resolved provider is threaded so the
// dispatcher can enforce `OwnCapabilities` scope on Installed
// observers (serrrfirat finding #3).
let _ = self
.dispatcher
.dispatch_observer_at_with_provider(
crate::registry::HookPointSpec::AfterCapability,
self.tenant_id.clone(),
provider,
)
.await;
result
}
async fn invoke_capability_batch(
&self,
request: CapabilityBatchInvocation,
) -> Result<CapabilityBatchOutcome, AgentLoopHostError> {
// Two-phase batch dispatch that preserves the inner port's batch
// semantics when hooks are active:
//
// Phase 1 — preflight: walk invocations in order, run each through
// `BeforeCapability` hook dispatch, and translate restrictive
// decisions (deny / pause / fail-closed) into outcome slots
// immediately. Entries the hooks allow are queued for the inner
// port. If a hook-translated outcome is itself a suspension and
// `stop_on_first_suspension` is set, preflight stops there and the
// remaining invocations are dropped — mirroring the previous
// sequential semantics.
//
// Phase 2 — inner batch: forward all queued (hook-allowed)
// invocations to the inner port as a SINGLE `invoke_capability_batch`
// call, then splice its outcomes back into their original index
// positions. The inner port may stop early on its own suspensions;
// any queued entry without a corresponding inner outcome is treated
// the same as a hook-suspension stop (dropped, no observer).
//
// AfterCapability observers fire per resolved entry in the merged
// outcome vec, in original index order, matching the per-entry
// semantics established in PR #3573 (serrrfirat P2 #3).
let CapabilityBatchInvocation {
invocations,
stop_on_first_suspension,
} = request;
// Phase 1: preflight hooks for each invocation in order.
enum Slot {
/// Hook produced a final outcome — no inner call needed.
Resolved {
outcome: Box<CapabilityOutcome>,
provider: Option<ironclaw_host_api::ExtensionId>,
},
/// Hooks allowed; the inner port will produce the outcome.
Pending {
provider: Option<ironclaw_host_api::ExtensionId>,
},
}
let mut slots: Vec<Slot> = Vec::with_capacity(invocations.len());
let mut pending: Vec<CapabilityInvocation> = Vec::new();
let mut stopped_in_preflight = false;
for invocation in invocations {
let provider = self
.provider_resolver
.provider_for(&invocation.capability_id.to_string())
.await;
let dispatch = self.run_dispatch(&invocation, provider.clone()).await;
match self.decision_to_outcome(&dispatch).await {
Some(translated) => {
let is_suspension = translated.is_suspension();
slots.push(Slot::Resolved {
outcome: Box::new(translated),
provider,
});
if is_suspension && stop_on_first_suspension {
stopped_in_preflight = true;
break;
}
}
None => {
slots.push(Slot::Pending {
provider: provider.clone(),
});
pending.push(invocation);
}
}
}
// Phase 2: forward the surviving (hook-allowed) entries to the inner
// port as a SINGLE batched call. Empty batches skip the inner call so
// we don't perturb implementations that special-case empty input.
let inner_result: Result<CapabilityBatchOutcome, AgentLoopHostError> = if pending.is_empty()
{
Ok(CapabilityBatchOutcome {
outcomes: Vec::new(),
stopped_on_suspension: false,
})
} else {
self.inner
.invoke_capability_batch(CapabilityBatchInvocation {
invocations: pending,
stop_on_first_suspension,
})
.await
};
// If the inner port errored, we still owe per-entry AfterCapability
// observers for every slot we already produced an outcome for (Phase 1
// resolved slots). Pending slots have no outcome to observe against;
// matching the single-invocation path, we fire one observer per
// pending slot so failed batch entries remain visible to telemetry
// (serrrfirat P2 #3 on PR #3573).
let inner_outcome = match inner_result {
Ok(outcome) => outcome,
Err(err) => {
for slot in slots {
let provider = match slot {
Slot::Resolved { provider, .. } => provider,
Slot::Pending { provider } => provider,
};
let _ = self
.dispatcher
.dispatch_observer_at_with_provider(
crate::registry::HookPointSpec::AfterCapability,
self.tenant_id.clone(),
provider,
)
.await;
}
return Err(err);
}
};
let CapabilityBatchOutcome {
outcomes: mut inner_outcomes,
stopped_on_suspension: inner_stopped,
} = inner_outcome;
// We pop from the front by reversing so we can take in original order.
inner_outcomes.reverse();
// Merge: walk slots in order, splicing inner outcomes into pending
// slots. Dispatch AfterCapability observer per merged entry.
//
// Suspension handling preserves the per-entry observer contract
// from PR #3573 (serrrfirat P2 #3): a hook-resolved suspension
// slot that follows an allowed slot must still fire its
// observer, and must still surface in `outcomes`, even when
// `stop_on_first_suspension` is set. The pre-fix loop seeded
// `stopped_on_suspension` from `stopped_in_preflight` and broke
// on the first iteration, dropping any trailing Resolved
// suspension slot — see the
// `batch_invocation_fires_observer_for_hook_suspended_entry_after_allowed_entry_with_stop_on_first_suspension`
// regression test (henrypark133 review M1 on PR #3911).
//
// Today the loop runs to completion when only Resolved
// (hook-resolved) entries remain — every observer fires and
// every outcome is pushed — and only breaks early when a
// Pending slot has no inner outcome (inner port stopped on its
// own suspension and consumed fewer outcomes than we queued).
let mut outcomes = Vec::with_capacity(slots.len());
let mut stopped_on_suspension = stopped_in_preflight;
let mut pending_after_stop = false;
for slot in slots {
let outcome_and_provider = match slot {
Slot::Resolved { outcome, provider } => Some((*outcome, provider)),
Slot::Pending { provider } => {
if pending_after_stop {
// We already stopped on a prior suspension and
// queued no work for the inner port past that
// point. A trailing Pending slot has no outcome
// to surface; drop it.
None
} else {
// `pop()` returns `None` when the inner port
// stopped early (its own suspension) and
// consumed fewer outcomes than we queued. Drop
// pending slots without an outcome and continue
// — observers on any trailing Resolved slots
// must still fire.
inner_outcomes.pop().map(|inner| (inner, provider))
}
}
};
let Some((outcome, provider)) = outcome_and_provider else {
continue;
};
let _ = self
.dispatcher
.dispatch_observer_at_with_provider(
crate::registry::HookPointSpec::AfterCapability,
self.tenant_id.clone(),
provider,
)
.await;
if outcome.is_suspension() && stop_on_first_suspension {
stopped_on_suspension = true;
pending_after_stop = true;
}
outcomes.push(outcome);
}
if inner_stopped {
stopped_on_suspension = true;
}
Ok(CapabilityBatchOutcome {
outcomes,
stopped_on_suspension,
})
}
}
impl HookedLoopCapabilityPort {
/// Translates a dispatcher outcome into a `CapabilityOutcome`. Returns
/// `Some(outcome)` when the hook decision is restrictive (deny / pause /
/// failure-closed), or `None` if the hooks allowed the call and the
/// inner port should be consulted.
///
/// This is async because pause-class decisions await the
/// `HookGateRefFactory` to mint a real `LoopGateRef`. If the factory
/// fails, the middleware falls back to `Denied` with a sanitized
/// `hook_gate_ref_unavailable` reason.
async fn decision_to_outcome(
&self,
dispatched: &BeforeCapabilityDispatchOutcome,
) -> Option<CapabilityOutcome> {
match dispatched.decision.inner() {
GateDecisionInner::Allow => None,
GateDecisionInner::Deny { reason } => {
Some(CapabilityOutcome::Denied(CapabilityDenied {
reason_kind: CapabilityDeniedReasonKind::unknown("hook_denied")
.expect("hook_denied is a valid loop-safe identifier"), // safety: literal ASCII identifier, validated by LoopGateRef constructor contract
safe_summary: reason.as_str().to_string(),
}))
}
GateDecisionInner::PauseApproval { reason } => {
match self
.gate_ref_factory
.mint_approval_ref(reason.as_str())
.await
{
Ok(gate_ref) => Some(CapabilityOutcome::ApprovalRequired {
gate_ref,
safe_summary: reason.as_str().to_string(),
approval_resume: None,
}),
Err(_) => Some(fail_closed_gate_ref_unavailable(reason.as_str())),
}
}
GateDecisionInner::PauseAuth { reason } => {
match self.gate_ref_factory.mint_auth_ref(reason.as_str()).await {
Ok(gate_ref) => Some(CapabilityOutcome::AuthRequired {
gate_ref,
credential_requirements: Vec::new(),
safe_summary: reason.as_str().to_string(),
auth_resume: None,
}),
Err(_) => Some(fail_closed_gate_ref_unavailable(reason.as_str())),
}
}
}
}
}
/// Fail-closed translation when the gate-ref factory cannot mint a ref for a
/// pause-class decision. The safe summary intentionally carries only the
/// hook's already-sanitized reason — the underlying host error is dropped to
/// avoid leaking internal gate-router state into model-visible output.
fn fail_closed_gate_ref_unavailable(sanitized_reason: &str) -> CapabilityOutcome {
CapabilityOutcome::Denied(CapabilityDenied {
reason_kind: CapabilityDeniedReasonKind::unknown("hook_gate_ref_unavailable")
.expect("hook_gate_ref_unavailable is a valid loop-safe identifier"), // safety: literal ASCII identifier, validated by LoopGateRef constructor contract
safe_summary: sanitized_reason.to_string(),
})
}
/// Counts the JSON-serialized byte length of `value` without allocating
/// an intermediate `Vec<u8>`. `serde_json::to_writer` writes into a
/// trivial `std::io::Write` impl that only increments a counter, so the
/// happy-path measurement skips one buffer allocation and one
/// `Vec<u8>::drop` per resolved invocation (henrypark133 review L1 on
/// PR #3913).
fn serialized_len(value: &serde_json::Value) -> Result<u64, serde_json::Error> {
struct CountingWriter(u64);
impl std::io::Write for CountingWriter {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
self.0 = self.0.saturating_add(buf.len() as u64);
Ok(buf.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
let mut writer = CountingWriter(0);
serde_json::to_writer(&mut writer, value)?;
Ok(writer.0)
}
/// Stable digest of capability invocation identity for hook context. The
/// middleware hashes the `(capability_id, input_ref)` pair so two
/// invocations with the same capability id and the same input ref produce
/// the same digest, enabling repetition / rate-cap logic without exposing
/// raw arguments to hook code. The digest is over input-ref identity, not
/// over the resolved argument content the input-ref points at — two
/// distinct refs that happen to resolve to identical JSON will NOT share a
/// digest, and the same ref representing changed underlying content will
/// keep the same digest.
///
/// # Stability contract
///
/// This digest is part of the **public hook contract**. Repetition-detection
/// hooks key on `BeforeCapabilityHookContext.arguments_digest` across
/// invocations; a shifted digest silently breaks them. Changing the hashing
/// structure (length-prefix ordering, hasher choice, which fields contribute)
/// requires:
///
/// 1. Updating the fixture in
/// `tests::invocation_arguments_digest_is_stable_for_known_inputs` with
/// the new captured hex.
/// 2. Surfacing the change in the cross-crate wire-format contract section
/// of `crate::identity` (the same section that pins `HookId::to_hex()`).
/// 3. Bumping the hook framework's contract version if downstream
/// consumers exist.
///
/// What this digest is NOT:
///
/// - **Not** a content digest of the resolved capability arguments. Hooks
/// that want to key on resolved content should use
/// `CapabilityInputResolver` + `SanitizedArguments`, not this digest.
/// - **Not** suitable as a primary key for cross-process deduplication —
/// two distinct invocations with the same `input_ref` (rare but legal)
/// produce the same digest.
fn invocation_arguments_digest(invocation: &CapabilityInvocation) -> [u8; 32] {
let mut hasher = blake3::Hasher::new();
let cap = invocation.capability_id.to_string();
hasher.update(&(cap.len() as u64).to_le_bytes());
hasher.update(cap.as_bytes());
// `as_str()` is the stable accessor for `CapabilityInputRef`. We avoid
// `format!("{:?}", ...)` because `Debug` is not a stability contract —
// a field rename or stdlib formatter change would silently shift the
// digest, breaking any repetition-detection hook keyed on it.
let input = invocation.input_ref.as_str();
hasher.update(&(input.len() as u64).to_le_bytes());
hasher.update(input.as_bytes());
hasher.finalize().into()
}
#[cfg(test)]
mod tests {
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),
progress: ironclaw_turns::run_profile::CapabilityProgress::MadeProgress,
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,
auth_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"
);
}
/// Snapshot regression: pins `invocation_arguments_digest` for a known
/// `(capability_id, input_ref)` pair. If this assertion fails, the
/// digest's hashing structure changed — see the stability contract on
/// `invocation_arguments_digest`. **Do not update the expected hex
/// without auditing every caller that keys on `arguments_digest`.**
#[test]
fn invocation_arguments_digest_is_stable_for_known_inputs() {
let invocation = 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,
auth_resume: None,
};
let digest = invocation_arguments_digest(&invocation);
let hex: String = digest.iter().map(|b| format!("{b:02x}")).collect();
assert_eq!(
hex, "4d0ab78e009b32615c2766bd1c26921bd59ef81b5741a75387707f82f0344315",
"invocation_arguments_digest shifted for a fixed input — \
this is a wire-contract break. See the stability-contract \
rustdoc on `invocation_arguments_digest`."
);
}
/// serrrfirat #3637 regression: pin the digest at the boundary that
/// hook authors actually observe — `BeforeCapabilityHookContext.arguments_digest`
/// produced by `HookedLoopCapabilityPort::hook_context`. If caller-side
/// wiring drifts (wrong field set, transform inserted, default value
/// leaked, or an alternate path bypassing the helper), this assertion
/// catches it while the helper-only snapshot would stay green.
#[tokio::test]
async fn hook_context_arguments_digest_is_stable_at_middleware_boundary() {
use ironclaw_host_api::TenantId;
use std::sync::Arc as StdArc;
struct NoopInner;
#[async_trait]
impl LoopCapabilityPort for NoopInner {
async fn visible_capabilities(
&self,
_request: VisibleCapabilityRequest,
) -> Result<VisibleCapabilitySurface, AgentLoopHostError> {
unreachable!("snapshot test never calls visible_capabilities")
}
async fn invoke_capability(
&self,
_request: CapabilityInvocation,
) -> Result<CapabilityOutcome, AgentLoopHostError> {
unreachable!("snapshot test never invokes through inner port")
}
async fn invoke_capability_batch(
&self,
_request: CapabilityBatchInvocation,
) -> Result<CapabilityBatchOutcome, AgentLoopHostError> {
unreachable!("snapshot test never invokes through inner port")
}
}
let port = HookedLoopCapabilityPort::new(
StdArc::new(NoopInner),
StdArc::new(HookDispatcher::new(HookRegistry::new())),
TenantId::new("alpha").expect("ok"),
);
let invocation = 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,
auth_resume: None,
};
let ctx = port.hook_context(&invocation, None).await;
let hex: String = ctx
.arguments_digest
.iter()
.map(|b| format!("{b:02x}"))
.collect();
assert_eq!(
hex, "4d0ab78e009b32615c2766bd1c26921bd59ef81b5741a75387707f82f0344315",
"BeforeCapabilityHookContext.arguments_digest shifted at the \
middleware boundary; this is a hook-visible wire-contract \
break, not just a helper-output drift."
);
}
/// 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");
assert!(matches!(outcome, CapabilityOutcome::Completed(_)));
assert_eq!(
inner.calls().len(),
1,
"allowed invocation must reach inner"
);
assert_hook_observed_snapshot_digest(&hook, "invoke_capability");
}