1use std::fmt;
23use std::path::Path;
24
25use lean_ctx_time::UtcDateTime;
26use serde::{Deserialize, Serialize};
27use serde_json::Value;
28
29use super::auth::Session;
30use super::config::CloudConfig;
31use super::consent::{self, Broker, ConsentError, Kind, Trust};
32use super::identity_v2;
33use super::state::MATCH_FILE;
34use super::vault::{VaultRecord, identity_digest, resolve_request};
35use super::{CloudError, CloudStore};
36use lean_ctx_protocol::cloud::vault::{VaultRefV1, VaultV1};
37
38pub use lean_ctx_protocol::cloud::vault::{
39 VAULT_MATCH_REQUEST_SCHEMA as MATCH_REQUEST_SCHEMA, VAULT_MATCH_SCHEMA as MATCH_SCHEMA,
40};
41const REPROBE_SECONDS: i64 = 24 * 60 * 60;
43pub const NEW_VAULT_WS: &str = "new";
45
46#[derive(Debug, Clone, PartialEq, Eq)]
48pub enum MapError {
49 Cloud(CloudError),
50 Consent(ConsentError),
52}
53
54impl fmt::Display for MapError {
55 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
56 match self {
57 Self::Cloud(error) => error.fmt(f),
58 Self::Consent(error) => write!(f, "{}: {error}", error.code()),
59 }
60 }
61}
62
63impl From<CloudError> for MapError {
64 fn from(error: CloudError) -> Self {
65 Self::Cloud(error)
66 }
67}
68
69impl From<ConsentError> for MapError {
70 fn from(error: ConsentError) -> Self {
71 Self::Consent(error)
72 }
73}
74
75impl From<MapError> for CloudError {
76 fn from(error: MapError) -> Self {
77 match error {
78 MapError::Cloud(error) => error,
79 MapError::Consent(error) => error.into(),
80 }
81 }
82}
83
84#[derive(Serialize)]
85struct MatchCandidate {
86 kind: &'static str,
87 digest: String,
88}
89
90#[derive(Serialize)]
93struct MatchRequest<'a> {
94 schema: &'static str,
95 org_salt_id: &'a str,
96 candidates: &'a [MatchCandidate],
97}
98
99fn match_candidates(root: &Path, salt: &[u8]) -> Vec<MatchCandidate> {
102 salted(&identity_v2::match_candidates(root), salt)
103}
104
105fn salted(candidates: &[identity_v2::Candidate], salt: &[u8]) -> Vec<MatchCandidate> {
106 candidates
107 .iter()
108 .map(|c| MatchCandidate {
109 kind: c.kind.as_str(),
110 digest: identity_digest(salt, &c.stable),
111 })
112 .collect()
113}
114
115#[derive(Debug, Clone, Deserialize)]
118pub struct MatchAnswer {
119 pub schema: String,
120 #[serde(rename = "match")]
121 pub outcome: String,
122 #[serde(default)]
123 pub vault: Option<VaultV1>,
124 #[serde(default)]
125 pub suggestion: Option<VaultRefV1>,
126 #[serde(default)]
127 pub can_create: bool,
128}
129
130#[derive(Debug, Clone, PartialEq, Eq)]
132pub enum Step {
133 Mapped(VaultV1),
135 Suggested(VaultRefV1),
137 Create,
139 NoVault,
141}
142
143pub fn step_from_answer(answer: MatchAnswer) -> Result<Step, CloudError> {
145 let bad = |why: &str| CloudError::Protocol(format!("vault match: {why}"));
146 if answer.schema != MATCH_SCHEMA {
147 return Err(bad("unknown schema"));
148 }
149 match answer.outcome.as_str() {
150 "bound" => {
151 let vault = answer.vault.ok_or_else(|| bad("bound without a vault"))?;
152 vault.validate().map_err(|e| bad(&e.to_string()))?;
153 Ok(Step::Mapped(vault))
154 }
155 "suggested" => {
156 let vault = answer
157 .suggestion
158 .ok_or_else(|| bad("suggested without a suggestion"))?;
159 vault.validate().map_err(|e| bad(&e.to_string()))?;
160 Ok(Step::Suggested(vault))
161 }
162 "none" if answer.can_create => Ok(Step::Create),
163 "none" => Ok(Step::NoVault),
164 _ => Err(bad("unknown match")),
165 }
166}
167
168pub fn route_missing(error: &CloudError) -> bool {
171 matches!(
172 error,
173 CloudError::NotFound
174 | CloudError::Server {
175 status: 404 | 405 | 426,
176 ..
177 }
178 )
179}
180
181#[derive(Serialize, Deserialize)]
182struct MatchProbe {
183 unsupported_at: i64,
185}
186
187pub fn match_available(store: &CloudStore, now: i64) -> bool {
190 if !super::bus::relay_v2::speaks_v2(store) {
191 return false;
192 }
193 store
194 .read_config::<MatchProbe>(MATCH_FILE)
195 .ok()
196 .flatten()
197 .is_none_or(|probe| {
198 now < probe.unsupported_at || now - probe.unsupported_at >= REPROBE_SECONDS
199 })
200}
201
202fn remember_missing(store: &CloudStore, now: i64) {
203 let _ = store.write_config(
205 MATCH_FILE,
206 &MatchProbe {
207 unsupported_at: now,
208 },
209 );
210}
211
212pub fn first_share_gated(session: &Session) -> bool {
215 super::connect::decision(&session.store, &session.instance.org_id).is_some()
216}
217
218#[derive(Debug, Clone, PartialEq, Eq)]
220pub enum Target {
221 Bind(VaultRefV1),
223 Own,
226}
227
228pub fn new_vault_name(root: &Path) -> String {
230 let raw = root
231 .file_name()
232 .map(|n| n.to_string_lossy().to_lowercase())
233 .unwrap_or_default();
234 let slug: String = raw
235 .chars()
236 .map(|c| {
237 if c.is_ascii_lowercase() || c.is_ascii_digit() {
238 c
239 } else {
240 '-'
241 }
242 })
243 .collect();
244 let slug: String = slug.trim_matches('-').chars().take(40).collect();
245 let slug = slug.trim_end_matches('-');
246 if slug.len() >= 2 {
247 slug.to_string()
248 } else {
249 "project".into()
250 }
251}
252
253pub fn consent_subject(target: &Target, stable: &str, root: &Path) -> Value {
256 let vault = match target {
257 Target::Bind(vault) => format!("{}/{}", vault.ns, vault.name),
258 Target::Own => format!("{NEW_VAULT_WS}/{}", new_vault_name(root)),
259 };
260 let text = |value: Option<String>| {
261 value
262 .filter(|v| (1..=500).contains(&v.chars().count()))
263 .map_or(Value::Null, Value::String)
264 };
265 consent::subject(&[
266 (
267 "bound_repo",
268 text(root.file_name().map(|n| n.to_string_lossy().into_owned())),
269 ),
270 ("link_digest", Value::String(stable.to_string())),
271 ("remote_seen", text(identity_v2::origin_remote(root))),
272 ("target_vault", Value::Null),
273 ("vault", Value::String(vault)),
274 ])
275}
276
277fn require(
278 session: &Session,
279 config: &CloudConfig,
280 target: &Target,
281 stable: &str,
282 root: &Path,
283) -> Result<(), MapError> {
284 let broker = Broker::open(&session.store, Trust::load(&session.store, config));
285 let now = u64::try_from(UtcDateTime::now().timestamp_millis()).unwrap_or_default();
286 broker.require(Kind::LinkVault, &consent_subject(target, stable, root), now)?;
287 Ok(())
288}
289
290pub fn satisfied(record: &consent::Record, map: &super::vault::VaultMap) -> bool {
294 record
295 .subject
296 .get("link_digest")
297 .and_then(Value::as_str)
298 .and_then(|stable| map.vaults.get(stable))
299 .is_some_and(|mapped| satisfied_by(record, mapped))
300}
301
302fn satisfied_by(record: &consent::Record, mapped: &VaultRecord) -> bool {
306 if record.kind != Kind::LinkVault || !record.subject["target_vault"].is_null() {
307 return false;
308 }
309 let vault = record.subject["vault"].as_str().unwrap_or_default();
310 vault == format!("{}/{}", mapped.ns, mapped.name)
311 || vault.starts_with(&format!("{NEW_VAULT_WS}/"))
312}
313
314pub fn close_satisfied(
320 session: &Session,
321 config: &CloudConfig,
322 stable: &str,
323 mapped: &VaultRecord,
324) -> Vec<String> {
325 let broker = Broker::open(&session.store, Trust::load(&session.store, config));
326 let closed = broker
327 .close_satisfied(&|r| r.subject["link_digest"] == stable && satisfied_by(r, mapped))
328 .unwrap_or_else(|error| {
329 tracing::info!("cloud consent close: {error}");
330 Vec::new()
331 });
332 for id in &closed {
333 let _ = session.with_client(|client| {
334 consent::web::withdraw_relayed(client, id);
335 Ok(())
336 });
337 }
338 closed
339}
340
341pub fn map_root(
345 session: &Session,
346 config: &CloudConfig,
347 salt: &(String, Vec<u8>),
348 stable: &str,
349 root: &Path,
350 known: Option<&VaultRecord>,
351) -> Result<VaultV1, MapError> {
352 super::company_bound::on_map(&session.store, &session.instance, stable)?;
355 let (resolved, mut request) = resolve_request(root, &salt.0, &salt.1, config.vault_labels)?;
356 if resolved != stable {
357 return Err(CloudError::Config(format!(
358 "{} changed its identity since the draft was made",
359 root.display()
360 ))
361 .into());
362 }
363 let gated = first_share_gated(session) && known.is_none();
364 let now = UtcDateTime::now().timestamp();
365 let candidates = match_candidates(root, &salt.1);
366 let mut matched = false;
369 let target = match request.vault.clone() {
372 Some(vault) => Target::Bind(vault),
373 None if match_available(&session.store, now) => {
374 let step = ask_match(session, &salt.0, &candidates, now)?;
375 matched = step.is_some();
376 match step {
377 Some(Step::Mapped(vault)) => {
378 return confirm_move(session, config, stable, root, known, vault);
379 }
380 Some(Step::Suggested(vault)) if gated => Target::Bind(vault),
381 Some(Step::NoVault) => {
382 return Err(CloudError::Refused(
383 "this project has no vault in the workspace and this instance may not create one; ask a maintainer, or name one with `lean-ctx cloud link <workspace>/<vault>`".into(),
384 )
385 .into());
386 }
387 Some(Step::Suggested(_) | Step::Create) | None => Target::Own,
390 }
391 }
392 None => Target::Own,
393 };
394 if gated {
395 require(session, config, &target, stable, root)?;
396 }
397 if let Target::Bind(vault) = &target {
398 request.vault = Some(vault.clone());
399 }
400 if matched && let Some(exact) = candidates.iter().find(|c| c.kind == "exact") {
401 request.identity_digest.clone_from(&exact.digest);
402 }
403 let body = serde_json::to_value(&request).map_err(|e| CloudError::Local(e.to_string()))?;
404 let answer = session.with_client(|c| c.post("/vaults/resolve", &body))?;
405 let vault: VaultV1 =
406 serde_json::from_value(answer).map_err(|e| CloudError::Protocol(format!("vault: {e}")))?;
407 vault
408 .validate()
409 .map_err(|e| CloudError::Protocol(e.to_string()))?;
410 if matched {
411 let _ = ask_match(session, &salt.0, &candidates, now);
414 }
415 confirm_move(session, config, stable, root, known, vault)
416}
417
418fn confirm_move(
421 session: &Session,
422 config: &CloudConfig,
423 stable: &str,
424 root: &Path,
425 known: Option<&VaultRecord>,
426 vault: VaultV1,
427) -> Result<VaultV1, MapError> {
428 if first_share_gated(session)
429 && let Some(known) = known
430 && known.ns != vault.vault.ns
431 {
432 require(
433 session,
434 config,
435 &Target::Bind(vault.vault.clone()),
436 stable,
437 root,
438 )?;
439 }
440 Ok(vault)
441}
442
443pub fn bound_elsewhere(session: &Session, root: &Path, ours: &VaultRefV1) -> Option<VaultRefV1> {
448 let now = UtcDateTime::now().timestamp();
449 if !match_available(&session.store, now) {
450 return None;
451 }
452 let salt = super::knowledge::pull::org_salt(session).ok()?;
453 match ask_match(session, &salt.0, &match_candidates(root, &salt.1), now) {
454 Ok(Some(Step::Mapped(vault))) if vault.vault != *ours => Some(vault.vault),
455 _ => None,
456 }
457}
458
459fn ask_match(
461 session: &Session,
462 org_salt_id: &str,
463 candidates: &[MatchCandidate],
464 now: i64,
465) -> Result<Option<Step>, CloudError> {
466 if candidates.is_empty() {
467 return Ok(None);
468 }
469 let body = match_body(org_salt_id, candidates)?;
470 match session.with_client(|c| c.post("/vaults/match", &body)) {
471 Ok(answer) => {
472 let answer: MatchAnswer = serde_json::from_value(answer)
473 .map_err(|e| CloudError::Protocol(format!("vault match: {e}")))?;
474 step_from_answer(answer).map(Some)
475 }
476 Err(error) if route_missing(&error) => {
477 remember_missing(&session.store, now);
478 Ok(None)
479 }
480 Err(error) => Err(error),
481 }
482}
483
484fn match_body(org_salt_id: &str, candidates: &[MatchCandidate]) -> Result<Value, CloudError> {
485 serde_json::to_value(MatchRequest {
486 schema: MATCH_REQUEST_SCHEMA,
487 org_salt_id,
488 candidates,
489 })
490 .map_err(|e| CloudError::Local(e.to_string()))
491}
492
493#[cfg(test)]
494mod tests {
495 use super::*;
496 use serde_json::json;
497
498 fn vault_json() -> Value {
499 json!({
500 "schema": "leanctx.cloud.vault/v1",
501 "vault_id": "3f6c1e9a0b7d4c2e8f5a1b6c9d0e7f42",
502 "vault": {"ns": "acme", "name": "payments"},
503 "sealed": false,
504 })
505 }
506
507 fn answer(value: Value) -> MatchAnswer {
508 serde_json::from_value(value).unwrap()
509 }
510
511 fn route_fixture(name: &str) -> Value {
512 let path = Path::new(concat!(env!("CARGO_MANIFEST_DIR"), "/../.."))
513 .join("crates/lean-ctx-protocol/tests/fixtures/cloud-v2/routes")
514 .join(name);
515 serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap()
516 }
517
518 #[test]
521 fn the_match_request_is_the_contract_fixture() {
522 use base64::Engine as _;
523 let vectors = identity_v2::contract_vectors();
524 let salt = base64::engine::general_purpose::STANDARD
525 .decode(vectors["salt"].as_str().unwrap())
526 .unwrap();
527 let input = &vectors["cases"][0]["input"];
528 let candidates = identity_v2::candidates_from(
529 &identity_v2::vector_parts(input),
530 input["legacy_identity"].as_str(),
531 );
532 let body = match_body(
533 vectors["org_salt_id"].as_str().unwrap(),
534 &salted(&candidates, &salt),
535 )
536 .unwrap();
537 assert_eq!(body, route_fixture("vault_match.request.json"));
538 }
539
540 #[test]
543 fn the_contract_responses_become_steps() {
544 let step = |name: &str| step_from_answer(answer(route_fixture(name)));
545 assert!(
546 matches!(step("vault_match.bound.response.json"), Ok(Step::Mapped(v)) if v.vault.name == "payments")
547 );
548 assert!(
549 matches!(step("vault_match.bound_legacy.response.json"), Ok(Step::Mapped(v)) if !v.sealed)
550 );
551 assert!(
552 matches!(step("vault_match.suggested.response.json"), Ok(Step::Suggested(v)) if v.ns == "acme")
553 );
554 assert_eq!(step("vault_match.none.response.json"), Ok(Step::Create));
555 let mut sealed = route_fixture("vault_match.bound.response.json");
557 sealed["vault"]["sealed"] = Value::Bool(true);
558 let refused = step_from_answer(answer(sealed)).unwrap_err();
559 assert!(
560 refused
561 .to_string()
562 .contains("sealed vaults are not supported"),
563 "{refused}"
564 );
565 let mut bound = route_fixture("vault_match.bound.response.json");
566 bound.as_object_mut().unwrap().remove("vault");
567 assert!(
568 step_from_answer(answer(bound)).is_err(),
569 "bound_without_vault"
570 );
571 }
572
573 #[test]
574 fn match_answers_become_steps_and_broken_ones_are_refused() {
575 let bound = answer(json!({
576 "schema": MATCH_SCHEMA, "match": "bound", "matched": "legacy",
577 "vault": vault_json(), "something_new": 1,
578 }));
579 match step_from_answer(bound).unwrap() {
580 Step::Mapped(vault) => assert_eq!(vault.vault.name, "payments"),
581 other => panic!("{other:?}"),
582 }
583 let suggested = answer(json!({
584 "schema": MATCH_SCHEMA, "match": "suggested", "matched": "history",
585 "suggestion": {"ns": "acme", "name": "payments"},
586 }));
587 assert!(
588 matches!(step_from_answer(suggested).unwrap(), Step::Suggested(v) if v.ns == "acme")
589 );
590 let create = answer(json!({"schema": MATCH_SCHEMA, "match": "none", "can_create": true}));
591 assert_eq!(step_from_answer(create).unwrap(), Step::Create);
592 let none = answer(json!({"schema": MATCH_SCHEMA, "match": "none"}));
593 assert_eq!(step_from_answer(none).unwrap(), Step::NoVault);
594
595 for broken in [
596 json!({"schema": MATCH_SCHEMA, "match": "bound"}),
597 json!({"schema": MATCH_SCHEMA, "match": "suggested"}),
598 json!({"schema": MATCH_SCHEMA, "match": "maybe"}),
599 json!({"schema": "leanctx.cloud.vault-match/v0", "match": "none"}),
600 json!({"schema": MATCH_SCHEMA, "match": "suggested",
601 "suggestion": {"ns": "acme", "name": "../etc"}}),
602 ] {
603 assert!(
604 step_from_answer(answer(broken.clone())).is_err(),
605 "{broken}"
606 );
607 }
608 }
609
610 #[test]
611 fn only_a_missing_route_means_no_match() {
612 assert!(route_missing(&CloudError::NotFound));
613 assert!(route_missing(&CloudError::Server {
614 status: 404,
615 code: "unknown".into()
616 }));
617 assert!(route_missing(&CloudError::Server {
618 status: 405,
619 code: "unknown".into()
620 }));
621 assert!(!route_missing(&CloudError::Forbidden));
622 assert!(!route_missing(&CloudError::Offline("x".into())));
623 assert!(!route_missing(&CloudError::Server {
624 status: 500,
625 code: "internal".into()
626 }));
627 }
628
629 #[test]
630 fn the_match_route_is_asked_on_c0_2_cloudes_and_a_404_rests_for_a_day() {
631 let dir = tempfile::tempdir().unwrap();
632 let store = CloudStore::at(dir.path().join("config"), dir.path().join("data"));
633 let now = 1_800_000_000;
634 assert!(!match_available(&store, now), "1.x: never asked");
635 super::super::bus::relay_v2::record_protocol(&store, true).unwrap();
636 assert!(match_available(&store, now));
637 remember_missing(&store, now);
638 assert!(!match_available(&store, now + 60));
639 assert!(match_available(&store, now + REPROBE_SECONDS));
640 assert!(
641 match_available(&store, now - 60),
642 "a clock that moved back asks again"
643 );
644 store.forget(true).unwrap();
645 assert!(!store.config_dir().join(MATCH_FILE).exists());
646 }
647
648 #[test]
649 fn the_consent_subject_names_the_vault_and_stays_on_shape() {
650 let base = tempfile::tempdir().unwrap();
651 let root = base.path().join("Payments Service");
652 std::fs::create_dir_all(root.join(".git")).unwrap();
653 let stable =
654 lean_ctx_protocol::cloud::vault::stable_identity("git:github.com/acme/payments");
655 let own = consent_subject(&Target::Own, &stable, &root);
656 consent::check_subject(Kind::LinkVault, &own).unwrap();
657 assert_eq!(own["vault"], "new/payments-service");
658 assert_eq!(own["bound_repo"], "Payments Service");
659 let bind = consent_subject(
660 &Target::Bind(VaultRefV1 {
661 ns: "acme".into(),
662 name: "payments".into(),
663 }),
664 &stable,
665 &root,
666 );
667 consent::check_subject(Kind::LinkVault, &bind).unwrap();
668 assert_eq!(bind["vault"], "acme/payments");
669 assert_ne!(
670 consent::subject_digest(&own).unwrap(),
671 consent::subject_digest(&bind).unwrap(),
672 "a yes for one target never covers another"
673 );
674 assert_eq!(new_vault_name(Path::new("/w/x")), "project");
675 assert_eq!(new_vault_name(Path::new("/w/Über_App")), "ber-app");
676 assert_eq!(new_vault_name(&base.path().join("a".repeat(60))).len(), 40);
677 }
678
679 #[test]
684 fn a_first_share_for_a_mapped_checkout_is_closed_a_move_keeps_waiting() {
685 let dir = tempfile::tempdir().unwrap();
686 let store = CloudStore::at(dir.path().join("config"), dir.path().join("data"));
687 let broker = Broker::open(
688 &store,
689 Trust {
690 presence: None,
691 consent_keys: std::collections::BTreeMap::new(),
692 owner_user_id: None,
693 },
694 );
695 let root = dir.path().join("journey-demo");
696 std::fs::create_dir_all(root.join(".git")).unwrap();
697 let stable =
698 lean_ctx_protocol::cloud::vault::stable_identity("git:github.com/acme/journey-demo");
699 let pending = |target: &Target| match broker.require(
700 Kind::LinkVault,
701 &consent_subject(target, &stable, &root),
702 1_792_800_000_000,
703 ) {
704 Err(ConsentError::Required { consent_id, .. }) => broker.get(&consent_id).unwrap(),
705 other => panic!("{other:?}"),
706 };
707 let own = pending(&Target::Own);
708 let team = pending(&Target::Bind(VaultRefV1 {
709 ns: "acme-team".into(),
710 name: "journey-demo".into(),
711 }));
712 let mut map = super::super::vault::VaultMap::default();
713 assert!(!satisfied(&own, &map), "not mapped yet: it waits");
714 map.vaults.insert(
715 stable.clone(),
716 VaultRecord {
717 vault_id: "vlt_1".into(),
718 ns: "ada".into(),
719 name: "journey-demo".into(),
720 sealed: false,
721 roots: vec![root.to_string_lossy().into_owned()],
722 },
723 );
724 assert!(satisfied(&own, &map), "mapped: nothing to answer");
725 assert!(!satisfied(&team, &map), "a move into another vault waits");
726 let mapped = map.vaults[&stable].clone();
727 let closed = broker
728 .close_satisfied(&|r| {
729 r.subject["link_digest"] == stable.as_str() && satisfied_by(r, &mapped)
730 })
731 .unwrap();
732 assert_eq!(closed, vec![own.consent_id.clone()]);
733 assert!(broker.get(&own.consent_id).is_err(), "closed");
734 assert_eq!(
735 broker.get(&team.consent_id).unwrap().state,
736 consent::State::Pending
737 );
738 }
739
740 #[test]
741 fn consent_errors_keep_their_code_for_the_outbox_and_hide_the_id() {
742 let error = MapError::Consent(ConsentError::Required {
743 consent_id: "cns_aaaaaaaaaaaaaaaa".into(),
744 kind: Kind::LinkVault,
745 });
746 let shown = error.to_string();
747 assert!(shown.starts_with("consent_required"), "{shown}");
748 assert!(
749 !shown.contains("cns_"),
750 "the id is never handed to an agent"
751 );
752 assert!(matches!(CloudError::from(error), CloudError::Refused(_)));
753 }
754}