Skip to main content

hyprstream_core/cli/
policy_handlers.rs

1//! Handlers for policy management commands
2//!
3//! Cisco-inspired transactional UX for managing access control policies.
4//!
5//! Policy states:
6//! - **Running** = Current active (HEAD of .registry/policies/)
7//! - **Draft** = Uncommitted changes
8//! - **History** = Previous versions (HEAD~n)
9//!
10//! All commands route through PolicyService RPCs except `edit` which opens
11//! a local editor (but still uses RPC for draft status detection afterward).
12// CLI handlers intentionally print to stdout/stderr for user interaction
13#![allow(clippy::print_stdout, clippy::print_stderr)]
14
15use crate::auth::{jwt, Claims};
16use anyhow::{Context, Result};
17use chrono::Duration;
18use ed25519_dalek::SigningKey;
19use hyprstream_pds::repo_authority::is_path_form_did_web;
20use hyprstream_rpc_std::policy_client::{
21    AddGrouping, ApplyDraft, ApplyTemplate, GetDiff, GetHistory, PolicyCheck, PolicyClient,
22    RemoveGrouping, RollbackPolicy,
23};
24use std::io::{self, Write};
25use std::path::Path;
26use std::process::Command;
27
28/// Create a PolicyClient for RPC calls.
29///
30/// Required profile resolves through the checkpoint-backed discovery resolver;
31/// compatibility bootstrap dials the deterministic same-host PolicyService IPC
32/// endpoint, which unlike `registered_endpoint` is available to a separate
33/// `podman exec` process that did not start the PolicyService itself.
34pub(crate) fn create_policy_client(signing_key: &SigningKey) -> Result<PolicyClient> {
35    if hyprstream_discovery::native_network_required() {
36        return PolicyClient::from_provider(
37            &hyprstream_discovery::ProductionRpcClientProvider,
38            signing_key.clone(),
39            None,
40        );
41    }
42    let registry = hyprstream_rpc::registry::try_global()
43        .ok_or_else(|| anyhow::anyhow!("EndpointRegistry not initialized"))?;
44    let transport = policy_ipc_transport(&registry)?;
45    PolicyClient::for_local_transport_bootstrap(
46        &transport,
47        signing_key.clone(),
48        signing_key.verifying_key(),
49        None,
50    )
51}
52
53/// Resolve the deterministic same-host PolicyService REP socket without
54/// requiring a process-local service registration.
55fn policy_ipc_transport(
56    registry: &hyprstream_rpc::registry::EndpointRegistry,
57) -> Result<hyprstream_rpc::transport::TransportConfig> {
58    registry
59        .try_endpoint("policy", hyprstream_rpc::registry::SocketKind::Rep)
60        .context("resolve local PolicyService IPC endpoint")
61}
62
63/// Handle `policy show` - Display the running policy via RPC
64pub async fn handle_policy_show(signing_key: &SigningKey, raw: bool) -> Result<()> {
65    let client = create_policy_client(signing_key)?;
66    let policy_info = client
67        .get_policy()
68        .await
69        .context("Failed to get policy from PolicyService. Are services running?")?;
70
71    if raw {
72        // Reconstruct CSV from structured data
73        for rule in &policy_info.rules {
74            println!(
75                "p, {}, {}, {}, {}, {}",
76                rule.subject, rule.domain, rule.resource, rule.action, rule.effect
77            );
78        }
79        for grouping in &policy_info.groupings {
80            println!("g, {}, {}", grouping.user, grouping.role);
81        }
82    } else {
83        if policy_info.rules.is_empty() && policy_info.groupings.is_empty() {
84            println!("No policies defined.");
85            println!("\nTo get started, apply a template:");
86            println!("  hyprstream quick policy list-templates  # see all available templates");
87            println!("\nOr edit manually:");
88            println!("  hyprstream quick policy edit");
89            return Ok(());
90        }
91
92        // Print policy rules as a table
93        if !policy_info.rules.is_empty() {
94            println!(
95                "┌──────────────────────────────────────────────────────────────────────────────┐"
96            );
97            println!(
98                "│ Policy Rules                                                                 │"
99            );
100            println!(
101                "├────────────────┬────────────────┬────────────────┬────────────────┬──────────┤"
102            );
103            println!(
104                "│ Subject        │ Domain         │ Resource       │ Action         │ Effect   │"
105            );
106            println!(
107                "├────────────────┼────────────────┼────────────────┼────────────────┼──────────┤"
108            );
109
110            for rule in &policy_info.rules {
111                println!(
112                    "│ {:14} │ {:14} │ {:14} │ {:14} │ {:8} │",
113                    truncate_str(&rule.subject, 14),
114                    truncate_str(&rule.domain, 14),
115                    truncate_str(&rule.resource, 14),
116                    truncate_str(&rule.action, 14),
117                    truncate_str(&rule.effect, 8)
118                );
119            }
120            println!(
121                "└────────────────┴────────────────┴────────────────┴────────────────┴──────────┘"
122            );
123        }
124
125        // Print role assignments
126        if !policy_info.groupings.is_empty() {
127            println!();
128            println!("┌────────────────────────────────────────────┐");
129            println!("│ Role Assignments                           │");
130            println!("├────────────────────┬───────────────────────┤");
131            println!("│ User               │ Role                  │");
132            println!("├────────────────────┼───────────────────────┤");
133
134            for g in &policy_info.groupings {
135                println!(
136                    "│ {:18} │ {:21} │",
137                    truncate_str(&g.user, 18),
138                    truncate_str(&g.role, 21)
139                );
140            }
141            println!("└────────────────────┴───────────────────────┘");
142        }
143    }
144
145    Ok(())
146}
147
148/// Handle `policy history` - Show policy commit history via RPC
149pub async fn handle_policy_history(
150    signing_key: &SigningKey,
151    count: usize,
152    _oneline: bool,
153) -> Result<()> {
154    let client = create_policy_client(signing_key)?;
155    let history = client
156        .get_history(&GetHistory {
157            count: count as u32,
158        })
159        .await
160        .context("Failed to get policy history from PolicyService. Are services running?")?;
161
162    if history.entries.is_empty() {
163        println!("No policy history found.");
164        println!("\nPolicies are versioned using git commits in .registry/");
165        return Ok(());
166    }
167
168    for entry in &history.entries {
169        println!(
170            "\x1b[33m{}\x1b[0m \x1b[32m{}\x1b[0m {}",
171            entry.hash, entry.date, entry.message
172        );
173    }
174
175    Ok(())
176}
177
178/// Handle `policy edit` - Open policy in $VISUAL/$EDITOR
179///
180/// The editor itself must be local, but draft detection uses PolicyService RPC.
181pub async fn handle_policy_edit(signing_key: &SigningKey, policy_csv_path: &Path) -> Result<()> {
182    // Get editor from environment
183    let editor = std::env::var("VISUAL")
184        .or_else(|_| std::env::var("EDITOR"))
185        .unwrap_or_else(|_| "vi".to_owned());
186
187    println!("Opening {} in {}", policy_csv_path.display(), editor);
188    println!();
189    println!("After editing, use:");
190    println!("  hyprstream quick policy diff     # Preview changes");
191    println!("  hyprstream quick policy apply    # Commit changes");
192    println!();
193
194    // Run editor
195    let status = Command::new(&editor)
196        .arg(policy_csv_path)
197        .status()
198        .context(format!("Failed to run editor: {editor}"))?;
199
200    if !status.success() {
201        anyhow::bail!("Editor exited with non-zero status");
202    }
203
204    // Check for draft changes via PolicyService RPC
205    let client = create_policy_client(signing_key)?;
206    match client.get_draft_status().await {
207        Ok(draft) if draft.has_changes => {
208            println!();
209            println!(
210                "✏️  Draft changes detected ({}). Run 'hyprstream quick policy diff' to review.",
211                draft.summary
212            );
213        }
214        Ok(_) => {} // No changes
215        Err(_) => {
216            // Service may not be running; just suggest the commands
217            println!();
218            println!("Run 'hyprstream quick policy diff' to review changes.");
219        }
220    }
221
222    Ok(())
223}
224
225/// Handle `policy diff` - Show diff between draft and running policy via RPC
226pub async fn handle_policy_diff(signing_key: &SigningKey, against: Option<String>) -> Result<()> {
227    let client = create_policy_client(signing_key)?;
228    let git_ref = against.as_deref().unwrap_or("");
229
230    let diff_text = client
231        .get_diff(&GetDiff {
232            git_ref: Some(git_ref.to_owned()),
233        })
234        .await
235        .context("Failed to get diff from PolicyService. Are services running?")?;
236
237    if diff_text.is_empty() {
238        let ref_display = if git_ref.is_empty() { "HEAD" } else { git_ref };
239        println!("No changes from {ref_display} policy.");
240        return Ok(());
241    }
242
243    let ref_display = if git_ref.is_empty() { "HEAD" } else { git_ref };
244    println!("Changes vs {ref_display}:\n");
245
246    // Colorize the diff output
247    for line in diff_text.lines() {
248        if let Some(rest) = line.strip_prefix('+') {
249            println!("\x1b[32m+{rest}\x1b[0m");
250        } else if let Some(rest) = line.strip_prefix('-') {
251            println!("\x1b[31m-{rest}\x1b[0m");
252        } else {
253            println!("{line}");
254        }
255    }
256
257    Ok(())
258}
259
260/// Handle `policy apply` - Commit draft changes via RPC
261pub async fn handle_policy_apply(
262    signing_key: &SigningKey,
263    dry_run: bool,
264    message: Option<String>,
265) -> Result<()> {
266    let client = create_policy_client(signing_key)?;
267
268    // Check for uncommitted changes via RPC
269    let draft = client
270        .get_draft_status()
271        .await
272        .context("Failed to check draft status from PolicyService. Are services running?")?;
273
274    if !draft.has_changes {
275        println!("No changes to apply.");
276        return Ok(());
277    }
278
279    // Show what would be committed
280    let diff_text = client
281        .get_diff(&GetDiff {
282            git_ref: Some(String::new()),
283        })
284        .await
285        .context("Failed to get diff from PolicyService.")?;
286
287    println!("Changes to be applied ({}):", draft.summary);
288    for line in diff_text.lines() {
289        if let Some(rest) = line.strip_prefix('+') {
290            println!("  \x1b[32m+{rest}\x1b[0m");
291        } else if let Some(rest) = line.strip_prefix('-') {
292            println!("  \x1b[31m-{rest}\x1b[0m");
293        }
294    }
295    println!();
296
297    if dry_run {
298        println!("--dry-run specified, no changes committed.");
299        return Ok(());
300    }
301
302    // Use PolicyService RPC to validate, stage, and commit
303    let commit_msg = message.unwrap_or_else(|| {
304        let timestamp = chrono::Local::now().format("%Y-%m-%d %H:%M:%S");
305        format!("policy: update access control rules ({timestamp})")
306    });
307
308    let result_msg = client
309        .apply_draft(&ApplyDraft {
310            message: Some(commit_msg),
311        })
312        .await
313        .context("Failed to apply draft via PolicyService.")?;
314
315    println!("✓ Policy applied successfully.");
316    println!("  {result_msg}");
317
318    Ok(())
319}
320
321/// Handle `policy rollback [ref]` - Revert to a previous policy version via RPC
322pub async fn handle_policy_rollback(
323    signing_key: &SigningKey,
324    git_ref: &str,
325    dry_run: bool,
326) -> Result<()> {
327    let client = create_policy_client(signing_key)?;
328
329    if dry_run {
330        // Use history RPC to show what we'd be rolling back to
331        let history = client
332            .get_history(&GetHistory { count: 20 })
333            .await
334            .context("Failed to get history from PolicyService. Are services running?")?;
335
336        // Find the matching entry
337        let target = history
338            .entries
339            .iter()
340            .find(|e| e.hash.starts_with(git_ref) || git_ref.contains('~'));
341        if let Some(entry) = target {
342            println!("Rolling back to: {} {}", entry.hash, entry.message);
343        } else {
344            println!("Rolling back to: {git_ref}");
345        }
346        println!("\n--dry-run specified, no changes applied.");
347        return Ok(());
348    }
349
350    // Confirm
351    print!("Roll back policy to {git_ref}? [y/N] ");
352    io::stdout().flush()?;
353
354    let mut input = String::new();
355    io::stdin().read_line(&mut input)?;
356
357    if !input.trim().eq_ignore_ascii_case("y") {
358        println!("Aborted.");
359        return Ok(());
360    }
361
362    // Use PolicyService RPC
363    let result_msg = client
364        .rollback(&RollbackPolicy {
365            git_ref: git_ref.to_owned(),
366        })
367        .await
368        .context("Failed to rollback via PolicyService. Are services running?")?;
369
370    println!();
371    println!("✓ Policy rolled back to {git_ref}");
372    println!("  {result_msg}");
373
374    Ok(())
375}
376
377/// Handle `policy check <user> <resource> <action>` - Test permission via RPC
378pub async fn handle_policy_check(
379    signing_key: &SigningKey,
380    user: &str,
381    resource: &str,
382    action: &str,
383) -> Result<()> {
384    let client = create_policy_client(signing_key)?;
385
386    let allowed = client
387        .check(&PolicyCheck {
388            subject: user.to_owned(),
389            domain: user.to_owned(),
390            resource: resource.to_owned(),
391            operation: action.to_owned(),
392        })
393        .await
394        .context("Failed to check policy via PolicyService. Are services running?")?;
395
396    println!("User:     {user}");
397    println!("Resource: {resource}");
398    println!("Action:   {action}");
399    println!();
400
401    if allowed {
402        println!("Result:   ✓ ALLOWED");
403    } else {
404        println!("Result:   ✗ DENIED");
405    }
406
407    Ok(())
408}
409
410// === Token handlers ===
411
412/// Handle `policy token create` - Create a new JWT API token
413///
414/// Generates a JWT token signed with Ed25519. The token is self-contained
415/// and can be validated statelessly by any server with the public key.
416pub async fn handle_token_create(
417    signing_key: &SigningKey,
418    user: &str,
419    name: Option<String>,
420    expires: &str,
421    scopes: Vec<String>,
422) -> Result<()> {
423    // Parse expiration
424    let expires_duration = parse_duration(expires)?;
425
426    // Default expiration is 90 days if not specified and not "never"
427    let duration = expires_duration.unwrap_or_else(|| Duration::days(90));
428
429    // Generate name for display (not stored in JWT, just for user reference)
430    let name =
431        name.unwrap_or_else(|| format!("token-{}", chrono::Utc::now().format("%Y%m%d-%H%M%S")));
432
433    // Mint JWT with proper iss/aud claims for OAI middleware compatibility
434    let (token, exp) = mint_local_token(signing_key, user, duration)?;
435
436    // Display the token (only shown once)
437    println!();
438    println!("JWT token created for subject '{user}':");
439    println!();
440    println!("  {token}");
441    println!();
442    println!("  Name:    {name} (reference only, not in token)");
443
444    // Calculate expiration for display
445    let expires_at = chrono::DateTime::from_timestamp(exp, 0);
446    if let Some(expires_at) = expires_at {
447        let days = duration.num_days();
448        println!(
449            "  Expires: {} ({} days)",
450            expires_at.format("%Y-%m-%d %H:%M UTC"),
451            days
452        );
453    } else {
454        println!("  Expires: never");
455    }
456
457    if scopes.is_empty() || scopes.contains(&"*".to_owned()) {
458        println!("  Scopes:  * (all resources)");
459    } else {
460        println!("  Scopes:  {}", scopes.join(", "));
461    }
462
463    println!();
464    println!("  \x1b[33m⚠️  Save this token now - it cannot be retrieved again.\x1b[0m");
465    println!();
466    println!("  Usage:");
467    let display_len = std::cmp::min(30, token.len());
468    println!(
469        "    curl -H \"Authorization: Bearer {}...\" http://localhost:8080/v1/models",
470        &token[..display_len]
471    );
472    println!();
473
474    Ok(())
475}
476
477/// Load or generate the Ed25519 node signing key from the configured secrets
478/// directory.
479///
480/// The `_keys_dir` parameter is retained for API compatibility but ignored; the
481/// actual path is always resolved via `HyprConfig::resolve_secrets_dir()`.
482///
483/// Resolution order:
484/// 1. `HYPRSTREAM__SIGNING_KEY` / `config.signing_key` test bypass.
485/// 2. File at `<secrets_dir>/signing-key`.
486/// 3. Generate new key, write to file (writable dir only).
487pub async fn load_or_generate_signing_key(_keys_dir: &Path) -> Result<SigningKey> {
488    if let Some(sk) = crate::config::HyprConfig::node_signing_key_bypass()? {
489        return Ok(sk);
490    }
491    let secrets_dir = crate::config::HyprConfig::resolve_secrets_dir()?;
492    crate::auth::identity_store::load_or_generate_node_signing_key(&secrets_dir)
493}
494
495/// Mint a JWT locally with proper iss/aud claims.
496///
497/// Sets `iss` to the OAuth issuer URL and `aud` to the OAI resource URL,
498/// matching the claim structure expected by the OAI HTTP middleware.
499/// Does NOT require a running PolicyService — signs directly with the local key.
500pub(crate) fn mint_local_token(
501    signing_key: &SigningKey,
502    subject: &str,
503    duration: Duration,
504) -> Result<(String, i64)> {
505    if is_path_form_did_web(subject) {
506        anyhow::bail!(
507            "path-form did:web account subjects are frozen; host-form account minting is not available yet (#1159)"
508        );
509    }
510
511    let now = chrono::Utc::now().timestamp();
512    let exp = now + duration.num_seconds();
513
514    let config = crate::config::HyprConfig::load();
515    let (issuer, audience) = match config {
516        Ok(ref c) => (c.oauth.issuer_url(), c.oai.resource_url()),
517        Err(_) => {
518            // Fallback to defaults when config is not available
519            let local_origin = "http://localhost";
520            (
521                format!("{local_origin}:6791"),
522                format!("{local_origin}:6789"),
523            )
524        }
525    };
526
527    let claims = Claims::new(subject.to_owned(), now, exp)
528        .with_issuer(issuer)
529        .with_audience(Some(audience));
530
531    let jwt_key =
532        hyprstream_rpc::node_identity::derive_purpose_key(signing_key, "hyprstream-jwt-v1");
533    let token = jwt::encode(&claims, &jwt_key);
534    Ok((token, exp))
535}
536
537/// Ensure the local user has an Ed25519 signing keypair.
538///
539/// Loads from `<secrets_dir>/user-signing-key`, generating on first run.
540/// This key is per-OS-user (not per-hyprstream-user). The wizard only
541/// registers it for the local admin. Other users generate their own keys.
542#[allow(dead_code)]
543pub(crate) fn ensure_user_signing_key() -> Result<(SigningKey, ed25519_dalek::VerifyingKey)> {
544    if let Some(pair) = crate::config::HyprConfig::user_signing_key_bypass()? {
545        return Ok(pair);
546    }
547    let secrets_dir = crate::config::HyprConfig::resolve_secrets_dir()?;
548    crate::auth::identity_store::load_or_generate_user_signing_key(&secrets_dir)
549}
550
551/// Parse duration string like "30d", "90d", "1y", "never"
552pub(crate) fn parse_duration(s: &str) -> Result<Option<Duration>> {
553    let s = s.trim().to_lowercase();
554
555    if s.is_empty() {
556        return Ok(None);
557    }
558
559    if s == "never" {
560        return Ok(Some(Duration::days(36500))); // ~100 years
561    }
562
563    let (num_str, unit) = if s.ends_with('d') {
564        (&s[..s.len() - 1], 'd')
565    } else if s.ends_with('y') {
566        (&s[..s.len() - 1], 'y')
567    } else if s.ends_with('h') {
568        (&s[..s.len() - 1], 'h')
569    } else {
570        // Assume days if no unit
571        (s.as_str(), 'd')
572    };
573
574    let num: i64 = num_str
575        .parse()
576        .context(format!("Invalid duration number: {num_str}"))?;
577
578    let duration = match unit {
579        'd' => Duration::days(num),
580        'y' => Duration::days(num * 365),
581        'h' => Duration::hours(num),
582        _ => anyhow::bail!("Unknown duration unit: {}", unit),
583    };
584
585    Ok(Some(duration))
586}
587
588// === Helper functions ===
589
590/// Truncate a string to max length, adding "..." if truncated.
591/// Uses char_indices for O(n) slicing without intermediate allocation.
592fn truncate_str(s: &str, max_len: usize) -> String {
593    if s.len() <= max_len {
594        s.to_owned()
595    } else if max_len > 3 {
596        let end = s
597            .char_indices()
598            .nth(max_len - 3)
599            .map_or(s.len(), |(i, _)| i);
600        format!("{}...", &s[..end])
601    } else {
602        let end = s.char_indices().nth(max_len).map_or(s.len(), |(i, _)| i);
603        s[..end].to_owned()
604    }
605}
606
607// Re-export policy templates from shared location
608pub use crate::auth::policy_templates::{get_template, get_templates, PolicyTemplate};
609
610// === Role handlers ===
611
612/// Handle `policy role add <user> <role>` - Assign a role to a user via RPC
613pub async fn handle_policy_role_add(
614    signing_key: &SigningKey,
615    user: &str,
616    role: &str,
617    dry_run: bool,
618) -> Result<()> {
619    if dry_run {
620        println!("Would add: g, {user}, {role}");
621        return Ok(());
622    }
623
624    let client = create_policy_client(signing_key)?;
625    let sha = client
626        .add_grouping(&AddGrouping {
627            user: user.to_owned(),
628            role: role.to_owned(),
629        })
630        .await
631        .context("Failed to add role assignment via PolicyService. Are services running?")?;
632
633    println!("Role assigned. Commit: {}", &sha[..sha.len().min(8)]);
634    Ok(())
635}
636
637/// Handle `policy role remove <user> <role>` - Remove a role from a user via RPC
638pub async fn handle_policy_role_remove(
639    signing_key: &SigningKey,
640    user: &str,
641    role: &str,
642    force: bool,
643) -> Result<()> {
644    if !force {
645        print!("Remove role '{role}' from '{user}'? [y/N] ");
646        io::stdout().flush()?;
647
648        let mut input = String::new();
649        io::stdin().read_line(&mut input)?;
650
651        if !input.trim().eq_ignore_ascii_case("y") {
652            println!("Aborted.");
653            return Ok(());
654        }
655    }
656
657    let client = create_policy_client(signing_key)?;
658    let sha = client
659        .remove_grouping(&RemoveGrouping {
660            user: user.to_owned(),
661            role: role.to_owned(),
662        })
663        .await
664        .context("Failed to remove role assignment via PolicyService. Are services running?")?;
665
666    println!("Role removed. Commit: {}", &sha[..sha.len().min(8)]);
667    Ok(())
668}
669
670/// Handle `policy role list` - List role assignments (g-lines) via RPC
671pub async fn handle_policy_role_list(
672    signing_key: &SigningKey,
673    user: Option<&str>,
674    role: Option<&str>,
675) -> Result<()> {
676    let client = create_policy_client(signing_key)?;
677    let policy_info = client
678        .get_policy()
679        .await
680        .context("Failed to get policy from PolicyService. Are services running?")?;
681
682    let groupings: Vec<_> = policy_info
683        .groupings
684        .iter()
685        .filter(|g| user.is_none_or(|u| g.user == u))
686        .filter(|g| role.is_none_or(|r| g.role == r))
687        .collect();
688
689    if groupings.is_empty() {
690        println!("No role assignments found.");
691        return Ok(());
692    }
693
694    for g in groupings {
695        println!("g, {}, {}", g.user, g.role);
696    }
697
698    Ok(())
699}
700
701/// Handle `policy list-templates` - List available templates
702pub async fn handle_policy_list_templates() -> Result<()> {
703    let templates = get_templates();
704
705    println!("Available policy templates:\n");
706    println!("{:<20} DESCRIPTION", "NAME");
707    println!("{}", "-".repeat(60));
708
709    for template in templates {
710        println!("{:<20} {}", template.name, template.description);
711    }
712
713    println!();
714    println!("Apply with: hyprstream quick policy apply-template <name>");
715
716    Ok(())
717}
718
719/// Handle `policy apply-template <name>` - Apply a built-in template via RPC
720pub async fn handle_policy_apply_template(
721    signing_key: &SigningKey,
722    template_name: &str,
723    dry_run: bool,
724) -> Result<()> {
725    let template = get_template(template_name)
726        .ok_or_else(|| anyhow::anyhow!(
727            "Unknown template: '{}'. Use 'hyprstream quick policy list-templates' to see available templates.",
728            template_name
729        ))?;
730
731    let rules_csv = template.to_csv();
732
733    println!("Applying template: {template_name}");
734    println!("Description: {}", template.description);
735    println!();
736    println!("Rules:");
737    for line in rules_csv.lines() {
738        if !line.trim().is_empty() {
739            println!("  {line}");
740        }
741    }
742    println!();
743
744    if dry_run {
745        println!("--dry-run specified, no changes applied.");
746        return Ok(());
747    }
748
749    // Use PolicyService RPC to apply the template (writes file, validates, stages, commits)
750    let client = create_policy_client(signing_key)?;
751    let result_msg = client
752        .apply_template(&ApplyTemplate {
753            name: template_name.to_owned(),
754        })
755        .await
756        .context("Failed to apply template via PolicyService. Are services running?")?;
757
758    println!();
759    println!("✓ Template '{template_name}' applied successfully.");
760    println!("  {result_msg}");
761
762    Ok(())
763}
764
765#[cfg(test)]
766#[allow(clippy::unwrap_used, clippy::expect_used)]
767mod tests {
768    use super::*;
769
770    #[test]
771    fn local_token_mint_rejects_path_form_account_subject() {
772        let signing_key = SigningKey::from_bytes(&[0x71; 32]);
773        let error = mint_local_token(
774            &signing_key,
775            "did:web:accounts.example:users:alice",
776            Duration::hours(1),
777        )
778        .expect_err("path-form account subject must not reach the direct CLI signer");
779
780        assert!(error
781            .to_string()
782            .contains("path-form did:web account subjects are frozen"));
783    }
784
785    #[test]
786    fn local_token_mint_allows_ordinary_subject() {
787        let signing_key = SigningKey::from_bytes(&[0x72; 32]);
788        let (token, _) = mint_local_token(&signing_key, "alice", Duration::hours(1))
789            .expect("ordinary CLI subject must still mint");
790
791        let claims =
792            hyprstream_rpc::auth::decode_unverified(&token).expect("minted token must decode");
793        assert_eq!(claims.sub, "alice");
794    }
795
796    #[test]
797    fn policy_cli_uses_ipc_default_without_process_local_registration() {
798        let registry = hyprstream_rpc::registry::EndpointRegistry::new(
799            hyprstream_rpc::registry::EndpointMode::Ipc,
800            Some(std::path::PathBuf::from("/run/hyprstream")),
801        );
802
803        assert!(
804            registry
805                .registered_endpoint("policy", hyprstream_rpc::registry::SocketKind::Rep)
806                .is_none(),
807            "this simulates the distinct podman-exec CLI process"
808        );
809        let transport = policy_ipc_transport(&registry)
810            .expect("IPC mode must provide the deterministic policy REP socket");
811        assert_eq!(
812            transport.endpoint_string(),
813            "ipc:///run/hyprstream/policy.sock",
814        );
815    }
816}