Skip to main content

hyprstream_core/auth/
mod.rs

1//! Authorization module for RBAC/ABAC access control
2//!
3//! Uses Casbin for policy-based access control with policies
4//! stored in the `.registry/policies/` directory.
5//!
6//! Also provides JWT token authentication with Ed25519 signatures.
7
8/// The canonical tenant-component syntax (D4): the HTTP authorization-domain
9/// middleware, the MAC PDS PEP, and the federate admission/mint/consumption
10/// paths all enforce exactly this rule, so a tenant Policy can carry is never
11/// one the HTTP middleware would reject. Non-empty, at most 253 bytes, never
12/// ".", ".." or "*", ASCII alphanumeric plus '.', '_' and '-' only.
13pub(crate) fn valid_tenant_component(tenant: &str) -> bool {
14    !tenant.is_empty()
15        && tenant.len() <= 253
16        && tenant != "."
17        && tenant != ".."
18        && tenant != "*"
19        && tenant
20            .bytes()
21            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-'))
22}
23
24/// Validate a subject at a resource boundary without changing the general
25/// username/path grammar of `Subject::validate`. Hosted accounts use a raw
26/// host-form DID as their signed local subject. Its single account label must
27/// belong to the exact authority-verified tenant carried by that token.
28pub(crate) fn valid_resource_subject(
29    subject: &hyprstream_rpc::Subject,
30    issuer: &str,
31    local_issuers: &[&str],
32    verified_tenant: Option<&str>,
33) -> bool {
34    let Some(name) = subject.name() else {
35        return false;
36    };
37    // A raw DID must be classified first: Subject::validate treats any
38    // `://` substring as federated, including malformed DID path text.
39    let Some(host) = name.strip_prefix("did:web:") else {
40        return subject.validate().is_ok();
41    };
42    let Some(tenant) = verified_tenant else {
43        return false;
44    };
45    if issuer.is_empty()
46        || !local_issuers
47            .iter()
48            .any(|local| !local.is_empty() && *local == issuer)
49    {
50        return false;
51    }
52    let Ok(zone) = crate::account::AccountZone::new(tenant) else {
53        return false;
54    };
55    let Some(label) = host.strip_suffix(&format!(".{}", zone.apex())) else {
56        return false;
57    };
58    hyprstream_pds::AccountLabel::parse(label).is_ok()
59}
60
61#[cfg(test)]
62mod resource_subject_tests {
63    use super::*;
64
65    #[test]
66    fn hosted_did_requires_exact_signed_zone_and_local_issuer() {
67        let issuer = "https://oauth.publisher.test";
68        let local = [issuer];
69        let valid = hyprstream_rpc::Subject::new(
70            "did:web:canary-agent.publisher.staging.lab.hyprstream.com",
71        );
72        let tenant = "publisher.staging.lab.hyprstream.com";
73        assert!(valid_resource_subject(&valid, issuer, &local, Some(tenant)));
74        for (name, zone) in [
75            (
76                "did:web:canary-agent.publisher.staging.lab.hyprstream.com:users",
77                tenant,
78            ),
79            (
80                "did:web:canary-agent.publisher.staging.lab.hyprstream.com://evil",
81                tenant,
82            ),
83            (
84                "did:web:canary-agent%2Epublisher.staging.lab.hyprstream.com",
85                tenant,
86            ),
87            ("did:web:../publisher.staging.lab.hyprstream.com", tenant),
88            (
89                "did:web:canary-agent.other.staging.lab.hyprstream.com",
90                tenant,
91            ),
92            (
93                "did:web:CANARY.publisher.staging.lab.hyprstream.com",
94                tenant,
95            ),
96            (
97                "did:web:canary-agent.publisher.staging.lab.hyprstream.com",
98                "other.staging.lab.hyprstream.com",
99            ),
100        ] {
101            assert!(
102                !valid_resource_subject(
103                    &hyprstream_rpc::Subject::new(name),
104                    issuer,
105                    &local,
106                    Some(zone)
107                ),
108                "accepted malformed or foreign DID: {name}"
109            );
110        }
111        assert!(!valid_resource_subject(&valid, issuer, &local, None));
112        assert!(!valid_resource_subject(&valid, "", &local, Some(tenant)));
113        assert!(!valid_resource_subject(
114            &valid,
115            "https://foreign.test",
116            &local,
117            Some(tenant)
118        ));
119        assert!(valid_resource_subject(
120            &hyprstream_rpc::Subject::new("ordinary_user"),
121            issuer,
122            &local,
123            None
124        ));
125    }
126}
127
128pub(crate) mod age_seal;
129#[cfg(any(feature = "pglite", feature = "postgres"))]
130mod cipher_glue;
131pub mod device_challenge;
132#[cfg_attr(not(feature = "pglite"), allow(dead_code))]
133pub mod encrypted_columns;
134pub mod federation;
135pub mod federation_admission;
136pub mod id_token_verify;
137pub mod identity_store;
138pub mod jwks_fetcher;
139pub mod jwt;
140pub mod key_rotation;
141pub mod mesh_trust;
142pub mod op_log;
143#[cfg(feature = "pglite")]
144pub mod pglite_store;
145mod policy_file_adapter;
146mod policy_manager;
147pub mod policy_migration;
148pub mod policy_templates;
149#[cfg(feature = "postgres-replay")]
150pub mod postgres_replay;
151#[cfg(feature = "postgres")]
152pub mod postgres_store;
153mod production_user_store;
154pub mod proof_enrollment;
155// The legacy RocksDB credential/device store (the `rocksdb` feature, valkey
156// precedent). Production UserStore admission is PGlite under credential-pds;
157// the rocksdb-backed DeviceStore and refresh-token store remain the only
158// local persistence backends and ride the same feature.
159#[cfg(feature = "rocksdb")]
160pub mod rocksdb_store;
161pub mod service_enrollment;
162pub mod service_jwt;
163pub mod user_store;
164#[cfg(feature = "valkey")]
165pub mod valkey;
166
167pub use hyprstream_rpc::annotations_capnp::ScopeAction;
168
169pub use federation::FederationKeyResolver;
170pub use jwt::{Claims, JwtError};
171pub use key_rotation::{Es256KeySlot, Es256SigningKeyStore, RotationStores, SigningKeyStore};
172pub use key_rotation::{MlDsaKeySlot, MlDsaSigningKeyStore};
173pub use op_log::{
174    load_head_verifying_key, load_or_init_head_signing_key, publish_head_verifying_key,
175    resolve_oplog_state_dir, seal_op_log_head, ActiveGeneration, ActiveGenerationSource,
176    FixedGenerationSource, SealedHeadEs256Source, SealedOpLogHead,
177};
178#[cfg(feature = "pglite")]
179pub use pglite_store::PgliteUserStore;
180pub use policy_manager::{
181    federation_registration_resource, global_policy_manager, set_global_policy_manager,
182    write_policy_file, PolicyError, PolicyManager,
183};
184pub use policy_migration::migrate_policy_csv;
185pub use policy_templates::{
186    get_template, get_templates, PolicyTemplate, ServicePolicyRule, SERVICE_BASE_POLICIES,
187};
188#[cfg(feature = "postgres")]
189pub use postgres_store::PostgresUserStore;
190pub use production_user_store::ProductionUserStore;
191#[cfg(feature = "rocksdb")]
192pub use rocksdb_store::RocksDbUserStore;
193pub use user_store::{
194    decode_pubkey_base64, pubkey_fingerprint, AccountKeyCustody, DeviceRecord, DeviceStore,
195    ExternalIdentityBinding, ExternalIdentityResolution, HostedAccountProvisionError,
196    HostedAccountProvisioning, KeyAlgorithm, PubkeyEntry, UserFilter, UserProfile,
197    UserProfilePatch, UserStore,
198};
199#[cfg(feature = "valkey")]
200pub use valkey::ValkeyUserStore;
201
202/// Every schema-defined scope action, in its Cap'n Proto ordinal order.
203///
204/// This is the closed vocabulary used by wildcard UCAN-to-TE expansion. The
205/// values come from the generated schema enum rather than a hand-written MAC
206/// mirror, so adding or reordering a schema action cannot silently change the
207/// action understood by the policy compiler.
208pub const SCHEMA_SCOPE_ACTIONS: [ScopeAction; 14] = [
209    ScopeAction::Query,
210    ScopeAction::Subscribe,
211    ScopeAction::Write,
212    ScopeAction::Create,
213    ScopeAction::Publish,
214    ScopeAction::Infer,
215    ScopeAction::Train,
216    ScopeAction::Context,
217    ScopeAction::Serve,
218    ScopeAction::Spawn,
219    ScopeAction::Manage,
220    ScopeAction::MeshInvoke,
221    ScopeAction::MeshStage,
222    ScopeAction::MeshDelta,
223];
224
225/// Return the canonical capability token for a generated schema action.
226///
227/// This is the single string bridge shared by runtime [`Operation`] parsing
228/// and the MAC permission map.
229pub const fn scope_action_name(action: ScopeAction) -> &'static str {
230    match action {
231        ScopeAction::Query => "query",
232        ScopeAction::Subscribe => "subscribe",
233        ScopeAction::Write => "write",
234        ScopeAction::Create => "create",
235        ScopeAction::Publish => "publish",
236        ScopeAction::Infer => "infer",
237        ScopeAction::Train => "train",
238        ScopeAction::Context => "context",
239        ScopeAction::Serve => "serve",
240        ScopeAction::Spawn => "spawn",
241        ScopeAction::Manage => "manage",
242        ScopeAction::MeshInvoke => "meshInvoke",
243        ScopeAction::MeshStage => "meshStage",
244        ScopeAction::MeshDelta => "meshDelta",
245    }
246}
247
248/// Parse a canonical capability token into the generated schema action.
249/// Unknown tokens fail closed.
250pub fn scope_action_from_name(action: &str) -> Option<ScopeAction> {
251    SCHEMA_SCOPE_ACTIONS
252        .into_iter()
253        .find(|candidate| scope_action_name(*candidate) == action)
254}
255
256/// Operation types that can be controlled via policies
257#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
258//
259// VARIANT ORDER IS LOAD-BEARING (S3, #569): the first 14 variants are kept 1:1
260// (in order) with the `ScopeAction` enum ordinals in
261// `crates/hyprstream-rpc/schema/annotations.capnp`. The semantic blocks are:
262//   Block A read-class:        Query @0, Subscribe @1
263//   Block B write/authority:   Write @2, Create @3, Publish @4, Infer @5,
264//                              Train @6, Context @7, Serve @8, Spawn @9
265//   Block C admin authority:   Manage @10
266//   Block D mesh authority:    MeshInvoke @11, MeshStage @12, MeshDelta @13
267// `MeshStatus` is appended AFTER the 14 ScopeAction-mirrored variants: it is NOT a
268// distinct ScopeAction (it shares the `query`/`query.status` wire action), so it has
269// no ordinal in the schema enum and is excluded from the exact-inverse round-trip.
270pub enum Operation {
271    // ── Block A: read-class (ScopeAction @0..@1) ──────────────────────────
272    /// Query data (q)
273    Query,
274    /// Subscribe to a stream/notification (b)
275    Subscribe,
276    // ── Block B: write/authority-class (ScopeAction @2..@9) ───────────────
277    /// Write data (w)
278    Write,
279    /// Create a resource (r)
280    Create,
281    /// Publish/broadcast to subscribers (l)
282    Publish,
283    /// Run model inference (i)
284    Infer,
285    /// Train/fine-tune model (t)
286    Train,
287    /// Context-augmented generation (c)
288    Context,
289    /// Serve via API (s)
290    Serve,
291    /// Spawn a process or task (p)
292    Spawn,
293    // ── Block C: admin authority (ScopeAction @10) ────────────────────────
294    /// Admin operations (m)
295    Manage,
296    // ─────────────────────────────────────────────────────────────────────
297    // Block D: Inference-mesh (#319) — host↔host pipeline RPC abilities.
298    // (ScopeAction @11..@13)
299    //
300    // These gate calls between inference hosts on the cluster mesh (e.g. the
301    // router→host activation hand-off and host→aggregator delta submission).
302    // They are split read-vs-authority so an operator can grant a *group* of
303    // hosts the read ability cheaply while keeping the authority abilities
304    // strictly per-host least-privilege (see policy_templates::mesh-host).
305    //
306    // The dot-strings are designed to map 1:1 onto a future UCAN `cmd`:
307    //   Operation::MeshInvoke   ⇄ cmd=/mesh/rpc        (umbrella invoke right)
308    //   Operation::MeshStage    ⇄ cmd=/mesh/infer/stage
309    //   Operation::MeshDelta    ⇄ cmd=/mesh/delta/submit
310    //   Operation::MeshStatus   ⇄ cmd=/mesh/query/status
311    // (resource caveats — tenant/job/layers — live in the `mesh://` path).
312    /// Umbrella mesh invoke right — `inference:peer-call` / `mesh:rpc` (authority).
313    MeshInvoke,
314    /// Submit an inference activation/stage to a peer host (authority).
315    MeshStage,
316    /// Submit a TTT delta to a peer/aggregator host (authority).
317    MeshDelta,
318    /// Read a peer host's mesh job/pipeline status (read-only).
319    MeshStatus,
320}
321
322impl Operation {
323    /// Convert a schema action to its runtime authorization operation.
324    ///
325    /// The exhaustive match is intentional: adding a `ScopeAction` in the
326    /// schema makes this crate fail to compile until runtime enforcement is
327    /// defined for it.
328    pub const fn from_scope_action(action: ScopeAction) -> Self {
329        match action {
330            ScopeAction::Query => Self::Query,
331            ScopeAction::Subscribe => Self::Subscribe,
332            ScopeAction::Write => Self::Write,
333            ScopeAction::Create => Self::Create,
334            ScopeAction::Publish => Self::Publish,
335            ScopeAction::Infer => Self::Infer,
336            ScopeAction::Train => Self::Train,
337            ScopeAction::Context => Self::Context,
338            ScopeAction::Serve => Self::Serve,
339            ScopeAction::Spawn => Self::Spawn,
340            ScopeAction::Manage => Self::Manage,
341            ScopeAction::MeshInvoke => Self::MeshInvoke,
342            ScopeAction::MeshStage => Self::MeshStage,
343            ScopeAction::MeshDelta => Self::MeshDelta,
344        }
345    }
346
347    /// Return the generated schema action represented by this operation.
348    /// `MeshStatus` is the sole runtime-only operation and reuses the `query`
349    /// capability token at authorization boundaries.
350    pub const fn scope_action(self) -> Option<ScopeAction> {
351        Some(match self {
352            Self::Query => ScopeAction::Query,
353            Self::Subscribe => ScopeAction::Subscribe,
354            Self::Write => ScopeAction::Write,
355            Self::Create => ScopeAction::Create,
356            Self::Publish => ScopeAction::Publish,
357            Self::Infer => ScopeAction::Infer,
358            Self::Train => ScopeAction::Train,
359            Self::Context => ScopeAction::Context,
360            Self::Serve => ScopeAction::Serve,
361            Self::Spawn => ScopeAction::Spawn,
362            Self::Manage => ScopeAction::Manage,
363            Self::MeshInvoke => ScopeAction::MeshInvoke,
364            Self::MeshStage => ScopeAction::MeshStage,
365            Self::MeshDelta => ScopeAction::MeshDelta,
366            Self::MeshStatus => return None,
367        })
368    }
369
370    /// Get the short code for this operation
371    pub fn code(&self) -> char {
372        match self {
373            Operation::Infer => 'i',
374            Operation::Train => 't',
375            Operation::Query => 'q',
376            Operation::Write => 'w',
377            Operation::Serve => 's',
378            Operation::Manage => 'm',
379            Operation::Context => 'c',
380            Operation::Subscribe => 'b',
381            Operation::Publish => 'l',
382            Operation::Spawn => 'p',
383            Operation::Create => 'r',
384            // Mesh ops (#319) — distinct codes, so they share the `check_all`
385            // bitmask with the model-capability codes without colliding.
386            Operation::MeshInvoke => 'e',
387            Operation::MeshStage => 'g',
388            Operation::MeshDelta => 'd',
389            Operation::MeshStatus => 'u',
390        }
391    }
392
393    /// The unified scope-action vocabulary (S3, epic #547).
394    ///
395    /// Returns this operation's `ScopeAction` enumerant name — the SAME token used
396    /// by the `$scope`/`$capability` capnp annotation and stored in
397    /// [`crate::auth::Scope::action`]. There is one action vocabulary, not two:
398    /// the schema annotation, the runtime `Scope`, and this enum all agree.
399    ///
400    /// This is the canonical bridge between the compile-time TE baseline (schema
401    /// annotation) and runtime enforcement. `MeshStatus` shares `query` because the
402    /// mesh read ability IS the canonical status read (#319), matching `as_str()`.
403    pub fn as_capability(&self) -> &'static str {
404        match self.scope_action() {
405            Some(action) => scope_action_name(action),
406            None => "query", // MeshStatus is the runtime specialization of query.
407        }
408    }
409
410    /// Parse an [`Operation`] from a unified scope-action token (a `ScopeAction`
411    /// enumerant name — what the `$scope`/`$capability` annotation emits and what
412    /// [`crate::auth::Scope::action`] carries). The inverse of [`Self::as_capability`].
413    ///
414    /// Returns `None` for an unknown token; callers MUST fail closed (no default-allow).
415    pub fn from_capability(action: &str) -> Option<Self> {
416        scope_action_from_name(action).map(Self::from_scope_action)
417    }
418
419    /// Get the dot-namespaced operation name for policy matching.
420    ///
421    /// Returns the canonical dot-namespaced string for this operation variant.
422    ///
423    /// Forwarded verbatim to the Casbin enforcer, which uses `keyMatch` to accept
424    /// both this format and legacy flat strings stored in policy files.
425    ///
426    /// **Note on `Manage`:** This enum variant is a coarse gate over the `ttt.*`
427    /// namespace. `as_str()` returns `"ttt.writeback"` as a representative string,
428    /// but sub-actions (`ttt.evict`, `ttt.zero`) are all gated by the same `Manage`
429    /// variant. When callers need to enforce at sub-action granularity (e.g. in an
430    /// RPC handler), they should pass the specific dot-namespaced string directly to
431    /// `check_with_domain` rather than going through this method.
432    ///
433    /// `Operation::Manage.as_str()` (i.e. `"ttt.writeback"`) is intentionally used
434    /// only for gates that specifically require the *highest* privilege in the `ttt.*`
435    /// namespace, such as issuing tokens on behalf of another subject. Handlers that
436    /// only need any `ttt.*` permission (e.g. `ttt.evict`) must pass the specific
437    /// action string to avoid incorrectly denying callers who hold a lesser `ttt.*`
438    /// permission but not `ttt.writeback`.
439    pub fn as_str(&self) -> &'static str {
440        match self {
441            Operation::Infer => "infer.generate",
442            Operation::Train => "ttt.train",
443            // `Query` (model status) and `MeshStatus` (mesh read ability) are
444            // the SAME wire action `query.status` by design — the mesh read
445            // right IS the canonical status read (#319). `from_dot_str` resolves
446            // the string back to `Query` (its canonical owner).
447            Operation::Query | Operation::MeshStatus => "query.status",
448            Operation::Write => "persist.save",
449            Operation::Serve => "serve.api",
450            Operation::Manage => "ttt.writeback",
451            Operation::Context => "context.augment",
452            Operation::Subscribe => "subscribe",
453            Operation::Publish => "publish",
454            Operation::Spawn => "spawn",
455            Operation::Create => "create",
456            // Mesh (#319). `mesh.rpc` is the umbrella invoke right (alias
457            // `inference:peer-call` accepted on parse). The authority actions
458            // `infer.stage` / `delta.submit` are deliberately distinct strings
459            // from the model-namespace `infer.generate` / `persist.save` so a
460            // model grant can never satisfy a mesh-authority gate. (The read
461            // ability `MeshStatus` shares the `query.status` arm above.)
462            Operation::MeshInvoke => "mesh.rpc",
463            Operation::MeshStage => "infer.stage",
464            Operation::MeshDelta => "delta.submit",
465        }
466    }
467
468    /// Parse an operation from a dot-namespaced or legacy flat string.
469    ///
470    /// Returns `None` for unrecognized strings.  Handles both the new
471    /// dot-namespaced format (`"infer.generate"`) and the old flat format
472    /// (`"infer"`) for migration compatibility.
473    pub fn from_dot_str(s: &str) -> Option<Self> {
474        match s {
475            // New dot-namespaced and legacy flat strings merged per variant
476            "infer.generate" | "infer" => Some(Self::Infer),
477            "ttt.train" | "train" => Some(Self::Train),
478            "ttt.writeback" | "ttt.evict" | "ttt.zero" | "manage" => Some(Self::Manage),
479            "query.status" | "query.delta" | "query" => Some(Self::Query),
480            "persist.save" | "persist.export" | "persist.snapshot" | "write" => Some(Self::Write),
481            "context.augment" | "context" => Some(Self::Context),
482            "serve.api" | "serve" => Some(Self::Serve),
483            "subscribe" => Some(Self::Subscribe),
484            "publish" => Some(Self::Publish),
485            "spawn" => Some(Self::Spawn),
486            "create" => Some(Self::Create),
487            // Mesh (#319). `query.status` (the mesh read ability) is owned by
488            // `Query` above, so it is intentionally NOT repeated here.
489            "mesh.rpc" | "mesh:rpc" | "inference:peer-call" => Some(Self::MeshInvoke),
490            "infer.stage" => Some(Self::MeshStage),
491            "delta.submit" => Some(Self::MeshDelta),
492            _ => None,
493        }
494    }
495
496    /// Parse from short code
497    pub fn from_code(c: char) -> Option<Self> {
498        match c {
499            'i' => Some(Operation::Infer),
500            't' => Some(Operation::Train),
501            'q' => Some(Operation::Query),
502            'w' => Some(Operation::Write),
503            's' => Some(Operation::Serve),
504            'm' => Some(Operation::Manage),
505            'c' => Some(Operation::Context),
506            'b' => Some(Operation::Subscribe),
507            'l' => Some(Operation::Publish),
508            'p' => Some(Operation::Spawn),
509            'r' => Some(Operation::Create),
510            // Mesh (#319)
511            'e' => Some(Operation::MeshInvoke),
512            'g' => Some(Operation::MeshStage),
513            'd' => Some(Operation::MeshDelta),
514            'u' => Some(Operation::MeshStatus),
515            _ => None,
516        }
517    }
518
519    /// All operations — every enum variant, so `PolicyManager::check_all` can
520    /// report each one. Hand-maintained until #1091 R4a generates the
521    /// vocabulary from the schema; keep in sync with the enum above.
522    pub fn all() -> &'static [Operation] {
523        &[
524            Operation::Infer,
525            Operation::Train,
526            Operation::Query,
527            Operation::Write,
528            Operation::Serve,
529            Operation::Manage,
530            Operation::Context,
531            Operation::Subscribe,
532            Operation::Create,
533            Operation::Publish,
534            Operation::Spawn,
535            Operation::MeshInvoke,
536            Operation::MeshStage,
537            Operation::MeshDelta,
538            Operation::MeshStatus,
539        ]
540    }
541}
542
543impl std::str::FromStr for Operation {
544    type Err = anyhow::Error;
545
546    fn from_str(s: &str) -> Result<Self, Self::Err> {
547        Self::from_dot_str(s).ok_or_else(|| anyhow::anyhow!("Unknown operation: {}", s))
548    }
549}
550
551impl std::fmt::Display for Operation {
552    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
553        write!(f, "{}", self.as_str())
554    }
555}
556
557/// Convert capabilities to an access string based on policy
558///
559/// Returns a comma-separated list of permitted operations (e.g., "infer,train,serve").
560/// Only includes operations that both the resource supports AND the user is permitted.
561pub fn capabilities_to_access_string(
562    policy_manager: &PolicyManager,
563    user: &str,
564    resource: &str,
565    capabilities: &crate::archetypes::capabilities::CapabilitySet,
566) -> String {
567    use crate::archetypes::capabilities::{Context, Infer, Manage, Query, Serve, Train, Write};
568
569    let mut permitted = Vec::new();
570
571    // Only show access for capabilities the resource actually has AND user is permitted
572    if capabilities.has::<Infer>() && policy_manager.check_sync(user, resource, Operation::Infer) {
573        permitted.push("infer");
574    }
575    if capabilities.has::<Train>() && policy_manager.check_sync(user, resource, Operation::Train) {
576        permitted.push("train");
577    }
578    if capabilities.has::<Query>() && policy_manager.check_sync(user, resource, Operation::Query) {
579        permitted.push("query");
580    }
581    if capabilities.has::<Write>() && policy_manager.check_sync(user, resource, Operation::Write) {
582        permitted.push("write");
583    }
584    if capabilities.has::<Serve>() && policy_manager.check_sync(user, resource, Operation::Serve) {
585        permitted.push("serve");
586    }
587    if capabilities.has::<Manage>() && policy_manager.check_sync(user, resource, Operation::Manage)
588    {
589        permitted.push("manage");
590    }
591    if capabilities.has::<Context>()
592        && policy_manager.check_sync(user, resource, Operation::Context)
593    {
594        permitted.push("context");
595    }
596
597    permitted.join(",")
598}
599
600#[cfg(test)]
601mod tests {
602    use super::*;
603    use std::str::FromStr;
604
605    #[test]
606    fn test_operation_codes() {
607        assert_eq!(Operation::Infer.code(), 'i');
608        assert_eq!(Operation::Train.code(), 't');
609        assert_eq!(Operation::Query.code(), 'q');
610        assert_eq!(Operation::Write.code(), 'w');
611        assert_eq!(Operation::Serve.code(), 's');
612        assert_eq!(Operation::Manage.code(), 'm');
613        assert_eq!(Operation::Context.code(), 'c');
614    }
615
616    #[test]
617    fn test_operation_from_code() {
618        assert_eq!(Operation::from_code('i'), Some(Operation::Infer));
619        assert_eq!(Operation::from_code('t'), Some(Operation::Train));
620        assert_eq!(Operation::from_code('c'), Some(Operation::Context));
621        assert_eq!(Operation::from_code('x'), None);
622    }
623
624    #[test]
625    fn test_operation_dot_namespaced_strings() {
626        assert_eq!(Operation::Infer.as_str(), "infer.generate");
627        assert_eq!(Operation::Train.as_str(), "ttt.train");
628        assert_eq!(Operation::Query.as_str(), "query.status");
629        assert_eq!(Operation::Write.as_str(), "persist.save");
630        assert_eq!(Operation::Manage.as_str(), "ttt.writeback");
631        assert_eq!(Operation::Context.as_str(), "context.augment");
632        assert_eq!(Operation::Serve.as_str(), "serve.api");
633    }
634
635    #[test]
636    #[allow(clippy::expect_used)]
637    fn test_operation_from_str() {
638        // Legacy flat strings still parse correctly
639        assert!(matches!(Operation::from_str("infer"), Ok(Operation::Infer)));
640        assert!(matches!(Operation::from_str("train"), Ok(Operation::Train)));
641        assert!(matches!(Operation::from_str("query"), Ok(Operation::Query)));
642        assert!(matches!(Operation::from_str("write"), Ok(Operation::Write)));
643        assert!(matches!(Operation::from_str("serve"), Ok(Operation::Serve)));
644        assert!(matches!(
645            Operation::from_str("manage"),
646            Ok(Operation::Manage)
647        ));
648        assert!(matches!(
649            Operation::from_str("context"),
650            Ok(Operation::Context)
651        ));
652        // Dot-namespaced strings (emitted by Display) must also round-trip
653        assert!(matches!(
654            "infer.generate".parse::<Operation>(),
655            Ok(Operation::Infer)
656        ));
657        assert!(matches!(
658            "ttt.train".parse::<Operation>(),
659            Ok(Operation::Train)
660        ));
661        assert!(matches!(
662            "ttt.writeback".parse::<Operation>(),
663            Ok(Operation::Manage)
664        ));
665        assert!(matches!(
666            "query.status".parse::<Operation>(),
667            Ok(Operation::Query)
668        ));
669        assert!(matches!(
670            "persist.save".parse::<Operation>(),
671            Ok(Operation::Write)
672        ));
673        assert!(matches!(
674            "serve.api".parse::<Operation>(),
675            Ok(Operation::Serve)
676        ));
677        assert!(matches!(
678            "context.augment".parse::<Operation>(),
679            Ok(Operation::Context)
680        ));
681        // Verify format!("{}", op).parse() round-trip for every variant.
682        for op in Operation::all() {
683            let displayed = format!("{}", op);
684            let parsed: Operation = displayed.parse().expect("round-trip parse failed");
685            // `MeshStatus` shares the `query.status` wire action, which parses
686            // back to its canonical owner `Query` by design (see as_str()).
687            let expected = if *op == Operation::MeshStatus {
688                &Operation::Query
689            } else {
690                op
691            };
692            assert_eq!(&parsed, expected);
693        }
694        assert!(Operation::from_str("foo").is_err());
695    }
696
697    #[test]
698    fn test_mesh_operation_vocab() {
699        // Authority + umbrella mesh actions round-trip via their distinct strings.
700        assert_eq!(Operation::MeshInvoke.as_str(), "mesh.rpc");
701        assert_eq!(Operation::MeshStage.as_str(), "infer.stage");
702        assert_eq!(Operation::MeshDelta.as_str(), "delta.submit");
703        assert_eq!(
704            Operation::from_dot_str("mesh.rpc"),
705            Some(Operation::MeshInvoke)
706        );
707        assert_eq!(
708            Operation::from_dot_str("mesh:rpc"),
709            Some(Operation::MeshInvoke)
710        );
711        assert_eq!(
712            Operation::from_dot_str("inference:peer-call"),
713            Some(Operation::MeshInvoke)
714        );
715        assert_eq!(
716            Operation::from_dot_str("infer.stage"),
717            Some(Operation::MeshStage)
718        );
719        assert_eq!(
720            Operation::from_dot_str("delta.submit"),
721            Some(Operation::MeshDelta)
722        );
723        // The mesh-authority strings are DISTINCT from the model-namespace
724        // strings, so a model grant can never satisfy a mesh-authority gate.
725        assert_ne!(Operation::MeshStage.as_str(), Operation::Infer.as_str());
726        assert_ne!(Operation::MeshDelta.as_str(), Operation::Write.as_str());
727        // The mesh read ability reuses the canonical `query.status` wire action.
728        assert_eq!(Operation::MeshStatus.as_str(), "query.status");
729        assert_eq!(
730            Operation::from_dot_str("query.status"),
731            Some(Operation::Query)
732        );
733        // Codes are distinct from the model-capability codes.
734        for op in [
735            Operation::MeshInvoke,
736            Operation::MeshStage,
737            Operation::MeshDelta,
738            Operation::MeshStatus,
739        ] {
740            assert_eq!(Operation::from_code(op.code()), Some(op));
741        }
742        // Mesh ops are part of `all()` so `check_all` can report them (#1096).
743        for op in &[
744            Operation::MeshInvoke,
745            Operation::MeshStage,
746            Operation::MeshDelta,
747            Operation::MeshStatus,
748        ] {
749            assert!(Operation::all().contains(op));
750        }
751    }
752
753    #[test]
754    fn test_capability_token_is_exact_inverse() {
755        // `as_capability`/`from_capability` are the canonical scope-action bridge and
756        // MUST be exact inverses (1:1 with `ScopeAction`). Regression guard for the
757        // grant/enforcement divergence (#569 peer review): `subscribe`/`publish` were
758        // collapsed into `context`/`serve`, so a granted `subscribe`/`publish` scope was
759        // enforced as a different ability (granted ≠ enforced).
760        let ops = [
761            Operation::Query,
762            Operation::Write,
763            Operation::Manage,
764            Operation::Infer,
765            Operation::Train,
766            Operation::Serve,
767            Operation::Context,
768            Operation::Subscribe,
769            Operation::Publish,
770            Operation::Spawn,
771            Operation::Create,
772            Operation::MeshInvoke,
773            Operation::MeshStage,
774            Operation::MeshDelta,
775        ];
776        for op in ops {
777            assert_eq!(
778                Operation::from_capability(op.as_capability()),
779                Some(op),
780                "capability token round-trip is not 1:1 for {op:?}",
781            );
782        }
783        // The runtime bridge is over the generated capnp enum itself, so the
784        // compiler/PEP id and the authorization token cannot drift apart.
785        for (ordinal, action) in SCHEMA_SCOPE_ACTIONS.into_iter().enumerate() {
786            let op = Operation::from_scope_action(action);
787            assert_eq!(op.scope_action(), Some(action));
788            assert_eq!(op.as_capability(), scope_action_name(action));
789            assert_eq!(u16::from(action) as usize, ordinal);
790        }
791        assert_eq!(Operation::MeshStatus.scope_action(), None);
792        // `subscribe`/`publish` are distinct enforced abilities — NOT context/serve.
793        assert_eq!(
794            Operation::from_capability("subscribe"),
795            Some(Operation::Subscribe)
796        );
797        assert_eq!(
798            Operation::from_capability("publish"),
799            Some(Operation::Publish)
800        );
801        assert_eq!(Operation::Subscribe.as_capability(), "subscribe");
802        assert_eq!(Operation::Publish.as_capability(), "publish");
803        // Unknown tokens fail closed.
804        assert_eq!(Operation::from_capability("nope"), None);
805    }
806
807    #[test]
808    fn test_operation_all() {
809        let all = Operation::all();
810        // All 15 variants: 11 core + 4 mesh (#319). Regression guard for #1096 —
811        // `all()` omitted 8 variants, so `check_all` could never report them.
812        let expected = [
813            Operation::Infer,
814            Operation::Train,
815            Operation::Query,
816            Operation::Write,
817            Operation::Serve,
818            Operation::Manage,
819            Operation::Context,
820            Operation::Subscribe,
821            Operation::Create,
822            Operation::Publish,
823            Operation::Spawn,
824            Operation::MeshInvoke,
825            Operation::MeshStage,
826            Operation::MeshDelta,
827            Operation::MeshStatus,
828        ];
829        assert_eq!(all.len(), expected.len());
830        for op in expected {
831            assert!(all.contains(&op), "Operation::all() is missing {op:?}");
832        }
833    }
834
835    #[test]
836    fn test_operation_from_dot_str() {
837        // New dot-namespaced strings
838        assert_eq!(
839            Operation::from_dot_str("infer.generate"),
840            Some(Operation::Infer)
841        );
842        assert_eq!(Operation::from_dot_str("ttt.train"), Some(Operation::Train));
843        assert_eq!(
844            Operation::from_dot_str("ttt.writeback"),
845            Some(Operation::Manage)
846        );
847        assert_eq!(
848            Operation::from_dot_str("ttt.evict"),
849            Some(Operation::Manage)
850        );
851        assert_eq!(Operation::from_dot_str("ttt.zero"), Some(Operation::Manage));
852        assert_eq!(
853            Operation::from_dot_str("query.status"),
854            Some(Operation::Query)
855        );
856        assert_eq!(
857            Operation::from_dot_str("query.delta"),
858            Some(Operation::Query)
859        );
860        assert_eq!(
861            Operation::from_dot_str("persist.save"),
862            Some(Operation::Write)
863        );
864        assert_eq!(
865            Operation::from_dot_str("persist.export"),
866            Some(Operation::Write)
867        );
868        assert_eq!(
869            Operation::from_dot_str("persist.snapshot"),
870            Some(Operation::Write)
871        );
872        assert_eq!(
873            Operation::from_dot_str("context.augment"),
874            Some(Operation::Context)
875        );
876        assert_eq!(Operation::from_dot_str("serve.api"), Some(Operation::Serve));
877        // Legacy flat strings
878        assert_eq!(Operation::from_dot_str("infer"), Some(Operation::Infer));
879        assert_eq!(Operation::from_dot_str("train"), Some(Operation::Train));
880        assert_eq!(Operation::from_dot_str("query"), Some(Operation::Query));
881        assert_eq!(Operation::from_dot_str("write"), Some(Operation::Write));
882        assert_eq!(Operation::from_dot_str("serve"), Some(Operation::Serve));
883        assert_eq!(Operation::from_dot_str("manage"), Some(Operation::Manage));
884        assert_eq!(Operation::from_dot_str("context"), Some(Operation::Context));
885        // Unknown
886        assert_eq!(Operation::from_dot_str("unknown"), None);
887        assert_eq!(Operation::from_dot_str(""), None);
888    }
889}