use std::collections::BTreeMap;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use super::effective_floor::{check, floor_dir_in, read};
use super::{CloudError, CloudStore};
pub const FILE: &str = "company_projects.json";
pub const SCHEMA: &str = "leanctx.cloud.company-projects/v1";
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct Registry {
schema: String,
projects: BTreeMap<String, String>,
}
fn key(stable: &str) -> String {
hex::encode(Sha256::digest(stable.as_bytes()))
}
fn load(store: &CloudStore) -> Registry {
store
.read_config::<Registry>(FILE)
.ok()
.flatten()
.filter(|r| r.schema == SCHEMA)
.unwrap_or_default()
}
pub fn forbids(store: &CloudStore) -> bool {
let Ok((floor, required)) = read(&floor_dir_in(store.data_dir())) else {
return false;
};
let Ok(Some(floor)) = check(floor.as_deref(), required.as_deref()) else {
return false;
};
let forbid = |p: &lean_ctx_protocol::cloud::effective_policy::EffectivePolicyV1| {
p.sharing.personal_workspace.as_deref() == Some("forbid")
};
forbid(&floor.policy.effective) || floor.policy.vaults.iter().any(|v| forbid(&v.effective))
}
pub fn record<'a>(
store: &CloudStore,
company: &str,
stables: impl IntoIterator<Item = &'a str>,
) -> Result<(), CloudError> {
let mut r = load(store);
let before = r.clone();
r.schema = SCHEMA.into();
for stable in stables {
r.projects.insert(key(stable), company.to_string());
}
if r == before {
return Ok(());
}
store.write_config(FILE, &r)
}
pub fn company_of(store: &CloudStore, stable: &str) -> Option<String> {
load(store).projects.get(&key(stable)).cloned()
}
fn company_name(instance: &super::state::InstanceRecord) -> String {
instance
.company_name
.clone()
.unwrap_or_else(|| instance.org_name.clone())
}
pub fn on_map(
store: &CloudStore,
instance: &super::state::InstanceRecord,
stable: &str,
) -> Result<(), CloudError> {
match instance.org_kind.as_deref() {
Some("team") if forbids(store) => record(store, &company_name(instance), [stable]),
Some("personal") => match company_of(store, stable) {
Some(company) => Err(CloudError::Refused(format!(
"{company} keeps the knowledge of this project out of Personal workspaces (company policy sharing.personal_workspace: forbid); work on it in the company's team"
))),
None => Ok(()),
},
_ => Ok(()),
}
}
pub fn on_policy(store: &CloudStore, instance: &super::state::InstanceRecord) {
if instance.org_kind.as_deref() != Some("team") || !forbids(store) {
return;
}
let map = super::vault::connected_map(store);
let _ = record(
store,
&company_name(instance),
map.vaults.keys().map(String::as_str),
);
}
#[cfg(test)]
mod tests {
use super::*;
use crate::state::InstanceRecord;
fn instance(kind: &str) -> InstanceRecord {
InstanceRecord {
instance_id: "inst_1".into(),
org_id: "org_1".into(),
org_name: "Platform".into(),
label: "mbp".into(),
url: "https://cloud.example".into(),
org_salt_id: "s".into(),
enrolled_at: "2026-10-26T10:00:00Z".into(),
web_url: None,
org_kind: Some(kind.into()),
company_name: (kind == "team").then(|| "Acme Group".into()),
}
}
fn install(store: &CloudStore, mode: &str) {
let dir = floor_dir_in(store.data_dir());
let floor = serde_json::json!({
"schema": super::super::effective_floor::FLOOR_SCHEMA,
"version": 3, "digest": format!("sha256:{}", "a".repeat(64)),
"not_after": "2099-01-01T00:00:00Z",
"policy": {"effective": {"schema": "leanctx.cloud.policy/v1", "security": {}, "context": {},
"sharing": {"personal_workspace": mode}},
"vaults": []}
});
super::super::state::write_private(
&dir,
super::super::effective_floor::FLOOR_FILE,
&serde_json::to_vec(&floor).unwrap(),
)
.unwrap();
super::super::state::write_private(
&dir,
super::super::effective_floor::REQUIRED_FILE,
br#"{"version":3}"#,
)
.unwrap();
}
#[test]
fn a_team_project_never_gets_a_personal_vault_when_the_company_forbids() {
let dir = tempfile::tempdir().unwrap();
let store = CloudStore::at(dir.path().join("config"), dir.path().join("data"));
let team = instance("team");
let personal = instance("personal");
install(&store, "allow");
on_map(&store, &team, "git:acme/payments").unwrap();
assert_eq!(company_of(&store, "git:acme/payments"), None);
install(&store, "forbid");
assert!(forbids(&store));
on_map(&store, &team, "git:acme/payments").unwrap();
assert_eq!(
company_of(&store, "git:acme/payments").as_deref(),
Some("Acme Group")
);
let text = String::from_utf8(store.read_config_bytes(FILE).unwrap().unwrap()).unwrap();
assert!(!text.contains("payments"), "{text}");
let _ = std::fs::remove_dir_all(floor_dir_in(store.data_dir()));
let refused = on_map(&store, &personal, "git:acme/payments").unwrap_err();
assert!(
refused.to_string().contains("Acme Group keeps"),
"{refused}"
);
on_map(&store, &personal, "git:me/dotfiles").unwrap();
store.forget(false).unwrap();
assert!(on_map(&store, &personal, "git:acme/payments").is_err());
}
}