Skip to main content

hyprstream_core/auth/
policy_templates.rs

1//! Built-in policy templates for bootstrapping access control
2//!
3//! Templates provide pre-configured policy rules that can be applied
4//! via CLI or PolicyService RPC.
5//!
6//! Also defines [`SERVICE_BASE_POLICIES`] — mandatory service-to-service
7//! authorization rules that are always injected into the Casbin enforcer.
8
9/// A single Casbin policy rule with named fields.
10///
11/// Casbin format: `p, subject, domain, resource, action, effect`
12/// This struct makes field order impossible to get wrong.
13#[derive(Clone, Copy)]
14pub struct ServicePolicyRule {
15    pub subject: &'static str,
16    pub domain: &'static str,
17    pub resource: &'static str,
18    pub action: &'static str,
19    pub effect: &'static str,
20}
21
22impl ServicePolicyRule {
23    /// Convert to the Vec<String> Casbin expects for `add_policy()` / `add_policies()`.
24    pub fn to_vec(&self) -> Vec<String> {
25        vec![
26            self.subject.into(),
27            self.domain.into(),
28            self.resource.into(),
29            self.action.into(),
30            self.effect.into(),
31        ]
32    }
33
34    /// Convert to a CSV line: `p, subject, domain, resource, action, effect`
35    pub fn to_csv_line(&self) -> String {
36        format!(
37            "p, {}, {}, {}, {}, {}",
38            self.subject, self.domain, self.resource, self.action, self.effect
39        )
40    }
41}
42
43/// A role grouping rule.
44///
45/// Casbin format: `g, user, role`
46pub struct ServiceGrouping {
47    pub user: &'static str,
48    pub role: &'static str,
49}
50
51impl ServiceGrouping {
52    pub fn to_vec(&self) -> Vec<String> {
53        vec![self.user.into(), self.role.into()]
54    }
55
56    pub fn to_csv_line(&self) -> String {
57        format!("g, {}, {}", self.user, self.role)
58    }
59}
60
61// ─────────────────────────────────────────────────────────────────────────────
62// Base service-to-service rules (always injected into the enforcer)
63// ─────────────────────────────────────────────────────────────────────────────
64
65/// Base service-to-service authorization rules.
66///
67/// These rules are ALWAYS present in the Casbin enforcer — injected at init
68/// and re-injected after every reload. They grant each local service the
69/// permissions it needs to operate. Templates and user-facing rules are
70/// added ON TOP of these rules, never replacing them.
71///
72/// Because they're structured Rust data, field count/order is compile-time
73/// validated. No CSV parsing needed.
74pub const SERVICE_BASE_POLICIES: &[ServicePolicyRule] = &[
75    // PolicyService: CA — issues tokens, manages policy rules, assigns roles
76    ServicePolicyRule {
77        subject: "service:policy",
78        domain: "*",
79        resource: "*",
80        action: "*",
81        effect: "allow",
82    },
83    // User-token issuance belongs to OAuth, not every enrolled workload.
84    // Service credential renewal uses its separately verified renewal path.
85    ServicePolicyRule {
86        subject: "service:oauth",
87        domain: "*",
88        resource: "policy:IssueToken",
89        action: "manage",
90        effect: "allow",
91    },
92    // Credential revocation publication: only the OAuth revocation authority
93    // (the RFC 7009 endpoint) may publish to the canonical store.
94    ServicePolicyRule {
95        subject: "service:oauth",
96        domain: "*",
97        resource: "policy:RevokeCredential",
98        action: "manage",
99        effect: "allow",
100    },
101    // Revocation checks: every enrolled service verifies credentials (and
102    // probes the authority at startup); anonymous/end-user callers may not.
103    ServicePolicyRule {
104        subject: "service:*",
105        domain: "*",
106        resource: "policy:CheckCredentialRevocation",
107        action: "query",
108        effect: "allow",
109    },
110    // Session lifecycle: only the OAuth authority (which owns user-session
111    // issuance) may register or revoke sessions.
112    ServicePolicyRule {
113        subject: "service:oauth",
114        domain: "*",
115        resource: "policy:RegisterSession",
116        action: "manage",
117        effect: "allow",
118    },
119    ServicePolicyRule {
120        subject: "service:oauth",
121        domain: "*",
122        resource: "policy:RevokeSession",
123        action: "manage",
124        effect: "allow",
125    },
126    // Session checks: every enrolled service verifies session-bearing
127    // credentials; anonymous/end-user callers may not.
128    ServicePolicyRule {
129        subject: "service:*",
130        domain: "*",
131        resource: "policy:CheckSession",
132        action: "query",
133        effect: "allow",
134    },
135    // Services that perform policy authorization checks
136    // OAuth account-management RPC relays the verified upstream caller to
137    // Policy; this admits the relay, not the caller's requested operation.
138    ServicePolicyRule {
139        subject: "service:oauth",
140        domain: "*",
141        resource: "policy:PolicyCheck",
142        action: "check",
143        effect: "allow",
144    },
145    ServicePolicyRule {
146        subject: "service:registry",
147        domain: "*",
148        resource: "policy:*",
149        action: "check",
150        effect: "allow",
151    },
152    ServicePolicyRule {
153        subject: "service:model",
154        domain: "*",
155        resource: "policy:*",
156        action: "check",
157        effect: "allow",
158    },
159    ServicePolicyRule {
160        subject: "service:worker",
161        domain: "*",
162        resource: "policy:*",
163        action: "check",
164        effect: "allow",
165    },
166    ServicePolicyRule {
167        subject: "service:oai",
168        domain: "*",
169        resource: "policy:*",
170        action: "check",
171        effect: "allow",
172    },
173    ServicePolicyRule {
174        subject: "service:tui",
175        domain: "*",
176        resource: "policy:*",
177        action: "check",
178        effect: "allow",
179    },
180    ServicePolicyRule {
181        subject: "service:discovery",
182        domain: "*",
183        resource: "policy:*",
184        action: "check",
185        effect: "allow",
186    },
187    ServicePolicyRule {
188        subject: "service:notification",
189        domain: "*",
190        resource: "policy:*",
191        action: "check",
192        effect: "allow",
193    },
194    ServicePolicyRule {
195        subject: "service:metrics",
196        domain: "*",
197        resource: "policy:*",
198        action: "check",
199        effect: "allow",
200    },
201    ServicePolicyRule {
202        subject: "service:mcp",
203        domain: "*",
204        resource: "policy:*",
205        action: "*",
206        effect: "allow",
207    },
208    ServicePolicyRule {
209        subject: "service:flight",
210        domain: "*",
211        resource: "policy:*",
212        action: "check",
213        effect: "allow",
214    },
215    // Service key resolution: any service can resolve other service keys via policy
216    ServicePolicyRule {
217        subject: "service:oauth",
218        domain: "*",
219        resource: "policy:*",
220        action: "query",
221        effect: "allow",
222    },
223    ServicePolicyRule {
224        subject: "service:registry",
225        domain: "*",
226        resource: "policy:*",
227        action: "query",
228        effect: "allow",
229    },
230    ServicePolicyRule {
231        subject: "service:model",
232        domain: "*",
233        resource: "policy:*",
234        action: "query",
235        effect: "allow",
236    },
237    ServicePolicyRule {
238        subject: "service:worker",
239        domain: "*",
240        resource: "policy:*",
241        action: "query",
242        effect: "allow",
243    },
244    ServicePolicyRule {
245        subject: "service:oai",
246        domain: "*",
247        resource: "policy:*",
248        action: "query",
249        effect: "allow",
250    },
251    ServicePolicyRule {
252        subject: "service:tui",
253        domain: "*",
254        resource: "policy:*",
255        action: "query",
256        effect: "allow",
257    },
258    ServicePolicyRule {
259        subject: "service:discovery",
260        domain: "*",
261        resource: "policy:*",
262        action: "query",
263        effect: "allow",
264    },
265    ServicePolicyRule {
266        subject: "service:notification",
267        domain: "*",
268        resource: "policy:*",
269        action: "query",
270        effect: "allow",
271    },
272    ServicePolicyRule {
273        subject: "service:metrics",
274        domain: "*",
275        resource: "policy:*",
276        action: "query",
277        effect: "allow",
278    },
279    // Registry access (services that create RegistryClient)
280    ServicePolicyRule {
281        subject: "service:model",
282        domain: "*",
283        resource: "registry:*",
284        action: "*",
285        effect: "allow",
286    },
287    ServicePolicyRule {
288        subject: "service:oai",
289        domain: "*",
290        resource: "registry:*",
291        action: "*",
292        effect: "allow",
293    },
294    ServicePolicyRule {
295        subject: "service:flight",
296        domain: "*",
297        resource: "registry:*",
298        action: "*",
299        effect: "allow",
300    },
301    // Model/inference access (services that create ModelClient)
302    ServicePolicyRule {
303        subject: "service:model",
304        domain: "*",
305        resource: "model:*",
306        action: "*",
307        effect: "allow",
308    },
309    ServicePolicyRule {
310        subject: "service:oai",
311        domain: "*",
312        resource: "model:*",
313        action: "*",
314        effect: "allow",
315    },
316    // Discovery: services announce and query endpoints
317    ServicePolicyRule {
318        subject: "service:discovery",
319        domain: "*",
320        resource: "discovery:*",
321        action: "*",
322        effect: "allow",
323    },
324    ServicePolicyRule {
325        subject: "service:model",
326        domain: "*",
327        resource: "discovery:*",
328        action: "*",
329        effect: "allow",
330    },
331    ServicePolicyRule {
332        subject: "service:oai",
333        domain: "*",
334        resource: "discovery:*",
335        action: "*",
336        effect: "allow",
337    },
338    ServicePolicyRule {
339        subject: "service:worker",
340        domain: "*",
341        resource: "discovery:*",
342        action: "*",
343        effect: "allow",
344    },
345    // #446: EVERY socket-served service announces its own QUIC endpoint to
346    // DiscoveryService on startup (the generic `factory.rs` announce hook). Now
347    // that those IPC callers resolve as their authoritative `service:<name>`
348    // identity (not `anonymous`), they need the least-privilege grant to write
349    // their OWN announcement. Scoped to `discovery:Announce` + `write` only
350    // (NOT `discovery:*`), so these services can register their endpoint but not
351    // mutate the rest of the discovery namespace. The services already granted
352    // broad `discovery:*` above (discovery/model/oai/worker) are unaffected.
353    ServicePolicyRule {
354        subject: "service:mcp",
355        domain: "*",
356        resource: "discovery:Announce",
357        action: "write",
358        effect: "allow",
359    },
360    // MCP resolves Model before presenting the caller's delegated bearer to Model.
361    ServicePolicyRule {
362        subject: "service:mcp",
363        domain: "*",
364        resource: "discovery:model",
365        action: "query",
366        effect: "allow",
367    },
368    ServicePolicyRule {
369        subject: "service:metrics",
370        domain: "*",
371        resource: "discovery:Announce",
372        action: "write",
373        effect: "allow",
374    },
375    ServicePolicyRule {
376        subject: "service:notification",
377        domain: "*",
378        resource: "discovery:Announce",
379        action: "write",
380        effect: "allow",
381    },
382    ServicePolicyRule {
383        subject: "service:registry",
384        domain: "*",
385        resource: "discovery:Announce",
386        action: "write",
387        effect: "allow",
388    },
389    ServicePolicyRule {
390        subject: "service:tui",
391        domain: "*",
392        resource: "discovery:Announce",
393        action: "write",
394        effect: "allow",
395    },
396    ServicePolicyRule {
397        subject: "service:oauth",
398        domain: "*",
399        resource: "discovery:Announce",
400        action: "write",
401        effect: "allow",
402    },
403    // Revocation/session authority resolution: every policy-dependent
404    // service resolves the Policy endpoint through Discovery for its
405    // fail-closed startup probe (services/revocation.rs). The probe's RPC
406    // methods themselves are already service:*-granted above
407    // (policy:CheckCredentialRevocation / policy:CheckSession); without
408    // endpoint resolution the probe cannot reach the authority it exists
409    // to verify. This grants endpoint lookup only — no policy data, no
410    // other Discovery records. The signed MAC boot policy cannot carry
411    // this grant (configured artifacts are enrollment-only).
412    ServicePolicyRule {
413        subject: "service:*",
414        domain: "*",
415        resource: "discovery:policy",
416        action: "query",
417        effect: "allow",
418    },
419    // OAuth serves browser provisioning for the two staging RPC services.
420    // Its production resolver must query their accepted-current Discovery
421    // records; this grants no announcement mutation or unrelated lookups.
422    ServicePolicyRule {
423        subject: "service:oauth",
424        domain: "*",
425        resource: "discovery:registry",
426        action: "query",
427        effect: "allow",
428    },
429    ServicePolicyRule {
430        subject: "service:oauth",
431        domain: "*",
432        resource: "discovery:model",
433        action: "query",
434        effect: "allow",
435    },
436    ServicePolicyRule {
437        subject: "service:event",
438        domain: "*",
439        resource: "discovery:Announce",
440        action: "write",
441        effect: "allow",
442    },
443    ServicePolicyRule {
444        subject: "service:streams",
445        domain: "*",
446        resource: "discovery:Announce",
447        action: "write",
448        effect: "allow",
449    },
450    ServicePolicyRule {
451        subject: "service:flight",
452        domain: "*",
453        resource: "discovery:Announce",
454        action: "write",
455        effect: "allow",
456    },
457    ServicePolicyRule {
458        subject: "service:policy",
459        domain: "*",
460        resource: "discovery:Announce",
461        action: "write",
462        effect: "allow",
463    },
464    // NOTE: Federation (`federation:register` resource) is deny-by-default.
465    // This is the single, atproto-style trust gate that governs both:
466    //   - third-party clients registering via CIMD (Client ID Metadata
467    //     Documents — published metadata at an HTTPS origin), and
468    //   - remote peer servers whose entity statements we'd resolve via
469    //     FederationKeyResolver / DiscoveryService.
470    //
471    // Operators opt in by applying the `federation-open` template, or
472    // by allowlisting specific origins:
473    //   p, *, *, federation:register:https://app.partner.org,        check, allow
474    //   p, *, *, federation:register:https://*.partner.org,          check, allow
475    //   p, *, *, federation:register:https://hyprstream.partner.org, check, allow
476    //
477    // The same rule shape covers a CIMD client at app.partner.org and
478    // a peer hyprstream instance at hyprstream.partner.org. Wizard may
479    // suggest `federation-open` at setup time for operators who want
480    // to join the broader MCP/atproto network.
481    //
482    // Infra services — scoped to their own domain
483    ServicePolicyRule {
484        subject: "service:oauth",
485        domain: "*",
486        resource: "oauth:*",
487        action: "*",
488        effect: "allow",
489    },
490    ServicePolicyRule {
491        subject: "service:streams",
492        domain: "*",
493        resource: "streams:*",
494        action: "*",
495        effect: "allow",
496    },
497    ServicePolicyRule {
498        subject: "service:event",
499        domain: "*",
500        resource: "event:*",
501        action: "*",
502        effect: "allow",
503    },
504];
505
506/// Convert structured base policies to the Vec<Vec<String>> Casbin expects.
507pub fn base_policies_to_vec() -> Vec<Vec<String>> {
508    SERVICE_BASE_POLICIES
509        .iter()
510        .map(ServicePolicyRule::to_vec)
511        .collect()
512}
513
514/// Convert structured base policies to a CSV string (for default_policy_csv only).
515pub fn base_policies_to_csv() -> String {
516    SERVICE_BASE_POLICIES
517        .iter()
518        .map(ServicePolicyRule::to_csv_line)
519        .collect::<Vec<_>>()
520        .join("\n")
521}
522
523// ─────────────────────────────────────────────────────────────────────────────
524// Policy templates
525// ─────────────────────────────────────────────────────────────────────────────
526
527/// Built-in policy template
528pub struct PolicyTemplate {
529    pub name: &'static str,
530    pub description: &'static str,
531    /// Static policy rules, or None if generated dynamically.
532    pub policies: Option<&'static [ServicePolicyRule]>,
533    /// Static grouping rules (g, user, role).
534    pub groupings: Option<&'static [ServiceGrouping]>,
535}
536
537impl PolicyTemplate {
538    /// Get expanded policy rules for this template. All templates now
539    /// carry static `policies`; the dynamic-OS-username "local" template
540    /// was removed because its expansion (`anonymous → *`) was
541    /// indistinguishable from `public-*` templates and the name
542    /// misrepresented its scope.
543    pub fn expanded_policies(&self) -> Vec<ServicePolicyRule> {
544        self.policies.map(<[_]>::to_vec).unwrap_or_default()
545    }
546
547    /// Convert all rules (policies + groupings) to a CSV string.
548    ///
549    /// Used only for generating initial policy.csv content and for
550    /// CLI display. The enforcer path uses structured data directly.
551    pub fn to_csv(&self) -> String {
552        let mut lines = Vec::new();
553        let policies = self.expanded_policies();
554        for p in &policies {
555            lines.push(p.to_csv_line());
556        }
557        if let Some(groupings) = self.groupings {
558            for g in groupings {
559                lines.push(g.to_csv_line());
560            }
561        }
562        lines.join("\n")
563    }
564}
565
566/// Get all available policy templates.
567///
568/// Templates are **composable and additive**: each `policy apply-template`
569/// adds the template's rules to the running policy via Casbin's
570/// `add_policies` / `add_grouping_policies` (deduplicating, so repeat
571/// application is idempotent). Operators can layer templates as
572/// needed — e.g. `cimd-open` + `public-inference` + `ttt.user`.
573///
574/// No template removes rules. To revoke a previously-applied template
575/// operators use `policy edit` to remove the lines, or
576/// `policy rollback <ref>` to restore an earlier commit.
577pub fn get_templates() -> &'static [PolicyTemplate] {
578    &[
579        PolicyTemplate {
580            name: "federation-open",
581            description: "Open federation: accept third-party apps and remote peer servers from any HTTPS origin (atproto-style, recommended for MCP/peer compatibility)",
582            policies: Some(&[
583                // Unified federation trust gate. Covers BOTH:
584                //   - CIMD third-party clients (their HTTPS metadata URL)
585                //   - Remote peer servers (their entity-statement URL)
586                // Operators wanting tighter posture replace with origin-
587                // specific allow rules; the matcher is the same.
588                ServicePolicyRule {
589                    subject: "*",
590                    domain: "*",
591                    resource: "federation:register:*",
592                    action: "check",
593                    effect: "allow",
594                },
595            ]),
596            groupings: None,
597        },
598        PolicyTemplate {
599            name: "cyberdione-staging-ui",
600            description: "Cyberdione staging only: allow OAuth CIMD and peer registration from https://www.staging.lab.hyprstream.com",
601            policies: Some(&[
602                // The current policy model intentionally uses this same exact
603                // origin gate for OAuth client metadata and peer registration.
604                // It does not auto-register a peer or open federation to any
605                // other origin.
606                ServicePolicyRule {
607                    subject: "*",
608                    domain: "*",
609                    resource: "federation:register:https://www.staging.lab.hyprstream.com",
610                    action: "check",
611                    effect: "allow",
612                },
613            ]),
614            groupings: None,
615        },
616        PolicyTemplate {
617            name: "cyberdione-staging-e2e",
618            description: "One Federate staging test DID in the local tenant, limited to the pinned Registry and Model acceptance calls",
619            policies: Some(&[
620                ServicePolicyRule { subject: "did:plc:3f7ldey5bivhfjapwqi2sljy", domain: "local", resource: "registry:qwen2.5-0.5b-instruct", action: "query", effect: "allow" },
621                ServicePolicyRule { subject: "did:plc:3f7ldey5bivhfjapwqi2sljy", domain: "local", resource: "model:Load", action: "write", effect: "allow" },
622                ServicePolicyRule { subject: "did:plc:3f7ldey5bivhfjapwqi2sljy", domain: "local", resource: "model:Status", action: "query", effect: "allow" },
623                ServicePolicyRule { subject: "did:plc:3f7ldey5bivhfjapwqi2sljy", domain: "local", resource: "model:qwen2.5-0.5b-instruct:main", action: "infer", effect: "allow" },
624            ]),
625            groupings: None,
626        },
627        PolicyTemplate {
628            name: "cyberdione-staging-operator",
629            description: "One authorized staging operator DID in the local tenant, limited to the pinned Registry and Model acceptance calls",
630            policies: Some(&[
631                ServicePolicyRule { subject: "did:plc:rjqczurevrpoz4mcnax2kgw4", domain: "local", resource: "registry:qwen2.5-0.5b-instruct", action: "query", effect: "allow" },
632                ServicePolicyRule { subject: "did:plc:rjqczurevrpoz4mcnax2kgw4", domain: "local", resource: "model:Load", action: "write", effect: "allow" },
633                ServicePolicyRule { subject: "did:plc:rjqczurevrpoz4mcnax2kgw4", domain: "local", resource: "model:Status", action: "query", effect: "allow" },
634                ServicePolicyRule { subject: "did:plc:rjqczurevrpoz4mcnax2kgw4", domain: "local", resource: "model:qwen2.5-0.5b-instruct:main", action: "infer", effect: "allow" },
635            ]),
636            groupings: None,
637        },
638        PolicyTemplate {
639            name: "public-inference",
640            description: "Anonymous users can infer and query models",
641            policies: Some(&[
642                ServicePolicyRule { subject: "anonymous", domain: "*", resource: "model:*", action: "infer.generate", effect: "allow" },
643                ServicePolicyRule { subject: "anonymous", domain: "*", resource: "model:*", action: "query.status", effect: "allow" },
644            ]),
645            groupings: None,
646        },
647        PolicyTemplate {
648            name: "public-read",
649            description: "Anonymous users can query the registry (read-only)",
650            policies: Some(&[
651                ServicePolicyRule { subject: "anonymous", domain: "*", resource: "registry:*", action: "query.status", effect: "allow" },
652            ]),
653            groupings: None,
654        },
655        PolicyTemplate {
656            name: "ttt.user",
657            description: "TTT user: infer, query, persist on all models",
658            policies: Some(&[
659                ServicePolicyRule { subject: "ttt.user", domain: "*", resource: "model:*", action: "infer.generate", effect: "allow" },
660                ServicePolicyRule { subject: "ttt.user", domain: "*", resource: "model:*", action: "query.status", effect: "allow" },
661                ServicePolicyRule { subject: "ttt.user", domain: "*", resource: "model:*", action: "query.delta", effect: "allow" },
662                ServicePolicyRule { subject: "ttt.user", domain: "*", resource: "model:*", action: "persist.save", effect: "allow" },
663                ServicePolicyRule { subject: "ttt.user", domain: "*", resource: "model:*", action: "persist.export", effect: "allow" },
664                ServicePolicyRule { subject: "ttt.user", domain: "*", resource: "model:*", action: "persist.snapshot", effect: "allow" },
665            ]),
666            groupings: None,
667        },
668        PolicyTemplate {
669            name: "ttt.agent",
670            description: "TTT agent: alias for ttt.user",
671            policies: None,
672            groupings: Some(&[
673                ServiceGrouping { user: "ttt.agent", role: "ttt.user" },
674            ]),
675        },
676        // ─────────────────────────────────────────────────────────────────
677        // Inference mesh (#319) — host↔host pipeline RPC authorization.
678        //
679        // SECURITY MODEL (deny-by-default, fail-closed, least-privilege):
680        //   * The mesh AUTHORITY actions (`infer.stage`, `delta.submit`, and the
681        //     `mesh.rpc` umbrella invoke right) are NEVER granted to `*`,
682        //     `service:*`, or `anonymous`. They are granted ONLY to specific,
683        //     non-wildcard `service:inference:host-<id>` subjects (#328), and
684        //     ONLY within a single tenant's domain. A host enrolled for tenant
685        //     `acme` thus cannot stage on tenant `beta` (the Casbin matcher does
686        //     an exact `r.dom == p.dom` check unless the rule's domain is `*`,
687        //     which mesh-authority rules MUST NOT use).
688        //   * The READ ability (`query.status`) MAY be granted to a *group* of
689        //     hosts via Casbin grouping (`g`) — see the `mesh-host-group`
690        //     template — so an operator can give a fleet read visibility without
691        //     per-host duplication. Authority stays per-host.
692        //
693        // RESOURCE SHAPE — `mesh://<tenant>/<job>/<…>` (UCAN-translatable):
694        //   The tenant is BOTH the Casbin domain (for ambient isolation) AND the
695        //   first path segment (so the caveat survives translation to a future
696        //   UCAN delegation, which has no domain column). The 1:1 mapping is:
697        //
698        //     Casbin: p, service:inference:host-7, acme, mesh://acme/job/j7, infer.stage, allow
699        //     UCAN:   { iss: <policy-root>, aud: host-7, sub: <policy-root>,
700        //               cmd: /mesh/infer/stage,
701        //               pol: [["==", ".tenant", "acme"], ["==", ".job", "j7"]] }
702        //
703        //   action ⇄ cmd, subject ⇄ aud, and the tenant/job caveats live in the
704        //   resource path so a future UCAN layer maps without loss. `query.status`
705        //   ⇄ /mesh/query/status, `delta.submit` ⇄ /mesh/delta/submit, the
706        //   `mesh.rpc` umbrella ⇄ /mesh/rpc.
707        //
708        // This template is a WORKED EXAMPLE for two hosts in tenant `acme`.
709        // Operators copy it and substitute their real host labels / tenant /
710        // job via `policy edit` (the per-host authority lines are intentionally
711        // explicit, never wildcarded). It is NOT injected into the base policy.
712        PolicyTemplate {
713            name: "mesh-host",
714            description: "Inference mesh (#319): per-host pipeline RPC grants for tenant `acme` (worked example — substitute real host labels/tenant; authority is strictly non-wildcard per-host)",
715            policies: Some(&[
716                // Router → host: ModelService stages activations onto enrolled
717                // hosts within the tenant. `service:model` is the router identity.
718                ServicePolicyRule { subject: "service:model", domain: "acme", resource: "mesh://acme/*", action: "infer.stage", effect: "allow" },
719                // Host → host: peer activation hand-off + status read.
720                ServicePolicyRule { subject: "service:inference:host-1", domain: "acme", resource: "mesh://acme/*", action: "mesh.rpc", effect: "allow" },
721                ServicePolicyRule { subject: "service:inference:host-1", domain: "acme", resource: "mesh://acme/*", action: "infer.stage", effect: "allow" },
722                ServicePolicyRule { subject: "service:inference:host-1", domain: "acme", resource: "mesh://acme/*", action: "query.status", effect: "allow" },
723                ServicePolicyRule { subject: "service:inference:host-2", domain: "acme", resource: "mesh://acme/*", action: "mesh.rpc", effect: "allow" },
724                ServicePolicyRule { subject: "service:inference:host-2", domain: "acme", resource: "mesh://acme/*", action: "infer.stage", effect: "allow" },
725                ServicePolicyRule { subject: "service:inference:host-2", domain: "acme", resource: "mesh://acme/*", action: "query.status", effect: "allow" },
726                // Host → aggregator: TTT delta submission (authority).
727                ServicePolicyRule { subject: "service:inference:host-1", domain: "acme", resource: "mesh://acme/*", action: "delta.submit", effect: "allow" },
728                ServicePolicyRule { subject: "service:inference:host-2", domain: "acme", resource: "mesh://acme/*", action: "delta.submit", effect: "allow" },
729            ]),
730            groupings: None,
731        },
732        // Group-policy variant: grant the READ ability to a whole fleet via a
733        // Casbin role, WITHOUT per-host duplication, while authority stays
734        // per-host (granted by `mesh-host`). The grouping rule `g,
735        // service:inference:host-<id>, mesh-readers` makes each host inherit the
736        // role's grants; the role gets ONLY `query.status` (read), never an
737        // authority action. Operators add `g, <host>, mesh-readers` per host.
738        PolicyTemplate {
739            name: "mesh-host-group",
740            description: "Inference mesh (#319): grant the read ability (query.status) to the `mesh-readers` host group for tenant `acme` (authority stays per-host via `mesh-host`)",
741            policies: Some(&[
742                ServicePolicyRule { subject: "mesh-readers", domain: "acme", resource: "mesh://acme/*", action: "query.status", effect: "allow" },
743            ]),
744            groupings: Some(&[
745                ServiceGrouping { user: "service:inference:host-1", role: "mesh-readers" },
746                ServiceGrouping { user: "service:inference:host-2", role: "mesh-readers" },
747            ]),
748        },
749        PolicyTemplate {
750            name: "ttt.privileged",
751            description: "TTT privileged: extends ttt.user with ttt.* operations",
752            policies: Some(&[
753                ServicePolicyRule { subject: "ttt.privileged", domain: "*", resource: "model:*", action: "ttt.train", effect: "allow" },
754                ServicePolicyRule { subject: "ttt.privileged", domain: "*", resource: "model:*", action: "ttt.writeback", effect: "allow" },
755                ServicePolicyRule { subject: "ttt.privileged", domain: "*", resource: "model:*", action: "ttt.evict", effect: "allow" },
756                ServicePolicyRule { subject: "ttt.privileged", domain: "*", resource: "model:*", action: "ttt.zero", effect: "allow" },
757            ]),
758            groupings: Some(&[
759                ServiceGrouping { user: "ttt.privileged", role: "ttt.user" },
760            ]),
761        },
762    ]
763}
764
765/// Get a template by name
766pub fn get_template(name: &str) -> Option<&'static PolicyTemplate> {
767    get_templates().iter().find(|t| t.name == name)
768}