use std::collections::BTreeMap;
use anyhow::{Result, anyhow};
use systemprompt_database::DbPool;
use systemprompt_runtime::AppContext;
use systemprompt_security::authz::repository::AccessControlRepository;
use super::ExportYamlArgs;
use crate::CliConfig;
use crate::shared::CommandResult;
pub(super) async fn run(
_args: ExportYamlArgs,
_config: &CliConfig,
) -> Result<CommandResult<String>> {
let ctx = AppContext::new().await?;
let yaml = render_yaml_snapshot(ctx.db_pool()).await?;
Ok(CommandResult::raw_text(yaml)
.with_title("Access-control baseline (paste into services/access-control YAML)"))
}
async fn render_yaml_snapshot(pool: &DbPool) -> Result<String> {
let grouped = load_grouped_rules(pool).await?;
let mut out = String::new();
out.push_str("# Generated by `systemprompt admin access-control export-yaml`\n");
out.push_str("# This snapshot reflects this instance's DB at export time.\n");
out.push_str("# Per-user overrides (rule_type='user') are intentionally omitted.\n\n");
write_rules(&mut out, &grouped);
Ok(out)
}
async fn load_grouped_rules(pool: &DbPool) -> Result<BTreeMap<GroupKey, GroupValue>> {
let repo = AccessControlRepository::new(pool).map_err(|e| anyhow!("acquire repo: {e}"))?;
let rows = repo
.list_role_rules_for_export()
.await
.map_err(|e| anyhow!("query access_control_rules: {e}"))?;
let mut grouped: BTreeMap<GroupKey, GroupValue> = BTreeMap::new();
for row in rows {
let key = GroupKey {
entity_type: row.entity_type,
entity_id: row.entity_id,
access: row.access,
justification: row.justification.clone(),
};
let entry = grouped.entry(key).or_default();
if row.rule_type == "role" {
entry.roles.push(row.rule_value);
}
}
Ok(grouped)
}
fn write_rules(out: &mut String, grouped: &BTreeMap<GroupKey, GroupValue>) {
out.push_str("rules:\n");
if grouped.is_empty() {
out.push_str(" []\n");
return;
}
for (key, value) in grouped {
write_rule(out, key, value);
}
}
fn write_rule(out: &mut String, key: &GroupKey, value: &GroupValue) {
out.push_str(" - entity_type: ");
out.push_str(&yaml_scalar(&key.entity_type));
out.push('\n');
out.push_str(" entity_id: ");
out.push_str(&yaml_scalar(&key.entity_id));
out.push('\n');
out.push_str(" access: ");
out.push_str(&yaml_scalar(&key.access));
out.push('\n');
write_string_array(out, " roles", &value.roles);
if let Some(j) = &key.justification {
out.push_str(" justification: ");
out.push_str(&yaml_scalar(j));
out.push('\n');
}
}
fn write_string_array(out: &mut String, key: &str, items: &[String]) {
if items.is_empty() {
return;
}
out.push_str(key);
out.push_str(": [");
out.push_str(
&items
.iter()
.map(|s| yaml_scalar(s))
.collect::<Vec<_>>()
.join(", "),
);
out.push_str("]\n");
}
#[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
struct GroupKey {
entity_type: String,
entity_id: String,
access: String,
justification: Option<String>,
}
#[derive(Debug, Default)]
struct GroupValue {
roles: Vec<String>,
}
fn yaml_scalar(s: &str) -> String {
let needs_quotes = s.is_empty()
|| s.contains([':', '#', '\n', '"', '\'', '\\'])
|| s.starts_with([
'-', '?', '!', '&', '*', '[', ']', '{', '}', '|', '>', '%', '@', '`', ' ',
])
|| s.trim() != s
|| matches!(
s.to_lowercase().as_str(),
"true" | "false" | "yes" | "no" | "on" | "off" | "null" | "~"
)
|| s.parse::<f64>().is_ok();
if needs_quotes {
let escaped = s.replace('\\', "\\\\").replace('"', "\\\"");
format!("\"{escaped}\"")
} else {
s.to_owned()
}
}