1use 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
50pub fn set_global_policy_manager(pm: Arc<PolicyManager>) {
52 let _ = GLOBAL_POLICY_MANAGER.set(pm);
53}
54
55pub fn global_policy_manager() -> Option<Arc<PolicyManager>> {
57 GLOBAL_POLICY_MANAGER.get().cloned()
58}
59
60#[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
85const MAX_POLICY_COMPONENT_LEN: usize = 256;
87
88pub const FEDERATION_REGISTER_RESOURCE_PREFIX: &str = "federation:register:";
94
95pub 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 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
193fn 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 Ok(())
237}
238
239const 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
270fn 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
301fn 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 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 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 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 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 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
370pub 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
441async 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
491pub struct PolicyManager {
493 enforcer: Arc<RwLock<Enforcer>>,
495 policies_dir: PathBuf,
497}
498
499impl PolicyManager {
500 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 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 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 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(&policy_path)?;
537
538 let model = DefaultModel::from_file(&model_path)
540 .await
541 .map_err(|e| PolicyError::ModelLoadError(e.to_string()))?;
542
543 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 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 pub async fn permissive() -> Result<Self, PolicyError> {
593 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 enforcer
606 .add_policy(vec![
607 "*".to_owned(), "*".to_owned(), "*".to_owned(), "*".to_owned(), "allow".to_owned(), ])
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 #[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 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 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 }
700 }
701 }
702
703 pub fn check_sync(&self, user: &str, resource: &str, operation: Operation) -> bool {
707 if let Ok(handle) = tokio::runtime::Handle::try_current() {
709 tokio::task::block_in_place(|| handle.block_on(self.check(user, resource, operation)))
711 } else {
712 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 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 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 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_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 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 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 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_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 pub async fn add_role_for_user(&self, user: &str, role: &str) -> Result<bool, PolicyError> {
857 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 pub async fn remove_role_for_user(&self, user: &str, role: &str) -> Result<bool, PolicyError> {
872 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 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 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 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 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 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 pub async fn get_policy(&self) -> Vec<Vec<String>> {
945 let enforcer = self.enforcer.read().await;
946 enforcer.get_policy()
947 }
948
949 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 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 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 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 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 let mut enforcer = self.enforcer.write().await;
1022
1023 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 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 enforcer
1076 .save_policy()
1077 .await
1078 .map_err(|e| PolicyError::PolicySaveError(e.to_string()))?;
1079
1080 Ok(())
1081 }
1082
1083 pub fn policies_dir(&self) -> &Path {
1085 &self.policies_dir
1086 }
1087
1088 pub fn model_conf_path(&self) -> PathBuf {
1090 self.policies_dir.join("model.conf")
1091 }
1092
1093 pub fn policy_csv_path(&self) -> PathBuf {
1095 self.policies_dir.join("policy.csv")
1096 }
1097
1098 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 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 let pm = PolicyManager::new(&policies_dir).await?;
1163
1164 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 assert!(policies_dir.join("model.conf").exists());
1173 assert!(policies_dir.join("policy.csv").exists());
1174
1175 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 pm.remove_policy("*", "*", "*").await?;
1188
1189 assert!(!pm.check("user", "model:test", Operation::Infer).await);
1191
1192 pm.add_policy("user", "model:test", "infer.generate")
1194 .await?;
1195
1196 assert!(pm.check("user", "model:test", Operation::Infer).await);
1198 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 pm.remove_policy("*", "*", "*").await?;
1209
1210 pm.add_policy("trainer", "model:*", "infer.generate")
1212 .await?;
1213 pm.add_policy("trainer", "model:*", "ttt.train").await?;
1214
1215 pm.add_role_for_user("alice", "trainer").await?;
1217
1218 assert!(pm.check("alice", "model:test", Operation::Infer).await);
1220 assert!(pm.check("alice", "model:test", Operation::Train).await);
1221
1222 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 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 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 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 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 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 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 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 pm.add_policy_with_domain("alice", "*", "model:qwen3:main", "ttt.writeback", "allow")
1544 .await
1545 .unwrap();
1546
1547 assert!(
1549 !pm.check_with_domain("bob", "*", "model:qwen3:main", "infer.generate")
1550 .await
1551 );
1552
1553 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 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 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 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 assert!(
1591 pm.check_with_domain("alice", "*", "model:qwen3:main", "ttt.writeback")
1592 .await
1593 );
1594 }
1595
1596 #[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 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 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 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 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 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 assert!(
1674 pm.check_with_domain("service:policy", "*", "policy:IssueToken", "manage")
1675 .await
1676 );
1677 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 assert!(
1718 !pm.check_with_domain("service:unknown", "*", "policy:ResolveServiceKey", "query")
1719 .await
1720 );
1721 }
1722
1723 #[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 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 let allowed = pm
1766 .check_with_domain("service:oauth", "*", "policy:ResolveServiceKey", "query")
1767 .await;
1768 eprintln!("service:oauth query policy:ResolveServiceKey = {}", allowed);
1769
1770 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 fn model_resource(name: &str, branch: &str) -> String {
1800 format!("model:{name}:{branch}")
1801 }
1802 fn user_ns(subject: &str) -> String {
1804 format!("user:{subject}:*")
1805 }
1806 fn subscribe_scope(prefix: &str) -> String {
1808 format!("subscribe:events:{prefix}.*")
1809 }
1810 fn mesh_job(tenant: &str, job: &str) -> String {
1813 format!("mesh://{tenant}/job/{job}")
1814 }
1815 fn mesh_host(id: &str) -> String {
1817 format!("service:inference:host-{id}")
1818 }
1819
1820 #[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 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 #[tokio::test]
1841 #[allow(clippy::unwrap_used)]
1842 async fn test_self_namespace_isolation() {
1843 let pm = PolicyManager::new_in_memory().await.unwrap();
1844 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 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 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 #[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 assert!(
1886 !pm.check_with_domain("mallory", "*", &resource, "infer.generate")
1887 .await
1888 );
1889
1890 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 assert!(
1901 !pm.check_with_domain("alice", "*", &resource, "ttt.writeback")
1902 .await,
1903 "infer grant must not confer manage"
1904 );
1905 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 assert!(
1918 !pm.check_with_domain("mallory", "*", &resource, "infer.generate")
1919 .await
1920 );
1921 }
1922
1923 #[tokio::test]
1927 #[allow(clippy::unwrap_used)]
1928 async fn test_subscribe_prefix_isolation() {
1929 let pm = PolicyManager::new_in_memory().await.unwrap();
1930 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 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 assert!(
1959 !pm.check_with_domain("bob", "*", "subscribe:events:public.metrics", "subscribe")
1960 .await
1961 );
1962 }
1963
1964 #[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 #[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 apply_template(&pm, "federation-open").await;
2058 apply_template(&pm, "public-inference").await;
2059 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 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 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 #[tokio::test]
2092 #[allow(clippy::unwrap_used)]
2093 async fn test_mesh_tenant_isolation() {
2094 let pm = PolicyManager::new_in_memory().await.unwrap();
2095 apply_template(&pm, "mesh-host").await;
2097
2098 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 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 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 #[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 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 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 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 #[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}