Skip to main content

hyprstream_core/auth/
policy_migration.rs

1//! Policy CSV migration from flat to dot-namespaced action strings.
2//!
3//! Hyprstream 0.x policy files used flat action names (`infer`, `manage`, etc.).
4//! Version 0.y and later use dot-namespaced actions (`infer.generate`, `ttt.writeback`).
5//! This module provides a helper that rewrites flat action strings to their
6//! dot-namespaced equivalents in a `policy.csv` string.
7
8/// Map a flat action string to its canonical dot-namespaced equivalent.
9/// Returns `None` if the string is not a recognized flat action — this includes
10/// already dot-namespaced strings as well as completely unknown strings.
11pub fn migrate_action(action: &str) -> Option<&'static str> {
12    match action {
13        "infer" => Some("infer.generate"),
14        "train" => Some("ttt.train"),
15        "query" => Some("query.status"),
16        "write" => Some("persist.save"),
17        "serve" => Some("serve.api"),
18        "manage" => Some("ttt.writeback"),
19        "context" => Some("context.augment"),
20        _ => None,
21    }
22}
23
24/// Rewrite a `policy.csv` string, upgrading flat action strings to dot-namespaced form.
25///
26/// - Lines that already have dot-namespaced actions (containing `.`) are left unchanged.
27/// - `g`-lines (role inheritance) and comments are left unchanged.
28/// - Only 6-field `p`-lines (`p, sub, dom, obj, act, eft`) are rewritten.
29pub fn migrate_policy_csv(csv: &str) -> String {
30    csv.lines()
31        .map(|line| {
32            let trimmed = line.trim();
33            // Only rewrite p-lines (policy rules), not g-lines or comments
34            if !trimmed.starts_with("p,") {
35                return line.to_owned();
36            }
37            let parts: Vec<&str> = trimmed.splitn(6, ',').collect();
38            // p, sub, dom, obj, act, eft — 6 parts
39            if parts.len() == 6 {
40                let act = parts[4].trim();
41                if let Some(new_act) = migrate_action(act) {
42                    return format!(
43                        "{}, {}, {}, {}, {}, {}",
44                        parts[0].trim(),
45                        parts[1].trim(),
46                        parts[2].trim(),
47                        parts[3].trim(),
48                        new_act,
49                        parts[5].trim(),
50                    );
51                }
52            }
53            line.to_owned()
54        })
55        .collect::<Vec<_>>()
56        .join("\n")
57        + if csv.ends_with('\n') { "\n" } else { "" }
58}
59
60#[cfg(test)]
61mod tests {
62    use super::*;
63
64    #[test]
65    fn test_migrate_flat_p_rule() {
66        let csv = "p, alice, *, model:*, infer, allow";
67        assert_eq!(
68            migrate_policy_csv(csv),
69            "p, alice, *, model:*, infer.generate, allow"
70        );
71    }
72
73    #[test]
74    fn test_migrate_all_flat_actions() {
75        for (flat, expected) in [
76            ("infer", "infer.generate"),
77            ("train", "ttt.train"),
78            ("query", "query.status"),
79            ("write", "persist.save"),
80            ("serve", "serve.api"),
81            ("manage", "ttt.writeback"),
82            ("context", "context.augment"),
83        ] {
84            let csv = format!("p, alice, *, model:*, {flat}, allow");
85            let result = migrate_policy_csv(&csv);
86            assert!(
87                result.contains(expected),
88                "Expected '{expected}' in migrated output for flat action '{flat}', got: {result}"
89            );
90        }
91    }
92
93    #[test]
94    fn test_migrate_leaves_g_lines_unchanged() {
95        let csv = "g, alice, ttt.user";
96        assert_eq!(migrate_policy_csv(csv), csv);
97    }
98
99    #[test]
100    fn test_migrate_leaves_already_namespaced_unchanged() {
101        let csv = "p, alice, *, model:*, infer.generate, allow";
102        assert_eq!(migrate_policy_csv(csv), csv);
103    }
104
105    #[test]
106    fn test_migrate_leaves_comments_unchanged() {
107        let csv = "# This is a comment";
108        assert_eq!(migrate_policy_csv(csv), csv);
109    }
110
111    #[test]
112    fn test_migrate_preserves_trailing_newline() {
113        let csv_with = "p, alice, *, model:*, infer, allow\n";
114        let csv_without = "p, alice, *, model:*, infer, allow";
115        assert!(migrate_policy_csv(csv_with).ends_with('\n'));
116        assert!(!migrate_policy_csv(csv_without).ends_with('\n'));
117    }
118
119    #[test]
120    fn test_migrate_multiline() {
121        let csv = "# Comment\np, alice, *, model:*, infer, allow\ng, alice, ttt.user\np, bob, *, model:*, manage, allow";
122        let result = migrate_policy_csv(csv);
123        assert!(result.contains("infer.generate"));
124        assert!(result.contains("ttt.writeback"));
125        assert!(result.contains("g, alice, ttt.user"));
126        assert!(result.contains("# Comment"));
127    }
128}