Skip to main content

rightkit_context/
native_init.rs

1//! Explicit native `membrane init` enrollment.
2//!
3//! Operator-owned registry mutation: nothing here starts, stops or installs the
4//! resident.
5
6use serde_json::{json, Map, Value};
7use std::{
8    fs,
9    path::{Path, PathBuf},
10};
11
12#[derive(Debug, Clone)]
13pub struct InitOptions {
14    pub root: PathBuf,
15    pub repository_id: String,
16    pub scope_id: String,
17    pub rebind_from: Option<PathBuf>,
18    pub virtual_id: Option<String>,
19    pub tenant_id: Option<String>,
20    pub parents: Vec<String>,
21    pub native: Option<String>,
22    pub config: Option<PathBuf>,
23    pub dry_run: bool,
24}
25
26pub fn init(options: &InitOptions) -> Result<Value, String> {
27    let path = rightkit_context_runtime::authorization::default_registry_path()
28        .ok_or_else(|| "registry path is unresolvable".to_string())?;
29    if options.rebind_from.is_some() {
30        rebind_at(options, &path)
31    } else {
32        init_at(options, &path, None)
33    }
34}
35
36fn registry_key(path: &Path) -> String {
37    let absolute = if path.is_absolute() {
38        path.to_path_buf()
39    } else {
40        std::env::current_dir().unwrap_or_default().join(path)
41    };
42    let mut value = absolute.to_string_lossy().replace('\\', "/");
43    if let Some(rest) = value.strip_prefix("//?/") {
44        value = rest.to_owned();
45    }
46    while value.len() > 1 && value.ends_with('/') {
47        value.pop();
48    }
49    if cfg!(windows) {
50        value.to_ascii_lowercase()
51    } else {
52        value
53    }
54}
55
56fn rebind_at(options: &InitOptions, path: &Path) -> Result<Value, String> {
57    let old_requested = options
58        .rebind_from
59        .as_ref()
60        .ok_or("rebind source is required")?;
61    let new_root = fs::canonicalize(&options.root).map_err(|e| {
62        format!(
63            "canonicalize repository root {}: {e}",
64            options.root.display()
65        )
66    })?;
67    if !new_root.is_dir() {
68        return Err("new repository root must be a directory".into());
69    }
70    let old_key = registry_key(old_requested);
71    let old_canonical_key = fs::canonicalize(old_requested)
72        .ok()
73        .map(|path| registry_key(&path));
74    let new_key = registry_key(&new_root);
75    if old_key == new_key {
76        return Err("rebind source and target must differ".into());
77    }
78    let _lock = (!options.dry_run)
79        .then(|| registry_lock(path))
80        .transpose()?;
81    let mut registry = match fs::read(path) {
82        Ok(bytes) => serde_json::from_slice::<Value>(&bytes)
83            .map_err(|e| format!("registry is malformed: {e}"))?,
84        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
85            return Err("registry is missing".into())
86        }
87        Err(e) => return Err(format!("read registry {}: {e}", path.display())),
88    };
89    normalize_registry(&mut registry)?;
90    let bindings = registry
91        .get_mut("bindings")
92        .and_then(Value::as_object_mut)
93        .ok_or("registry bindings must be an object")?;
94    let matches = bindings
95        .keys()
96        .filter(|candidate| {
97            registry_key(Path::new(candidate)) == old_key
98                || fs::canonicalize(candidate)
99                    .ok()
100                    .is_some_and(|resolved| Some(registry_key(&resolved)) == old_canonical_key)
101        })
102        .cloned()
103        .collect::<Vec<_>>();
104    if matches.len() != 1 {
105        return Err(format!(
106            "rebind source must match exactly one registry binding (found {})",
107            matches.len()
108        ));
109    }
110    if bindings.keys().any(|candidate| {
111        registry_key(Path::new(candidate)) == new_key
112            || fs::canonicalize(candidate)
113                .ok()
114                .is_some_and(|resolved| registry_key(&resolved) == new_key)
115    }) {
116        return Err("rebind target already has a registry binding".into());
117    }
118    let source_key = matches.into_iter().next().unwrap();
119    let mut binding = bindings
120        .remove(&source_key)
121        .ok_or("rebind source disappeared")?;
122    if binding.get("repository_id").and_then(Value::as_str) != Some(options.repository_id.as_str())
123        || binding.get("scope_id").and_then(Value::as_str) != Some(options.scope_id.as_str())
124    {
125        return Err("rebind identity arguments do not match source binding".into());
126    }
127    if let Some(descriptor) = binding
128        .get_mut("scope_descriptor")
129        .and_then(Value::as_object_mut)
130    {
131        let descriptor_path = descriptor
132            .get("path")
133            .and_then(Value::as_str)
134            .map(Path::new);
135        let descriptor_matches_old = descriptor_path.is_some_and(|path| {
136            registry_key(path) == old_key
137                || fs::canonicalize(path)
138                    .ok()
139                    .is_some_and(|resolved| Some(registry_key(&resolved)) == old_canonical_key)
140        });
141        if descriptor.get("kind").and_then(Value::as_str) == Some("filesystem")
142            && descriptor_matches_old
143        {
144            descriptor.insert(
145                "path".into(),
146                Value::String(new_root.to_string_lossy().into_owned()),
147            );
148        }
149    }
150    bindings.insert(new_root.to_string_lossy().into_owned(), binding);
151    let receipt = json!({"action":"rebind","source_root":source_key,"root":new_root,"registry":path,"dry_run":options.dry_run});
152    if !options.dry_run {
153        write_atomic(path, &registry)?;
154    }
155    Ok(receipt)
156}
157
158fn init_at(
159    options: &InitOptions,
160    path: &Path,
161    injected_binding: Option<Value>,
162) -> Result<Value, String> {
163    let root = fs::canonicalize(&options.root).map_err(|e| {
164        format!(
165            "canonicalize repository root {}: {e}",
166            options.root.display()
167        )
168    })?;
169    if !root.is_dir() {
170        return Err("project root must be a directory".into());
171    }
172    if options.repository_id.trim().is_empty() || options.scope_id.trim().is_empty() {
173        return Err("repository & scope are required".into());
174    }
175    let descriptor = if let Some(id) = &options.virtual_id {
176        if id.trim().is_empty() {
177            return Err("--virtual-id is invalid".into());
178        }
179        let tenant = options
180            .tenant_id
181            .as_deref()
182            .filter(|v| !v.trim().is_empty())
183            .ok_or_else(|| "--tenant-id is required with --virtual-id".to_string())?;
184        json!({"kind":"virtual","id":id,"tenant_id":tenant,"parents":options.parents,"inherit_global":false})
185    } else {
186        if options.tenant_id.is_some() || !options.parents.is_empty() {
187            return Err("--tenant-id/--parent require --virtual-id".into());
188        }
189        json!({"kind":"filesystem","path":options.scope_id})
190    };
191    validate_descriptor(&descriptor)?;
192    let provider = {
193        let mut value = Map::from_iter([(String::from("transport"), json!("loopback"))]);
194        if let Some(path) = &options.config {
195            value.insert("config".into(), json!({"path":path}));
196        }
197        if let Some(name) = &options.native {
198            value.insert("native".into(), json!({"name":name}));
199        }
200        if !options.dry_run {
201            let binding = match injected_binding.clone() {
202                Some(binding) => binding,
203                None => rightkit_context_runtime::service::installed_binding_projection()?,
204            };
205            value.insert("installation_binding".into(), binding);
206        }
207        Value::Object(value)
208    };
209    let receipt_installation_binding = provider.get("installation_binding").cloned();
210    let _lock = (!options.dry_run)
211        .then(|| registry_lock(path))
212        .transpose()?;
213    let mut registry = match fs::read(path) {
214        Ok(bytes) => serde_json::from_slice::<Value>(&bytes)
215            .map_err(|e| format!("registry is malformed: {e}"))?,
216        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
217            json!({"schema_version":2,"bindings":{}})
218        }
219        Err(e) => return Err(format!("read registry {}: {e}", path.display())),
220    };
221    normalize_registry(&mut registry)?;
222    let bindings = registry
223        .get_mut("bindings")
224        .and_then(Value::as_object_mut)
225        .ok_or_else(|| "registry bindings must be an object".to_string())?;
226    let key = root.to_string_lossy().into_owned();
227    #[cfg(windows)]
228    let key = if let Some(unc) = key.strip_prefix(r"\\?\UNC\") {
229        format!(r"\\{unc}")
230    } else {
231        key.strip_prefix(r"\\?\").unwrap_or(&key).to_string()
232    };
233    // JS realpath & Rust canonicalize spell Windows device paths differently.
234    // Resolve existing keys before replacing so enrollment cannot fork authority
235    // or lose token metadata solely because of spelling/case.
236    let prior_keys = bindings
237        .keys()
238        .filter(|candidate| {
239            *candidate == &key || fs::canonicalize(candidate).ok().as_ref() == Some(&root)
240        })
241        .cloned()
242        .collect::<Vec<_>>();
243    if prior_keys.len() > 1 {
244        return Err("registry contains duplicate canonical repository roots".into());
245    }
246    let prior = prior_keys
247        .first()
248        .and_then(|prior_key| bindings.remove(prior_key));
249    let prior_object = prior.as_ref().and_then(Value::as_object);
250    let mut object = Map::new();
251    object.insert("repository_id".into(), json!(options.repository_id));
252    object.insert("scope_id".into(), json!(options.scope_id));
253    object.insert("scope_descriptor".into(), descriptor);
254    object.insert("provider_config".into(), provider);
255    // Public Pull remains read-only, while public Push writes exact agent-authored
256    // memory. Normal enrollment must therefore admit the narrow write operation.
257    object.insert("grant_policy".into(), json!({"level":"write-proposed"}));
258    for field in ["token_grant", "token_audit"] {
259        if let Some(value) = prior_object.and_then(|prior| prior.get(field)) {
260            object.insert(field.into(), value.clone());
261        }
262    }
263    bindings.insert(key.clone(), Value::Object(object));
264    let installation = json!({"precedence":"native_then_config","selected":if options.native.is_some(){"native"}else if options.config.is_some(){"config"}else{"loopback"},"native":options.native.as_ref().map(|name| json!({"name":name})),"config":options.config.as_ref().map(|path| json!({"path":path}))});
265    let mut receipt = json!({"action":"enroll","root":key,"repository_id":options.repository_id,"scope_id":options.scope_id,"registry":path,"installation":installation,"dry_run":options.dry_run});
266    if let Some(binding) = receipt_installation_binding {
267        receipt["installation_binding"] = binding.clone();
268    }
269    if !options.dry_run {
270        write_atomic(path, &registry)?;
271    }
272    Ok(receipt)
273}
274
275fn validate_descriptor(value: &Value) -> Result<(), String> {
276    let object = value
277        .as_object()
278        .ok_or("scope_descriptor must be an object")?;
279    match object.get("kind").and_then(Value::as_str) {
280        Some("filesystem")
281            if object.get("path").and_then(Value::as_str).is_some()
282                && object.keys().all(|k| k == "kind" || k == "path") =>
283        {
284            Ok(())
285        }
286        Some("virtual") => {
287            if object
288                .get("id")
289                .and_then(Value::as_str)
290                .is_none_or(|v| v.trim().is_empty())
291                || object
292                    .get("tenant_id")
293                    .and_then(Value::as_str)
294                    .is_none_or(|v| v.trim().is_empty())
295            {
296                return Err("virtual scope_descriptor identity is invalid".into());
297            }
298            let parents = object
299                .get("parents")
300                .and_then(Value::as_array)
301                .ok_or("virtual scope_descriptor parents are invalid")?;
302            if parents.len() > 7 {
303                return Err("virtual scope_descriptor parents are invalid".into());
304            }
305            let mut seen = std::collections::HashSet::new();
306            if parents.iter().any(|v| {
307                v.as_str().is_none_or(|p| {
308                    p.trim().is_empty() || p.starts_with("virtual:") || !seen.insert(p)
309                })
310            }) {
311                return Err("virtual scope_descriptor parents are invalid".into());
312            }
313            if object.get("inherit_global") != Some(&Value::Bool(false))
314                || object.keys().any(|k| {
315                    !["kind", "id", "tenant_id", "parents", "inherit_global"].contains(&k.as_str())
316                })
317            {
318                return Err("virtual scope_descriptor global inheritance is invalid".into());
319            }
320            Ok(())
321        }
322        _ => Err("scope_descriptor kind is invalid".into()),
323    }
324}
325
326fn normalize_registry(registry: &mut Value) -> Result<(), String> {
327    let version = registry
328        .get("schema_version")
329        .and_then(Value::as_u64)
330        .ok_or("schema_version must be 1 or 2")?;
331    if version != 1 && version != 2 {
332        return Err("schema_version must be 1 or 2".into());
333    }
334    if version == 1 {
335        registry["schema_version"] = json!(2);
336        if let Some(bindings) = registry.get_mut("bindings").and_then(Value::as_object_mut) {
337            for (root, binding) in bindings.iter_mut() {
338                if !binding.is_object() {
339                    return Err(format!("binding {root} is malformed"));
340                }
341                if binding.get("scope_descriptor").is_none() {
342                    let scope = binding
343                        .get("scope_id")
344                        .and_then(Value::as_str)
345                        .unwrap_or(root);
346                    binding["scope_descriptor"] = json!({"kind":"filesystem","path":scope});
347                }
348            }
349        }
350    }
351    if !registry.get("bindings").is_some_and(Value::is_object) {
352        return Err("registry bindings must be an object".into());
353    }
354    for (root, binding) in registry["bindings"].as_object().unwrap() {
355        let object = binding
356            .as_object()
357            .ok_or_else(|| format!("binding {root} is malformed"))?;
358        if object
359            .get("repository_id")
360            .and_then(Value::as_str)
361            .is_none_or(|v| v.trim().is_empty())
362            || object
363                .get("scope_id")
364                .and_then(Value::as_str)
365                .is_none_or(|v| v.trim().is_empty())
366        {
367            return Err(format!("binding {root} identity is invalid"));
368        }
369        if let Some(descriptor) = object.get("scope_descriptor") {
370            validate_descriptor(descriptor)?;
371        }
372    }
373    Ok(())
374}
375
376fn write_atomic(path: &Path, value: &Value) -> Result<(), String> {
377    let parent = path.parent().ok_or("registry has no parent")?;
378    fs::create_dir_all(parent).map_err(|e| format!("create registry directory: {e}"))?;
379    let bytes = serde_json::to_vec_pretty(value).map_err(|e| format!("serialize registry: {e}"))?;
380    rightkit_fs::atomic_write(path, &bytes).map_err(|e| format!("replace registry: {e}"))
381}
382
383/// Serializes registry read-modify-write across processes. The OS lock is released on exit or
384/// crash, so a killed writer cannot leave the registry busy.
385fn registry_lock(registry: &Path) -> Result<rightkit_fs::lock::FileLock, String> {
386    let path = registry.with_extension("json.lock");
387    fs::create_dir_all(registry.parent().ok_or("registry has no parent")?)
388        .map_err(|e| format!("create registry directory: {e}"))?;
389    rightkit_fs::lock::FileLock::acquire(&path, &rightkit_fs::lock::LockOptions::default())
390        .map_err(|e| format!("registry is busy: {e}"))
391}