Repository navigation
Expand file tree
/
Copy pathspecialized.rs
More file actions
939 lines (883 loc) · 33 KB
/
Copy pathspecialized.rs
File metadata and controls
939 lines (883 loc) · 33 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
//! Server-owned governance for canonical gateway tools whose exact action policy
//! cannot be represented by one static ToolDefinition contract.
//!
//! Plugin and managed SSH gateways keep their native execution protocols. This
//! layer owns only the authority facts that must be resolved before any effect:
//! exact scope, Workflow Session authority/guards, permission policy, and a
//! bounded ledger lifecycle.
use serde_json::{json, Value};
use super::permissions::{
add_permission_to_result, permission_execution_denied_result, PermissionDecision,
};
use super::session_context::{session_guard_denied_result, session_lifecycle_denied_result};
use super::sessions::{
SessionPathHint, SessionToolContract, SessionTransport, ToolCallRecorderMetadata, ToolCallStart,
};
use super::{ToolResult, ToolRuntime};
use crate::auth::AuthContext;
/// Shared Browser/Computer terminal diagnostics. Missing state keeps the
/// established success-dependent default; it is not a general retry proof.
pub(super) fn specialized_terminal(result: &ToolResult) -> (&str, Option<&str>) {
let facts = super::execution_outcome::ExecutionOutcomeFacts::from_result(result);
(
facts.execution_state_name().unwrap_or(if result.success {
"completed"
} else {
"not_started"
}),
facts.preferred_failure_kind(),
)
}
#[cfg(test)]
#[path = "tests/specialized_terminal.rs"]
mod terminal_tests;
/// The closed heterogeneous gateway boundary. `None` leaves ordinary tools
/// untouched for the kernel's generic lifecycle. Recognized gateways never fall
/// through, including on parse or governance denial.
///
/// Reuse the canonical typed ToolCall parser; action policy and native result
/// conversion remain gateway-owned. Only trusted recorder/auth/transport context
/// crosses this boundary: generic InvocationMetadata has no specialized meaning.
pub(crate) async fn try_dispatch_specialized_gateway(
runtime: &ToolRuntime,
request: &super::kernel::ToolCallRequest,
context: super::kernel::ToolCallContext<'_>,
) -> Option<super::kernel::ToolCallOutcome> {
use super::kernel::{ToolCallErrorStatus, ToolCallOutcome};
use super::sessions::strip_tool_call_expectation_metadata;
use super::ToolCall;
if !matches!(
request.tool_name.as_str(),
crate::plugin_gateway::PLUGIN_TOOL_NAME
| crate::ssh_resource_gateway::SSH_RESOURCE_TOOL_NAME
| "observe_browser"
| "control_browser"
| "observe_computer"
| "control_computer"
) {
return None;
}
let arguments = strip_tool_call_expectation_metadata(request.arguments.clone());
let call = match ToolCall::from_tool_name(&request.tool_name, arguments) {
Ok(call) => call,
Err(message) => {
return Some(ToolCallOutcome {
success: false,
result: None,
error_status: Some(ToolCallErrorStatus::InvalidArguments { message }),
project: None,
model_ergonomics: None,
canonical_audit_output: None,
canonical_state_changed: None,
correlation: Default::default(),
});
}
};
let invocation = match call {
ToolCall::PluginTool(call) => crate::plugin_gateway::invoke(
runtime,
call,
context.session_id,
context.auth,
context.transport.into(),
)
.await
.map(|invocation| invocation.to_tool_result()),
ToolCall::SshResource(call) => crate::ssh_resource_gateway::invoke(
runtime,
call,
context.session_id,
context.auth,
context.transport.into(),
)
.await
.map(|invocation| invocation.to_tool_result()),
ToolCall::BrowserObserve(call) => {
runtime
.invoke_browser_observe_gateway(
call,
context.session_id,
context.auth,
context.transport.into(),
)
.await
}
ToolCall::BrowserAct(call) => {
runtime
.invoke_browser_act_gateway(
call,
context.session_id,
context.auth,
context.transport.into(),
)
.await
}
ToolCall::ComputerObserve(call) => {
runtime
.invoke_computer_observe_gateway(
call,
context.session_id,
context.auth,
context.transport.into(),
)
.await
}
ToolCall::ComputerControl(call) => {
runtime
.invoke_computer_control_gateway(
call,
context.session_id,
context.auth,
context.transport.into(),
)
.await
}
_ => unreachable!("specialized gateway name must parse to its canonical ToolCall"),
};
Some(match invocation {
Ok(result) => {
let mut correlation = super::window_activity::ToolCallCorrelation::default();
if let Some(session_id) = context.session_id {
correlation.add_workflow_session(
super::window_activity::WorkflowSessionCorrelation {
session_id: session_id.to_string(),
project: runtime.sessions.session_project(session_id).flatten(),
relation:
super::window_activity::WorkflowSessionCorrelationRelation::Recording,
},
);
}
ToolCallOutcome {
success: result.success,
result: Some(result),
error_status: None,
project: None,
model_ergonomics: None,
canonical_audit_output: None,
canonical_state_changed: None,
correlation,
}
}
Err(SpecializedGovernanceDenial::Tool(result)) => ToolCallOutcome {
success: result.success,
result: Some(result),
error_status: None,
project: None,
model_ergonomics: None,
canonical_audit_output: None,
canonical_state_changed: None,
correlation: Default::default(),
},
Err(SpecializedGovernanceDenial::Scope {
required_scope,
description,
}) => ToolCallOutcome {
success: false,
result: None,
error_status: Some(ToolCallErrorStatus::InsufficientScope {
required_scope: Some(required_scope),
description,
}),
project: None,
model_ergonomics: None,
canonical_audit_output: None,
canonical_state_changed: None,
correlation: Default::default(),
},
})
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum SpecializedSource {
Plugin,
SshResource,
Browser,
Computer,
}
impl SpecializedSource {
pub(crate) fn as_str(self) -> &'static str {
match self {
Self::Plugin => "plugin",
Self::SshResource => "ssh-resource",
Self::Browser => "browser",
Self::Computer => "computer",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum SpecializedEffect {
Read,
LocalExecution,
Management,
}
impl SpecializedEffect {
pub(crate) fn as_str(self) -> &'static str {
match self {
Self::Read => "read",
Self::LocalExecution => "local_execution",
Self::Management => "management",
}
}
fn consequential(self) -> bool {
!matches!(self, Self::Read)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum SpecializedAuthorityRequirement {
Scope(&'static str),
All(&'static [&'static str]),
}
impl SpecializedAuthorityRequirement {
pub(crate) fn first_missing(self, auth: Option<&AuthContext>) -> Option<&'static str> {
let scope_missing = |scope: &'static str| match auth {
Some(auth) => !auth.has_scope(scope),
None => crate::auth::scopes::scope_requires_explicit_unauthenticated_authority(scope),
};
match self {
Self::Scope(scope) => scope_missing(scope).then_some(scope),
Self::All(scopes) => scopes.iter().copied().find(|scope| scope_missing(scope)),
}
}
fn audit_projection(self) -> Value {
match self {
Self::Scope(scope) => json!({"policy": "require", "scopes": [scope]}),
Self::All(scopes) => json!({"policy": "require_all", "scopes": scopes}),
}
}
fn description(self) -> String {
match self {
Self::Scope(scope) => scope.to_string(),
Self::All(scopes) => scopes.join(", "),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct SpecializedOperationPolicy {
pub(crate) source: SpecializedSource,
pub(crate) operation: &'static str,
pub(crate) authority: SpecializedAuthorityRequirement,
pub(crate) effect: SpecializedEffect,
pub(crate) risk: &'static str,
/// Management operations which mutate durable/local state are write-like.
pub(crate) write_like: bool,
/// Operations that start or invoke local executable code are shell-like for
/// Workflow Session guard purposes, irrespective of provider annotations.
pub(crate) shell_like: bool,
}
impl SpecializedOperationPolicy {
pub(crate) fn read(
source: SpecializedSource,
operation: &'static str,
required_scope: &'static str,
) -> Self {
Self::read_with_authority(
source,
operation,
SpecializedAuthorityRequirement::Scope(required_scope),
)
}
pub(crate) fn read_all(
source: SpecializedSource,
operation: &'static str,
required_scopes: &'static [&'static str],
) -> Self {
Self::read_with_authority(
source,
operation,
SpecializedAuthorityRequirement::All(required_scopes),
)
}
fn read_with_authority(
source: SpecializedSource,
operation: &'static str,
authority: SpecializedAuthorityRequirement,
) -> Self {
Self {
source,
operation,
authority,
effect: SpecializedEffect::Read,
risk: "specialized_read",
write_like: false,
shell_like: false,
}
}
pub(crate) fn local_execution(
source: SpecializedSource,
operation: &'static str,
required_scope: &'static str,
) -> Self {
Self {
source,
operation,
authority: SpecializedAuthorityRequirement::Scope(required_scope),
effect: SpecializedEffect::LocalExecution,
risk: "specialized_local_execution",
write_like: false,
shell_like: true,
}
}
pub(crate) fn management(
source: SpecializedSource,
operation: &'static str,
required_scope: &'static str,
write_like: bool,
shell_like: bool,
) -> Self {
Self {
source,
operation,
authority: SpecializedAuthorityRequirement::Scope(required_scope),
effect: SpecializedEffect::Management,
risk: "specialized_management",
write_like,
shell_like,
}
}
pub(crate) fn consequential_all(
source: SpecializedSource,
operation: &'static str,
required_scopes: &'static [&'static str],
risk: &'static str,
) -> Self {
Self {
source,
operation,
authority: SpecializedAuthorityRequirement::All(required_scopes),
effect: SpecializedEffect::Management,
risk,
write_like: true,
shell_like: false,
}
}
pub(crate) fn consequential(
source: SpecializedSource,
operation: &'static str,
required_scope: &'static str,
risk: &'static str,
) -> Self {
Self {
source,
operation,
authority: SpecializedAuthorityRequirement::Scope(required_scope),
effect: SpecializedEffect::Management,
risk,
write_like: true,
shell_like: false,
}
}
fn session_contract(self) -> SessionToolContract {
SessionToolContract {
risk_class: self.risk,
read_like: self.effect == SpecializedEffect::Read,
write_like: self.write_like,
shell_like: self.shell_like,
git_like: false,
change_summary_like: false,
project_write: false,
path_hint: SessionPathHint::None,
}
}
pub(crate) fn audit_projection(self) -> Value {
json!({
"source": self.source.as_str(),
"operation": self.operation,
"effect": self.effect.as_str(),
"risk": self.risk,
"authority": self.authority.audit_projection(),
"permission_required": self.effect.consequential(),
})
}
}
#[derive(Debug)]
pub(crate) enum SpecializedGovernanceDenial {
Scope {
required_scope: &'static str,
description: String,
},
Tool(ToolResult),
}
#[derive(Debug)]
pub(crate) struct SpecializedInvocationPermit {
policy: SpecializedOperationPolicy,
session_start: Option<ToolCallStart>,
permission: Option<PermissionDecision>,
}
fn bounded_ledger_arguments(policy: SpecializedOperationPolicy, identity: &Value) -> Value {
json!({
"specialized": policy.audit_projection(),
"identity": identity,
})
}
fn denial_terminal_projection(policy: SpecializedOperationPolicy, kind: &str) -> Value {
json!({
"specialized": policy.audit_projection(),
"dispatch_certainty": "not_started",
"success": false,
"failure_kind": kind,
})
}
impl ToolRuntime {
/// Resolve the shared authority boundary for one already-classified
/// specialized operation. Transport is explicit provenance only; it never
/// changes authority or infers a Workflow Session.
pub(crate) async fn govern_specialized_invocation(
&self,
external_tool_name: &str,
policy: SpecializedOperationPolicy,
transport: SessionTransport,
recording_session_id: Option<&str>,
auth: Option<&AuthContext>,
identity: &Value,
) -> Result<SpecializedInvocationPermit, SpecializedGovernanceDenial> {
self.govern_specialized_invocation_on_project(
external_tool_name,
policy,
transport,
recording_session_id,
auth,
identity,
None,
)
.await
}
/// An already-authorized business target selects Project permission policy.
/// A recording Session remains provenance/guard context, never target authority.
#[allow(clippy::too_many_arguments)]
pub(crate) async fn govern_specialized_invocation_on_project(
&self,
external_tool_name: &str,
policy: SpecializedOperationPolicy,
transport: SessionTransport,
recording_session_id: Option<&str>,
auth: Option<&AuthContext>,
identity: &Value,
target_project: Option<&str>,
) -> Result<SpecializedInvocationPermit, SpecializedGovernanceDenial> {
if let Some(required_scope) = policy.authority.first_missing(auth) {
return Err(SpecializedGovernanceDenial::Scope {
required_scope,
description: format!(
"{} operation '{}' requires scopes: {}",
policy.source.as_str(),
policy.operation,
policy.authority.description()
),
});
}
let mut resolved_session_project = None;
if let Some(session_id) = recording_session_id {
match self
.authorize_session_target(session_id, external_tool_name, auth)
.await
{
Ok(resolved) => {
resolved_session_project = resolved.map(|project| project.resolved_id);
}
Err(mut result) => {
result.output["dispatch_certainty"] = Value::String("not_started".to_string());
return Err(SpecializedGovernanceDenial::Tool(result));
}
}
}
let business_project = target_project
.map(str::to_string)
.or_else(|| resolved_session_project.clone());
let contract = policy.session_contract();
let recorder_metadata = ToolCallRecorderMetadata {
recording_session_id: recording_session_id.map(str::to_string),
recording_session_project: resolved_session_project.clone(),
recording_session_authorized: recording_session_id.is_some(),
..Default::default()
};
let mut session_start = self.sessions.record_tool_call_started_with_metadata(
recording_session_id,
transport,
external_tool_name,
&bounded_ledger_arguments(policy, identity),
business_project.clone(),
recorder_metadata,
contract,
);
if let Some(session_id) = recording_session_id {
if let Some(denial) =
self.sessions
.lifecycle_denial(session_id, external_tool_name, contract)
{
let mut result =
session_lifecycle_denied_result(session_id, external_tool_name, denial);
result.output["dispatch_certainty"] = Value::String("not_started".to_string());
self.sessions.record_tool_call_finished(
session_start,
false,
&denial_terminal_projection(policy, "session_lifecycle_denied"),
result.error.as_deref(),
Some("session_lifecycle_denied"),
);
return Err(SpecializedGovernanceDenial::Tool(result));
}
if let Some(denial) = self.sessions.guard_denial(session_id, contract) {
let mut result =
session_guard_denied_result(session_id, external_tool_name, denial);
result.output["dispatch_certainty"] = Value::String("not_started".to_string());
self.sessions.record_tool_call_finished(
session_start,
false,
&denial_terminal_projection(policy, "session_guard_denied"),
result.error.as_deref(),
Some("session_guard_denied"),
);
return Err(SpecializedGovernanceDenial::Tool(result));
}
}
let permission = if policy.effect.consequential() {
let decision = self.permission_evaluator.evaluate_resolved_required(
external_tool_name,
business_project.as_deref(),
policy.risk,
);
if let Some(start) = session_start.as_mut() {
self.sessions
.record_permission_decision(start, decision.clone());
}
if decision.status == "denied" || decision.status == "pending" {
let mut result = permission_execution_denied_result(&decision);
add_permission_to_result(&mut result, &decision);
result.output["dispatch_certainty"] = Value::String("not_started".to_string());
self.sessions.record_tool_call_finished(
session_start,
false,
&denial_terminal_projection(policy, "permission_denied"),
result.error.as_deref(),
Some("permission_denied"),
);
return Err(SpecializedGovernanceDenial::Tool(result));
}
Some(decision)
} else {
None
};
Ok(SpecializedInvocationPermit {
policy,
session_start,
permission,
})
}
/// Close the authoritative specialized ledger lifecycle with only bounded
/// terminal facts. Provider output and raw arguments never enter Session
/// evidence here.
pub(crate) fn finish_specialized_invocation(
&self,
permit: SpecializedInvocationPermit,
success: bool,
dispatch_certainty: &str,
failure_kind: Option<&str>,
) {
let terminal = json!({
"specialized": permit.policy.audit_projection(),
"dispatch_certainty": dispatch_certainty,
"success": success,
"failure_kind": failure_kind,
"permission_status": permit.permission.as_ref().map(|decision| decision.status.as_str()),
});
self.sessions.record_tool_call_finished(
permit.session_start,
success,
&terminal,
(!success).then_some("specialized operation failed"),
failure_kind,
);
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::auth::{
AuthContext, AuthKind, SCOPE_BROWSER_CONTROL, SCOPE_BROWSER_LAUNCH, SCOPE_BROWSER_READ,
SCOPE_PLUGIN_INSPECT, SCOPE_PLUGIN_INVOKE,
};
use crate::tool_runtime::permissions::{AuthorityMode, PermissionEvaluator};
use std::sync::{
atomic::{AtomicUsize, Ordering},
Arc,
};
fn auth(owner: &str, scopes: &[&str]) -> AuthContext {
let mut auth = AuthContext::new(AuthKind::ApiToken);
auth.user_id = Some(format!("user-{owner}"));
auth.username = Some(owner.to_string());
auth.api_key_id = Some(format!("key-{owner}"));
auth.scopes
.extend(scopes.iter().map(|scope| (*scope).to_string()));
auth
}
fn session(
runtime: &ToolRuntime,
owner: &AuthContext,
mode: crate::tool_runtime::SessionMode,
) -> crate::tool_runtime::sessions::SessionSummary {
let fingerprint = crate::tool_runtime::workflow_session_authority_fingerprint(Some(owner))
.expect("test authority fingerprint");
runtime
.sessions
.start_session_with_options(
crate::tool_runtime::sessions::SessionCreateOptions::new(
None,
Some("specialized governance".to_string()),
mode,
crate::tool_runtime::sessions::SessionGuards::default(),
)
.with_owner_authority_fingerprint(Some(fingerprint)),
)
.unwrap()
}
#[test]
fn specialized_scope_checks_preserve_explicit_gateway_authority_without_auth() {
assert_eq!(
SpecializedAuthorityRequirement::Scope(SCOPE_PLUGIN_INSPECT).first_missing(None),
Some(SCOPE_PLUGIN_INSPECT)
);
}
#[tokio::test]
async fn specialized_read_only_session_allows_read_and_denies_local_execution() {
let runtime = ToolRuntime::new_for_tests();
let auth = auth("alice", &[SCOPE_PLUGIN_INSPECT, SCOPE_PLUGIN_INVOKE]);
let session = session(&runtime, &auth, crate::tool_runtime::SessionMode::ReadOnly);
let read = runtime
.govern_specialized_invocation(
"plugin_tool",
SpecializedOperationPolicy::read(
SpecializedSource::Plugin,
"list",
SCOPE_PLUGIN_INSPECT,
),
SessionTransport::Mcp,
Some(&session.session_id),
Some(&auth),
&json!({"plugin": "repo-tools"}),
)
.await
.expect("read-like Plugin inspection remains allowed");
runtime.finish_specialized_invocation(read, true, "completed", None);
let denied = runtime
.govern_specialized_invocation(
"plugin_tool",
SpecializedOperationPolicy::local_execution(
SpecializedSource::Plugin,
"call",
SCOPE_PLUGIN_INVOKE,
),
SessionTransport::Mcp,
Some(&session.session_id),
Some(&auth),
&json!({"plugin": "repo-tools"}),
)
.await
.expect_err("read-only Session must deny local Plugin execution");
let SpecializedGovernanceDenial::Tool(result) = denied else {
panic!("expected Session guard denial");
};
assert_eq!(result.output["error_kind"], "session_guard_denied");
assert_eq!(result.output["dispatch_certainty"], "not_started");
}
#[tokio::test]
async fn browser_read_only_session_allows_observation_and_denies_control_before_dispatch() {
let runtime = ToolRuntime::new_for_tests();
let auth = auth(
"browser-owner",
&[
SCOPE_BROWSER_READ,
SCOPE_BROWSER_CONTROL,
SCOPE_BROWSER_LAUNCH,
],
);
let session = session(&runtime, &auth, crate::tool_runtime::SessionMode::ReadOnly);
let read = runtime
.govern_specialized_invocation(
"observe_browser",
SpecializedOperationPolicy::read(
SpecializedSource::Browser,
"targets",
SCOPE_BROWSER_READ,
),
SessionTransport::Mcp,
Some(&session.session_id),
Some(&auth),
&json!({"action":"targets"}),
)
.await
.expect("read-only Browser observation remains allowed");
runtime.finish_specialized_invocation(read, true, "completed", None);
let denied = runtime
.govern_specialized_invocation(
"control_browser",
SpecializedOperationPolicy::consequential(
SpecializedSource::Browser,
"navigate",
SCOPE_BROWSER_CONTROL,
"browser_control",
),
SessionTransport::Mcp,
Some(&session.session_id),
Some(&auth),
&json!({"action":"navigate"}),
)
.await
.expect_err("read-only Session must deny Browser control");
let SpecializedGovernanceDenial::Tool(result) = denied else {
panic!("expected Browser Session guard denial");
};
assert_eq!(result.output["error_kind"], "session_guard_denied");
assert_eq!(result.output["dispatch_certainty"], "not_started");
}
#[tokio::test]
async fn browser_control_permission_is_checked_while_observe_skips_permission() {
let counter = Arc::new(AtomicUsize::new(0));
let runtime = ToolRuntime::new_for_tests().with_permission_evaluator(
PermissionEvaluator::with_mode(AuthorityMode::Restricted)
.with_eval_counter(counter.clone()),
);
let auth = auth(
"browser-owner",
&[SCOPE_BROWSER_READ, SCOPE_BROWSER_CONTROL],
);
let read = runtime
.govern_specialized_invocation(
"observe_browser",
SpecializedOperationPolicy::read(
SpecializedSource::Browser,
"targets",
SCOPE_BROWSER_READ,
),
SessionTransport::Mcp,
None,
Some(&auth),
&json!({}),
)
.await
.expect("Browser observation skips approval");
runtime.finish_specialized_invocation(read, true, "completed", None);
assert_eq!(counter.load(Ordering::SeqCst), 0);
let denied = runtime
.govern_specialized_invocation(
"control_browser",
SpecializedOperationPolicy::consequential(
SpecializedSource::Browser,
"click",
SCOPE_BROWSER_CONTROL,
"browser_control",
),
SessionTransport::Mcp,
None,
Some(&auth),
&json!({}),
)
.await
.expect_err("Browser control requires Standard permission");
let SpecializedGovernanceDenial::Tool(result) = denied else {
panic!("expected Browser permission denial");
};
assert_eq!(counter.load(Ordering::SeqCst), 1);
assert_eq!(result.output["failure_kind"], "permission_denied");
assert_eq!(result.output["dispatch_certainty"], "not_started");
}
#[tokio::test]
async fn specialized_permission_evaluator_denies_effect_before_dispatch_but_skips_reads() {
let counter = Arc::new(AtomicUsize::new(0));
let runtime = ToolRuntime::new_for_tests().with_permission_evaluator(
PermissionEvaluator::with_mode(AuthorityMode::Restricted)
.with_eval_counter(counter.clone()),
);
let auth = auth("alice", &[SCOPE_PLUGIN_INSPECT, SCOPE_PLUGIN_INVOKE]);
let read = runtime
.govern_specialized_invocation(
"plugin_tool",
SpecializedOperationPolicy::read(
SpecializedSource::Plugin,
"list",
SCOPE_PLUGIN_INSPECT,
),
SessionTransport::Mcp,
None,
Some(&auth),
&json!({}),
)
.await
.expect("read-like operation skips permission approval");
runtime.finish_specialized_invocation(read, true, "completed", None);
assert_eq!(counter.load(Ordering::SeqCst), 0);
let denied = runtime
.govern_specialized_invocation(
"plugin_tool",
SpecializedOperationPolicy::local_execution(
SpecializedSource::Plugin,
"call",
SCOPE_PLUGIN_INVOKE,
),
SessionTransport::Mcp,
None,
Some(&auth),
&json!({}),
)
.await
.expect_err("restricted authority must deny specialized local execution");
let SpecializedGovernanceDenial::Tool(result) = denied else {
panic!("expected permission denial");
};
assert_eq!(counter.load(Ordering::SeqCst), 1);
assert_eq!(result.output["failure_kind"], "permission_denied");
assert_eq!(result.output["dispatch_certainty"], "not_started");
}
#[tokio::test]
async fn specialized_explicit_business_project_selects_permission_target_without_a_recorder() {
let runtime = ToolRuntime::new_for_tests()
.with_permission_evaluator(PermissionEvaluator::with_mode(AuthorityMode::TrustedAgent));
let auth = auth("alice", &[SCOPE_PLUGIN_INVOKE]);
let permit = runtime
.govern_specialized_invocation_on_project(
"plugin_tool",
SpecializedOperationPolicy::local_execution(
SpecializedSource::Plugin,
"call",
SCOPE_PLUGIN_INVOKE,
),
SessionTransport::Mcp,
None,
Some(&auth),
&json!({"project":"untrusted-observation"}),
Some("agent:runner:authorized-target"),
)
.await
.unwrap();
assert_eq!(
permit.permission.as_ref().unwrap().project.as_deref(),
Some("agent:runner:authorized-target")
);
runtime.finish_specialized_invocation(permit, true, "completed", None);
}
#[tokio::test]
async fn specialized_recording_session_authority_is_exact_and_fail_closed() {
let runtime = ToolRuntime::new_for_tests();
let owner = auth("alice", &[SCOPE_PLUGIN_INSPECT]);
let foreign = auth("bob", &[SCOPE_PLUGIN_INSPECT]);
let session = session(&runtime, &owner, crate::tool_runtime::SessionMode::Normal);
let denied = runtime
.govern_specialized_invocation(
"plugin_tool",
SpecializedOperationPolicy::read(
SpecializedSource::Plugin,
"list",
SCOPE_PLUGIN_INSPECT,
),
SessionTransport::Mcp,
Some(&session.session_id),
Some(&foreign),
&json!({}),
)
.await
.expect_err("foreign authority must not attach to exact recording Session");
let SpecializedGovernanceDenial::Tool(result) = denied else {
panic!("expected exact Session authority denial");
};
assert_eq!(result.output["failure_kind"], "session_authority_denied");
assert_eq!(result.output["dispatch_certainty"], "not_started");
}
}