Skip to main content

ratify_protocol/
scope.rs

1//! Canonical scope vocabulary for Ratify Protocol v1.
2//!
3//! MUST stay in lock-step with Go's scope.go, TS's scope.ts, and Python's scope.py.
4
5#[cfg(not(feature = "std"))]
6use alloc::{
7    collections::BTreeMap, collections::BTreeSet, format, string::String, string::ToString,
8    vec::Vec,
9};
10#[cfg(feature = "std")]
11use std::collections::{BTreeMap, BTreeSet};
12
13// --- Meeting scopes ---
14pub const SCOPE_MEETING_ATTEND: &str = "meeting:attend";
15pub const SCOPE_MEETING_SPEAK: &str = "meeting:speak";
16pub const SCOPE_MEETING_VIDEO: &str = "meeting:video";
17pub const SCOPE_MEETING_CHAT: &str = "meeting:chat";
18pub const SCOPE_MEETING_SHARE_SCREEN: &str = "meeting:share_screen";
19pub const SCOPE_MEETING_RECORD: &str = "meeting:record"; // sensitive
20
21// --- Communication scopes ---
22pub const SCOPE_COMMS_MESSAGE_READ: &str = "comms:message:read";
23pub const SCOPE_COMMS_MESSAGE_SEND: &str = "comms:message:send";
24pub const SCOPE_COMMS_MESSAGE_DELETE: &str = "comms:message:delete"; // sensitive
25pub const SCOPE_COMMS_EMAIL_READ: &str = "comms:email:read";
26pub const SCOPE_COMMS_EMAIL_SEND: &str = "comms:email:send";
27pub const SCOPE_COMMS_EMAIL_DELETE: &str = "comms:email:delete"; // sensitive
28pub const SCOPE_COMMS_CALENDAR_READ: &str = "comms:calendar:read";
29pub const SCOPE_COMMS_CALENDAR_WRITE: &str = "comms:calendar:write";
30
31// --- File scopes ---
32pub const SCOPE_FILES_READ: &str = "files:read";
33pub const SCOPE_FILES_WRITE: &str = "files:write"; // sensitive
34
35// --- Identity scopes ---
36pub const SCOPE_IDENTITY_PROVE: &str = "identity:prove";
37pub const SCOPE_IDENTITY_DELEGATE: &str = "identity:delegate"; // sensitive
38
39// --- Presence scopes ---
40// SCOPE_PRESENCE_REPRESENT: (sensitive) the agent is authorized to attend
41// and interact as a direct representative of the principal — other parties
42// in the interaction may be interacting with this agent as if it were the
43// principal. Covers both non-likeness representatives and full likeness
44// agents (Tavus, HeyGen, etc.).
45//
46// Distinct from generate:deepfake (content generation, not real-time
47// representation) and identity:delegate (key delegation). Does NOT imply
48// identity:prove — issuers grant both explicitly when both are needed;
49// scope lists are literal, with no implication table.
50//
51// Verifiers accepting this scope are expected to surface the
52// representation relationship to the other participants. That disclosure
53// is platform policy, not a protocol constraint — see SPEC §9.1.
54pub const SCOPE_PRESENCE_REPRESENT: &str = "presence:represent"; // sensitive
55
56// --- Transaction scopes (v1, core to the "transaction horizon" thesis) ---
57pub const SCOPE_TRANSACT_PURCHASE: &str = "transact:purchase";
58pub const SCOPE_TRANSACT_SELL: &str = "transact:sell";
59pub const SCOPE_PAYMENTS_SEND: &str = "payments:send";
60pub const SCOPE_PAYMENTS_RECEIVE: &str = "payments:receive";
61pub const SCOPE_PAYMENTS_AUTHORIZE: &str = "payments:authorize"; // sensitive
62
63// --- Contract scopes ---
64pub const SCOPE_CONTRACT_READ: &str = "contract:read";
65pub const SCOPE_CONTRACT_SIGN: &str = "contract:sign"; // sensitive
66
67// --- Data scopes (structured application data, distinct from files) ---
68pub const SCOPE_DATA_READ: &str = "data:read";
69pub const SCOPE_DATA_WRITE: &str = "data:write"; // sensitive
70pub const SCOPE_DATA_DELETE: &str = "data:delete"; // sensitive
71pub const SCOPE_DATA_EXPORT: &str = "data:export"; // sensitive — exfiltration
72pub const SCOPE_DATA_SHARE: &str = "data:share";
73
74// --- Execute scopes ---
75pub const SCOPE_EXECUTE_TOOL: &str = "execute:tool";
76pub const SCOPE_EXECUTE_CODE: &str = "execute:code"; // sensitive
77
78// --- Generate scopes (AI content generation on someone's behalf) ---
79pub const SCOPE_GENERATE_CONTENT: &str = "generate:content";
80// Sensitive by policy: any "imitate a real person" generation creates
81// an auditable explicit authorization trail.
82pub const SCOPE_GENERATE_DEEPFAKE: &str = "generate:deepfake"; // sensitive
83
84// --- Physical-world scopes (v1, first-class coverage for embodied agents) ---
85// Ratify is channel-agnostic: same cert/bundle/verify semantics for software
86// agents and for robots, drones, vehicles, infrastructure controllers.
87// Location / time / speed / amount / rate bounds live in first-class
88// Constraint objects on DelegationCert (see types.rs).
89
90pub const SCOPE_PHYSICAL_ENTER: &str = "physical:enter";
91pub const SCOPE_PHYSICAL_EXIT: &str = "physical:exit";
92pub const SCOPE_PHYSICAL_ACTUATE: &str = "physical:actuate"; // sensitive
93pub const SCOPE_PHYSICAL_MANIPULATE: &str = "physical:manipulate"; // sensitive
94
95pub const SCOPE_ROBOT_OPERATE: &str = "robot:operate";
96pub const SCOPE_ROBOT_MOVE: &str = "robot:move";
97pub const SCOPE_ROBOT_INTERACT: &str = "robot:interact";
98
99pub const SCOPE_DRONE_FLY: &str = "drone:fly"; // sensitive
100pub const SCOPE_DRONE_DELIVER: &str = "drone:deliver";
101pub const SCOPE_DRONE_CAPTURE: &str = "drone:capture";
102
103pub const SCOPE_VEHICLE_OPERATE: &str = "vehicle:operate"; // sensitive
104pub const SCOPE_VEHICLE_TRANSPORT: &str = "vehicle:transport";
105pub const SCOPE_VEHICLE_CHARGE: &str = "vehicle:charge";
106
107pub const SCOPE_INFRASTRUCTURE_MONITOR: &str = "infrastructure:monitor";
108pub const SCOPE_INFRASTRUCTURE_CONTROL: &str = "infrastructure:control"; // sensitive
109pub const SCOPE_INFRASTRUCTURE_ACCESS: &str = "infrastructure:access"; // sensitive
110
111pub const SCOPE_ACTUATE_VALVE: &str = "actuate:valve"; // sensitive
112pub const SCOPE_ACTUATE_MOTOR: &str = "actuate:motor"; // sensitive
113pub const SCOPE_ACTUATE_SWITCH: &str = "actuate:switch"; // sensitive
114
115// --- Extension pattern ---
116/// Any scope string starting with CUSTOM_SCOPE_PREFIX is accepted by
117/// validate_scopes, passes through expand_scopes unchanged, and is treated as
118/// non-sensitive unless the application opts in via out-of-band policy.
119///
120/// Example: `"custom:acme:inventory:read"`
121pub const CUSTOM_SCOPE_PREFIX: &str = "custom:";
122
123fn sensitive_scopes() -> &'static [&'static str] {
124    &[
125        SCOPE_MEETING_RECORD,
126        SCOPE_COMMS_MESSAGE_DELETE,
127        SCOPE_COMMS_EMAIL_DELETE,
128        SCOPE_FILES_WRITE,
129        SCOPE_IDENTITY_DELEGATE,
130        SCOPE_PRESENCE_REPRESENT,
131        SCOPE_PAYMENTS_AUTHORIZE,
132        SCOPE_CONTRACT_SIGN,
133        SCOPE_DATA_WRITE,
134        SCOPE_DATA_DELETE,
135        SCOPE_DATA_EXPORT,
136        SCOPE_EXECUTE_CODE,
137        SCOPE_GENERATE_DEEPFAKE,
138        SCOPE_PHYSICAL_ACTUATE,
139        SCOPE_PHYSICAL_MANIPULATE,
140        SCOPE_DRONE_FLY,
141        SCOPE_VEHICLE_OPERATE,
142        SCOPE_INFRASTRUCTURE_CONTROL,
143        SCOPE_INFRASTRUCTURE_ACCESS,
144        SCOPE_ACTUATE_VALVE,
145        SCOPE_ACTUATE_MOTOR,
146        SCOPE_ACTUATE_SWITCH,
147    ]
148}
149
150fn valid_scopes() -> &'static [&'static str] {
151    &[
152        SCOPE_MEETING_ATTEND,
153        SCOPE_MEETING_SPEAK,
154        SCOPE_MEETING_VIDEO,
155        SCOPE_MEETING_CHAT,
156        SCOPE_MEETING_SHARE_SCREEN,
157        SCOPE_MEETING_RECORD,
158        SCOPE_COMMS_MESSAGE_READ,
159        SCOPE_COMMS_MESSAGE_SEND,
160        SCOPE_COMMS_MESSAGE_DELETE,
161        SCOPE_COMMS_EMAIL_READ,
162        SCOPE_COMMS_EMAIL_SEND,
163        SCOPE_COMMS_EMAIL_DELETE,
164        SCOPE_COMMS_CALENDAR_READ,
165        SCOPE_COMMS_CALENDAR_WRITE,
166        SCOPE_FILES_READ,
167        SCOPE_FILES_WRITE,
168        SCOPE_IDENTITY_PROVE,
169        SCOPE_IDENTITY_DELEGATE,
170        SCOPE_PRESENCE_REPRESENT,
171        SCOPE_TRANSACT_PURCHASE,
172        SCOPE_TRANSACT_SELL,
173        SCOPE_PAYMENTS_SEND,
174        SCOPE_PAYMENTS_RECEIVE,
175        SCOPE_PAYMENTS_AUTHORIZE,
176        SCOPE_CONTRACT_READ,
177        SCOPE_CONTRACT_SIGN,
178        SCOPE_DATA_READ,
179        SCOPE_DATA_WRITE,
180        SCOPE_DATA_DELETE,
181        SCOPE_DATA_EXPORT,
182        SCOPE_DATA_SHARE,
183        SCOPE_EXECUTE_TOOL,
184        SCOPE_EXECUTE_CODE,
185        SCOPE_GENERATE_CONTENT,
186        SCOPE_GENERATE_DEEPFAKE,
187        SCOPE_PHYSICAL_ENTER,
188        SCOPE_PHYSICAL_EXIT,
189        SCOPE_PHYSICAL_ACTUATE,
190        SCOPE_PHYSICAL_MANIPULATE,
191        SCOPE_ROBOT_OPERATE,
192        SCOPE_ROBOT_MOVE,
193        SCOPE_ROBOT_INTERACT,
194        SCOPE_DRONE_FLY,
195        SCOPE_DRONE_DELIVER,
196        SCOPE_DRONE_CAPTURE,
197        SCOPE_VEHICLE_OPERATE,
198        SCOPE_VEHICLE_TRANSPORT,
199        SCOPE_VEHICLE_CHARGE,
200        SCOPE_INFRASTRUCTURE_MONITOR,
201        SCOPE_INFRASTRUCTURE_CONTROL,
202        SCOPE_INFRASTRUCTURE_ACCESS,
203        SCOPE_ACTUATE_VALVE,
204        SCOPE_ACTUATE_MOTOR,
205        SCOPE_ACTUATE_SWITCH,
206    ]
207}
208
209// Every wildcard shorthand recognized by `wildcard_expansion`. Kept in
210// lex order; `scope_wildcards()` derives the public map from it.
211const WILDCARD_SCOPES: &[&str] = &[
212    "comms:*",
213    "comms:email:*",
214    "comms:message:*",
215    "data:*",
216    "drone:*",
217    "execute:*",
218    "generate:*",
219    "infrastructure:*",
220    "meeting:*",
221    "payments:*",
222    "physical:*",
223    "robot:*",
224    "transact:*",
225    "vehicle:*",
226];
227
228fn wildcard_expansion(w: &str) -> Option<&'static [&'static str]> {
229    match w {
230        "meeting:*" => Some(&[
231            SCOPE_MEETING_ATTEND,
232            SCOPE_MEETING_SPEAK,
233            SCOPE_MEETING_VIDEO,
234            SCOPE_MEETING_CHAT,
235            SCOPE_MEETING_SHARE_SCREEN,
236        ]),
237        "comms:message:*" => Some(&[SCOPE_COMMS_MESSAGE_READ, SCOPE_COMMS_MESSAGE_SEND]),
238        "comms:email:*" => Some(&[SCOPE_COMMS_EMAIL_READ, SCOPE_COMMS_EMAIL_SEND]),
239        "comms:*" => Some(&[
240            SCOPE_COMMS_MESSAGE_READ,
241            SCOPE_COMMS_MESSAGE_SEND,
242            SCOPE_COMMS_EMAIL_READ,
243            SCOPE_COMMS_EMAIL_SEND,
244            SCOPE_COMMS_CALENDAR_READ,
245            SCOPE_COMMS_CALENDAR_WRITE,
246        ]),
247        "transact:*" => Some(&[SCOPE_TRANSACT_PURCHASE, SCOPE_TRANSACT_SELL]),
248        "payments:*" => Some(&[SCOPE_PAYMENTS_SEND, SCOPE_PAYMENTS_RECEIVE]),
249        "data:*" => Some(&[SCOPE_DATA_READ, SCOPE_DATA_SHARE]),
250        "execute:*" => Some(&[SCOPE_EXECUTE_TOOL]),
251        "generate:*" => Some(&[SCOPE_GENERATE_CONTENT]),
252        "physical:*" => Some(&[SCOPE_PHYSICAL_ENTER, SCOPE_PHYSICAL_EXIT]),
253        "robot:*" => Some(&[SCOPE_ROBOT_OPERATE, SCOPE_ROBOT_MOVE, SCOPE_ROBOT_INTERACT]),
254        "drone:*" => Some(&[SCOPE_DRONE_DELIVER, SCOPE_DRONE_CAPTURE]),
255        "vehicle:*" => Some(&[SCOPE_VEHICLE_TRANSPORT, SCOPE_VEHICLE_CHARGE]),
256        "infrastructure:*" => Some(&[SCOPE_INFRASTRUCTURE_MONITOR]),
257        // actuate:* — every member sensitive; NO wildcard expansion.
258        // presence:* — presence:represent is sensitive, so NO wildcard
259        // expansion. Representation must always be granted explicitly.
260        _ => None,
261    }
262}
263
264/// Return the complete canonical scope vocabulary for v1, sorted
265/// lexicographically. The Vec is a fresh copy — callers may modify it
266/// freely. Consumers that present scope choices to users (consoles, policy
267/// editors) should derive their lists from this accessor rather than
268/// hardcoding scope strings, so UI vocabularies cannot drift from the
269/// protocol. Mirrors Go's `Vocabulary()`.
270pub fn vocabulary() -> Vec<&'static str> {
271    let mut out = valid_scopes().to_vec();
272    out.sort_unstable();
273    out
274}
275
276/// Return the wildcard expansion map: wildcard shorthand to constituent
277/// NON-sensitive scopes. Sensitive scopes are never included in wildcards —
278/// they must be granted explicitly. The map is a fresh copy on every call.
279pub fn scope_wildcards() -> BTreeMap<&'static str, &'static [&'static str]> {
280    let mut out = BTreeMap::new();
281    for w in WILDCARD_SCOPES {
282        if let Some(children) = wildcard_expansion(w) {
283            out.insert(*w, children);
284        }
285    }
286    out
287}
288
289fn is_custom_scope(s: &str) -> bool {
290    s.starts_with(CUSTOM_SCOPE_PREFIX) && s.len() > CUSTOM_SCOPE_PREFIX.len()
291}
292
293/// Return an error message if any scope is invalid; None if all valid.
294/// Custom scopes (prefix "custom:") are accepted as valid extensions.
295pub fn validate_scopes(scopes: &[String]) -> Option<String> {
296    for s in scopes {
297        if valid_scopes().contains(&s.as_str()) {
298            continue;
299        }
300        if wildcard_expansion(s).is_some() {
301            continue;
302        }
303        if is_custom_scope(s) {
304            continue;
305        }
306        return Some(format!(
307            "unknown scope \"{}\": not in canonical vocabulary and not a custom: extension",
308            s
309        ));
310    }
311    None
312}
313
314/// True if the scope is flagged as sensitive. Custom scopes are non-sensitive
315/// by default; applications may enforce policy out-of-band.
316pub fn is_sensitive(scope: &str) -> bool {
317    sensitive_scopes().contains(&scope)
318}
319
320/// Replace wildcard scopes with their constituent non-sensitive scopes.
321/// Deduplicates and returns lex-sorted. Custom scopes pass through unchanged.
322pub fn expand_scopes(scopes: &[String]) -> Vec<String> {
323    let mut seen = BTreeSet::new();
324    for s in scopes {
325        if let Some(children) = wildcard_expansion(s) {
326            for c in children {
327                seen.insert((*c).to_string());
328            }
329        } else {
330            seen.insert(s.clone());
331        }
332    }
333    seen.into_iter().collect()
334}
335
336pub fn has_scope(granted: &[String], required: &str) -> bool {
337    expand_scopes(granted).iter().any(|s| s == required)
338}
339
340/// Set of scopes in every input list after wildcard expansion. Lex-sorted.
341pub fn intersect_scopes(lists: &[&[String]]) -> Vec<String> {
342    if lists.is_empty() {
343        return Vec::new();
344    }
345    let mut effective: BTreeSet<String> =
346        expand_scopes(lists[0]).into_iter().collect();
347    for list in &lists[1..] {
348        let expanded: BTreeSet<String> =
349            expand_scopes(list).into_iter().collect();
350        effective = effective.intersection(&expanded).cloned().collect();
351    }
352    effective.into_iter().collect()
353}