Skip to main content

hyprstream_core/auth/
policy_manager.rs

1//! Casbin-powered policy manager for RBAC/ABAC access control
2//!
3//! Policies are stored in the `.registry/policies/` directory:
4//! - `model.conf` - Casbin access control model definition
5//! - `policy.csv` - Authorization rules
6//!
7//! Policy format follows Casbin conventions:
8//! ```text
9//! # model.conf defines the policy structure
10//! [request_definition]
11//! r = sub, obj, act
12//!
13//! [policy_definition]
14//! p = sub, obj, act
15//!
16//! [role_definition]
17//! g = _, _
18//!
19//! [policy_effect]
20//! e = some(where (p.eft == allow))
21//!
22//! [matchers]
23//! m = g(r.sub, p.sub) && keyMatch(r.obj, p.obj) && r.act == p.act
24//! ```
25//!
26//! ```text
27//! # policy.csv defines the actual rules
28//! p, operator, *, *, *, allow
29//! p, trainer, *, model:*, infer, allow
30//! p, trainer, *, model:*, train, allow
31//! g, alice, trainer
32//! ```
33
34use crate::auth::policy_file_adapter::PolicyFileAdapter;
35use crate::auth::policy_templates::{
36    base_policies_to_csv, base_policies_to_vec, ServiceGrouping, ServicePolicyRule,
37};
38use crate::auth::Operation;
39use casbin::function_map::{dynamic_to_str, OperatorFunction};
40use casbin::rhai::Dynamic;
41use casbin::{CoreApi, DefaultModel, Enforcer, MemoryAdapter, MgmtApi, RbacApi};
42use std::path::{Path, PathBuf};
43use std::sync::{Arc, OnceLock};
44use thiserror::Error;
45use tokio::sync::RwLock;
46use tracing::{debug, info, warn};
47
48static GLOBAL_POLICY_MANAGER: OnceLock<Arc<PolicyManager>> = OnceLock::new();
49
50/// Set the process-global PolicyManager. Called once by the PolicyService factory.
51pub fn set_global_policy_manager(pm: Arc<PolicyManager>) {
52    let _ = GLOBAL_POLICY_MANAGER.set(pm);
53}
54
55/// Access the process-global PolicyManager. Returns `None` before PolicyService starts.
56pub fn global_policy_manager() -> Option<Arc<PolicyManager>> {
57    GLOBAL_POLICY_MANAGER.get().cloned()
58}
59
60/// Errors from policy operations
61#[derive(Error, Debug)]
62pub enum PolicyError {
63    #[error("Failed to load policy model: {0}")]
64    ModelLoadError(String),
65
66    #[error("Failed to load policy rules: {0}")]
67    PolicyLoadError(String),
68
69    #[error("Failed to save policy: {0}")]
70    PolicySaveError(String),
71
72    #[error("Casbin error: {0}")]
73    CasbinError(#[from] casbin::Error),
74
75    #[error("IO error: {0}")]
76    IoError(#[from] std::io::Error),
77
78    #[error("Policy directory not found: {0}")]
79    PolicyDirNotFound(PathBuf),
80
81    #[error("Invalid policy component: {0}")]
82    ValidationError(String),
83}
84
85/// Maximum length for policy components (user, resource, operation)
86const MAX_POLICY_COMPONENT_LEN: usize = 256;
87
88/// Resource namespace for the unified third-party/peer federation gate.
89///
90/// The origin is policy data, not an authenticated principal. Keeping it in
91/// the resource means `PolicyCheck.subject` can remain inert while the
92/// decision still varies by the normalized RFC 6454 origin.
93pub const FEDERATION_REGISTER_RESOURCE_PREFIX: &str = "federation:register:";
94
95/// Encode a normalized federation origin as a policy resource.
96pub fn federation_registration_resource(origin: &str) -> Result<String, PolicyError> {
97    validate_policy_component(origin, "federation origin")?;
98    let resource = format!("{FEDERATION_REGISTER_RESOURCE_PREFIX}{origin}");
99    validate_policy_component(&resource, "federation registration resource")?;
100    Ok(resource)
101}
102
103fn federation_origin_pattern_matches(request_origin: &str, policy_origin: &str) -> bool {
104    if request_origin == policy_origin {
105        return true;
106    }
107    if policy_origin.matches('*').count() != 1 {
108        return false;
109    }
110
111    let Some((scheme, authority_pattern)) = policy_origin.split_once("://") else {
112        return false;
113    };
114    let Some(authority_suffix) = authority_pattern.strip_prefix("*.") else {
115        return false;
116    };
117    if authority_suffix.contains('*') {
118        return false;
119    }
120
121    // Substitute a valid DNS label so URL parsing can validate the scheme,
122    // authority, and optional port without ever evaluating an operator-provided
123    // glob as executable matcher syntax.
124    let Ok(policy_url) = url::Url::parse(&format!("{scheme}://wildcard.{authority_suffix}")) else {
125        return false;
126    };
127    let Ok(request_url) = url::Url::parse(request_origin) else {
128        return false;
129    };
130    if policy_url.path() != "/"
131        || request_url.path() != "/"
132        || policy_url.query().is_some()
133        || request_url.query().is_some()
134        || policy_url.fragment().is_some()
135        || request_url.fragment().is_some()
136        || !policy_url.username().is_empty()
137        || !request_url.username().is_empty()
138        || policy_url.password().is_some()
139        || request_url.password().is_some()
140        || policy_url.scheme() != request_url.scheme()
141        || policy_url.port_or_known_default() != request_url.port_or_known_default()
142    {
143        return false;
144    }
145
146    let Some(policy_host) = policy_url.host_str() else {
147        return false;
148    };
149    let Some(host_suffix) = policy_host.strip_prefix("wildcard.") else {
150        return false;
151    };
152    let Some(request_host) = request_url.host_str() else {
153        return false;
154    };
155    request_host
156        .strip_suffix(host_suffix)
157        .is_some_and(|prefix| !prefix.is_empty() && prefix.ends_with('.'))
158}
159
160fn federation_resource_matches(request_resource: &str, policy_resource: &str) -> bool {
161    if policy_resource == "*" {
162        return true;
163    }
164    let Some(request_origin) = request_resource.strip_prefix(FEDERATION_REGISTER_RESOURCE_PREFIX)
165    else {
166        return false;
167    };
168    let Some(policy_origin) = policy_resource.strip_prefix(FEDERATION_REGISTER_RESOURCE_PREFIX)
169    else {
170        return false;
171    };
172    if policy_origin == "*" {
173        return true;
174    }
175    federation_origin_pattern_matches(request_origin, policy_origin)
176}
177
178fn federation_match_operator(request: Dynamic, policy: Dynamic) -> Dynamic {
179    federation_resource_matches(
180        dynamic_to_str(&request).as_ref(),
181        dynamic_to_str(&policy).as_ref(),
182    )
183    .into()
184}
185
186fn install_policy_functions(enforcer: &mut Enforcer) {
187    enforcer.add_function(
188        "federationMatch",
189        OperatorFunction::Arg2(federation_match_operator),
190    );
191}
192
193/// Validate a policy component for security
194///
195/// Rejects:
196/// - Components longer than 256 characters
197/// - Null bytes
198/// - Line breaks (CSV injection prevention)
199fn validate_policy_component(component: &str, name: &str) -> Result<(), PolicyError> {
200    if component.len() > MAX_POLICY_COMPONENT_LEN {
201        return Err(PolicyError::ValidationError(format!(
202            "{name} exceeds maximum length of {MAX_POLICY_COMPONENT_LEN} characters"
203        )));
204    }
205
206    if component.contains('\0') {
207        return Err(PolicyError::ValidationError(format!(
208            "{name} contains null byte"
209        )));
210    }
211
212    if component.contains('\n') || component.contains('\r') {
213        return Err(PolicyError::ValidationError(format!(
214            "{name} contains line break (potential CSV injection)"
215        )));
216    }
217
218    if component.contains(',') {
219        return Err(PolicyError::ValidationError(format!(
220            "{name} contains comma (potential CSV injection)"
221        )));
222    }
223
224    // NOTE: wildcards ('*') are intentionally NOT rejected here. The Casbin model
225    // (DEFAULT_MODEL_CONF) is wildcard-based: every rule carries domain="*", and
226    // legitimate features rely on wildcard subjects/resources/actions — public
227    // models ("*" subject, see PolicyService::handle_set_branch_visibility),
228    // role-scoped resource grants ("model:*"), action namespaces ("ttt.*"), and
229    // the OIDC self-ownership grant. A blanket '*' ban here broke all of those
230    // (and made add_policy() — which injects domain="*" — always fail) while
231    // adding no real protection: who may mutate policy is enforced at the
232    // PolicyService RPC authz layer (the correct place for anti-escalation), not
233    // by banning '*' in policy *content*. The null/newline/comma/length checks
234    // above remain — those are genuine CSV-injection / DoS guards.
235
236    Ok(())
237}
238
239/// Default Casbin model configuration for hyprstream RBAC with domain support
240///
241/// Request format: (subject, domain, object, action)
242/// Policy format: (subject, domain, object, action, effect)
243///
244/// Supports:
245/// - Domain-scoped access control (e.g., HfModel, HfDataset)
246/// - Deny rules via explicit effect column
247/// - Wildcards for domain and action
248/// - Global-service role access via g() in the explicit `*` domain
249/// - Tenant-scoped role access via g2()
250const DEFAULT_MODEL_CONF: &str = r#"[request_definition]
251r = sub, dom, obj, act
252
253[policy_definition]
254p = sub, dom, obj, act, eft
255
256[role_definition]
257g = _, _
258g2 = _, _, _
259
260[policy_effect]
261e = some(where (p.eft == allow)) && !some(where (p.eft == deny))
262
263[matchers]
264m = ((r.dom == "*" && g(r.sub, p.sub)) || g2(r.sub, p.sub, r.dom) || keyMatch(r.sub, p.sub)) && \
265    (p.dom == "*" || r.dom == p.dom) && \
266    ((keyMatch(r.obj, "federation:register:*") && federationMatch(r.obj, p.obj)) || (!keyMatch(r.obj, "federation:register:*") && keyMatch(r.obj, p.obj))) && \
267    (p.act == "*" || keyMatch(r.act, p.act))
268"#;
269
270/// Default policy rules: deny-by-default with service grants
271///
272/// All access is denied until the operator explicitly configures policy via:
273///   hyprstream quick policy apply-template public-inference  # open inference API
274///
275/// Service-to-service rules are defined in [`policy_templates::SERVICE_BASE_POLICIES`].
276///
277/// Policy format: p, subject, domain, resource, action, effect
278fn default_policy_csv() -> String {
279    format!(
280        "# Hyprstream Access Control Policy — deny-by-default\n\
281        # Service-to-service base rules\n\
282        {}\n\
283        # The TUI display server is a local-only service; anonymous browser clients\n\
284        # (connecting via WebTransport from localhost) may access TUI resources.\n\
285        p, anonymous, *, tui:*, *, allow\n\
286        #\n\
287        # No other access is granted until you apply a policy template:\n\
288        #\n\
289        #   hyprstream quick policy apply-template public-inference  # anonymous inference\n\
290        #   hyprstream quick policy apply-template public-read       # anonymous registry browse\n\
291        #\n\
292        # Or add rules manually:\n\
293        #   p, alice, *, *, *, allow                           # Alice full access\n\
294        #   p, alice, *, model:*, infer, allow                 # Alice can infer\n\
295        #   p, anonymous, *, inference:*, infer, allow         # public inference\n\
296        #\n",
297        base_policies_to_csv(),
298    )
299}
300
301/// Validate policy.csv format before loading
302///
303/// Ensures all policy lines have the correct number of fields:
304/// - Policy lines (p, ...): 6 fields (p, subject, domain, resource, action, effect)
305/// - Global role lines (g, ...): 3 fields (g, user, role)
306/// - Domain role lines (g2, ...): 4 fields (g2, user, role, domain)
307fn validate_policy_csv(policy_path: &Path) -> Result<(), PolicyError> {
308    let content = std::fs::read_to_string(policy_path).map_err(PolicyError::IoError)?;
309
310    for (line_num, line) in content.lines().enumerate() {
311        let line = line.trim();
312        if line.is_empty() || line.starts_with('#') {
313            continue;
314        }
315
316        // Check policy lines (p, ...)
317        if line.starts_with("p,") || line.starts_with("p ") {
318            let fields: Vec<&str> = line.split(',').map(str::trim).collect();
319            if fields.len() != 6 {
320                // "p" + 5 fields
321                return Err(PolicyError::ValidationError(format!(
322                    "Invalid policy format at line {}:\n\
323                    Found:    {}\n\
324                    Expected: p, subject, domain, resource, action, effect\n\
325                    Example:  p, alice, *, *, *, allow\n\n\
326                    Your policy has {} fields but 6 are required.\n\
327                    Edit {} to fix the format.",
328                    line_num + 1,
329                    line,
330                    fields.len(),
331                    policy_path.display()
332                )));
333            }
334        }
335
336        // Check role lines (g, ...)
337        if line.starts_with("g,") || line.starts_with("g ") {
338            let fields: Vec<&str> = line.split(',').map(str::trim).collect();
339            if fields.len() != 3 {
340                // "g" + 2 fields
341                return Err(PolicyError::ValidationError(format!(
342                    "Invalid role format at line {}:\n\
343                    Found:    {}\n\
344                    Expected: g, user, role\n\
345                    Example:  g, alice, trainer",
346                    line_num + 1,
347                    line
348                )));
349            }
350        }
351
352        // Domain-scoped role membership (g2, user, role, domain)
353        if line.starts_with("g2,") || line.starts_with("g2 ") {
354            let fields: Vec<&str> = line.split(',').map(str::trim).collect();
355            if fields.len() != 4 {
356                return Err(PolicyError::ValidationError(format!(
357                    "Invalid domain role format at line {}:\n\
358                    Found:    {}\n\
359                    Expected: g2, user, role, domain\n\
360                    Example:  g2, alice, trainer, tenant-a",
361                    line_num + 1,
362                    line
363                )));
364            }
365        }
366    }
367    Ok(())
368}
369
370/// Write a policy file with restrictive permissions (0o640 on Unix).
371///
372/// Policy files contain authorization rules and should not be world-readable.
373/// Uses tokio::fs::write then sets permissions afterward. The policies directory
374/// itself should already be 0o750, limiting the window where the file is exposed.
375pub async fn write_policy_file(path: &Path, content: impl AsRef<[u8]>) -> Result<(), PolicyError> {
376    tokio::fs::write(path, content).await?;
377    #[cfg(unix)]
378    {
379        use std::os::unix::fs::PermissionsExt;
380        tokio::fs::set_permissions(path, std::fs::Permissions::from_mode(0o640)).await?;
381    }
382    Ok(())
383}
384
385async fn ensure_domain_role_model(model_path: &Path) -> Result<(), PolicyError> {
386    let content = tokio::fs::read_to_string(model_path).await?;
387    const GLOBAL_ROLE_CALL: &str = "g(r.sub, p.sub)";
388    const GUARDED_ROLE_MATCHER: &str =
389        "m = ((r.dom == \"*\" && g(r.sub, p.sub)) || g2(r.sub, p.sub, r.dom) || keyMatch(r.sub, p.sub))";
390    const SAFE_RESOURCE_MATCHER: &str = "((keyMatch(r.obj, \"federation:register:*\") && federationMatch(r.obj, p.obj)) || (!keyMatch(r.obj, \"federation:register:*\") && keyMatch(r.obj, p.obj)))";
391
392    if content.contains("g2 = _, _, _")
393        && content.contains(GUARDED_ROLE_MATCHER)
394        && content.contains(SAFE_RESOURCE_MATCHER)
395        && content.matches(GLOBAL_ROLE_CALL).count() == 1
396    {
397        return Ok(());
398    }
399
400    let mut migrated = content
401        .replacen(
402            "[role_definition]\ng = _, _",
403            "[role_definition]\ng = _, _\ng2 = _, _, _",
404            1,
405        )
406        .replacen(
407            "m = (g(r.sub, p.sub) || g2(r.sub, p.sub, r.dom) || keyMatch(r.sub, p.sub))",
408            GUARDED_ROLE_MATCHER,
409            1,
410        )
411        .replacen(
412            "m = (g(r.sub, p.sub) || keyMatch(r.sub, p.sub))",
413            GUARDED_ROLE_MATCHER,
414            1,
415        );
416    if !migrated.contains(SAFE_RESOURCE_MATCHER) {
417        migrated = migrated.replacen("keyMatch(r.obj, p.obj)", SAFE_RESOURCE_MATCHER, 1);
418    }
419    if !migrated.contains(SAFE_RESOURCE_MATCHER) {
420        migrated = migrated.replacen("keyMatch(r.obj,p.obj)", SAFE_RESOURCE_MATCHER, 1);
421    }
422    if !migrated.contains("g2 = _, _, _")
423        || !migrated.contains(GUARDED_ROLE_MATCHER)
424        || !migrated.contains(SAFE_RESOURCE_MATCHER)
425        || migrated.matches(GLOBAL_ROLE_CALL).count() != 1
426    {
427        return Err(PolicyError::ValidationError(format!(
428            "{} must restrict legacy g(user, role) membership to the global '*' domain, define domain-scoped g2(user, role, domain) membership, and use separator-aware matching for federation origins",
429            model_path.display()
430        )));
431    }
432
433    write_policy_file(model_path, migrated).await?;
434    Ok(())
435}
436
437fn is_legacy_federation_origin_subject(subject: &str) -> bool {
438    subject == "*" || subject.starts_with("https://") || subject.starts_with("http://")
439}
440
441/// Move pre-hardening federation rules from the caller identity slot into the
442/// resource slot. This preserves existing per-origin allow/deny lists without
443/// making an HTTPS origin a trusted envelope subject.
444async fn migrate_federation_origin_policies(enforcer: &mut Enforcer) -> Result<bool, PolicyError> {
445    let legacy: Vec<Vec<String>> = enforcer
446        .get_policy()
447        .into_iter()
448        .filter(|rule| {
449            rule.len() == 5
450                && rule
451                    .get(2)
452                    .is_some_and(|resource| resource == "federation:register")
453                && rule
454                    .first()
455                    .is_some_and(|subject| is_legacy_federation_origin_subject(subject))
456        })
457        .collect();
458
459    if legacy.is_empty() {
460        return Ok(false);
461    }
462
463    for old_rule in legacy {
464        let origin_pattern = old_rule
465            .first()
466            .ok_or_else(|| {
467                PolicyError::ValidationError(
468                    "legacy federation rule is missing its origin subject".to_owned(),
469                )
470            })?
471            .clone();
472        let mut migrated_rule = old_rule.clone();
473        migrated_rule[0] = "*".to_owned();
474        migrated_rule[2] = federation_registration_resource(&origin_pattern)?;
475
476        enforcer
477            .remove_policy(old_rule)
478            .await
479            .map_err(PolicyError::CasbinError)?;
480        if !enforcer.get_policy().contains(&migrated_rule) {
481            enforcer
482                .add_policy(migrated_rule)
483                .await
484                .map_err(PolicyError::CasbinError)?;
485        }
486    }
487
488    Ok(true)
489}
490
491/// Policy manager wrapping Casbin enforcer
492pub struct PolicyManager {
493    /// Casbin enforcer
494    enforcer: Arc<RwLock<Enforcer>>,
495    /// Path to policies directory (.registry/policies/)
496    policies_dir: PathBuf,
497}
498
499impl PolicyManager {
500    /// Create a new PolicyManager loading policies from the given directory
501    ///
502    /// If the policies directory doesn't exist, creates it with default policies.
503    pub async fn new(policies_dir: impl AsRef<Path>) -> Result<Self, PolicyError> {
504        let policies_dir = policies_dir.as_ref().to_path_buf();
505
506        // Ensure policies directory exists with restricted permissions
507        if !policies_dir.exists() {
508            info!("Creating policies directory at {:?}", policies_dir);
509            tokio::fs::create_dir_all(&policies_dir).await?;
510            #[cfg(unix)]
511            {
512                use std::os::unix::fs::PermissionsExt;
513                tokio::fs::set_permissions(&policies_dir, std::fs::Permissions::from_mode(0o750))
514                    .await?;
515            }
516        }
517
518        let model_path = policies_dir.join("model.conf");
519        let policy_path = policies_dir.join("policy.csv");
520
521        // Create default model.conf if not exists
522        if !model_path.exists() {
523            info!("Creating default model.conf");
524            write_policy_file(&model_path, DEFAULT_MODEL_CONF).await?;
525        }
526        ensure_domain_role_model(&model_path).await?;
527
528        // Create default policy.csv if not exists
529        if !policy_path.exists() {
530            info!("Creating default policy.csv (deny-by-default — run `hyprstream quick policy apply-template <name>` to grant access; see `policy list-templates`)");
531            write_policy_file(&policy_path, default_policy_csv()).await?;
532        }
533
534        // Validate policy.csv format before loading
535        // This catches common errors like missing domain or effect columns
536        validate_policy_csv(&policy_path)?;
537
538        // Load the model
539        let model = DefaultModel::from_file(&model_path)
540            .await
541            .map_err(|e| PolicyError::ModelLoadError(e.to_string()))?;
542
543        // Create enforcer with file adapter
544        let adapter = PolicyFileAdapter::new(policy_path.clone());
545        let mut enforcer = Enforcer::new(model, adapter)
546            .await
547            .map_err(|e| PolicyError::PolicyLoadError(e.to_string()))?;
548        install_policy_functions(&mut enforcer);
549        if migrate_federation_origin_policies(&mut enforcer).await? {
550            enforcer
551                .save_policy()
552                .await
553                .map_err(|e| PolicyError::PolicySaveError(e.to_string()))?;
554        }
555
556        // Inject SERVICE_BASE_POLICIES into the in-memory enforcer.
557        // These are code-defined infrastructure rules (service key resolution,
558        // policy checks, registry access) that must always be present regardless
559        // of what's in the on-disk policy.csv.
560        //
561        // Casbin's add_policies() aborts the ENTIRE batch if ANY rule already
562        // exists (early return on first duplicate), so we must filter out
563        // rules that were already loaded from the CSV.
564        let base = base_policies_to_vec();
565        let existing = enforcer.get_policy();
566        let new_rules: Vec<Vec<String>> = base
567            .into_iter()
568            .filter(|rule| !existing.contains(rule))
569            .collect();
570        if !new_rules.is_empty() {
571            enforcer
572                .add_policies(new_rules)
573                .await
574                .map_err(PolicyError::CasbinError)?;
575        }
576
577        info!(
578            "PolicyManager initialized with {} policies",
579            enforcer.get_policy().len()
580        );
581
582        Ok(Self {
583            enforcer: Arc::new(RwLock::new(enforcer)),
584            policies_dir,
585        })
586    }
587
588    /// Create a PolicyManager with allow-all policies (for tests only).
589    ///
590    /// WARNING: Not for production use. Production uses `new()` which loads
591    /// deny-by-default policies from disk.
592    pub async fn permissive() -> Result<Self, PolicyError> {
593        // Use the same model as DEFAULT_MODEL_CONF for consistency
594        let model = DefaultModel::from_str(DEFAULT_MODEL_CONF)
595            .await
596            .map_err(|e| PolicyError::ModelLoadError(e.to_string()))?;
597
598        let adapter = MemoryAdapter::default();
599        let mut enforcer = Enforcer::new(model, adapter)
600            .await
601            .map_err(|e| PolicyError::PolicyLoadError(e.to_string()))?;
602        install_policy_functions(&mut enforcer);
603
604        // Add permissive default rule: anyone can do anything in any domain
605        enforcer
606            .add_policy(vec![
607                "*".to_owned(),     // subject
608                "*".to_owned(),     // domain
609                "*".to_owned(),     // resource
610                "*".to_owned(),     // action
611                "allow".to_owned(), // effect
612            ])
613            .await
614            .map_err(PolicyError::CasbinError)?;
615
616        Ok(Self {
617            enforcer: Arc::new(RwLock::new(enforcer)),
618            policies_dir: PathBuf::new(),
619        })
620    }
621
622    /// Create a PolicyManager with a clean in-memory adapter and no pre-seeded rules.
623    ///
624    /// Intended for unit tests that need a blank-slate enforcer (deny-by-default)
625    /// without touching the filesystem or inheriting the permissive `*` rule from
626    /// [`permissive()`].
627    ///
628    /// WARNING: Not for production use.
629    #[cfg(test)]
630    pub async fn new_in_memory() -> Result<Self, PolicyError> {
631        let model = DefaultModel::from_str(DEFAULT_MODEL_CONF)
632            .await
633            .map_err(|e| PolicyError::ModelLoadError(e.to_string()))?;
634
635        let adapter = MemoryAdapter::default();
636        let mut enforcer = Enforcer::new(model, adapter)
637            .await
638            .map_err(|e| PolicyError::PolicyLoadError(e.to_string()))?;
639        install_policy_functions(&mut enforcer);
640
641        Ok(Self {
642            enforcer: Arc::new(RwLock::new(enforcer)),
643            policies_dir: PathBuf::new(),
644        })
645    }
646
647    /// Check if a user is allowed to perform an operation on a resource
648    ///
649    /// Uses wildcard "*" for domain. For domain-specific checks, use `check_with_domain()`.
650    ///
651    /// # Arguments
652    /// * `user` - The user or role requesting access
653    /// * `resource` - The resource being accessed (e.g., "model:qwen3-small")
654    /// * `operation` - The operation being requested
655    ///
656    /// # Returns
657    /// `true` if access is allowed, `false` otherwise
658    pub async fn check(&self, user: &str, resource: &str, operation: Operation) -> bool {
659        self.check_with_domain(user, "*", resource, operation.as_str())
660            .await
661    }
662
663    /// Check if a user is allowed to perform an operation on a resource in a specific domain
664    ///
665    /// Accepts any `&str` for `operation`, supporting both classic enum-backed actions
666    /// (e.g., `"infer"`, `"train"`) and dot-namespaced actions (e.g., `"ttt.writeback"`).
667    ///
668    /// # Arguments
669    /// * `user` - The user or role requesting access
670    /// * `domain` - The domain (e.g., "HfModel", "HfDataset")
671    /// * `resource` - The resource being accessed (e.g., "model:qwen3-small")
672    /// * `operation` - The operation string (e.g., "infer", "ttt.writeback", "*")
673    ///
674    /// # Returns
675    /// `true` if access is allowed, `false` otherwise
676    pub async fn check_with_domain(
677        &self,
678        user: &str,
679        domain: &str,
680        resource: &str,
681        operation: &str,
682    ) -> bool {
683        let enforcer = self.enforcer.read().await;
684        match enforcer.enforce((user, domain, resource, operation)) {
685            Ok(allowed) => {
686                debug!(
687                    "Policy check: user={}, domain={}, resource={}, op={} -> {}",
688                    user,
689                    domain,
690                    resource,
691                    operation,
692                    if allowed { "ALLOW" } else { "DENY" }
693                );
694                allowed
695            }
696            Err(e) => {
697                warn!("Policy enforcement error: {}", e);
698                false // Deny on error
699            }
700        }
701    }
702
703    /// Synchronous policy check (blocks on the async check)
704    ///
705    /// Use this in synchronous contexts. For async code, prefer `check()`.
706    pub fn check_sync(&self, user: &str, resource: &str, operation: Operation) -> bool {
707        // Try to use existing runtime, or create a temporary one
708        if let Ok(handle) = tokio::runtime::Handle::try_current() {
709            // We're in an async context, use block_in_place
710            tokio::task::block_in_place(|| handle.block_on(self.check(user, resource, operation)))
711        } else {
712            // No runtime, create a temporary one (less efficient)
713            let rt = tokio::runtime::Runtime::new().ok();
714            rt.map(|rt| rt.block_on(self.check(user, resource, operation)))
715                .unwrap_or(false)
716        }
717    }
718
719    /// Check multiple operations at once, returning a bitmask
720    pub async fn check_all(&self, user: &str, resource: &str) -> u32 {
721        let mut mask = 0u32;
722        for op in Operation::all() {
723            if self.check(user, resource, *op).await {
724                mask |= 1 << (op.code() as u32 - 'a' as u32);
725            }
726        }
727        mask
728    }
729
730    /// Add a policy rule (uses wildcard "*" for domain, "allow" for effect)
731    ///
732    /// For domain-specific policies, use `add_policy_with_domain()`.
733    ///
734    /// All inputs are validated for:
735    /// - Maximum length (256 characters)
736    /// - No null bytes
737    /// - No line breaks (CSV injection prevention)
738    pub async fn add_policy(
739        &self,
740        user: &str,
741        resource: &str,
742        operation: &str,
743    ) -> Result<bool, PolicyError> {
744        self.add_policy_with_domain(user, "*", resource, operation, "allow")
745            .await
746    }
747
748    /// Add a policy rule with domain and effect
749    ///
750    /// # Arguments
751    /// * `user` - The user or role this policy applies to
752    /// * `domain` - The domain (e.g., "HfModel", "HfDataset", "*" for all)
753    /// * `resource` - The resource pattern (e.g., "model:*", "data:sales-*")
754    /// * `operation` - The operation (e.g., "infer", "train", "*" for all)
755    /// * `effect` - "allow" or "deny"
756    pub async fn add_policy_with_domain(
757        &self,
758        user: &str,
759        domain: &str,
760        resource: &str,
761        operation: &str,
762        effect: &str,
763    ) -> Result<bool, PolicyError> {
764        let migrated_resource;
765        let (user, resource) =
766            if resource == "federation:register" && is_legacy_federation_origin_subject(user) {
767                migrated_resource = federation_registration_resource(user)?;
768                ("*", migrated_resource.as_str())
769            } else {
770                (user, resource)
771            };
772
773        // Validate all inputs
774        validate_policy_component(user, "user")?;
775        validate_policy_component(domain, "domain")?;
776        validate_policy_component(resource, "resource")?;
777        validate_policy_component(operation, "operation")?;
778        validate_policy_component(effect, "effect")?;
779
780        // Validate effect is "allow" or "deny"
781        if effect != "allow" && effect != "deny" {
782            return Err(PolicyError::ValidationError(
783                "effect must be 'allow' or 'deny'".to_owned(),
784            ));
785        }
786
787        let mut enforcer = self.enforcer.write().await;
788        enforcer
789            .add_policy(vec![
790                user.to_owned(),
791                domain.to_owned(),
792                resource.to_owned(),
793                operation.to_owned(),
794                effect.to_owned(),
795            ])
796            .await
797            .map_err(PolicyError::CasbinError)
798    }
799
800    /// Remove a policy rule (uses wildcard "*" for domain, "allow" for effect)
801    ///
802    /// For domain-specific policies, use `remove_policy_with_domain()`.
803    pub async fn remove_policy(
804        &self,
805        user: &str,
806        resource: &str,
807        operation: &str,
808    ) -> Result<bool, PolicyError> {
809        self.remove_policy_with_domain(user, "*", resource, operation, "allow")
810            .await
811    }
812
813    /// Remove a policy rule with domain and effect
814    ///
815    /// All inputs are validated for security.
816    pub async fn remove_policy_with_domain(
817        &self,
818        user: &str,
819        domain: &str,
820        resource: &str,
821        operation: &str,
822        effect: &str,
823    ) -> Result<bool, PolicyError> {
824        let migrated_resource;
825        let (user, resource) =
826            if resource == "federation:register" && is_legacy_federation_origin_subject(user) {
827                migrated_resource = federation_registration_resource(user)?;
828                ("*", migrated_resource.as_str())
829            } else {
830                (user, resource)
831            };
832
833        // Validate all inputs
834        validate_policy_component(user, "user")?;
835        validate_policy_component(domain, "domain")?;
836        validate_policy_component(resource, "resource")?;
837        validate_policy_component(operation, "operation")?;
838        validate_policy_component(effect, "effect")?;
839
840        let mut enforcer = self.enforcer.write().await;
841        enforcer
842            .remove_policy(vec![
843                user.to_owned(),
844                domain.to_owned(),
845                resource.to_owned(),
846                operation.to_owned(),
847                effect.to_owned(),
848            ])
849            .await
850            .map_err(PolicyError::CasbinError)
851    }
852
853    /// Add a role for a user
854    ///
855    /// All inputs are validated for security.
856    pub async fn add_role_for_user(&self, user: &str, role: &str) -> Result<bool, PolicyError> {
857        // Validate all inputs
858        validate_policy_component(user, "user")?;
859        validate_policy_component(role, "role")?;
860
861        let mut enforcer = self.enforcer.write().await;
862        enforcer
863            .add_grouping_policy(vec![user.to_owned(), role.to_owned()])
864            .await
865            .map_err(PolicyError::CasbinError)
866    }
867
868    /// Remove a role from a user
869    ///
870    /// All inputs are validated for security.
871    pub async fn remove_role_for_user(&self, user: &str, role: &str) -> Result<bool, PolicyError> {
872        // Validate all inputs
873        validate_policy_component(user, "user")?;
874        validate_policy_component(role, "role")?;
875
876        let mut enforcer = self.enforcer.write().await;
877        enforcer
878            .remove_grouping_policy(vec![user.to_owned(), role.to_owned()])
879            .await
880            .map_err(PolicyError::CasbinError)
881    }
882
883    /// Add a role membership scoped to one verified tenant/domain.
884    pub async fn add_role_for_user_in_domain(
885        &self,
886        user: &str,
887        role: &str,
888        domain: &str,
889    ) -> Result<bool, PolicyError> {
890        validate_policy_component(user, "user")?;
891        validate_policy_component(role, "role")?;
892        validate_policy_component(domain, "domain")?;
893
894        let mut enforcer = self.enforcer.write().await;
895        enforcer
896            .add_named_grouping_policy(
897                "g2",
898                vec![user.to_owned(), role.to_owned(), domain.to_owned()],
899            )
900            .await
901            .map_err(PolicyError::CasbinError)
902    }
903
904    /// Remove only the role membership belonging to one tenant/domain.
905    pub async fn remove_role_for_user_in_domain(
906        &self,
907        user: &str,
908        role: &str,
909        domain: &str,
910    ) -> Result<bool, PolicyError> {
911        validate_policy_component(user, "user")?;
912        validate_policy_component(role, "role")?;
913        validate_policy_component(domain, "domain")?;
914
915        let mut enforcer = self.enforcer.write().await;
916        enforcer
917            .remove_named_grouping_policy(
918                "g2",
919                vec![user.to_owned(), role.to_owned(), domain.to_owned()],
920            )
921            .await
922            .map_err(PolicyError::CasbinError)
923    }
924
925    /// Get domain-scoped role membership records (`user`, `role`, `domain`).
926    pub async fn get_domain_grouping_policy(&self) -> Vec<Vec<String>> {
927        let enforcer = self.enforcer.read().await;
928        enforcer.get_named_grouping_policy("g2")
929    }
930
931    /// Get all roles for a user
932    pub async fn get_roles_for_user(&self, user: &str) -> Vec<String> {
933        let enforcer = self.enforcer.read().await;
934        enforcer.get_roles_for_user(user, None)
935    }
936
937    /// Get all users with a role
938    pub async fn get_users_for_role(&self, role: &str) -> Vec<String> {
939        let enforcer = self.enforcer.read().await;
940        enforcer.get_users_for_role(role, None)
941    }
942
943    /// Get all policy rules
944    pub async fn get_policy(&self) -> Vec<Vec<String>> {
945        let enforcer = self.enforcer.read().await;
946        enforcer.get_policy()
947    }
948
949    /// Get all grouping rules (role assignments)
950    pub async fn get_grouping_policy(&self) -> Vec<Vec<String>> {
951        let enforcer = self.enforcer.read().await;
952        enforcer.get_grouping_policy()
953    }
954
955    /// Save policies to disk
956    pub async fn save(&self) -> Result<(), PolicyError> {
957        let mut enforcer = self.enforcer.write().await;
958        enforcer
959            .save_policy()
960            .await
961            .map_err(|e| PolicyError::PolicySaveError(e.to_string()))?;
962        Ok(())
963    }
964
965    /// Reload policies from disk and re-inject base rules.
966    ///
967    /// `load_policy()` wipes in-memory additions, so base rules must be
968    /// re-injected after every reload to guarantee they're always present.
969    pub async fn reload(&self) -> Result<(), PolicyError> {
970        let mut enforcer = self.enforcer.write().await;
971        enforcer
972            .load_policy()
973            .await
974            .map_err(|e| PolicyError::PolicyLoadError(e.to_string()))?;
975        if migrate_federation_origin_policies(&mut enforcer).await? {
976            enforcer
977                .save_policy()
978                .await
979                .map_err(|e| PolicyError::PolicySaveError(e.to_string()))?;
980        }
981        // Filter out rules already loaded from CSV (Casbin add_policies
982        // aborts the entire batch on first duplicate).
983        let base = base_policies_to_vec();
984        let existing = enforcer.get_policy();
985        let new_rules: Vec<Vec<String>> = base
986            .into_iter()
987            .filter(|rule| !existing.contains(rule))
988            .collect();
989        if !new_rules.is_empty() {
990            enforcer
991                .add_policies(new_rules)
992                .await
993                .map_err(PolicyError::CasbinError)?;
994        }
995        Ok(())
996    }
997
998    /// Apply a template's policies and groupings to the enforcer, then persist to disk.
999    ///
1000    /// Uses the Casbin enforcer's `add_policies()` + `add_grouping_policies()` APIs,
1001    /// then calls `save_policy()` to write everything (including base rules) to disk.
1002    pub async fn apply_template(
1003        &self,
1004        template: &crate::auth::policy_templates::PolicyTemplate,
1005    ) -> Result<(), PolicyError> {
1006        let policies = template.expanded_policies();
1007        let tenant_domains: std::collections::BTreeSet<&str> = policies
1008            .iter()
1009            .map(|policy| policy.domain)
1010            .filter(|domain| *domain != "*")
1011            .collect();
1012        if template.groupings.is_some() && tenant_domains.len() > 1 {
1013            return Err(PolicyError::ValidationError(format!(
1014                "template '{}' has role assignments spanning multiple tenant domains",
1015                template.name
1016            )));
1017        }
1018
1019        // Validate the complete template before mutating the enforcer so a
1020        // rejected multi-tenant grouping cannot leave partial policy rows.
1021        let mut enforcer = self.enforcer.write().await;
1022
1023        // Add policy rules
1024        let existing_policies = enforcer.get_policy();
1025        let policy_vecs: Vec<Vec<String>> = policies
1026            .iter()
1027            .map(ServicePolicyRule::to_vec)
1028            .filter(|rule| !existing_policies.contains(rule))
1029            .collect();
1030        if !policy_vecs.is_empty() {
1031            enforcer
1032                .add_policies(policy_vecs)
1033                .await
1034                .map_err(PolicyError::CasbinError)?;
1035        }
1036
1037        // Add grouping rules. A template whose policies name one concrete
1038        // tenant gets g2 memberships in that tenant. Global/role-alias
1039        // templates retain g memberships, which the model evaluates only when
1040        // the verified request domain itself is `*`.
1041        if let Some(groupings) = template.groupings {
1042            if let Some(domain) = tenant_domains.first() {
1043                let existing_groupings = enforcer.get_named_grouping_policy("g2");
1044                for grouping in groupings {
1045                    let grouping = vec![
1046                        grouping.user.to_owned(),
1047                        grouping.role.to_owned(),
1048                        (*domain).to_owned(),
1049                    ];
1050                    if existing_groupings.contains(&grouping) {
1051                        continue;
1052                    }
1053                    enforcer
1054                        .add_named_grouping_policy("g2", grouping)
1055                        .await
1056                        .map_err(PolicyError::CasbinError)?;
1057                }
1058            } else {
1059                let existing_groupings = enforcer.get_grouping_policy();
1060                let grouping_vecs: Vec<Vec<String>> = groupings
1061                    .iter()
1062                    .map(ServiceGrouping::to_vec)
1063                    .filter(|grouping| !existing_groupings.contains(grouping))
1064                    .collect();
1065                if !grouping_vecs.is_empty() {
1066                    enforcer
1067                        .add_grouping_policies(grouping_vecs)
1068                        .await
1069                        .map_err(PolicyError::CasbinError)?;
1070                }
1071            }
1072        }
1073
1074        // Persist full enforcer state (base + template) to disk via FileAdapter
1075        enforcer
1076            .save_policy()
1077            .await
1078            .map_err(|e| PolicyError::PolicySaveError(e.to_string()))?;
1079
1080        Ok(())
1081    }
1082
1083    /// Get the policies directory path
1084    pub fn policies_dir(&self) -> &Path {
1085        &self.policies_dir
1086    }
1087
1088    /// Get the model.conf path
1089    pub fn model_conf_path(&self) -> PathBuf {
1090        self.policies_dir.join("model.conf")
1091    }
1092
1093    /// Get the policy.csv path
1094    pub fn policy_csv_path(&self) -> PathBuf {
1095        self.policies_dir.join("policy.csv")
1096    }
1097
1098    /// Format policies as a human-readable string for display
1099    pub async fn format_policy(&self) -> String {
1100        let policies = self.get_policy().await;
1101        let groupings = self.get_grouping_policy().await;
1102        let domain_groupings = self.get_domain_grouping_policy().await;
1103
1104        let mut output = String::new();
1105
1106        if !policies.is_empty() {
1107            output.push_str("# Policy Rules\n");
1108            for p in &policies {
1109                output.push_str(&format!("p, {}\n", p.join(", ")));
1110            }
1111        }
1112
1113        if !groupings.is_empty() {
1114            if !output.is_empty() {
1115                output.push('\n');
1116            }
1117            output.push_str("# Role Assignments\n");
1118            for g in &groupings {
1119                output.push_str(&format!("g, {}\n", g.join(", ")));
1120            }
1121        }
1122
1123        if !domain_groupings.is_empty() {
1124            if !output.is_empty() {
1125                output.push('\n');
1126            }
1127            output.push_str("# Domain Role Assignments\n");
1128            for grouping in &domain_groupings {
1129                output.push_str(&format!("g2, {}\n", grouping.join(", ")));
1130            }
1131        }
1132
1133        if output.is_empty() {
1134            output.push_str("# No policies defined\n");
1135        }
1136
1137        output
1138    }
1139}
1140
1141#[cfg(test)]
1142mod tests {
1143    use super::*;
1144    use tempfile::TempDir;
1145
1146    #[tokio::test]
1147    async fn test_permissive_policy_manager() -> Result<(), PolicyError> {
1148        let pm = PolicyManager::permissive().await?;
1149
1150        // Permissive policy allows everything
1151        assert!(pm.check("anyone", "anything", Operation::Infer).await);
1152        assert!(pm.check("user", "model:test", Operation::Train).await);
1153        Ok(())
1154    }
1155
1156    #[tokio::test]
1157    async fn test_policy_manager_from_dir() -> Result<(), PolicyError> {
1158        let temp = TempDir::new().map_err(PolicyError::IoError)?;
1159        let policies_dir = temp.path().join("policies");
1160
1161        // Create policy manager (should create default files)
1162        let pm = PolicyManager::new(&policies_dir).await?;
1163
1164        // Default policy is deny-all — no access until explicitly configured
1165        assert!(!pm.check("user", "model:test", Operation::Infer).await);
1166        assert!(
1167            !pm.check("local:alice", "model:test", Operation::Infer)
1168                .await
1169        );
1170
1171        // Verify files were created
1172        assert!(policies_dir.join("model.conf").exists());
1173        assert!(policies_dir.join("policy.csv").exists());
1174
1175        // After adding explicit policy, access should work
1176        pm.add_policy("user", "model:test", "infer.generate")
1177            .await?;
1178        assert!(pm.check("user", "model:test", Operation::Infer).await);
1179        Ok(())
1180    }
1181
1182    #[tokio::test]
1183    async fn test_add_and_check_policy() -> Result<(), PolicyError> {
1184        let pm = PolicyManager::permissive().await?;
1185
1186        // Remove the default permissive rule
1187        pm.remove_policy("*", "*", "*").await?;
1188
1189        // Now access should be denied
1190        assert!(!pm.check("user", "model:test", Operation::Infer).await);
1191
1192        // Add specific policy
1193        pm.add_policy("user", "model:test", "infer.generate")
1194            .await?;
1195
1196        // Now this specific access should work
1197        assert!(pm.check("user", "model:test", Operation::Infer).await);
1198        // But not other operations
1199        assert!(!pm.check("user", "model:test", Operation::Train).await);
1200        Ok(())
1201    }
1202
1203    #[tokio::test]
1204    async fn test_role_based_access() -> Result<(), PolicyError> {
1205        let pm = PolicyManager::permissive().await?;
1206
1207        // Remove permissive rule
1208        pm.remove_policy("*", "*", "*").await?;
1209
1210        // Add role-based policies
1211        pm.add_policy("trainer", "model:*", "infer.generate")
1212            .await?;
1213        pm.add_policy("trainer", "model:*", "ttt.train").await?;
1214
1215        // Assign role to user
1216        pm.add_role_for_user("alice", "trainer").await?;
1217
1218        // Alice should have trainer permissions
1219        assert!(pm.check("alice", "model:test", Operation::Infer).await);
1220        assert!(pm.check("alice", "model:test", Operation::Train).await);
1221
1222        // Bob without role should not
1223        assert!(!pm.check("bob", "model:test", Operation::Infer).await);
1224        Ok(())
1225    }
1226
1227    #[tokio::test]
1228    async fn cross_tenant_global_role_mutation_is_denied() -> Result<(), PolicyError> {
1229        let pm = PolicyManager::new_in_memory().await?;
1230        for tenant in ["tenant-a", "tenant-b"] {
1231            pm.add_policy_with_domain("trainer", tenant, "model:*", "infer.generate", "allow")
1232                .await?;
1233        }
1234
1235        pm.add_role_for_user_in_domain("alice", "trainer", "tenant-a")
1236            .await?;
1237
1238        assert!(
1239            pm.check_with_domain("alice", "tenant-a", "model:test", "infer.generate")
1240                .await
1241        );
1242        assert!(
1243            !pm.check_with_domain("alice", "tenant-b", "model:test", "infer.generate")
1244                .await,
1245            "tenant-a role membership must not authorize tenant-b"
1246        );
1247        assert!(
1248            pm.get_grouping_policy().await.is_empty(),
1249            "mutable assignment must not create a global g(user, role) entry"
1250        );
1251        assert_eq!(
1252            pm.get_domain_grouping_policy().await,
1253            vec![vec![
1254                "alice".to_owned(),
1255                "trainer".to_owned(),
1256                "tenant-a".to_owned()
1257            ]]
1258        );
1259
1260        assert!(
1261            !pm.remove_role_for_user_in_domain("alice", "trainer", "tenant-b")
1262                .await?,
1263            "tenant-b removal must not delete tenant-a membership"
1264        );
1265        assert!(
1266            pm.check_with_domain("alice", "tenant-a", "model:test", "infer.generate")
1267                .await
1268        );
1269        Ok(())
1270    }
1271
1272    #[tokio::test]
1273    async fn legacy_global_role_grant_is_inert_in_tenant_domains() -> Result<(), PolicyError> {
1274        let pm = PolicyManager::new_in_memory().await?;
1275        for tenant in ["tenant-a", "tenant-b"] {
1276            pm.add_policy_with_domain("operator", tenant, "model:*", "ttt.writeback", "allow")
1277                .await?;
1278        }
1279
1280        // Simulate a pre-#1196 g(user, role) row already present in policy.csv.
1281        pm.add_role_for_user("alice", "operator").await?;
1282
1283        for tenant in ["tenant-a", "tenant-b"] {
1284            assert!(
1285                !pm.check_with_domain("alice", tenant, "model:test", "ttt.writeback")
1286                    .await,
1287                "legacy global role membership must not authorize tenant {tenant}"
1288            );
1289        }
1290
1291        pm.add_role_for_user_in_domain("alice", "operator", "tenant-a")
1292            .await?;
1293        assert!(
1294            pm.check_with_domain("alice", "tenant-a", "model:test", "ttt.writeback")
1295                .await
1296        );
1297        assert!(
1298            !pm.check_with_domain("alice", "tenant-b", "model:test", "ttt.writeback")
1299                .await
1300        );
1301        Ok(())
1302    }
1303
1304    #[test]
1305    fn federation_origin_wildcards_are_dns_label_scoped_and_fail_closed() {
1306        let pattern = "https://*.partner.example";
1307        assert!(federation_origin_pattern_matches(
1308            "https://app.partner.example",
1309            pattern
1310        ));
1311        assert!(federation_origin_pattern_matches(
1312            "https://deep.app.partner.example",
1313            pattern
1314        ));
1315        for denied in [
1316            "https://partner.example",
1317            "https://blocked.example",
1318            "https://app.partner.example.evil",
1319            "http://app.partner.example",
1320            "https://app.partner.example:8443",
1321        ] {
1322            assert!(
1323                !federation_origin_pattern_matches(denied, pattern),
1324                "{denied} must not match {pattern}"
1325            );
1326        }
1327        assert!(!federation_origin_pattern_matches(
1328            "https://app.partner.example",
1329            "https://*.*.partner.example"
1330        ));
1331        assert!(federation_origin_pattern_matches(
1332            "https://[::1]:8443",
1333            "https://[::1]:8443"
1334        ));
1335        assert!(!federation_resource_matches(
1336            "federation:register:https://app.partner.example",
1337            "federation:register"
1338        ));
1339    }
1340
1341    #[tokio::test]
1342    async fn legacy_federation_origin_rule_is_migrated_to_resource() -> Result<(), PolicyError> {
1343        let temp = TempDir::new().map_err(PolicyError::IoError)?;
1344        let policies_dir = temp.path().join("policies");
1345        tokio::fs::create_dir_all(&policies_dir).await?;
1346        write_policy_file(&policies_dir.join("model.conf"), DEFAULT_MODEL_CONF).await?;
1347        write_policy_file(
1348            &policies_dir.join("policy.csv"),
1349            "p, https://allowed.example, *, federation:register, check, allow\n\
1350             p, https://*.partner.example, *, federation:register, check, allow\n",
1351        )
1352        .await?;
1353
1354        let pm = PolicyManager::new(&policies_dir).await?;
1355        let allowed = federation_registration_resource("https://allowed.example")?;
1356        let wildcard_allowed = federation_registration_resource("https://app.partner.example")?;
1357        let blocked = federation_registration_resource("https://blocked.example")?;
1358
1359        assert!(
1360            pm.check_with_domain("service:oauth", "*", &allowed, "check")
1361                .await,
1362            "the migrated decision must still admit its configured origin"
1363        );
1364        assert!(
1365            pm.check_with_domain("service:oauth", "*", &wildcard_allowed, "check")
1366                .await,
1367            "migrated wildcard origin patterns must remain effective"
1368        );
1369        assert!(
1370            !pm.check_with_domain("service:oauth", "*", &blocked, "check")
1371                .await,
1372            "the decision must vary by origin instead of the deputy service"
1373        );
1374
1375        let policies = pm.get_policy().await;
1376        assert!(policies.iter().any(|rule| {
1377            rule == &vec![
1378                "*".to_owned(),
1379                "*".to_owned(),
1380                allowed.clone(),
1381                "check".to_owned(),
1382                "allow".to_owned(),
1383            ]
1384        }));
1385        assert!(!policies.iter().any(|rule| {
1386            rule.first()
1387                .is_some_and(|subject| subject.starts_with("https://"))
1388                && rule
1389                    .get(2)
1390                    .is_some_and(|resource| resource == "federation:register")
1391        }));
1392        Ok(())
1393    }
1394
1395    #[tokio::test]
1396    async fn legacy_model_is_migrated_before_global_roles_are_loaded() -> Result<(), PolicyError> {
1397        let temp = TempDir::new().map_err(PolicyError::IoError)?;
1398        let policies_dir = temp.path().join("policies");
1399        tokio::fs::create_dir_all(&policies_dir).await?;
1400        let legacy_model = DEFAULT_MODEL_CONF.replace(
1401            "m = ((r.dom == \"*\" && g(r.sub, p.sub)) || g2(r.sub, p.sub, r.dom) || keyMatch(r.sub, p.sub))",
1402            "m = (g(r.sub, p.sub) || g2(r.sub, p.sub, r.dom) || keyMatch(r.sub, p.sub))",
1403        );
1404        write_policy_file(&policies_dir.join("model.conf"), legacy_model).await?;
1405        write_policy_file(
1406            &policies_dir.join("policy.csv"),
1407            "p, operator, tenant-a, model:*, ttt.writeback, allow\n\
1408             p, operator, tenant-b, model:*, ttt.writeback, allow\n\
1409             g, alice, operator\n",
1410        )
1411        .await?;
1412
1413        let pm = PolicyManager::new(&policies_dir).await?;
1414        let migrated = tokio::fs::read_to_string(policies_dir.join("model.conf")).await?;
1415        assert!(migrated.contains("r.dom == \"*\" && g(r.sub, p.sub)"));
1416        for tenant in ["tenant-a", "tenant-b"] {
1417            assert!(
1418                !pm.check_with_domain("alice", tenant, "model:test", "ttt.writeback")
1419                    .await,
1420                "loaded legacy grant must be inert in tenant {tenant}"
1421            );
1422        }
1423        Ok(())
1424    }
1425
1426    #[tokio::test]
1427    async fn multiple_identities_share_only_their_tenant_grant() -> Result<(), PolicyError> {
1428        let pm = PolicyManager::new_in_memory().await?;
1429        pm.add_policy_with_domain("*", "tenant-a", "event:orders", "subscribe", "allow")
1430            .await?;
1431
1432        for identity in ["alice", "bob"] {
1433            assert!(
1434                pm.check_with_domain(identity, "tenant-a", "event:orders", "subscribe")
1435                    .await,
1436                "{identity} should receive the shared tenant-a grant"
1437            );
1438            assert!(
1439                !pm.check_with_domain(identity, "tenant-b", "event:orders", "subscribe")
1440                    .await,
1441                "{identity} must not receive the tenant-a grant in tenant-b"
1442            );
1443        }
1444        Ok(())
1445    }
1446
1447    #[tokio::test]
1448    async fn test_format_policy() -> Result<(), PolicyError> {
1449        let pm = PolicyManager::permissive().await?;
1450
1451        pm.add_policy("operator", "*", "*").await?;
1452        pm.add_role_for_user("alice", "operator").await?;
1453
1454        let formatted = pm.format_policy().await;
1455        assert!(formatted.contains("Policy Rules"));
1456        assert!(formatted.contains("operator"));
1457        assert!(formatted.contains("Role Assignments"));
1458        assert!(formatted.contains("alice"));
1459        Ok(())
1460    }
1461
1462    #[tokio::test]
1463    async fn test_input_validation_rejects_null_bytes() -> Result<(), PolicyError> {
1464        let pm = PolicyManager::permissive().await?;
1465
1466        // Null bytes should be rejected
1467        let result = pm.add_policy("user\0evil", "model:test", "infer").await;
1468        assert!(matches!(result, Err(PolicyError::ValidationError(_))));
1469
1470        let result = pm.add_policy("user", "model:test\0evil", "infer").await;
1471        assert!(matches!(result, Err(PolicyError::ValidationError(_))));
1472        Ok(())
1473    }
1474
1475    #[tokio::test]
1476    async fn test_input_validation_rejects_line_breaks() -> Result<(), PolicyError> {
1477        let pm = PolicyManager::permissive().await?;
1478
1479        // Line breaks should be rejected (CSV injection)
1480        let result = pm
1481            .add_policy("user\np, evil, *, *", "model:test", "infer")
1482            .await;
1483        assert!(matches!(result, Err(PolicyError::ValidationError(_))));
1484
1485        let result = pm.add_role_for_user("user\revil", "operator").await;
1486        assert!(matches!(result, Err(PolicyError::ValidationError(_))));
1487        Ok(())
1488    }
1489
1490    #[tokio::test]
1491    async fn test_input_validation_rejects_long_strings() -> Result<(), PolicyError> {
1492        let pm = PolicyManager::permissive().await?;
1493
1494        // Strings over 256 chars should be rejected
1495        let long_string = "a".repeat(257);
1496        let result = pm.add_policy(&long_string, "model:test", "infer").await;
1497        assert!(matches!(result, Err(PolicyError::ValidationError(_))));
1498        Ok(())
1499    }
1500
1501    #[tokio::test]
1502    async fn test_input_validation_accepts_valid_input() -> Result<(), PolicyError> {
1503        let pm = PolicyManager::permissive().await?;
1504
1505        // Valid inputs should work
1506        assert!(pm
1507            .add_policy("user-123", "model:qwen3-*", "infer")
1508            .await
1509            .is_ok());
1510        assert!(pm.add_role_for_user("alice_test", "trainer").await.is_ok());
1511        Ok(())
1512    }
1513
1514    #[tokio::test]
1515    #[allow(clippy::unwrap_used)]
1516    async fn test_act_wildcard_keymatch() {
1517        let pm = PolicyManager::new_in_memory().await.unwrap();
1518        pm.add_policy_with_domain("alice", "*", "model:qwen3-small:main", "ttt.*", "allow")
1519            .await
1520            .unwrap();
1521        // Specific action should match the wildcard
1522        assert!(
1523            pm.check_with_domain("alice", "*", "model:qwen3-small:main", "ttt.writeback")
1524                .await
1525        );
1526        assert!(
1527            pm.check_with_domain("alice", "*", "model:qwen3-small:main", "ttt.evict")
1528                .await
1529        );
1530        // Different namespace should NOT match
1531        assert!(
1532            !pm.check_with_domain("alice", "*", "model:qwen3-small:main", "infer.generate")
1533                .await
1534        );
1535    }
1536
1537    #[tokio::test]
1538    #[allow(clippy::unwrap_used)]
1539    async fn test_set_branch_visibility_adds_removes_rules() {
1540        let pm = PolicyManager::new_in_memory().await.unwrap();
1541
1542        // Grant alice manage (ttt.writeback) on the model resource
1543        pm.add_policy_with_domain("alice", "*", "model:qwen3:main", "ttt.writeback", "allow")
1544            .await
1545            .unwrap();
1546
1547        // Initially bob cannot infer
1548        assert!(
1549            !pm.check_with_domain("bob", "*", "model:qwen3:main", "infer.generate")
1550                .await
1551        );
1552
1553        // Make public: add wildcard infer + query rules
1554        pm.add_policy_with_domain("*", "*", "model:qwen3:main", "infer.generate", "allow")
1555            .await
1556            .unwrap();
1557        pm.add_policy_with_domain("*", "*", "model:qwen3:main", "query.status", "allow")
1558            .await
1559            .unwrap();
1560
1561        // After making public, any user can infer and query
1562        assert!(
1563            pm.check_with_domain("bob", "*", "model:qwen3:main", "infer.generate")
1564                .await
1565        );
1566        assert!(
1567            pm.check_with_domain("carol", "*", "model:qwen3:main", "query.status")
1568                .await
1569        );
1570
1571        // Make private: remove wildcard rules
1572        pm.remove_policy_with_domain("*", "*", "model:qwen3:main", "infer.generate", "allow")
1573            .await
1574            .unwrap();
1575        pm.remove_policy_with_domain("*", "*", "model:qwen3:main", "query.status", "allow")
1576            .await
1577            .unwrap();
1578
1579        // After making private, unauthenticated users are denied again
1580        assert!(
1581            !pm.check_with_domain("bob", "*", "model:qwen3:main", "infer.generate")
1582                .await
1583        );
1584        assert!(
1585            !pm.check_with_domain("carol", "*", "model:qwen3:main", "query.status")
1586                .await
1587        );
1588
1589        // Alice still has manage access (her rule was not removed)
1590        assert!(
1591            pm.check_with_domain("alice", "*", "model:qwen3:main", "ttt.writeback")
1592                .await
1593        );
1594    }
1595
1596    /// Verify that SERVICE_BASE_POLICIES are injected on init and allow
1597    /// service-to-service authorization (the exact scenario that broke OAuth startup).
1598    #[tokio::test]
1599    #[allow(clippy::unwrap_used)]
1600    async fn test_base_rules_injected_on_init() {
1601        let temp = TempDir::new().map_err(PolicyError::IoError).unwrap();
1602        let policies_dir = temp.path().join("policies");
1603
1604        let pm = PolicyManager::new(&policies_dir).await.unwrap();
1605
1606        // The OAuth startup failure: service:oauth cannot query on policy.
1607        // The dispatch codegen now passes resource="policy:ResolveServiceKey"
1608        // for struct-type RPCs. Base rules use "policy:*" which keyMatch matches.
1609        assert!(
1610            pm.check_with_domain("service:oauth", "*", "policy:ResolveServiceKey", "query")
1611                .await,
1612            "service:oauth should be able to query policy:ResolveServiceKey via base rules"
1613        );
1614
1615        // OAuth's public browser-provisioning route uses its own resolver to
1616        // project only Registry and Model accepted-current reach.
1617        for service in ["registry", "model"] {
1618            assert!(
1619                pm.check_with_domain(
1620                    "service:oauth",
1621                    "*",
1622                    &format!("discovery:{service}"),
1623                    "query"
1624                )
1625                .await,
1626                "service:oauth must resolve {service} for browser provisioning"
1627            );
1628        }
1629        // Every policy-dependent service (OAuth and Registry included) must
1630        // resolve the Policy endpoint for the fail-closed revocation/session
1631        // authority probe and for policy checks. Endpoint resolution only.
1632        for service in ["oauth", "registry"] {
1633            assert!(
1634                pm.check_with_domain(
1635                    &format!("service:{service}"),
1636                    "*",
1637                    "discovery:policy",
1638                    "query"
1639                )
1640                .await,
1641                "service:{service} must resolve discovery:policy for the authority probe"
1642            );
1643        }
1644        // Browser provisioning still must not grant arbitrary Discovery
1645        // queries: OAuth resolves only the staging records it projects.
1646        assert!(
1647            !pm.check_with_domain("service:oauth", "*", "discovery:event", "query")
1648                .await,
1649            "browser provisioning must not grant arbitrary Discovery queries"
1650        );
1651
1652        // MCP's infrastructure resolver queries Model before forwarding the
1653        // holder's delegated bearer on the Model RPC request.
1654        assert!(
1655            pm.check_with_domain("service:mcp", "*", "discovery:model", "query")
1656                .await
1657        );
1658        for (subject, resource, operation) in [
1659            ("service:mcp", "discovery:model", "write"),
1660            ("service:mcp", "discovery:registry", "query"),
1661            ("service:mcp", "model:Status", "query"),
1662            ("service:mcp", "model:Infer", "infer"),
1663            ("service:registry", "discovery:model", "query"),
1664        ] {
1665            assert!(
1666                !pm.check_with_domain(subject, "*", resource, operation)
1667                    .await,
1668                "unexpected base policy grant: {subject} {operation} {resource}"
1669            );
1670        }
1671
1672        // Other service grants from SERVICE_BASE_POLICIES
1673        assert!(
1674            pm.check_with_domain("service:policy", "*", "policy:IssueToken", "manage")
1675                .await
1676        );
1677        // The OAuth token issuance path: service:oauth must be able to issue tokens via
1678        // its exact service grant. Action must be
1679        // "manage" (not Operation::Manage.as_str() which returns "ttt.writeback").
1680        assert!(
1681            pm.check_with_domain("service:oauth", "*", "policy:IssueToken", "manage")
1682                .await,
1683            "service:oauth must be allowed to issue tokens"
1684        );
1685        for caller in [
1686            "service:discovery",
1687            "service:model",
1688            "service:registry",
1689            "service:unknown",
1690        ] {
1691            assert!(
1692                !pm.check_with_domain(caller, "*", "policy:IssueToken", "manage")
1693                    .await,
1694                "ordinary workload {caller} must not mint arbitrary credentials"
1695            );
1696            for resource in ["oauth:AddPubkey", "oauth:RemoveUser"] {
1697                assert!(
1698                    !pm.check_with_domain(caller, "*", resource, "manage").await,
1699                    "ordinary workload {caller} must not administer accounts"
1700                );
1701            }
1702        }
1703        assert!(
1704            pm.check_with_domain("service:model", "*", "policy:Check", "check")
1705                .await
1706        );
1707        assert!(
1708            pm.check_with_domain("service:model", "*", "registry:ListModels", "infer")
1709                .await
1710        );
1711        assert!(
1712            pm.check_with_domain("service:oai", "*", "model:Generate", "infer.generate")
1713                .await
1714        );
1715
1716        // Non-granted service should be denied
1717        assert!(
1718            !pm.check_with_domain("service:unknown", "*", "policy:ResolveServiceKey", "query")
1719                .await
1720        );
1721    }
1722
1723    /// Reproduce the exact server failure: load from the production policy.csv
1724    /// and verify service:oauth can query policy:ResolveServiceKey.
1725    #[tokio::test]
1726    #[allow(clippy::unwrap_used, clippy::print_stderr)]
1727    async fn test_production_policy_csv_oauth_query() {
1728        let prod_path = std::path::Path::new(
1729            "/home/birdetta/.local/share/hyprstream/models/.registry/policies",
1730        );
1731        if !prod_path.exists() {
1732            eprintln!("Skipping: production policy dir not found");
1733            return;
1734        }
1735
1736        // Copy production files to temp dir to avoid mutating real data
1737        let temp = TempDir::new().map_err(PolicyError::IoError).unwrap();
1738        let temp_policies = temp.path().join("policies");
1739        tokio::fs::create_dir_all(&temp_policies).await.unwrap();
1740        tokio::fs::copy(
1741            prod_path.join("model.conf"),
1742            temp_policies.join("model.conf"),
1743        )
1744        .await
1745        .unwrap();
1746        tokio::fs::copy(
1747            prod_path.join("policy.csv"),
1748            temp_policies.join("policy.csv"),
1749        )
1750        .await
1751        .unwrap();
1752
1753        let pm = PolicyManager::new(&temp_policies).await.unwrap();
1754
1755        let all_policies = pm.get_policy().await;
1756        eprintln!(
1757            "Loaded {} policies from production CSV:",
1758            all_policies.len()
1759        );
1760        for p in &all_policies {
1761            eprintln!("  p, {}", p.join(", "));
1762        }
1763
1764        // The exact failing check from the server
1765        let allowed = pm
1766            .check_with_domain("service:oauth", "*", "policy:ResolveServiceKey", "query")
1767            .await;
1768        eprintln!("service:oauth query policy:ResolveServiceKey = {}", allowed);
1769
1770        // List all rules that match oauth
1771        for p in &all_policies {
1772            if p[0].contains("oauth") || p[0] == "service:*" {
1773                eprintln!("  oauth-relevant: p, {}", p.join(", "));
1774            }
1775        }
1776
1777        assert!(
1778            allowed,
1779            "service:oauth should be able to query policy:ResolveServiceKey"
1780        );
1781    }
1782
1783    // ========================================================================
1784    // atproto-scoped authorization invariants
1785    //
1786    // These assert *behavioral* contracts that any authorization model must
1787    // hold (deny-by-default, per-identity isolation, public/private visibility,
1788    // stream isolation) — NOT the current Casbin mechanism/vocabulary. They are
1789    // written to survive the future tiles.run / atproto authz alignment: the
1790    // new model has to satisfy the same invariants, so these double as a
1791    // conformance harness. Resource identifiers go through the helpers below so
1792    // that when model resources move toward AT-URI form the naming changes
1793    // in one place, not every assertion. (OAuth scope-vocabulary tests are
1794    // intentionally deferred — hyprstream's `action:service:*` scopes are not
1795    // the access gate and will be replaced by atproto scopes.)
1796    // ========================================================================
1797
1798    /// Resource string for a model branch. Centralized for atproto forward-compat.
1799    fn model_resource(name: &str, branch: &str) -> String {
1800        format!("model:{name}:{branch}")
1801    }
1802    /// Resource pattern for an identity's own namespace (self-ownership).
1803    fn user_ns(subject: &str) -> String {
1804        format!("user:{subject}:*")
1805    }
1806    /// Resource string for a moq event-prefix subscribe scope.
1807    fn subscribe_scope(prefix: &str) -> String {
1808        format!("subscribe:events:{prefix}.*")
1809    }
1810    /// Resource string for an inference-mesh job (#319). The tenant is the first
1811    /// path segment so the caveat survives translation to a UCAN delegation.
1812    fn mesh_job(tenant: &str, job: &str) -> String {
1813        format!("mesh://{tenant}/job/{job}")
1814    }
1815    /// Per-host mesh authorization subject (#328).
1816    fn mesh_host(id: &str) -> String {
1817        format!("service:inference:host-{id}")
1818    }
1819
1820    /// Regression guard for the wildcard-validation bug: `add_policy` injects
1821    /// domain="*", so a blanket '*' ban made it always fail (even on
1822    /// wildcard-free input). It must succeed and take effect.
1823    #[tokio::test]
1824    #[allow(clippy::unwrap_used, clippy::expect_used)]
1825    async fn test_add_policy_succeeds_with_default_domain() {
1826        let pm = PolicyManager::new_in_memory().await.unwrap();
1827        // Wildcard-free 3-arg add_policy (internally domain="*") must succeed.
1828        pm.add_policy("alice", &model_resource("qwen3", "main"), "infer.generate")
1829            .await
1830            .expect("add_policy must succeed (domain=* is the legitimate global domain)");
1831        assert!(
1832            pm.check("alice", &model_resource("qwen3", "main"), Operation::Infer)
1833                .await,
1834            "the rule add_policy created must take effect"
1835        );
1836    }
1837
1838    /// P0a — self-namespace isolation: an identity may reach its own namespace,
1839    /// and MUST NOT reach another identity's namespace (cross-identity denial).
1840    #[tokio::test]
1841    #[allow(clippy::unwrap_used)]
1842    async fn test_self_namespace_isolation() {
1843        let pm = PolicyManager::new_in_memory().await.unwrap();
1844        // The self-ownership grant the OIDC callback issues on first login.
1845        pm.add_policy_with_domain("alice", "*", &user_ns("alice"), "*", "allow")
1846            .await
1847            .unwrap();
1848        pm.add_policy_with_domain("bob", "*", &user_ns("bob"), "*", "allow")
1849            .await
1850            .unwrap();
1851
1852        // Each identity reaches its own namespace.
1853        assert!(
1854            pm.check_with_domain("alice", "*", "user:alice:model1", "ttt.writeback")
1855                .await
1856        );
1857        assert!(
1858            pm.check_with_domain("bob", "*", "user:bob:model1", "ttt.writeback")
1859                .await
1860        );
1861
1862        // Neither identity may reach the other's namespace.
1863        assert!(
1864            !pm.check_with_domain("alice", "*", "user:bob:model1", "infer.generate")
1865                .await,
1866            "alice must not access bob's namespace"
1867        );
1868        assert!(
1869            !pm.check_with_domain("bob", "*", "user:alice:model1", "ttt.writeback")
1870                .await,
1871            "bob must not access alice's namespace"
1872        );
1873    }
1874
1875    /// P1a — deny-by-default and least-privilege: an unknown subject is denied,
1876    /// a scoped grant authorizes only that exact (resource, action) pair, and
1877    /// does not leak to other resources or actions.
1878    #[tokio::test]
1879    #[allow(clippy::unwrap_used)]
1880    async fn test_deny_by_default_and_least_privilege() {
1881        let pm = PolicyManager::new_in_memory().await.unwrap();
1882        let resource = model_resource("qwen3", "main");
1883
1884        // Deny-by-default: nobody is authorized until granted.
1885        assert!(
1886            !pm.check_with_domain("mallory", "*", &resource, "infer.generate")
1887                .await
1888        );
1889
1890        // Grant alice exactly infer on this model.
1891        pm.add_policy_with_domain("alice", "*", &resource, "infer.generate", "allow")
1892            .await
1893            .unwrap();
1894
1895        assert!(
1896            pm.check_with_domain("alice", "*", &resource, "infer.generate")
1897                .await
1898        );
1899        // Grant does not leak to other actions...
1900        assert!(
1901            !pm.check_with_domain("alice", "*", &resource, "ttt.writeback")
1902                .await,
1903            "infer grant must not confer manage"
1904        );
1905        // ...nor to other resources...
1906        assert!(
1907            !pm.check_with_domain(
1908                "alice",
1909                "*",
1910                &model_resource("llama", "main"),
1911                "infer.generate"
1912            )
1913            .await,
1914            "grant on one model must not confer another"
1915        );
1916        // ...nor to other subjects.
1917        assert!(
1918            !pm.check_with_domain("mallory", "*", &resource, "infer.generate")
1919                .await
1920        );
1921    }
1922
1923    /// P2a — moq subscribe-prefix isolation: a subscribe grant on one event
1924    /// prefix MUST NOT authorize a sibling/private prefix (no cross-tenant leak
1925    /// via prefix matching).
1926    #[tokio::test]
1927    #[allow(clippy::unwrap_used)]
1928    async fn test_subscribe_prefix_isolation() {
1929        let pm = PolicyManager::new_in_memory().await.unwrap();
1930        // alice may subscribe under the "public" prefix only.
1931        pm.add_policy_with_domain(
1932            "alice",
1933            "*",
1934            &subscribe_scope("public"),
1935            "subscribe",
1936            "allow",
1937        )
1938        .await
1939        .unwrap();
1940
1941        assert!(
1942            pm.check_with_domain("alice", "*", "subscribe:events:public.metrics", "subscribe")
1943                .await,
1944            "alice may subscribe within her granted prefix"
1945        );
1946        // A private prefix is NOT covered by the public-prefix grant.
1947        assert!(
1948            !pm.check_with_domain(
1949                "alice",
1950                "*",
1951                "subscribe:events:private.secrets",
1952                "subscribe"
1953            )
1954            .await,
1955            "public-prefix grant must not leak to a private prefix"
1956        );
1957        // An ungranted subject is denied entirely.
1958        assert!(
1959            !pm.check_with_domain("bob", "*", "subscribe:events:public.metrics", "subscribe")
1960                .await
1961        );
1962    }
1963
1964    // ========================================================================
1965    // Inference-mesh authorization invariants (#319)
1966    //
1967    // The mesh authority actions (`infer.stage`, `delta.submit`, `mesh.rpc`)
1968    // must be deny-by-default, granted ONLY to non-wildcard
1969    // `service:inference:host-<id>` subjects, scoped to a single tenant. The
1970    // read ability (`query.status`) may be granted to a host group. These
1971    // mirror the atproto-scoped invariant style above and double as the #319
1972    // security harness.
1973    // ========================================================================
1974
1975    /// Apply the worked-example `mesh-host` template rules to an enforcer.
1976    /// Mirrors what `policy apply-template mesh-host` does at runtime.
1977    #[allow(clippy::unwrap_used)]
1978    async fn apply_template(pm: &PolicyManager, name: &str) {
1979        let tmpl = crate::auth::policy_templates::get_template(name)
1980            .unwrap_or_else(|| panic!("template {name} must exist"));
1981        let policies = tmpl.expanded_policies();
1982        let tenant_domains: std::collections::BTreeSet<&str> = policies
1983            .iter()
1984            .map(|policy| policy.domain)
1985            .filter(|domain| *domain != "*")
1986            .collect();
1987        for r in policies {
1988            pm.add_policy_with_domain(r.subject, r.domain, r.resource, r.action, r.effect)
1989                .await
1990                .unwrap();
1991        }
1992        if let Some(groupings) = tmpl.groupings {
1993            for g in groupings {
1994                if let Some(domain) = tenant_domains.first() {
1995                    pm.add_role_for_user_in_domain(g.user, g.role, domain)
1996                        .await
1997                        .unwrap();
1998                } else {
1999                    pm.add_role_for_user(g.user, g.role).await.unwrap();
2000                }
2001            }
2002        }
2003    }
2004
2005    #[tokio::test]
2006    #[allow(clippy::unwrap_used)]
2007    async fn cyberdione_staging_ui_template_allows_only_its_exact_origin() {
2008        let pm = PolicyManager::new_in_memory().await.unwrap();
2009        apply_template(&pm, "cyberdione-staging-ui").await;
2010
2011        let allowed =
2012            federation_registration_resource("https://www.staging.lab.hyprstream.com").unwrap();
2013        assert!(
2014            pm.check_with_domain("service:oauth", "*", &allowed, "check")
2015                .await
2016        );
2017
2018        for denied_origin in [
2019            "https://staging-amp.hyprstream.com",
2020            "https://evil.www.staging.lab.hyprstream.com",
2021            "https://www.staging.lab.hyprstream.com.evil.example",
2022            "http://www.staging.lab.hyprstream.com",
2023        ] {
2024            let denied = federation_registration_resource(denied_origin).unwrap();
2025            assert!(
2026                !pm.check_with_domain("service:oauth", "*", &denied, "check")
2027                    .await,
2028                "staging policy must deny {denied_origin}"
2029            );
2030        }
2031
2032        let policies = pm.get_policy().await;
2033        assert_eq!(
2034            policies
2035                .iter()
2036                .filter(|rule| rule
2037                    .get(2)
2038                    .is_some_and(|resource| resource.starts_with("federation:register:")))
2039                .count(),
2040            1
2041        );
2042        assert!(policies
2043            .iter()
2044            .any(|rule| rule.get(2).is_some_and(|resource| resource == &allowed)));
2045    }
2046
2047    /// #319 invariant — the mesh authority actions are NEVER reachable by a
2048    /// wildcard (`*`) or `anonymous` subject, even when a `federation-open`-style
2049    /// wildcard rule AND the public-inference template are both loaded. Only a
2050    /// specific enrolled host subject may stage/submit.
2051    #[tokio::test]
2052    #[allow(clippy::unwrap_used)]
2053    async fn test_mesh_authority_never_matches_wildcard_or_anonymous() {
2054        let pm = PolicyManager::new_in_memory().await.unwrap();
2055        // Load a broad wildcard rule (federation-open) and the public-inference
2056        // template — neither must leak into mesh authority.
2057        apply_template(&pm, "federation-open").await;
2058        apply_template(&pm, "public-inference").await;
2059        // And the real per-host mesh grants for tenant acme.
2060        apply_template(&pm, "mesh-host").await;
2061
2062        let job = mesh_job("acme", "j7");
2063        for action in ["infer.stage", "delta.submit", "mesh.rpc"] {
2064            assert!(
2065                !pm.check_with_domain("*", "acme", &job, action).await,
2066                "wildcard subject must NEVER match mesh authority action {action}"
2067            );
2068            assert!(
2069                !pm.check_with_domain("anonymous", "acme", &job, action)
2070                    .await,
2071                "anonymous must NEVER match mesh authority action {action}"
2072            );
2073            // A non-enrolled host subject is likewise denied.
2074            assert!(
2075                !pm.check_with_domain(&mesh_host("99"), "acme", &job, action)
2076                    .await,
2077                "un-enrolled host must be denied mesh authority action {action}"
2078            );
2079        }
2080        // Positive control: an enrolled host CAN stage within its tenant.
2081        assert!(
2082            pm.check_with_domain(&mesh_host("1"), "acme", &job, "infer.stage")
2083                .await,
2084            "enrolled host-1 must be able to infer.stage in its tenant"
2085        );
2086    }
2087
2088    /// #319 invariant — tenant isolation: a host enrolled for tenant `acme`
2089    /// cannot exercise ANY mesh action against tenant `beta`'s resources, even
2090    /// for the same job name. The Casbin domain exact-match is the gate.
2091    #[tokio::test]
2092    #[allow(clippy::unwrap_used)]
2093    async fn test_mesh_tenant_isolation() {
2094        let pm = PolicyManager::new_in_memory().await.unwrap();
2095        // host-1 is granted on tenant acme via the worked-example template.
2096        apply_template(&pm, "mesh-host").await;
2097
2098        // In its own tenant: allowed.
2099        assert!(
2100            pm.check_with_domain(
2101                &mesh_host("1"),
2102                "acme",
2103                &mesh_job("acme", "j7"),
2104                "infer.stage"
2105            )
2106            .await
2107        );
2108        // Cross-tenant (domain beta): denied for every action, even though the
2109        // host holds the same grant in acme.
2110        for action in ["infer.stage", "delta.submit", "mesh.rpc", "query.status"] {
2111            assert!(
2112                !pm.check_with_domain(&mesh_host("1"), "beta", &mesh_job("beta", "j7"), action)
2113                    .await,
2114                "acme-scoped host-1 must NOT reach tenant beta for {action}"
2115            );
2116        }
2117        // Even pointing the resource path at beta while claiming the acme domain
2118        // must not match the acme rule (resource prefix differs).
2119        assert!(
2120            !pm.check_with_domain(
2121                &mesh_host("1"),
2122                "acme",
2123                &mesh_job("beta", "j7"),
2124                "infer.stage"
2125            )
2126            .await,
2127            "acme-domain rule must not match a beta resource path"
2128        );
2129    }
2130
2131    /// #319 invariant — group read, per-host authority: a host group may be
2132    /// granted the read ability (`query.status`) via Casbin grouping, but the
2133    /// group MUST NOT confer any authority action.
2134    #[tokio::test]
2135    #[allow(clippy::unwrap_used)]
2136    async fn test_mesh_group_read_not_authority() {
2137        let pm = PolicyManager::new_in_memory().await.unwrap();
2138        apply_template(&pm, "mesh-host-group").await;
2139
2140        let job = mesh_job("acme", "j7");
2141        // host-1 inherits the group read grant.
2142        assert!(
2143            pm.check_with_domain(&mesh_host("1"), "acme", &job, "query.status")
2144                .await,
2145            "grouped host must inherit the read ability"
2146        );
2147        // But the group does NOT confer authority.
2148        for action in ["infer.stage", "delta.submit", "mesh.rpc"] {
2149            assert!(
2150                !pm.check_with_domain(&mesh_host("1"), "acme", &job, action)
2151                    .await,
2152                "read group must NOT confer authority action {action}"
2153            );
2154        }
2155        // A host NOT in the group gets nothing.
2156        assert!(
2157            !pm.check_with_domain(&mesh_host("3"), "acme", &job, "query.status")
2158                .await,
2159            "un-grouped host must not inherit the read ability"
2160        );
2161    }
2162
2163    /// #319 invariant — deny-by-default: with no mesh template applied, an
2164    /// enrolled-looking host subject is denied every mesh action.
2165    #[tokio::test]
2166    #[allow(clippy::unwrap_used)]
2167    async fn test_mesh_deny_by_default() {
2168        let pm = PolicyManager::new_in_memory().await.unwrap();
2169        let job = mesh_job("acme", "j7");
2170        for action in ["infer.stage", "delta.submit", "mesh.rpc", "query.status"] {
2171            assert!(
2172                !pm.check_with_domain(&mesh_host("1"), "acme", &job, action)
2173                    .await,
2174                "un-granted host must be denied {action} (deny-by-default)"
2175            );
2176        }
2177    }
2178}