use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use crate::model::{
ExecutionSpec, ProfileEntry, ProfileResolution, ProfileSelection, ProfileSelectionSource,
ProfileView, SecretRef, now_ms,
};
use crate::store::Store;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub(crate) struct Profile {
pub(crate) name: String,
#[serde(default)]
pub(crate) literals: BTreeMap<String, String>,
#[serde(default)]
pub(crate) secrets: BTreeMap<String, SecretRef>,
pub(crate) generation: String,
pub(crate) updated_at: u64,
}
impl Profile {
pub(crate) fn empty(name: impl Into<String>) -> Self {
let mut profile = Self {
name: name.into(),
literals: BTreeMap::new(),
secrets: BTreeMap::new(),
generation: String::new(),
updated_at: now_ms(),
};
profile.refresh_generation();
profile
}
pub(crate) fn refresh_generation(&mut self) {
let encoded = serde_json::to_vec(&serde_json::json!({
"literals": self.literals,
"secrets": self.secrets,
}))
.expect("profile definitions serialize");
self.generation = format!("sha256:{:x}", Sha256::digest(encoded));
self.updated_at = now_ms();
}
pub(crate) fn selection(
&self,
source: ProfileSelectionSource,
matched_root: Option<String>,
) -> ProfileSelection {
let mut variables = self
.literals
.keys()
.chain(self.secrets.keys())
.cloned()
.collect::<Vec<_>>();
variables.sort();
variables.dedup();
ProfileSelection {
name: self.name.clone(),
generation: self.generation.clone(),
source,
matched_root,
variables,
}
}
}
pub(crate) fn validate_profile_name(name: &str) -> Result<(), String> {
let mut characters = name.chars();
let valid_first = characters
.next()
.is_some_and(|character| character.is_ascii_alphanumeric());
if name.len() > 64
|| !valid_first
|| !characters.all(|character| {
character.is_ascii_alphanumeric() || matches!(character, '.' | '_' | '-')
})
{
return Err(format!(
"PROFILE_NAME_INVALID: profile name \"{name}\" must match [A-Za-z0-9][A-Za-z0-9._-]{{0,63}}"
));
}
Ok(())
}
pub(crate) fn resolve_profile(
store: &Store,
cwd: Option<&str>,
explicit: Option<&str>,
) -> Result<ProfileResolution, String> {
let cwd = cwd.map(canonical_path).transpose()?;
let matched = cwd
.as_deref()
.map(|cwd| workspace_profile(store, cwd))
.transpose()?
.flatten();
if let (Some(explicit), Some((_, mapped))) = (explicit, matched.as_ref())
&& explicit != mapped
{
return Err(format!(
"PROFILE_CONFLICT: explicit profile \"{explicit}\" conflicts with workspace profile \"{mapped}\""
));
}
let (name, source, matched_root) = if let Some(explicit) = explicit {
(explicit.to_string(), ProfileSelectionSource::Explicit, None)
} else if let Some((root, name)) = matched {
(name, ProfileSelectionSource::Workspace, Some(root))
} else if let Some(default) = store.default_profile()? {
(default, ProfileSelectionSource::UserDefault, None)
} else {
return Ok(ProfileResolution {
cwd,
selection: None,
});
};
let profile = store
.get_profile(&name)?
.ok_or_else(|| format!("PROFILE_NOT_FOUND: profile \"{name}\" does not exist"))?;
Ok(ProfileResolution {
cwd,
selection: Some(profile.selection(source, matched_root)),
})
}
fn mapped_profile(store: &Store, cwd: &str) -> Result<Option<(String, String)>, String> {
let cwd = canonical_path(cwd)?;
workspace_profile(store, &cwd)
}
pub(crate) fn canonical_path(value: &str) -> Result<String, String> {
std::fs::canonicalize(value)
.map(|path| path.to_string_lossy().into_owned())
.map_err(|error| {
format!("PROFILE_ROOT_NOT_FOUND: could not canonicalize \"{value}\": {error}")
})
}
fn longest_root_match(cwd: &str, roots: &[(String, String)]) -> Option<(String, String)> {
let cwd = Path::new(cwd);
roots
.iter()
.filter(|(root, _)| cwd.starts_with(PathBuf::from(root)))
.max_by_key(|(root, _)| Path::new(root).components().count())
.cloned()
}
fn workspace_profile(store: &Store, cwd: &str) -> Result<Option<(String, String)>, String> {
if let Some(mapped) = longest_root_match(cwd, &store.list_profile_roots()?) {
return Ok(Some(mapped));
}
let profiles = store.list_profiles()?;
Ok(Path::new(cwd).ancestors().find_map(|ancestor| {
let component = ancestor.file_name()?.to_str()?;
profiles
.iter()
.find(|profile| profile.name == component)
.map(|profile| {
(
ancestor.to_string_lossy().into_owned(),
profile.name.clone(),
)
})
}))
}
pub(crate) fn profile_view(profile: &Profile, roots: Vec<String>, is_default: bool) -> ProfileView {
let mut entries = profile
.literals
.keys()
.map(|name| ProfileEntry {
name: name.clone(),
kind: "literal".to_string(),
resolvable: true,
error_code: None,
})
.collect::<Vec<_>>();
entries.extend(profile.secrets.iter().map(|(name, secret)| {
let resolvable = secret.provider == "env" && std::env::var_os(&secret.reference).is_some();
ProfileEntry {
name: name.clone(),
kind: "secret".to_string(),
resolvable,
error_code: (!resolvable).then(|| {
if secret.provider == "env" {
"SECRET_UNAVAILABLE"
} else {
"SECRET_PROVIDER_UNSUPPORTED"
}
.to_string()
}),
}
}));
entries.sort_by(|left, right| left.name.cmp(&right.name));
ProfileView {
name: profile.name.clone(),
generation: profile.generation.clone(),
is_default,
roots,
entries,
}
}
pub(crate) fn profile_view_by_name(store: &Store, name: &str) -> Result<ProfileView, String> {
let profile = store
.get_profile(name)?
.ok_or_else(|| format!("PROFILE_NOT_FOUND: profile \"{name}\" does not exist"))?;
let roots = store.roots_for_profile(name)?;
let is_default = store.default_profile()?.as_deref() == Some(name);
Ok(profile_view(&profile, roots, is_default))
}
pub(crate) fn profile_views(store: &Store) -> Result<Vec<ProfileView>, String> {
store
.list_profiles()?
.iter()
.map(|profile| profile_view_by_name(store, &profile.name))
.collect()
}
pub(crate) fn bind_profile(
store: &Store,
cwd: Option<&str>,
explicit: Option<&str>,
parent: Option<&Option<ProfileSelection>>,
spec: &mut ExecutionSpec,
) -> Result<(), String> {
let (selection, profile) = if let Some(Some(parent)) = parent {
if let Some(explicit) = explicit
&& explicit != parent.name
{
return Err(format!(
"PROFILE_BOUNDARY_VIOLATION: child requested profile \"{explicit}\" but its owner uses \"{}\"",
parent.name
));
}
if let Some((_, mapped)) = cwd
.map(|cwd| mapped_profile(store, cwd))
.transpose()?
.flatten()
&& mapped != parent.name
{
return Err(format!(
"PROFILE_BOUNDARY_VIOLATION: workspace profile \"{mapped}\" conflicts with owner profile \"{}\"",
parent.name
));
}
let profile = store
.get_profile_generation(&parent.name, &parent.generation)?
.ok_or_else(|| {
format!(
"PROFILE_GENERATION_NOT_FOUND: profile \"{}\" generation \"{}\" is unavailable",
parent.name, parent.generation
)
})?;
(Some(parent.clone()), Some(profile))
} else if parent.is_some() {
if let Some(explicit) = explicit {
return Err(format!(
"PROFILE_BOUNDARY_VIOLATION: credential-free owner cannot select profile \"{explicit}\""
));
}
if let Some((_, mapped)) = cwd
.map(|cwd| mapped_profile(store, cwd))
.transpose()?
.flatten()
{
return Err(format!(
"PROFILE_BOUNDARY_VIOLATION: credential-free owner cannot enter workspace profile \"{mapped}\""
));
}
(None, None)
} else {
let resolution = resolve_profile(store, cwd, explicit)?;
let profile = resolution
.selection
.as_ref()
.map(|selection| store.get_profile_generation(&selection.name, &selection.generation))
.transpose()?
.flatten();
(resolution.selection, profile)
};
let controlled = store.controlled_profile_keys()?;
if let crate::model::ExecutionProgram::Commands { commands, .. } = &spec.program {
for command in commands {
if let Some(selection) = selection.as_ref()
&& let Some((_, mapped)) = command
.cwd
.as_deref()
.map(|cwd| mapped_profile(store, cwd))
.transpose()?
.flatten()
&& mapped != selection.name
{
return Err(format!(
"PROFILE_BOUNDARY_VIOLATION: command \"{}\" workspace profile \"{mapped}\" conflicts with execution profile \"{}\"",
command.id, selection.name
));
}
if let Some(name) = command
.env
.keys()
.chain(command.secrets.keys())
.find(|name| controlled.binary_search(name).is_ok())
{
return Err(format!(
"PROFILE_VARIABLE_OVERRIDE: command \"{}\" cannot override profile-controlled variable \"{name}\"",
command.id
));
}
}
}
let explicit_literals = std::mem::take(&mut spec.env);
let explicit_secrets = std::mem::take(&mut spec.secrets);
if let Some(name) = explicit_literals
.keys()
.chain(explicit_secrets.keys())
.find(|name| controlled.binary_search(name).is_ok())
{
return Err(format!(
"PROFILE_VARIABLE_OVERRIDE: command input cannot override profile-controlled variable \"{name}\""
));
}
if let Some(profile) = profile {
spec.env = profile.literals;
spec.secrets = profile.secrets;
}
for (name, value) in explicit_literals {
spec.secrets.remove(&name);
spec.env.insert(name, value);
}
for (name, value) in explicit_secrets {
spec.env.remove(&name);
spec.secrets.insert(name, value);
}
spec.profile_selection = selection;
Ok(())
}
#[cfg(test)]
mod tests {
use tempfile::tempdir;
use super::*;
#[test]
fn resolver_uses_explicit_profile_before_defaults() {
let directory = tempdir().unwrap();
let store = Store::open(directory.path().join("state.sqlite3")).unwrap();
store.put_profile(&Profile::empty("velo")).unwrap();
let resolution = resolve_profile(
&store,
Some(directory.path().to_str().unwrap()),
Some("velo"),
)
.unwrap();
assert_eq!(
resolution
.selection
.as_ref()
.map(|selection| selection.name.as_str()),
Some("velo")
);
}
#[test]
fn resolver_uses_longest_component_root_and_rejects_explicit_conflicts() {
let directory = tempdir().unwrap();
let nested = directory.path().join("company/project");
std::fs::create_dir_all(&nested).unwrap();
let store = Store::open(directory.path().join("state.sqlite3")).unwrap();
store.put_profile(&Profile::empty("personal")).unwrap();
store.put_profile(&Profile::empty("velo")).unwrap();
let outer = canonical_path(directory.path().to_str().unwrap()).unwrap();
let inner = canonical_path(directory.path().join("company").to_str().unwrap()).unwrap();
store.put_profile_root("personal", &outer).unwrap();
store.put_profile_root("velo", &inner).unwrap();
let resolution = resolve_profile(&store, Some(nested.to_str().unwrap()), None).unwrap();
let selection = resolution.selection.unwrap();
assert_eq!(selection.name, "velo");
assert_eq!(selection.source, ProfileSelectionSource::Workspace);
assert_eq!(selection.matched_root.as_deref(), Some(inner.as_str()));
assert!(
resolve_profile(&store, Some(nested.to_str().unwrap()), Some("personal"))
.unwrap_err()
.starts_with("PROFILE_CONFLICT:")
);
}
#[test]
fn resolver_infers_the_nearest_profile_named_cwd_ancestor() {
let directory = tempdir().unwrap();
let profile_root = directory.path().join("personal/velo");
let nested = profile_root.join("project/src");
std::fs::create_dir_all(&nested).unwrap();
let store = Store::open(directory.path().join("state.sqlite3")).unwrap();
store.put_profile(&Profile::empty("personal")).unwrap();
store.put_profile(&Profile::empty("velo")).unwrap();
let resolution = resolve_profile(&store, Some(nested.to_str().unwrap()), None).unwrap();
let selection = resolution.selection.unwrap();
assert_eq!(selection.name, "velo");
assert_eq!(selection.source, ProfileSelectionSource::Workspace);
assert_eq!(
selection.matched_root.as_deref(),
Some(
canonical_path(profile_root.to_str().unwrap())
.unwrap()
.as_str()
)
);
assert!(
resolve_profile(&store, Some(nested.to_str().unwrap()), Some("personal"))
.unwrap_err()
.starts_with("PROFILE_CONFLICT:")
);
let explicit_root = canonical_path(directory.path().to_str().unwrap()).unwrap();
store.put_profile_root("personal", &explicit_root).unwrap();
let mapped = resolve_profile(&store, Some(nested.to_str().unwrap()), None)
.unwrap()
.selection
.unwrap();
assert_eq!(mapped.name, "personal");
assert_eq!(mapped.matched_root.as_deref(), Some(explicit_root.as_str()));
}
#[test]
fn resolver_falls_back_to_user_default_and_then_no_profile() {
let directory = tempdir().unwrap();
let store = Store::open(directory.path().join("state.sqlite3")).unwrap();
store.put_profile(&Profile::empty("personal")).unwrap();
store.set_default_profile(Some("personal")).unwrap();
assert_eq!(
resolve_profile(&store, Some(directory.path().to_str().unwrap()), None)
.unwrap()
.selection
.unwrap()
.source,
ProfileSelectionSource::UserDefault
);
store.set_default_profile(None).unwrap();
assert!(
resolve_profile(&store, Some(directory.path().to_str().unwrap()), None)
.unwrap()
.selection
.is_none()
);
}
#[test]
fn profile_names_follow_the_public_contract() {
assert!(validate_profile_name("velo.production-1").is_ok());
assert!(validate_profile_name("").is_err());
assert!(validate_profile_name("_private").is_err());
assert!(validate_profile_name(&"a".repeat(65)).is_err());
}
}