//! Serving and talking to remotes (spec §10.2, §16). use super::*; /// What a fetch brought in. #[derive(Debug, Clone, PartialEq, Eq, Default)] pub struct FetchReport { /// Bookmark name, its heads, and how many changes were new. pub refs: Vec<(String, Vec, usize)>, /// Tags adopted from the remote. pub new_tags: usize, /// The remote has never presented a policy, so nothing was verified /// against one (spec §14.5: warn loudly). pub unverified: bool, } #[derive(Debug, Clone, PartialEq, Eq)] pub struct PullReport { pub heads: Vec, pub changed: bool, pub checked_out: bool, } impl Repo { // ------------------------------------------------------------ serving (spec §16) fn ref_attest_path(&self, bookmark: &str) -> PathBuf { self.oxy.join("attest").join(bookmark) } /// The latest reference attestation stored for a bookmark. pub fn latest_ref_attest(&self, bookmark: &str) -> Result> { match fs::read_to_string(self.ref_attest_path(bookmark)) { Ok(h) => { let r = ObjectRef::from_hex(h.trim()).ok_or_else(|| RepoError::Msg("corrupt attestation pointer".into()))?; Ok(Some((r, SignedAttest { attest: self.store.get_attest(&r)?, sigs: self.store.signatures(&r)? }))) } Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None), Err(e) => Err(e.into()), } } fn set_ref_attest(&self, bookmark: &str, r: &ObjectRef) -> Result<()> { fs::create_dir_all(self.oxy.join("attest"))?; write_atomic(&self.ref_attest_path(bookmark), r.to_hex().as_bytes()) } pub fn remote_refs(&self) -> Result { let view = self.view()?; let mut out = Vec::new(); for (name, state) in &view.bookmarks { let latest = self.latest_ref_attest(name)?.map(|(_, a)| a); let last_serial = latest.as_ref().and_then(|a| match a.attest.body { AttestBody::Ref { serial, .. } => Some(serial), _ => None, }); let attestation = latest.filter(|a| matches!(&a.attest.body, AttestBody::Ref { new_state, .. } if new_state == state)); out.push(RemoteRef { name: name.clone(), state: *state, heads: self.store.get_state(state)?.heads, attestation, last_serial }); } let policy = self.current_policy()?.map(|(_, sp)| sp); let history = self.policy_history()?.into_iter().filter(|sp| policy.as_ref().is_some_and(|p| sp.policy.serial < p.policy.serial)).collect(); Ok(RefsResponse { refs: out, policy, tags: self.tag_refs()?, history }) } /// Every change reachable from `heads` that is in the store. fn closure_in_store(&self, heads: &[ChangeHash]) -> Result> { let mut seen = BTreeSet::new(); let mut stack: Vec = heads.to_vec(); while let Some(h) = stack.pop() { if seen.contains(&h) || !self.store.has(&h) { continue; } seen.insert(h); stack.extend(self.store.get_change(&h)?.deps); } Ok(seen) } /// The changes within `depth` dependency steps of `heads` (spec §17), /// nearest first; depth 1 is the heads themselves. pub fn shallow_changes(&self, heads: &[ChangeHash], depth: u32) -> Result> { let mut out = Vec::new(); let mut seen: BTreeSet = BTreeSet::new(); let mut layer: Vec = heads.to_vec(); for _ in 0..depth.max(1) { let mut next = Vec::new(); for h in layer { if !seen.insert(h) || !self.store.has(&h) { continue; } let c = self.store.get_change(&h)?; next.extend(c.deps.iter().copied()); out.push(h); } if next.is_empty() { break; } layer = next; } out.reverse(); Ok(out) } fn shallow_path(&self) -> PathBuf { self.oxy.join("shallow") } /// The shallow boundary: dependencies this repository does not hold (spec §17). pub fn boundary(&self) -> BTreeSet { fs::read_to_string(self.shallow_path()).map(|t| t.lines().filter_map(ObjectRef::from_hex).collect()).unwrap_or_default() } pub fn is_shallow(&self) -> bool { !self.boundary().is_empty() } fn write_boundary(&self, boundary: &BTreeSet) -> Result<()> { if boundary.is_empty() { let _ = fs::remove_file(self.shallow_path()); return Ok(()); } let text: String = boundary.iter().map(|h| format!("{}\n", h.to_hex())).collect(); write_atomic(&self.shallow_path(), text.as_bytes()) } /// Recompute the boundary from what is stored: every dependency of a /// stored change that is not itself stored. fn refresh_boundary(&self, imported: &[ChangeHash]) -> Result<()> { let mut boundary = self.boundary(); boundary.retain(|h| !self.store.has(h)); for h in imported { for d in self.store.get_change(h)?.deps { if !self.store.has(&d) { boundary.insert(d); } } } self.write_boundary(&boundary) } /// Fetch `depth` more levels of history below the shallow boundary. pub fn deepen(&self, remote_name: &str, depth: u32) -> Result { let boundary = self.boundary(); if boundary.is_empty() { return Ok(0); } let remote = self.open_named_remote(remote_name)?; let wanted = remote.shallow(&boundary.iter().copied().collect::>(), depth)?; let bundle = remote.fetch(&wanted, self.config.max_blob)?; let imported = self.import_bundle_shallow(&bundle, false)?; if self.config.max_blob.is_some() { self.register_missing_blobs(&imported, remote_name)?; } self.refresh_boundary(&imported)?; Ok(imported.len()) } /// `closure(want) \ closure(have)`, dependencies first (spec §16.2). pub fn negotiate(&self, have: &[ChangeHash], want: &[ChangeHash]) -> Result> { let have = self.closure_in_store(have)?; // In a shallow repository the walk stops at the boundary, whose // changes the remote is assumed to hold. let boundary = self.boundary(); let mut out = Vec::new(); let mut done: BTreeSet = have.clone(); done.extend(boundary.iter().copied()); // Iterative post-order DFS. let mut stack: Vec<(ChangeHash, bool)> = want.iter().rev().map(|h| (*h, false)).collect(); while let Some((h, expanded)) = stack.pop() { if done.contains(&h) { continue; } if !self.store.has(&h) { return fail(format!("change {} is not in this repository", h.short(12))); } if expanded { done.insert(h); out.push(h); continue; } stack.push((h, true)); for d in self.store.get_change(&h)?.deps { if !done.contains(&d) { stack.push((d, false)); } } } Ok(out) } /// Bundle changes (in the given dependency order) with their signatures, /// seals, identities, blobs, chunks. pub fn bundle_for(&self, changes: &[ChangeHash]) -> Result { self.bundle_for_filtered(changes, None) } /// Objects by reference for the `objects` endpoint; a blob brings its chunks. pub fn objects_for(&self, refs: &[ObjectRef]) -> Result)>> { let mut out = Vec::new(); for r in refs { let (ty, body) = match self.store.get(r) { Ok(x) => x, Err(StoreError::NotFound(_)) => continue, Err(e) => return Err(e.into()), }; if ty == ObjectType::Blob { for c in Blob::decode(&body)?.chunks { if let Ok((cty, cb)) = self.store.get(&c) { out.push((cty, cb)); } } } out.push((ty, body)); } Ok(out) } /// Like `bundle_for`, leaving out blobs larger than `max_blob` bytes /// (and their chunks) so the receiver fetches them lazily (spec §13.5). pub fn bundle_for_filtered(&self, changes: &[ChangeHash], max_blob: Option) -> Result { let mut bundle = Bundle::default(); let mut objects: BTreeSet = BTreeSet::new(); let mut seals: BTreeSet = BTreeSet::new(); let add_object = |r: &ObjectRef, objects: &mut BTreeSet| { if !r.is_zero() && self.store.has(r) { objects.insert(*r); } }; for h in changes { let c = self.store.get_change(h)?; let sigs = self.store.signatures(h)?; add_object(&c.author, &mut objects); for s in &sigs { add_object(&s.key, &mut objects); } for e in &c.edits { if let Edit::Replace { old, new, .. } = e { for b in [old, new].into_iter().flatten() { if self.store.has(b) { if let Ok(blob) = Blob::decode(&self.store.get_typed(b, ObjectType::Blob)?) { if max_blob.is_some_and(|m| blob.length > m) { continue; } objects.insert(*b); objects.extend(blob.chunks.iter().copied()); } } } } } for s in self.store.seals_for(h)? { seals.insert(s); } bundle.changes.push((c, sigs)); } for r in seals { let attest = self.store.get_attest(&r)?; let sigs = self.store.signatures(&r)?; for s in &sigs { add_object(&s.key, &mut objects); } bundle.attests.push(SignedAttest { attest, sigs }); } for r in objects { let (ty, body) = self.store.get(&r)?; bundle.objects.push((ty, body)); } Ok(bundle) } /// Store a bundle's contents. With `strict`, every change must /// authenticate (signature or seal by its author or a delegate). pub fn import_bundle(&self, bundle: &Bundle, strict: bool) -> Result> { self.import_bundle_inner(bundle, strict, false) } /// Like `import_bundle`, accepting changes whose dependencies are absent /// (they join the shallow boundary). pub fn import_bundle_shallow(&self, bundle: &Bundle, strict: bool) -> Result> { self.import_bundle_inner(bundle, strict, true) } fn import_bundle_inner(&self, bundle: &Bundle, strict: bool, shallow: bool) -> Result> { for (ty, body) in &bundle.objects { match ty { ObjectType::Chunk | ObjectType::Blob | ObjectType::Identity | ObjectType::State | ObjectType::Checkpoint => { self.store.put(*ty, body)?; } other => return fail(format!("bundle may not carry {} objects", other.name())), } } for sa in &bundle.attests { let r = self.store.put_attest(&sa.attest)?; for sig in &sa.sigs { self.store.put_signature(&r, sig)?; } if let AttestBody::Seal { hashes } = &sa.attest.body { for h in hashes { self.store.index_seal(h, &r)?; } } } let incoming: BTreeSet = bundle.changes.iter().map(|(c, _)| c.hash()).collect(); let boundary = self.boundary(); let mut imported = Vec::new(); for (c, sigs) in &bundle.changes { let h = c.hash(); for d in &c.deps { if !self.store.has(d) && !incoming.contains(d) && !shallow && !boundary.contains(d) { return fail(format!("change {} depends on {}, which is neither stored nor in the bundle", h.short(12), d.short(12))); } } self.store.put_change(c)?; for sig in sigs { self.store.put_signature(&h, sig)?; } imported.push(h); } if strict { for h in &imported { if !matches!(self.authenticate_change(h)?, SignatureStatus::Valid { .. }) { return fail(format!("change {} is not authenticated by its author", h.short(12))); } } } Ok(imported) } /// Verify a reference attestation against an update it claims to describe. /// `allow_equal` lets a client re-read the attestation it already has; a /// server receiving a push requires a strictly greater serial. fn check_ref_attest(&self, sa: &SignedAttest, name: &str, old_state: &ObjectRef, new_state: &ObjectRef, last_serial: Option, allow_equal: bool) -> std::result::Result { let AttestBody::Ref { name: n, old_state: o, new_state: nw, serial } = &sa.attest.body else { return Err("attestation is not a ref attestation".into()); }; if n != name || o != old_state || nw != new_state { return Err("attestation does not describe this update".into()); } if sa.attest.repo != self.id().map_err(|e| e.to_string())? { return Err("attestation is for a different repository".into()); } if let Some(last) = last_serial { if *serial < last || (*serial == last && !allow_equal) { return Err(format!("attestation serial {serial} is not greater than the last seen {last}")); } } let r = sa.attest.hash(); let sig = sa.sigs.first().ok_or("attestation carries no signature")?; let id = self.store.get_identity(&sig.key).map_err(|_| format!("unknown key {}", sig.key.short(12)))?; verify_signature(&id, sig, Domain::Attest, &r).map_err(|e| e.to_string())?; Ok(*serial) } /// Accept a push (spec §16.4). Without a trust policy every repository /// is unverified, so unsigned changes and unattested updates are accepted; /// attestations that are present must still be valid. With a policy, /// every change and update is checked against it. A newer policy in the /// push is applied first when it is signed by the current roots. pub fn receive_push(&self, bundle: Bundle, updates: Vec, policy: Option, tags: Vec) -> Result> { let mut results = Vec::new(); if let Some(sp) = policy { match self.adopt_policy_chain(&bundle.policies, &sp, "push received") { Ok(()) => { results.push(RefResult { name: "policy".into(), ok: true, reason: format!("serial {}", sp.policy.serial) }); } Err(e) => { results.push(RefResult { name: "policy".into(), ok: false, reason: e }); for u in updates { results.push(RefResult { name: u.name, ok: false, reason: "policy update was rejected".into() }); } return Ok(results); } } } let policy = self.current_policy()?.map(|(_, sp)| sp.policy); if let Err(e) = self.import_bundle(&bundle, policy.is_some()) { for u in updates { results.push(RefResult { name: u.name, ok: false, reason: e.to_string() }); } return Ok(results); } let (op_ref, op) = self.head_op()?; let mut view = op.view.clone(); let mut names = Vec::new(); for u in updates { let outcome = self.apply_update(&mut view, &u, policy.as_ref()); let (ok, reason) = match outcome { Ok(()) => (true, String::new()), Err(e) => (false, e), }; if ok { names.push(u.name.clone()); } results.push(RefResult { name: u.name, ok, reason }); } for t in &tags { let name = format!("tags/{}", t.name); match self.adopt_tag(&mut view, t, policy.as_ref()) { Ok(()) => { names.push(name.clone()); results.push(RefResult { name, ok: true, reason: String::new() }); } Err(e) => results.push(RefResult { name, ok: false, reason: e }), } } if !names.is_empty() { self.record_op(&[op_ref], &format!("push received: {}", names.join(" ")), view)?; } Ok(results) } fn apply_update(&self, view: &mut View, u: &RefUpdate, policy: Option<&crate::policy::Policy>) -> std::result::Result<(), String> { if u.name == "policy" { return Err("the policy reference is updated by sending a policy, not a bookmark update".into()); } let empty = self.store.put_state(&StateObject::new(vec![])).map_err(|e| e.to_string())?; let current = view.bookmarks.get(&u.name).copied().unwrap_or(empty); if current != u.old_state { return Err("stale: the remote bookmark has moved; pull first".into()); } let new_state = self.store.get_state(&u.new_state).map_err(|_| "new state object is missing".to_string())?; for h in &new_state.heads { if !self.store.has(h) { return Err(format!("head {} is missing", h.short(12))); } } if !u.force { let old_heads = self.store.get_state(¤t).map_err(|e| e.to_string())?.heads; let closure = self.closure_in_store(&new_state.heads).map_err(|e| e.to_string())?; if let Some(h) = old_heads.iter().find(|h| !closure.contains(h)) { return Err(format!("not a fast-forward: current head {} would be dropped (use --force)", h.short(12))); } } if let Some(p) = policy { let Some(sa) = &u.attestation else { return Err(format!("{:?} requires a signed reference attestation under this repository's policy", u.name)); }; let signer = sa.sigs.first().map(|s| s.key).ok_or("attestation carries no signature")?; if !p.authorizes(&signer, &u.name) { return Err(format!("key {} may not update {:?} under this repository's policy", signer.short(12), u.name)); } let old_heads = self.store.get_state(¤t).map_err(|e| e.to_string())?.heads; self.state_allowed(&old_heads, &new_state.heads, p, &u.name)?; } if let Some(sa) = &u.attestation { let last = self.latest_ref_attest(&u.name).map_err(|e| e.to_string())?.and_then(|(_, a)| match a.attest.body { AttestBody::Ref { serial, .. } => Some(serial), _ => None, }); self.check_ref_attest(sa, &u.name, &u.old_state, &u.new_state, last, false)?; let r = self.store.put_attest(&sa.attest).map_err(|e| e.to_string())?; for sig in &sa.sigs { self.store.put_signature(&r, sig).map_err(|e| e.to_string())?; } self.set_ref_attest(&u.name, &r).map_err(|e| e.to_string())?; } view.bookmarks.insert(u.name.clone(), u.new_state); Ok(()) } // ------------------------------------------------------------ client side fn remote_url(&self, name: &str) -> Result { self.config.remotes.get(name).cloned().ok_or_else(|| RepoError::Msg(format!("no remote named {name:?}; add one with `oxy remote add`"))) } /// Credentials and trust for a remote: `remote..token` (else /// `$OXY_TOKEN`) and `remote..ca` (else `$OXY_CA`). fn remote_options(&self, name: &str) -> RemoteOptions { RemoteOptions { token: self.config.remote_tokens.get(name).cloned().or_else(|| std::env::var("OXY_TOKEN").ok()), ca: self.config.remote_cas.get(name).map(PathBuf::from).or_else(|| std::env::var("OXY_CA").ok().map(PathBuf::from)), } } fn open_named_remote(&self, name: &str) -> Result> { open_remote(&self.remote_url(name)?, &self.remote_options(name)) } fn serial_path(&self, remote: &str, bookmark: &str) -> PathBuf { self.oxy.join("remotes").join(remote).join(format!("{bookmark}.serial")) } fn last_seen_serial(&self, remote: &str, bookmark: &str) -> Option { fs::read_to_string(self.serial_path(remote, bookmark)).ok().and_then(|s| s.trim().parse().ok()) } fn record_serial(&self, remote: &str, bookmark: &str, serial: u64) -> Result<()> { let p = self.serial_path(remote, bookmark); fs::create_dir_all(p.parent().unwrap())?; write_atomic(&p, serial.to_string().as_bytes()) } fn policy_serial_path(&self, remote: &str) -> PathBuf { self.oxy.join("remotes").join(remote).join("policy.serial") } /// The highest policy serial `remote` has ever presented. fn remote_policy_serial(&self, remote: &str) -> Option { fs::read_to_string(self.policy_serial_path(remote)).ok().and_then(|s| s.trim().parse().ok()) } fn record_policy_serial(&self, remote: &str, serial: u64) -> Result<()> { let p = self.policy_serial_path(remote); fs::create_dir_all(p.parent().unwrap())?; write_atomic(&p, serial.to_string().as_bytes()) } fn lazy_dir(&self) -> PathBuf { self.oxy.join("lazy") } /// Remember that `blob` was withheld by `remote` (spec §13.5). fn register_lazy(&self, blob: &ObjectRef, remote: &str) -> Result<()> { fs::create_dir_all(self.lazy_dir())?; write_atomic(&self.lazy_dir().join(blob.to_hex()), remote.as_bytes()) } /// Which remote promised an absent blob, if any. pub fn lazy_remote(&self, blob: &ObjectRef) -> Option { fs::read_to_string(self.lazy_dir().join(blob.to_hex())).ok().map(|s| s.trim().to_string()) } /// Fetch an absent blob (and its chunks) from the remote that promised it. pub(crate) fn fetch_lazy_blob(&self, blob: &ObjectRef) -> Result<()> { let Some(remote_name) = self.lazy_remote(blob) else { return Err(RepoError::Store(StoreError::NotFound(*blob))); }; let remote = self.open_named_remote(&remote_name)?; let objects = remote.objects(&[*blob])?; for (ty, body) in objects { if matches!(ty, ObjectType::Blob | ObjectType::Chunk) { self.store.put(ty, &body)?; } } if !self.store.has(blob) { return fail(format!("{remote_name} did not send blob {}", blob.short(12))); } let _ = fs::remove_file(self.lazy_dir().join(blob.to_hex())); Ok(()) } /// After importing from `remote`, record every blob the changes reference /// that the store lacks as lazily available from that remote. fn register_missing_blobs(&self, changes: &[ChangeHash], remote: &str) -> Result { let mut n = 0; for h in changes { let c = self.store.get_change(h)?; for e in &c.edits { if let Edit::Replace { old, new, .. } = e { for b in [old, new].into_iter().flatten() { if !self.store.has(b) { self.register_lazy(b, remote)?; n += 1; } } } } } Ok(n) } /// Every head this repository knows: bookmarks, remote tracking, working copy. fn known_heads(&self, view: &View) -> Result> { let mut have: BTreeSet = BTreeSet::new(); for st in view.bookmarks.values().chain(view.remotes.values().flat_map(|b| b.values())) { if let Ok(s) = self.store.get_state(st) { have.extend(s.heads); } } have.extend(view.workspaces.values().copied()); Ok(have.into_iter().collect()) } /// Fetch every bookmark of a remote into `remotes//bookmarks/*` (spec §10.2). pub fn fetch(&self, remote_name: &str) -> Result { let remote = self.open_named_remote(remote_name)?; if remote.repo_id()? != self.id()? { return fail(format!("remote {remote_name:?} is a different repository (repository IDs differ)")); } let resp = remote.refs()?; // Trust policy (spec §14.5). Adopt the remote's policy when it is newer // and signed by roots we trust, or on first contact. A remote that // once presented a policy may never present none or an older one: // that is a downgrade. A remote that never presented one is // unverified, and this fetch is checked only as far as possible. let local_policy = self.current_policy()?.map(|(_, sp)| sp.policy); let seen = self.remote_policy_serial(remote_name); let mut unverified = false; match &resp.policy { Some(sp) => { if seen.is_some_and(|s| sp.policy.serial < s) { return fail(format!("{remote_name} presents policy serial {} but presented {} before: refusing the downgrade", sp.policy.serial, seen.unwrap())); } match &local_policy { Some(l) if sp.policy.serial < l.serial => {} Some(l) if sp.policy.serial == l.serial => { if sp.policy.hash() != l.hash() { return fail(format!("{remote_name} presents a different policy with the same serial {}", l.serial)); } } _ => { self.adopt_policy_chain(&resp.history, sp, &format!("oxy fetch {remote_name}")).map_err(|e| RepoError::Msg(format!("policy from {remote_name}: {e}")))?; } } self.record_policy_serial(remote_name, sp.policy.serial)?; } None => { if seen.is_some() { return fail(format!("{remote_name} presented a policy before but has none now: refusing the downgrade")); } unverified = true; } } let policy = if unverified { None } else { self.current_policy()?.map(|(_, sp)| sp.policy) }; let (op_ref, op) = self.head_op()?; let mut view = op.view.clone(); let have = self.known_heads(&view)?; let mut report = Vec::new(); let max_blob = self.config.max_blob; for r in resp.refs { let needed = remote.negotiate(&have, &r.heads)?; let bundle = remote.fetch(&needed, max_blob)?; // Changes are not individually re-verified here: the bookmark's // attestation (checked below) binds its whole state, and the // receiver of the push verified the added changes at that time. let imported = self.import_bundle(&bundle, false)?; if max_blob.is_some() { self.register_missing_blobs(&imported, remote_name)?; } for h in &r.heads { if !self.store.has(h) { return fail(format!("remote did not send head {}", h.short(12))); } } let state = self.store.put_state(&StateObject::new(r.heads.clone()))?; if state != r.state { return fail(format!("remote state {} does not match its heads", r.state.short(12))); } if let Some(p) = &policy { let Some(sa) = &r.attestation else { return fail(format!("{remote_name}/{} has no attestation, which its policy requires", r.name)); }; let signer = sa.sigs.first().map(|s| s.key).ok_or_else(|| RepoError::Msg("attestation carries no signature".into()))?; if !p.authorizes(&signer, &r.name) { return fail(format!("{remote_name}/{}: attested by {}, which the policy does not authorize", r.name, signer.short(12))); } } if let Some(sa) = &r.attestation { let AttestBody::Ref { old_state, new_state, .. } = &sa.attest.body else { return fail("remote sent a non-ref attestation for a bookmark"); }; let (old_state, new_state) = (*old_state, *new_state); let serial = self .check_ref_attest(sa, &r.name, &old_state, &new_state, self.last_seen_serial(remote_name, &r.name), true) .map_err(|e| RepoError::Msg(format!("attestation for {}/{}: {e}", remote_name, r.name)))?; if new_state != r.state { return fail(format!("attestation for {}/{} does not cover its current state", remote_name, r.name)); } let ar = self.store.put_attest(&sa.attest)?; for sig in &sa.sigs { self.store.put_signature(&ar, sig)?; } self.record_serial(remote_name, &r.name, serial)?; } view.remotes.entry(remote_name.to_string()).or_default().insert(r.name.clone(), state); report.push((r.name, r.heads, imported.len())); } let mut new_tags = 0; for t in &resp.tags { if view.tags.contains_key(&t.name) { continue; } // The tag's changes must be here: fetch them if the bookmarks did not bring them. let missing: Vec = t.heads.iter().filter(|h| !self.store.has(h)).copied().collect(); if !missing.is_empty() { let needed = remote.negotiate(&self.known_heads(&view)?, &missing)?; let bundle = remote.fetch(&needed, max_blob)?; self.import_bundle(&bundle, false)?; } self.store.put_state(&StateObject::new(t.heads.clone()))?; self.adopt_tag(&mut view, t, policy.as_ref()).map_err(|e| RepoError::Msg(format!("{remote_name} {}: {e}", t.name)))?; new_tags += 1; } if view != op.view { self.record_op(&[op_ref], &format!("oxy fetch {remote_name}"), view)?; } let _ = self.run_hook( "post-fetch", &format!( "{{\"event\":\"post-fetch\",\"remote\":{},\"bookmarks\":{}}}", json_str(remote_name), json_array(report.iter().map(|(n, heads, _)| format!("{{\"name\":{},\"heads\":{}}}", json_str(n), json_array(heads.iter().map(|h| json_str(&h.to_hex())))))) ), ); Ok(FetchReport { refs: report, unverified, new_tags }) } /// Shallow fetch of the remote's bookmark: its checkpoint as our base, /// the changes within `depth` steps of its heads, and the boundary below. pub fn fetch_shallow(&self, remote_name: &str, depth: u32) -> Result { let remote = self.open_named_remote(remote_name)?; if remote.repo_id()? != self.id()? { return fail(format!("remote {remote_name:?} is a different repository (repository IDs differ)")); } let resp = remote.refs()?; let bookmark = self.config.bookmark.clone(); if let Some(sp) = &resp.policy { self.adopt_policy_chain(&resp.history, sp, "oxy clone --depth").map_err(|e| RepoError::Msg(format!("policy from {remote_name}: {e}")))?; self.record_policy_serial(remote_name, sp.policy.serial)?; } let Some(r) = resp.refs.into_iter().find(|r| r.name == bookmark) else { return fail(format!("{remote_name} has no bookmark {bookmark:?}")); }; if r.heads.is_empty() { return Ok(0); } // Base: the remote's checkpoint of exactly these heads. let cp_bundle = remote.checkpoint(&r.heads)?; let mut cp_ref = None; for (ty, body) in &cp_bundle.objects { let put = self.store.put(*ty, body)?; if *ty == ObjectType::Checkpoint { cp_ref = Some(put); } } let Some(cp_ref) = cp_ref else { return fail(format!("{remote_name} sent no checkpoint")) }; self.install_checkpoint(&bookmark, &cp_ref)?; // History window. let wanted = remote.shallow(&r.heads, depth)?; let bundle = remote.fetch(&wanted, self.config.max_blob)?; let imported = self.import_bundle_shallow(&bundle, false)?; if self.config.max_blob.is_some() { self.register_missing_blobs(&imported, remote_name)?; } self.refresh_boundary(&imported)?; if let Some(sa) = &r.attestation { let ar = self.store.put_attest(&sa.attest)?; for sig in &sa.sigs { self.store.put_signature(&ar, sig)?; } if let AttestBody::Ref { serial, .. } = sa.attest.body { self.record_serial(remote_name, &r.name, serial)?; } } let state = self.store.put_state(&StateObject::new(r.heads.clone()))?; let (op_ref, op) = self.head_op()?; let mut view = op.view.clone(); view.remotes.entry(remote_name.to_string()).or_default().insert(r.name.clone(), state); self.record_op(&[op_ref], &format!("oxy fetch {remote_name} --depth {depth}"), view)?; Ok(imported.len()) } /// Fetch, then take the union of the local bookmark's state with the /// remote's: no merge change, conflicts become reified (spec §9.4). pub fn pull(&self, remote_name: &str) -> Result { self.fetch(remote_name)?; let (op_ref, op) = self.head_op()?; let bookmark = self.config.bookmark.clone(); let local = self.heads_of(&op.view, &bookmark)?; let Some(remote_state) = op.view.remotes.get(remote_name).and_then(|b| b.get(&bookmark)).copied() else { return Ok(PullReport { heads: local, changed: false, checked_out: false }); }; let remote_heads = self.store.get_state(&remote_state)?.heads; let mut all = local.clone(); all.extend(remote_heads); let st = self.load_state(&all)?; let mut heads = st.maximal(&all); heads.sort(); let mut sorted_local = local.clone(); sorted_local.sort(); if heads == sorted_local { return Ok(PullReport { heads, changed: false, checked_out: false }); } let mut view = op.view.clone(); view.bookmarks.insert(bookmark.clone(), self.store.put_state(&StateObject::new(heads.clone()))?); self.record_op(&[op_ref], &format!("oxy pull {remote_name}"), view)?; // Follow along if the working copy was clean and on the old heads. let snap = self.snapshot("oxy pull")?; let clean = snap.wc.tree_ops.is_empty() && snap.wc.edits.is_empty(); let mut base = snap.base.maximal(&snap.wc.deps); base.sort(); let mut checked_out = false; if clean && base == sorted_local { self.checkout(&heads, false, "oxy pull (checkout)")?; checked_out = true; } Ok(PullReport { heads, changed: true, checked_out }) } /// Push the current bookmark (spec §16.3), sealing this author's unsigned /// changes and attesting the reference when a key is available. pub fn push(&self, remote_name: &str, force: bool) -> Result> { let (op_ref, op) = self.head_op()?; let bookmark = self.config.bookmark.clone(); let local_heads = self.heads_of(&op.view, &bookmark)?; // pre-push hook: may veto before the remote is contacted. self.run_hook( "pre-push", &format!("{{\"event\":\"pre-push\",\"remote\":{},\"bookmark\":{},\"heads\":{}}}", json_str(remote_name), json_str(&bookmark), json_array(local_heads.iter().map(|h| json_str(&h.to_hex())))), )?; let remote = self.open_named_remote(remote_name)?; if remote.repo_id()? != self.id()? { return fail(format!("remote {remote_name:?} is a different repository (repository IDs differ)")); } let resp = remote.refs()?; let local_policy = self.current_policy()?.map(|(_, sp)| sp); let resp_policy_serial = resp.policy.as_ref().map(|p| p.policy.serial); let policy_to_send = match (&local_policy, &resp.policy) { (Some(l), Some(r)) if l.policy.serial > r.policy.serial => Some(l.clone()), (Some(l), None) => Some(l.clone()), (Some(l), Some(r)) if l.policy.serial < r.policy.serial => { return fail(format!("{remote_name} has a newer policy (serial {}); fetch first", r.policy.serial)); } _ => None, }; let remote_has_policy = resp.policy.is_some() || policy_to_send.is_some(); if remote_has_policy && self.secret_key()?.is_none() { return fail(format!("{remote_name} enforces a trust policy; pushing needs an identity (`oxy identity create`)")); } let remote_tags: BTreeSet = resp.tags.iter().map(|t| t.name.clone()).collect(); let tags_to_send: Vec = self.tag_refs()?.into_iter().filter(|t| !remote_tags.contains(&t.name)).collect(); let refs = resp.refs; let empty = self.store.put_state(&StateObject::new(vec![]))?; let (remote_state, remote_heads, last_serial) = match refs.iter().find(|r| r.name == bookmark) { Some(r) => (r.state, r.heads.clone(), r.last_serial), None => (empty, vec![], None), }; let new_state = self.store.put_state(&StateObject::new(local_heads.clone()))?; // A push that carries a policy re-attests the bookmark even when its // state is unchanged, so the current attestation is always by a key // the current policy authorizes (a revoked key's attestation would // otherwise be refused by every later fetch). if new_state == remote_state && policy_to_send.is_none() && tags_to_send.is_empty() { return Ok(vec![RefResult { name: bookmark, ok: true, reason: "already up to date".into() }]); } for h in &remote_heads { if !self.store.has(h) { return fail(format!("the remote has change {} which you do not; pull first", h.short(12))); } } if !force { let closure = self.closure_in_store(&local_heads)?; if let Some(h) = remote_heads.iter().find(|h| !closure.contains(h)) { return fail(format!("not a fast-forward: remote head {} is not in your state; pull first or use --force", h.short(12))); } } let to_send = self.negotiate(&remote_heads, &local_heads)?; let mut bundle = self.bundle_for(&to_send)?; let key = self.secret_key()?.map(|(k, _)| k); if let Some(key) = key { // Seal this author's changes that carry no valid authenticator. let mut unsigned = Vec::new(); for h in &to_send { let c = self.store.get_change(h)?; if c.author == key && !matches!(self.authenticate_change(h)?, SignatureStatus::Valid { .. }) { unsigned.push(*h); } } for chunk in unsigned.chunks(crate::attest::MAX_SEAL_HASHES) { let sa = self.sign_attest(&Attest::seal(self.id()?, chunk.to_vec()))?; bundle.attests.push(sa); } bundle = self.bundle_for(&to_send)?; } bundle.objects.push((ObjectType::State, StateObject::new(local_heads.clone()).encode())); let attestation = match key { Some(_) => Some(self.sign_attest(&Attest { repo: self.id()?, hlc: Hlc::now(), body: AttestBody::Ref { name: bookmark.clone(), old_state: remote_state, new_state, serial: last_serial.unwrap_or(0) + 1 }, })?), None => None, }; let serial = attestation.as_ref().and_then(|a| match a.attest.body { AttestBody::Ref { serial, .. } => Some(serial), _ => None, }); let sent_serial = policy_to_send.as_ref().map(|p| p.policy.serial); // Tag states must be present on the remote: bundle their changes too. for t in &tags_to_send { let extra = self.negotiate(&remote_heads, &t.heads)?; let extra: Vec = extra.into_iter().filter(|h| !to_send.contains(h)).collect(); if !extra.is_empty() { let more = self.bundle_for(&extra)?; bundle.changes.extend(more.changes); bundle.attests.extend(more.attests); bundle.objects.extend(more.objects); } bundle.objects.push((ObjectType::State, StateObject::new(t.heads.clone()).encode())); } if let Some(l) = &policy_to_send { let remote_serial = resp_policy_serial; bundle.policies = self.policy_history()?.into_iter().filter(|sp| remote_serial.is_none_or(|r| sp.policy.serial > r) && sp.policy.serial < l.policy.serial).collect(); } let results = remote.push(bundle, vec![RefUpdate { name: bookmark.clone(), old_state: remote_state, new_state, force, attestation }], policy_to_send, tags_to_send)?; if let (Some(serial), true) = (sent_serial, results.iter().any(|r| r.ok && r.name == "policy")) { self.record_policy_serial(remote_name, serial)?; } if results.iter().any(|r| r.ok && r.name == bookmark) { let mut view = op.view.clone(); view.remotes.entry(remote_name.to_string()).or_default().insert(bookmark.clone(), new_state); self.record_op(&[op_ref], &format!("oxy push {remote_name}"), view)?; if let Some(s) = serial { self.record_serial(remote_name, &bookmark, s)?; } } Ok(results) } /// Clone a remote into `dest`: same repository ID, `origin` remote, /// bookmark set to the remote's, working copy checked out. pub fn clone(url: &str, dest: &Path) -> Result { Self::clone_with(url, dest, None, &[]) } /// Clone, leaving blobs above `max_blob` bytes to be fetched on first /// read, and materializing only `sparse` paths (which implies lazy blobs /// unless a size is given, so out-of-scope binaries are never fetched). pub fn clone_with(url: &str, dest: &Path, max_blob: Option, sparse: &[String]) -> Result { Self::clone_full(url, dest, max_blob, sparse, None) } /// Shallow clone (spec §17): a checkpoint of the bookmark's heads plus the /// changes within `depth` steps of them; the rest is the boundary. pub fn clone_shallow(url: &str, dest: &Path, depth: u32, max_blob: Option, sparse: &[String]) -> Result { Self::clone_full(url, dest, max_blob, sparse, Some(depth)) } fn clone_full(url: &str, dest: &Path, max_blob: Option, sparse: &[String], depth: Option) -> Result { let options = RemoteOptions { token: std::env::var("OXY_TOKEN").ok(), ca: std::env::var("OXY_CA").ok().map(PathBuf::from), }; let remote = open_remote(url, &options)?; let id = remote.repo_id()?; let mut repo = Repo::init_with_id(dest, id)?; repo.config.set("remote.origin.url", url)?; if let Some(m) = max_blob { repo.config.set("filter.max-blob", &m.to_string())?; } else if !sparse.is_empty() { repo.config.set("filter.max-blob", "0")?; } if !sparse.is_empty() { repo.config.set("filter.paths", &sparse.join(","))?; } repo.save_config()?; if let Some(depth) = depth { repo.fetch_shallow("origin", depth)?; } else { repo.fetch("origin")?; } let (op_ref, op) = repo.head_op()?; let bookmark = repo.config.bookmark.clone(); if let Some(state) = op.view.remotes.get("origin").and_then(|b| b.get(&bookmark)).copied() { let heads = repo.store.get_state(&state)?.heads; let mut view = op.view.clone(); view.bookmarks.insert(bookmark, state); repo.record_op(&[op_ref], &format!("oxy clone {url}"), view)?; repo.checkout(&heads, false, "oxy clone (checkout)")?; } Ok(repo) } }