Skip to main content

lean_ctx_cloud/
company_bound.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Personal beside the Company (owner decision 26.10.): a Personal workspace
3//! stays private and never belongs to a company, and a company may keep its
4//! teams' project knowledge out of personal workspaces with the policy
5//! member `sharing.personal_workspace: forbid` (tighten-only, default
6//! `allow`).
7//!
8//! An engine is enrolled in one workspace at a time, and Cloud never lets an
9//! engine of a team reach a vault of another workspace, so the leak this
10//! closes is local: the same machine, later enrolled in the person's
11//! Personal workspace, giving a project it worked on in the team a personal
12//! vault (and capturing its knowledge there). While enrolled in a team
13//! whose effective policy says `forbid`, the engine records every project
14//! it maps there (a digest of the project identity, never a path or remote)
15//! with the company's name in `<config_dir>/cloud/company_projects.json`
16//! (0600), which survives `cloud disconnect`. Enrolled in a Personal
17//! workspace, mapping such a project to a vault is refused.
18//!
19//! Cloud enforces what it can see on its own (moving a vault into a
20//! Personal workspace, W11). Another machine, another data directory or an
21//! engine before this one is not covered: there the member is advisory.
22
23use std::collections::BTreeMap;
24
25use serde::{Deserialize, Serialize};
26use sha2::{Digest, Sha256};
27
28use super::effective_floor::{check, floor_dir_in, read};
29use super::{CloudError, CloudStore};
30
31pub const FILE: &str = "company_projects.json";
32pub const SCHEMA: &str = "leanctx.cloud.company-projects/v1";
33
34#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
35#[serde(deny_unknown_fields)]
36struct Registry {
37    schema: String,
38    /// `sha256(identity)` → the company's name (the team's when unknown).
39    projects: BTreeMap<String, String>,
40}
41
42fn key(stable: &str) -> String {
43    hex::encode(Sha256::digest(stable.as_bytes()))
44}
45
46fn load(store: &CloudStore) -> Registry {
47    store
48        .read_config::<Registry>(FILE)
49        .ok()
50        .flatten()
51        .filter(|r| r.schema == SCHEMA)
52        .unwrap_or_default()
53}
54
55/// Whether the installed effective policy (the default or any vault's)
56/// says `sharing.personal_workspace: forbid`.
57pub fn forbids(store: &CloudStore) -> bool {
58    let Ok((floor, required)) = read(&floor_dir_in(store.data_dir())) else {
59        return false;
60    };
61    let Ok(Some(floor)) = check(floor.as_deref(), required.as_deref()) else {
62        return false;
63    };
64    let forbid = |p: &lean_ctx_protocol::cloud::effective_policy::EffectivePolicyV1| {
65        p.sharing.personal_workspace.as_deref() == Some("forbid")
66    };
67    forbid(&floor.policy.effective) || floor.policy.vaults.iter().any(|v| forbid(&v.effective))
68}
69
70/// Record `stables` as projects of `company`.
71pub fn record<'a>(
72    store: &CloudStore,
73    company: &str,
74    stables: impl IntoIterator<Item = &'a str>,
75) -> Result<(), CloudError> {
76    let mut r = load(store);
77    let before = r.clone();
78    r.schema = SCHEMA.into();
79    for stable in stables {
80        r.projects.insert(key(stable), company.to_string());
81    }
82    if r == before {
83        return Ok(());
84    }
85    store.write_config(FILE, &r)
86}
87
88/// The company that keeps the project `stable` out of personal workspaces.
89pub fn company_of(store: &CloudStore, stable: &str) -> Option<String> {
90    load(store).projects.get(&key(stable)).cloned()
91}
92
93/// The name a record carries: the team's company, else the team.
94fn company_name(instance: &super::state::InstanceRecord) -> String {
95    instance
96        .company_name
97        .clone()
98        .unwrap_or_else(|| instance.org_name.clone())
99}
100
101/// Before a project gets a vault in the enrolled workspace (`map_root`):
102/// in a team whose policy forbids, the project is recorded; in a Personal
103/// workspace, a recorded project is refused.
104pub fn on_map(
105    store: &CloudStore,
106    instance: &super::state::InstanceRecord,
107    stable: &str,
108) -> Result<(), CloudError> {
109    match instance.org_kind.as_deref() {
110        Some("team") if forbids(store) => record(store, &company_name(instance), [stable]),
111        Some("personal") => match company_of(store, stable) {
112            Some(company) => Err(CloudError::Refused(format!(
113                "{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"
114            ))),
115            None => Ok(()),
116        },
117        _ => Ok(()),
118    }
119}
120
121/// After a policy pull: in a team whose policy forbids, every project this
122/// machine already mapped is recorded too.
123pub fn on_policy(store: &CloudStore, instance: &super::state::InstanceRecord) {
124    if instance.org_kind.as_deref() != Some("team") || !forbids(store) {
125        return;
126    }
127    let map = super::vault::connected_map(store);
128    let _ = record(
129        store,
130        &company_name(instance),
131        map.vaults.keys().map(String::as_str),
132    );
133}
134
135#[cfg(test)]
136mod tests {
137    use super::*;
138    use crate::state::InstanceRecord;
139
140    fn instance(kind: &str) -> InstanceRecord {
141        InstanceRecord {
142            instance_id: "inst_1".into(),
143            org_id: "org_1".into(),
144            org_name: "Platform".into(),
145            label: "mbp".into(),
146            url: "https://cloud.example".into(),
147            org_salt_id: "s".into(),
148            enrolled_at: "2026-10-26T10:00:00Z".into(),
149            web_url: None,
150            org_kind: Some(kind.into()),
151            company_name: (kind == "team").then(|| "Acme Group".into()),
152        }
153    }
154
155    fn install(store: &CloudStore, mode: &str) {
156        let dir = floor_dir_in(store.data_dir());
157        let floor = serde_json::json!({
158            "schema": super::super::effective_floor::FLOOR_SCHEMA,
159            "version": 3, "digest": format!("sha256:{}", "a".repeat(64)),
160            "not_after": "2099-01-01T00:00:00Z",
161            "policy": {"effective": {"schema": "leanctx.cloud.policy/v1", "security": {}, "context": {},
162                                     "sharing": {"personal_workspace": mode}},
163                       "vaults": []}
164        });
165        super::super::state::write_private(
166            &dir,
167            super::super::effective_floor::FLOOR_FILE,
168            &serde_json::to_vec(&floor).unwrap(),
169        )
170        .unwrap();
171        super::super::state::write_private(
172            &dir,
173            super::super::effective_floor::REQUIRED_FILE,
174            br#"{"version":3}"#,
175        )
176        .unwrap();
177    }
178
179    #[test]
180    fn a_team_project_never_gets_a_personal_vault_when_the_company_forbids() {
181        let dir = tempfile::tempdir().unwrap();
182        let store = CloudStore::at(dir.path().join("config"), dir.path().join("data"));
183        let team = instance("team");
184        let personal = instance("personal");
185        // allow (the default): nothing is recorded, Personal maps freely.
186        install(&store, "allow");
187        on_map(&store, &team, "git:acme/payments").unwrap();
188        assert_eq!(company_of(&store, "git:acme/payments"), None);
189        // forbid: the team's project is recorded with the company's name.
190        install(&store, "forbid");
191        assert!(forbids(&store));
192        on_map(&store, &team, "git:acme/payments").unwrap();
193        assert_eq!(
194            company_of(&store, "git:acme/payments").as_deref(),
195            Some("Acme Group")
196        );
197        // The record keeps no identity in clear text.
198        let text = String::from_utf8(store.read_config_bytes(FILE).unwrap().unwrap()).unwrap();
199        assert!(!text.contains("payments"), "{text}");
200        // Enrolled in the person's Personal workspace (the team's policy
201        // no longer installed): that project is refused, another one maps.
202        let _ = std::fs::remove_dir_all(floor_dir_in(store.data_dir()));
203        let refused = on_map(&store, &personal, "git:acme/payments").unwrap_err();
204        assert!(
205            refused.to_string().contains("Acme Group keeps"),
206            "{refused}"
207        );
208        on_map(&store, &personal, "git:me/dotfiles").unwrap();
209        // It survives a disconnect (forget keeps it).
210        store.forget(false).unwrap();
211        assert!(on_map(&store, &personal, "git:acme/payments").is_err());
212    }
213}