Skip to main content

systemprompt_models/profile/
mod.rs

1//! Profile configuration models — the deserialized shape of a
2//! `.systemprompt/profiles/<name>/profile.yaml` document.
3//!
4//! Covers server, database, paths, secrets, security, rate limits,
5//! gateway, governance, and runtime sections, plus validation rules and
6//! environment-variable interpolation.
7
8mod cloud;
9mod database;
10mod error;
11mod from_env;
12mod gateway;
13mod governance;
14mod info;
15mod paths;
16mod rate_limits;
17mod runtime;
18mod secrets;
19mod security;
20mod server;
21mod site;
22mod style;
23mod validation;
24
25pub use cloud::{CloudConfig, CloudValidationMode};
26pub use database::DatabaseConfig;
27pub use error::{ProfileError, ProfileResult};
28pub use gateway::{
29    GatewayCatalog, GatewayConfig, GatewayModel, GatewayProfileError, GatewayProvider,
30    GatewayResult, GatewayRoute, slugify_pattern, synthesize_route_id,
31};
32pub use governance::{
33    AuthzConfig, AuthzHookConfig, AuthzMode, GovernanceConfig, UNRESTRICTED_ACKNOWLEDGEMENT,
34};
35pub use info::ProfileInfo;
36pub use paths::{PathsConfig, expand_home, resolve_path, resolve_with_home};
37pub use rate_limits::{
38    RateLimitsConfig, TierMultipliers, default_a2a_multiplier, default_admin_multiplier,
39    default_agent_registry, default_agents, default_anon_multiplier, default_artifacts,
40    default_burst, default_content, default_contexts, default_mcp, default_mcp_multiplier,
41    default_mcp_registry, default_oauth_auth, default_oauth_public, default_service_multiplier,
42    default_stream, default_tasks, default_user_multiplier,
43};
44pub use runtime::{Environment, LogLevel, OutputFormat, RuntimeConfig};
45pub use secrets::{SecretsConfig, SecretsSource, SecretsValidationMode};
46pub use security::{SecurityConfig, TrustedIssuer};
47pub use server::{ContentNegotiationConfig, SecurityHeadersConfig, ServerConfig};
48pub use site::SiteConfig;
49pub use style::ProfileStyle;
50
51use regex::Regex;
52use serde::{Deserialize, Serialize};
53use std::path::Path;
54use std::sync::LazyLock;
55
56#[derive(Debug, Clone, Default, Serialize, Deserialize, schemars::JsonSchema)]
57#[serde(deny_unknown_fields)]
58pub struct ExtensionsConfig {
59    #[serde(default)]
60    pub disabled: Vec<String>,
61}
62
63impl ExtensionsConfig {
64    pub fn is_disabled(&self, extension_id: &str) -> bool {
65        self.disabled.iter().any(|id| id == extension_id)
66    }
67}
68
69#[allow(clippy::expect_used)]
70static ENV_VAR_REGEX: LazyLock<Regex> = LazyLock::new(|| {
71    Regex::new(r"\$\{(\w+)\}")
72        .expect("ENV_VAR_REGEX is a valid regex - this is a compile-time constant")
73});
74
75fn env_var_regex() -> &'static Regex {
76    &ENV_VAR_REGEX
77}
78
79fn substitute_env_vars(content: &str) -> String {
80    env_var_regex()
81        .replace_all(content, |caps: &regex::Captures| {
82            let var_name = &caps[1];
83            std::env::var(var_name).unwrap_or_else(|_| caps[0].to_string())
84        })
85        .to_string()
86}
87
88#[derive(
89    Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default, schemars::JsonSchema,
90)]
91#[serde(rename_all = "lowercase")]
92pub enum ProfileType {
93    #[default]
94    Local,
95    Cloud,
96}
97
98impl ProfileType {
99    pub const fn is_cloud(&self) -> bool {
100        matches!(self, Self::Cloud)
101    }
102
103    pub const fn is_local(&self) -> bool {
104        matches!(self, Self::Local)
105    }
106}
107
108#[derive(Debug, Clone, Serialize, Deserialize, schemars::JsonSchema)]
109#[serde(deny_unknown_fields)]
110pub struct Profile {
111    pub name: String,
112
113    pub display_name: String,
114
115    #[serde(default)]
116    pub target: ProfileType,
117
118    pub site: SiteConfig,
119
120    pub database: DatabaseConfig,
121
122    pub server: ServerConfig,
123
124    pub paths: PathsConfig,
125
126    pub security: SecurityConfig,
127
128    pub rate_limits: RateLimitsConfig,
129
130    pub system_admin: crate::services::SystemAdminConfig,
131
132    #[serde(default)]
133    pub runtime: RuntimeConfig,
134
135    #[serde(default)]
136    pub cloud: Option<CloudConfig>,
137
138    #[serde(default)]
139    pub secrets: Option<SecretsConfig>,
140
141    #[serde(default)]
142    pub extensions: ExtensionsConfig,
143
144    #[serde(default)]
145    pub gateway: Option<GatewayConfig>,
146
147    #[serde(default)]
148    pub governance: Option<GovernanceConfig>,
149}
150
151impl Profile {
152    #[must_use]
153    pub fn is_local_trial(&self) -> bool {
154        self.cloud.as_ref().is_none_or(CloudConfig::is_local_trial)
155    }
156
157    pub fn from_yaml(content: &str, profile_path: &Path) -> ProfileResult<Self> {
158        let content = substitute_env_vars(content);
159
160        let mut profile: Self =
161            serde_yaml::from_str(&content).map_err(|source| ProfileError::ParseYaml {
162                path: profile_path.to_path_buf(),
163                source,
164            })?;
165
166        let profile_dir =
167            profile_path
168                .parent()
169                .ok_or_else(|| ProfileError::InvalidProfilePath {
170                    path: profile_path.to_path_buf(),
171                })?;
172
173        profile.paths.resolve_relative_to(profile_dir);
174
175        Ok(profile)
176    }
177
178    pub fn to_yaml(&self) -> ProfileResult<String> {
179        serde_yaml::to_string(self).map_err(ProfileError::SerializeYaml)
180    }
181
182    pub fn profile_style(&self) -> ProfileStyle {
183        match self.name.to_lowercase().as_str() {
184            "dev" | "development" | "local" => ProfileStyle::Development,
185            "prod" | "production" => ProfileStyle::Production,
186            "staging" | "stage" => ProfileStyle::Staging,
187            "test" | "testing" => ProfileStyle::Test,
188            _ => ProfileStyle::Custom,
189        }
190    }
191
192    pub fn mask_secret(value: &str, visible_chars: usize) -> String {
193        if value.is_empty() {
194            return "(not set)".to_string();
195        }
196        if value.len() <= visible_chars {
197            return "***".to_string();
198        }
199        format!("{}...", &value[..visible_chars])
200    }
201
202    pub fn mask_database_url(url: &str) -> String {
203        if let Some(at_pos) = url.find('@') {
204            if let Some(colon_pos) = url[..at_pos].rfind(':') {
205                let prefix = &url[..=colon_pos];
206                let suffix = &url[at_pos..];
207                return format!("{}***{}", prefix, suffix);
208            }
209        }
210        url.to_string()
211    }
212
213    pub fn is_masked_database_url(url: &str) -> bool {
214        url.contains(":***@") || url.contains(":********@")
215    }
216}