OXYGENHUB

Coverage / crates/oxy-core/src/protocol.rs 83.0%

763 of 919 lines run, 142 of 215 functions · run #295 on main · run missed

1
//! Transport-agnostic protocol (spec §16): what a client asks of a remote and
2
//! what a server does with a push. `LocalRemote` serves another repository
3
//! directory in-process, `HttpRemote` speaks to an `oxy-server` over HTTP(S),
4
//! and the server side reuses `Repo::receive_push` and friends unchanged.
5
//!
6
//! Wire messages are deterministic CBOR (`wire` module); over HTTP each is a
7
//! request or response body with content type `application/oxy-cbor`.
8
9
use crate::attest::Attest;
10
use crate::cbor::{self, Value};
11
use crate::hash::{ChangeHash, ObjectRef, ObjectType};
12
use crate::identity::Signature;
13
use crate::objects::{self as o, Change, ObjectError};
14
use crate::policy::Policy;
15
use crate::repo::{Repo, RepoError, Result};
16
use std::path::{Path, PathBuf};
17
use std::sync::{Arc, Mutex};
18
19
pub const CONTENT_TYPE: &str = "application/oxy-cbor";
20
pub const PROTOCOL_VERSION: u64 = 1;
21
22
/// An attestation together with the signatures over its ObjectRef.
23
#[derive(Clone, Debug, PartialEq, Eq)]
24
pub struct SignedAttest {
25
    pub attest: Attest,
26
    pub sigs: Vec<Signature>,
27
}
28
29
/// A policy together with the root signatures over its ObjectRef.
30
#[derive(Clone, Debug, PartialEq, Eq)]
31
pub struct SignedPolicy {
32
    pub policy: Policy,
33
    pub sigs: Vec<Signature>,
34
}
35
36
impl SignedPolicy {
37
    /// The proposal-file encoding (`wire::policy_value`).
381×
    pub fn encode(&self) -> Vec<u8> {
391×
        crate::cbor::encode(&wire::policy_value(self))
401×
    }
411×
    pub fn decode(b: &[u8]) -> Result<SignedPolicy> {
421×
        wire::policy_from(
431×
            &crate::cbor::decode(b).map_err(|e| RepoError::Object(ObjectError::from(e)))?,
44
        )
451×
    }
46
}
47
48
/// What `refs` returns: every bookmark, every tag, and the current policy.
49
#[derive(Clone, Debug, Default)]
50
pub struct RefsResponse {
51
    pub refs: Vec<RemoteRef>,
52
    pub policy: Option<SignedPolicy>,
53
    pub tags: Vec<TagRef>,
54
    /// Earlier policies, ascending by serial, so a client behind by more
55
    /// than one update can verify each step (spec §14.5).
56
    pub history: Vec<SignedPolicy>,
57
    /// The bookmark a clone checks out (spec §16.1), when the remote names one.
58
    pub default_bookmark: Option<String>,
59
}
60
61
/// A tag as a remote reports it (spec §10.1).
62
#[derive(Clone, Debug, PartialEq, Eq)]
63
pub struct TagRef {
64
    pub name: String,
65
    pub state: ObjectRef,
66
    pub heads: Vec<ChangeHash>,
67
    pub attestation: Option<SignedAttest>,
68
}
69
70
/// One reference as a remote reports it.
71
#[derive(Clone, Debug)]
72
pub struct RemoteRef {
73
    pub name: String,
74
    pub state: ObjectRef,
75
    pub heads: Vec<ChangeHash>,
76
    /// The latest attestation, only when it describes `state`. An unattested
77
    /// push (accepted while no trust policy exists) leaves it `None`.
78
    pub attestation: Option<SignedAttest>,
79
    /// Serial of the latest attestation ever recorded, stale or not, so the
80
    /// next attestation continues the sequence.
81
    pub last_serial: Option<u64>,
82
}
83
84
/// Everything needed to add a set of changes to a repository.
85
#[derive(Clone, Debug, Default)]
86
pub struct Bundle {
87
    /// In dependency order, each with its individual signatures.
88
    pub changes: Vec<(Change, Vec<Signature>)>,
89
    /// Seals covering the changes.
90
    pub attests: Vec<SignedAttest>,
91
    /// Chunks, blobs, identities, and state objects referenced by the changes.
92
    pub objects: Vec<(ObjectType, Vec<u8>)>,
93
    /// Policies between the receiver's and the one sent with the push,
94
    /// ascending by serial (spec §14.5).
95
    pub policies: Vec<SignedPolicy>,
96
    /// Each change's hash, in the order of `changes`, when whoever made
97
    /// the bundle knows it: the store it came from, or the bytes it was
98
    /// decoded from. Never read from the wire. Empty when unknown.
99
    pub hashes: Vec<ChangeHash>,
100
    /// Changes as stored, with their signatures, in dependency order, for a
101
    /// fetch between repositories on one machine: their text blobs and
102
    /// chunks are among `objects`. Never on the wire.
103
    pub raw_changes: Vec<(Vec<u8>, Vec<Signature>)>,
104
}
105
106
impl Bundle {
10727×
    pub fn is_empty(&self) -> bool {
10827×
        self.changes.is_empty() && self.attests.is_empty() && self.objects.is_empty()
10927×
    }
110
}
111
112
/// A requested bookmark move (spec §10.2, §16.3).
113
#[derive(Clone, Debug)]
114
pub struct RefUpdate {
115
    pub name: String,
116
    pub old_state: ObjectRef,
117
    pub new_state: ObjectRef,
118
    pub force: bool,
119
    pub attestation: Option<SignedAttest>,
120
}
121
122
#[derive(Clone, Debug, PartialEq, Eq)]
123
pub struct RefResult {
124
    pub name: String,
125
    pub ok: bool,
126
    pub reason: String,
127
}
128
129
pub trait Remote {
130
    fn repo_id(&self) -> Result<[u8; 16]>;
131
    fn refs(&self) -> Result<RefsResponse>;
132
    /// Changes in the closure of `want` but not of `have`, in dependency order.
133
    fn negotiate(&self, have: &[ChangeHash], want: &[ChangeHash]) -> Result<Vec<ChangeHash>>;
134
    /// The changes with their signatures, seals, identities, and blobs; blobs
135
    /// larger than `max_blob` bytes are left out for lazy fetching (spec §13.5).
136
    fn fetch(&self, changes: &[ChangeHash], max_blob: Option<u64>) -> Result<Bundle>;
137
    /// Individual objects by reference (spec §16.1 `objects`); a blob comes
138
    /// with its chunks.
139
    fn objects(&self, refs: &[ObjectRef]) -> Result<Vec<(ObjectType, Vec<u8>)>>;
140
    /// A checkpoint of exactly `heads` (spec §16.1 `checkpoint`): the
141
    /// checkpoint object, its payload blob, and the blob's chunks.
142
    fn checkpoint(&self, heads: &[ChangeHash]) -> Result<Bundle>;
143
    /// The changes within `depth` dependency steps of `heads` (spec §17).
144
    fn shallow(&self, heads: &[ChangeHash], depth: u32) -> Result<Vec<ChangeHash>>;
145
    /// Push changes, bookmark updates, new tags, and optionally a newer
146
    /// policy. The policy is applied first; a result named `policy` reports
147
    /// it, and each tag reports as `tags/<name>`.
148
    fn push(
149
        &self,
150
        bundle: Bundle,
151
        updates: Vec<RefUpdate>,
152
        policy: Option<SignedPolicy>,
153
        tags: Vec<TagRef>,
154
    ) -> Result<Vec<RefResult>>;
155
}
156
157
// ---------------------------------------------------------------- local
158
159
/// Another repository on this machine, served in-process.
160
pub struct LocalRemote {
161
    pub repo: Repo,
162
    /// The pushing repository's id, which binds an unbound target on the
163
    /// first push, as `Oxy-Repo-Id` does over HTTP.
164
    pub claimed_id: Option<[u8; 16]>,
165
}
166
167
impl LocalRemote {
1681006×
    pub fn open(path: &Path) -> Result<LocalRemote> {
169
        Ok(LocalRemote {
1701006×
            repo: Repo::open(path)?,
1711006×
            claimed_id: None,
172
        })
1731006×
    }
174
}
175
176
impl Remote for LocalRemote {
177791×
    fn repo_id(&self) -> Result<[u8; 16]> {
178791×
        self.repo.id()
179791×
    }
180790×
    fn refs(&self) -> Result<RefsResponse> {
181790×
        self.repo.remote_refs()
182790×
    }
183296×
    fn negotiate(&self, have: &[ChangeHash], want: &[ChangeHash]) -> Result<Vec<ChangeHash>> {
184296×
        self.repo.negotiate(have, want)
185296×
    }
186299×
    fn fetch(&self, changes: &[ChangeHash], max_blob: Option<u64>) -> Result<Bundle> {
187299×
        self.repo.bundle_raw_for(changes, max_blob)
188299×
    }
1893×
    fn objects(&self, refs: &[ObjectRef]) -> Result<Vec<(ObjectType, Vec<u8>)>> {
1903×
        self.repo.objects_for(refs)
1913×
    }
1921×
    fn checkpoint(&self, heads: &[ChangeHash]) -> Result<Bundle> {
1931×
        self.repo.checkpoint_bundle_for(heads)
1941×
    }
1953×
    fn shallow(&self, heads: &[ChangeHash], depth: u32) -> Result<Vec<ChangeHash>> {
1963×
        self.repo.shallow_changes(heads, depth)
1973×
    }
198235×
    fn push(
199235×
        &self,
200235×
        bundle: Bundle,
201235×
        updates: Vec<RefUpdate>,
202235×
        policy: Option<SignedPolicy>,
203235×
        tags: Vec<TagRef>,
204235×
    ) -> Result<Vec<RefResult>> {
205235×
        if self.repo.is_unbound() {
20611×
            match self.claimed_id {
20711×
                Some(id) => self.repo.bind_id(id)?,
208
                None => {
2090×
                    return Err(RepoError::Msg(
2100×
                        "the remote is unbound and this client did not say which repository it is"
2110×
                            .into(),
2120×
                    ))
213
                }
214
            }
215224×
        }
216235×
        self.repo.receive_push(bundle, updates, policy, tags)
217235×
    }
218
}
219
220
// ---------------------------------------------------------------- http
221
222
/// How to reach a remote: credentials and trust.
223
#[derive(Clone, Debug, Default)]
224
pub struct RemoteOptions {
225
    /// Bearer token for pushes.
226
    pub token: Option<String>,
227
    /// PEM file with extra root certificates to trust for `https://` remotes
228
    /// (self-hosted servers); the system web roots are always trusted.
229
    pub ca: Option<PathBuf>,
230
    /// The local repository's id, sent as `Oxy-Repo-Id` so an unbound
231
    /// hosted repository can adopt it on the first push (spec §16.1).
232
    pub repo_id: Option<[u8; 16]>,
233
    /// Where a remote kept on a store (`dir://`, `s3://`, …) keeps its
234
    /// mirror and what it has seen: the remote's directory under
235
    /// `.oxy/remotes`. None (a clone, before there is a repository) means
236
    /// a temporary directory.
237
    pub cache_dir: Option<PathBuf>,
238
    /// Other tokens for the same hub, tried in turn when `token` is
239
    /// refused (401, 403 or 404): those of enclosing checkouts, when
240
    /// `token` came from the credential store rather than from this
241
    /// remote's own configuration (oxygen#112).
242
    pub fallback_tokens: Vec<String>,
243
}
244
245
/// Opens a store for a URL it understands, or passes (`None`). Stores that
246
/// need more than the standard library (the cloud ones) are added by the
247
/// program that links them, with [`register_store_opener`].
248
pub type StoreOpener =
249
    fn(&str, &RemoteOptions) -> Option<crate::strata::Result<Box<dyn crate::strata::Store>>>;
250
251
static STORE_OPENERS: Mutex<Vec<StoreOpener>> = Mutex::new(Vec::new());
252
253148×
pub fn register_store_opener(opener: StoreOpener) {
254148×
    STORE_OPENERS
255148×
        .lock()
256148×
        .unwrap_or_else(|p| p.into_inner())
257148×
        .push(opener);
258148×
}
259
260
/// A store for `url`, from `dir://` or any registered opener.
2611066×
pub fn open_store(
2621066×
    url: &str,
2631066×
    options: &RemoteOptions,
2641066×
) -> Option<crate::strata::Result<Box<dyn crate::strata::Store>>> {
2651066×
    if let Some(path) = url.strip_prefix("dir://") {
266
        return Some(
26759×
            crate::strata::LocalStore::open(path)
26859×
                .map(|s| Box::new(s) as Box<dyn crate::strata::Store>),
269
        );
2701007×
    }
2711007×
    let openers = STORE_OPENERS.lock().unwrap_or_else(|p| p.into_inner());
2721007×
    openers.iter().find_map(|open| open(url, options))
2731066×
}
274
275
/// The request header carrying the client's repository id.
276
pub const REPO_ID_HEADER: &str = "Oxy-Repo-Id";
277
278
/// The id of a hosted repository that has not adopted one yet.
279
pub const UNBOUND_ID: [u8; 16] = [0; 16];
280
281
/// A remote served by `oxy-server` at `<base>/oxy/v1/...`.
282
pub struct HttpRemote {
283
    base: String,
284
    /// The token in use, and those still to try when it is refused.
285
    token: Mutex<Option<String>>,
286
    fallbacks: Mutex<Vec<String>>,
287
    repo_id: Option<[u8; 16]>,
288
    agent: ureq::Agent,
289
}
290
291
/// A TLS client configuration trusting the web roots plus `ca`, if given:
292
/// the trust every oxy connection uses, shared with tools that call hub APIs.
293147×
pub fn tls_client_config(ca: Option<&Path>) -> Result<Arc<rustls::ClientConfig>> {
294147×
    let mut roots = rustls::RootCertStore::empty();
295147×
    roots.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
296147×
    if let Some(path) = ca {
29765×
        let pem = std::fs::read(path)
29865×
            .map_err(|e| RepoError::Msg(format!("reading CA file {}: {e}", path.display())))?;
29965×
        let certs = rustls_pemfile::certs(&mut pem.as_slice())
30065×
            .collect::<std::result::Result<Vec<_>, _>>()
30165×
            .map_err(|e| RepoError::Msg(format!("parsing CA file {}: {e}", path.display())))?;
30265×
        if certs.is_empty() {
3030×
            return Err(RepoError::Msg(format!(
3040×
                "CA file {} holds no certificates",
3050×
                path.display()
3060×
            )));
30765×
        }
30865×
        for c in certs {
30965×
            roots
31065×
                .add(c)
31165×
                .map_err(|e| RepoError::Msg(format!("CA file {}: {e}", path.display())))?;
312
        }
31382×
    }
314147×
    let cfg = rustls::ClientConfig::builder_with_provider(Arc::new(
315147×
        rustls::crypto::ring::default_provider(),
316
    ))
317147×
    .with_safe_default_protocol_versions()
318147×
    .map_err(|e| RepoError::Msg(e.to_string()))?
319147×
    .with_root_certificates(roots)
320147×
    .with_no_client_auth();
321147×
    Ok(Arc::new(cfg))
322147×
}
323
324
impl HttpRemote {
325143×
    pub fn new(base: &str, options: &RemoteOptions) -> Result<HttpRemote> {
326143×
        refuse_plain_token(base, options)?;
327143×
        let agent = ureq::AgentBuilder::new()
328143×
            .tls_config(tls_client_config(options.ca.as_deref())?)
329143×
            .build();
330143×
        Ok(HttpRemote {
331143×
            base: base.trim_end_matches('/').to_string(),
332143×
            token: Mutex::new(options.token.clone()),
333143×
            fallbacks: Mutex::new(options.fallback_tokens.iter().rev().cloned().collect()),
334143×
            repo_id: options.repo_id,
335143×
            agent,
336143×
        })
337143×
    }
338
339
    /// A request, tried again with the next fallback token while the
340
    /// hub refuses the one in use (oxygen#112).
341354×
    fn call(&self, post: bool, endpoint: &str, body: Option<&[u8]>) -> Result<Vec<u8>> {
342
        loop {
343355×
            let token = self.token.lock().unwrap_or_else(|p| p.into_inner()).clone();
344355×
            match self.call_once(post, endpoint, body, token.as_deref()) {
34511×
                Err(RepoError::Msg(m)) if token.is_some() && refused(&m) => {
3463×
                    let next = self
3473×
                        .fallbacks
3483×
                        .lock()
3493×
                        .unwrap_or_else(|p| p.into_inner())
3503×
                        .pop();
3513×
                    let Some(next) = next else {
3522×
                        return Err(RepoError::Msg(m));
353
                    };
3541×
                    crate::credentials::warn_once(&format!(
3551×
                        "{}: the stored token was refused; using the one an enclosing checkout has for this hub",
3561×
                        self.base
3571×
                    ));
3581×
                    *self.token.lock().unwrap_or_else(|p| p.into_inner()) = Some(next);
359
                }
360352×
                other => return other,
361
            }
362
        }
363354×
    }
364
365355×
    fn call_once(
366355×
        &self,
367355×
        post: bool,
368355×
        endpoint: &str,
369355×
        body: Option<&[u8]>,
370355×
        token: Option<&str>,
371355×
    ) -> Result<Vec<u8>> {
372355×
        let url = format!("{}/oxy/v1/{endpoint}", self.base);
373355×
        let mut req = if post {
374120×
            self.agent.post(&url)
375
        } else {
376235×
            self.agent.get(&url)
377
        };
378355×
        req = req.set("Accept", CONTENT_TYPE);
379355×
        if let Some(t) = token {
38022×
            req = req.set("Authorization", &format!("Bearer {t}"));
381333×
        }
382355×
        if let Some(id) = &self.repo_id {
383330×
            req = req.set(REPO_ID_HEADER, &hex::encode(id));
384330×
        }
385355×
        let resp = match body {
386120×
            Some(b) => req.set("Content-Type", CONTENT_TYPE).send_bytes(b),
387235×
            None => req.call(),
388
        };
38911×
        match resp {
390344×
            Ok(r) => {
391344×
                let mut out = Vec::new();
392344×
                r.into_reader()
393344×
                    .read_to_end(&mut out)
394344×
                    .map_err(|e| RepoError::Msg(format!("{url}: {e}")))?;
395344×
                Ok(out)
396
            }
3978×
            Err(ureq::Error::Status(code, r)) => {
3988×
                let text = r.into_string().unwrap_or_default();
3998×
                let msg = format!("{url}: HTTP {code}: {}", text.trim());
4008×
                Err(RepoError::Msg(with_hint(msg)))
401
            }
402
            // The transport error already names the URL.
4033×
            Err(e) => Err(RepoError::Msg(with_hint(e.to_string()))),
404
        }
405355×
    }
406
}
407
408
/// Whether a failed request's message says the hub refused its token:
409
/// HTTP 401, 403, or 404 (a hub hides a private repository from a token
410
/// that may not read it).
4114×
fn refused(message: &str) -> bool {
4124×
    [": HTTP 401", ": HTTP 403", ": HTTP 404"]
4134×
        .iter()
4146×
        .any(|c| message.contains(c))
4154×
}
416
417
/// Refuse to send a token where anyone on the way could read it: plain
418
/// `http` to another machine (see [`crate::credentials::token_allowed`]).
419143×
fn refuse_plain_token(url: &str, options: &RemoteOptions) -> Result<()> {
420143×
    if options.token.is_some() && !crate::credentials::token_allowed(url) {
4210×
        return Err(RepoError::Msg(format!(
4220×
            "{url}: refusing to send a token over plain http; use https"
4230×
        )));
424143×
    }
425143×
    Ok(())
426143×
}
427
428
/// What to do about a failed request, recognised from its message.
42919×
pub fn hint_for(message: &str) -> Option<&'static str> {
43019×
    let m = message.to_ascii_lowercase();
43119×
    let hint = if m.contains("http 401") {
4326×
        "the hub needs you signed in, or did not accept the token: run `oxy auth login HUB` (pushing needs repo:write)"
43313×
    } else if m.contains("http 403") {
4341×
        "the token or account lacks permission: pushing needs a token with repo:write and write access to the repository"
43512×
    } else if m.contains("http 404") {
4364×
        "nothing at this URL that you can see: check the owner and repository name; a private repository needs you signed in (`oxy auth login HUB`)"
4378×
    } else if m.contains("unknownissuer")
4386×
        || m.contains("unknown issuer")
4396×
        || m.contains("certificate")
4405×
        || m.contains("invalidcertificate")
441
    {
4423×
        "the server's certificate is not trusted: for a hub with a self-signed certificate, download it from /.well-known/oxyhub-ca.pem on the hub and run `oxy config remote.<remote>.ca FILE`"
4435×
    } else if m.contains("connection refused") {
4443×
        "nothing is listening there: check the URL and port, and that the server is running"
4452×
    } else if m.contains("dns")
4461×
        || m.contains("failed to lookup")
4471×
        || m.contains("name or service not known")
448
    {
4491×
        "the host name does not resolve: check the URL"
4501×
    } else if m.contains("timed out") || m.contains("timeout") {
4510×
        "the server did not answer in time: check the network, or try again"
452
    } else {
4531×
        return None;
454
    };
45518×
    Some(hint)
45619×
}
457
458
/// `message`, followed by what to do about it when that is known.
45911×
pub fn with_hint(message: String) -> String {
46011×
    match hint_for(&message) {
46111×
        Some(h) => format!("{message}\n  hint: {h}"),
4620×
        None => message,
463
    }
46411×
}
465
466
/// A JSON request to a hub API (`GET`, `POST` or `DELETE`), with the same
467
/// TLS trust and token rules as remotes. Returns the status and body, an
468
/// error status included; only transport failures are errors.
4690×
pub fn http_json(
4700×
    method: &str,
4710×
    url: &str,
4720×
    body: Option<&str>,
4730×
    options: &RemoteOptions,
4740×
) -> Result<(u16, String)> {
4750×
    refuse_plain_token(url, options)?;
4760×
    let agent = ureq::AgentBuilder::new()
4770×
        .tls_config(tls_client_config(options.ca.as_deref())?)
4780×
        .timeout(std::time::Duration::from_secs(60))
4790×
        .build();
4800×
    let mut req = agent.request(method, url).set("Accept", "application/json");
4810×
    if let Some(t) = &options.token {
4820×
        req = req.set("Authorization", &format!("Bearer {t}"));
4830×
    }
4840×
    let resp = match body {
4850×
        Some(b) => req.set("Content-Type", "application/json").send_string(b),
4860×
        None => req.call(),
487
    };
4880×
    match resp {
4890×
        Ok(r) => {
4900×
            let code = r.status();
4910×
            Ok((code, r.into_string().unwrap_or_default()))
492
        }
4930×
        Err(ureq::Error::Status(code, r)) => Ok((code, r.into_string().unwrap_or_default())),
4940×
        Err(e) => Err(RepoError::Msg(with_hint(e.to_string()))),
495
    }
4960×
}
497
498
/// An authenticated GET of any URL on a host, with the same TLS trust and
499
/// token as remotes use (for hub APIs: proposals). Returns the body.
5000×
pub fn http_get(url: &str, options: &RemoteOptions) -> Result<Vec<u8>> {
5010×
    refuse_plain_token(url, options)?;
5020×
    let agent = ureq::AgentBuilder::new()
5030×
        .tls_config(tls_client_config(options.ca.as_deref())?)
5040×
        .build();
5050×
    let mut req = agent.get(url).set("Accept", "application/json");
5060×
    if let Some(t) = &options.token {
5070×
        req = req.set("Authorization", &format!("Bearer {t}"));
5080×
    }
5090×
    match req.call() {
5100×
        Ok(r) => {
5110×
            let mut out = Vec::new();
5120×
            r.into_reader()
5130×
                .read_to_end(&mut out)
5140×
                .map_err(|e| RepoError::Msg(format!("{url}: {e}")))?;
5150×
            Ok(out)
516
        }
5170×
        Err(ureq::Error::Status(code, r)) => {
5180×
            let text = r.into_string().unwrap_or_default();
5190×
            Err(RepoError::Msg(with_hint(format!(
5200×
                "{url}: HTTP {code}: {}",
5210×
                text.trim()
5220×
            ))))
523
        }
524
        // The transport error already names the URL.
5250×
        Err(e) => Err(RepoError::Msg(with_hint(e.to_string()))),
526
    }
5270×
}
528
529
impl Remote for HttpRemote {
530122×
    fn repo_id(&self) -> Result<[u8; 16]> {
531122×
        wire::decode_capabilities(&self.call(false, "capabilities", None)?)
532122×
    }
533113×
    fn refs(&self) -> Result<RefsResponse> {
534113×
        Ok(wire::decode_refs(&self.call(false, "refs", None)?)?.1)
535113×
    }
53644×
    fn negotiate(&self, have: &[ChangeHash], want: &[ChangeHash]) -> Result<Vec<ChangeHash>> {
53744×
        wire::decode_hashes(&self.call(
538
            true,
53944×
            "negotiate",
54044×
            Some(&wire::encode_negotiate(have, want)),
5410×
        )?)
54244×
    }
54344×
    fn fetch(&self, changes: &[ChangeHash], max_blob: Option<u64>) -> Result<Bundle> {
54444×
        wire::decode_bundle(&self.call(
545
            true,
54644×
            "fetch",
54744×
            Some(&wire::encode_fetch(changes, max_blob)),
5480×
        )?)
54944×
    }
5501×
    fn objects(&self, refs: &[ObjectRef]) -> Result<Vec<(ObjectType, Vec<u8>)>> {
551
        Ok(
5521×
            wire::decode_bundle(&self.call(true, "objects", Some(&wire::encode_hashes(refs)))?)?
553
                .objects,
554
        )
5551×
    }
5560×
    fn checkpoint(&self, heads: &[ChangeHash]) -> Result<Bundle> {
5570×
        wire::decode_bundle(&self.call(true, "checkpoint", Some(&wire::encode_hashes(heads)))?)
5580×
    }
5590×
    fn shallow(&self, heads: &[ChangeHash], depth: u32) -> Result<Vec<ChangeHash>> {
5600×
        wire::decode_hashes(&self.call(
561
            true,
5620×
            "shallow",
5630×
            Some(&wire::encode_shallow(heads, depth)),
5640×
        )?)
5650×
    }
56630×
    fn push(
56730×
        &self,
56830×
        bundle: Bundle,
56930×
        updates: Vec<RefUpdate>,
57030×
        policy: Option<SignedPolicy>,
57130×
        tags: Vec<TagRef>,
57230×
    ) -> Result<Vec<RefResult>> {
57330×
        wire::decode_push_response(&self.call(
574
            true,
57530×
            "push",
57630×
            Some(&wire::encode_push(
57730×
                &bundle,
57830×
                &updates,
57930×
                policy.as_ref(),
58030×
                &tags,
58130×
            )),
5824×
        )?)
58330×
    }
584
}
585
586
/// A remote's URL as it is stored: an `http(s)://` URL as given, a local
587
/// path made absolute (with its `file://` kept), so it still names the same
588
/// repository from inside the clone (oxygen#57).
589246×
pub fn stored_url(url: &str) -> String {
590
    // Only a path is made absolute: a plain one, or one behind file:// or
591
    // dir://. Every other URL (a hub, a bucket) is kept as written.
592246×
    let (prefix, path) = match (url.strip_prefix("file://"), url.strip_prefix("dir://")) {
5931×
        (Some(p), _) => ("file://", p),
59411×
        (_, Some(p)) => ("dir://", p),
595234×
        _ if url.contains("://") => return url.to_string(),
596211×
        _ => ("", url),
597
    };
598223×
    match std::path::absolute(path) {
599223×
        Ok(abs) => format!("{prefix}{}", abs.display()),
6000×
        Err(_) => url.to_string(),
601
    }
602246×
}
603
604
/// Open a remote by URL: a local path (optionally `file://`), `http(s)://`
605
/// (a hub), or a store (`dir://`, and whatever openers are registered).
6061197×
pub fn open_remote(url: &str, options: &RemoteOptions) -> Result<Box<dyn Remote>> {
6071197×
    if url.starts_with("http://") || url.starts_with("https://") {
608143×
        return Ok(Box::new(HttpRemote::new(url, options)?));
6091054×
    }
6101054×
    if let Some(store) = open_store(url, options) {
61148×
        return crate::repo::strata::open_store_remote(store?, options);
6121006×
    }
6131006×
    let path = url.strip_prefix("file://").unwrap_or(url);
6141006×
    if path.contains("://") {
6150×
        return Err(RepoError::Msg(format!("unsupported remote URL {url:?}")));
6161006×
    }
6171006×
    let mut local = LocalRemote::open(Path::new(path))?;
6181006×
    local.claimed_id = options.repo_id;
6191006×
    Ok(Box::new(local))
6201197×
}
621
622
// ---------------------------------------------------------------- wire
623
624
/// CBOR encodings of the protocol messages (spec §16.1).
625
pub mod wire {
626
    use super::*;
627
6280×
    fn schema(msg: &str) -> RepoError {
6290×
        RepoError::Object(ObjectError::Schema(msg.into()))
6300×
    }
631134×
    fn sigs_value(sigs: &[Signature]) -> Value {
632134×
        Value::Array(sigs.iter().map(|s| s.to_value()).collect())
633134×
    }
634135×
    fn sigs_from(v: &Value) -> Result<Vec<Signature>> {
635135×
        Ok(o::array(v, "signatures")?
636135×
            .iter()
637135×
            .map(Signature::from_value)
638135×
            .collect::<std::result::Result<Vec<_>, _>>()?)
639135×
    }
640336×
    fn hashes_value(hs: &[ObjectRef]) -> Value {
641478×
        Value::Array(hs.iter().map(|h| Value::Bytes(h.0.to_vec())).collect())
642336×
    }
643395×
    fn hashes_from(v: &Value) -> Result<Vec<ObjectRef>> {
644395×
        Ok(o::array(v, "hashes")?
645395×
            .iter()
646538×
            .map(|h| o::oref(h, "hash"))
647395×
            .collect::<std::result::Result<Vec<_>, _>>()?)
648395×
    }
64921×
    fn attest_value(sa: &SignedAttest) -> Value {
65021×
        Value::Array(vec![Value::Bytes(sa.attest.encode()), sigs_value(&sa.sigs)])
65121×
    }
65237×
    fn attest_from(v: &Value) -> Result<SignedAttest> {
65337×
        let a = o::array(v, "signed attest")?;
65437×
        if a.len() != 2 {
6550×
            return Err(schema("signed attest: expected [attest, sigs]"));
65637×
        }
657
        Ok(SignedAttest {
65837×
            attest: Attest::decode(o::bytes(&a[0], "attest")?)?,
65937×
            sigs: sigs_from(&a[1])?,
660
        })
66137×
    }
662183×
    fn opt_attest_value(sa: &Option<SignedAttest>) -> Value {
663183×
        sa.as_ref().map(attest_value).unwrap_or(Value::Null)
664183×
    }
665238×
    fn opt_attest_from(v: &Value) -> Result<Option<SignedAttest>> {
666238×
        if v.is_null() {
667211×
            Ok(None)
668
        } else {
66927×
            attest_from(v).map(Some)
670
        }
671238×
    }
672
    /// `[policy bytes, [signature]]`: also the format of a policy proposal
673
    /// file exchanged between root holders (spec §14.5).
6747×
    pub fn policy_value(sp: &SignedPolicy) -> Value {
6757×
        Value::Array(vec![Value::Bytes(sp.policy.encode()), sigs_value(&sp.sigs)])
6767×
    }
6777×
    pub fn policy_from(v: &Value) -> Result<SignedPolicy> {
6787×
        let a = o::array(v, "signed policy")?;
6797×
        if a.len() != 2 {
6800×
            return Err(schema("signed policy: expected [policy, sigs]"));
6817×
        }
682
        Ok(SignedPolicy {
6837×
            policy: Policy::decode(o::bytes(&a[0], "policy")?)?,
6847×
            sigs: sigs_from(&a[1])?,
685
        })
6867×
    }
687172×
    fn opt_policy_value(sp: Option<&SignedPolicy>) -> Value {
688172×
        sp.map(policy_value).unwrap_or(Value::Null)
689172×
    }
690211×
    fn opt_policy_from(v: &Value) -> Result<Option<SignedPolicy>> {
691211×
        if v.is_null() {
692208×
            Ok(None)
693
        } else {
6943×
            policy_from(v).map(Some)
695
        }
696211×
    }
697860×
    fn map<'a>(v: &'a Value, what: &str) -> Result<&'a o::Map> {
698860×
        Ok(o::map(v, what)?)
699860×
    }
7002419×
    fn field<'a>(m: &'a o::Map, k: u64, what: &str) -> Result<&'a Value> {
7012419×
        Ok(o::field(m, k, what)?)
7022419×
    }
703
704
    /// A bundle's value. Each change's text blobs and their chunks (spec
705
    /// §6.1) are added to its objects when they are not already there, so a
706
    /// bundle can always be read on its own.
707108×
    pub fn bundle_value(b: &Bundle) -> Value {
708108×
        let mut changes = Vec::with_capacity(b.raw_changes.len() + b.changes.len());
709
        // Changes as stored are already their encoding, their texts among
710
        // the objects.
711108×
        for (bytes, s) in &b.raw_changes {
7120×
            changes.push(Value::Array(vec![
7130×
                Value::Bytes(bytes.clone()),
7140×
                sigs_value(s),
7150×
            ]));
7160×
        }
717108×
        let mut texts: Vec<(ObjectType, Vec<u8>)> = Vec::new();
718108×
        let mut listed: Option<std::collections::HashSet<ObjectRef>> = None;
719108×
        for (c, s) in &b.changes {
720106×
            let (bytes, stored) = c.encode_parts();
721106×
            for t in stored {
7220×
                let listed = listed.get_or_insert_with(|| {
7230×
                    b.objects
7240×
                        .iter()
7250×
                        .map(|(ty, body)| crate::hash::hash_object(*ty, body))
7260×
                        .collect()
7270×
                });
7280×
                if !listed.insert(t.blob.hash()) {
7290×
                    continue;
7300×
                }
7310×
                for chunk in crate::chunk::chunks(&t.content) {
7320×
                    if listed.insert(crate::hash::hash_object(ObjectType::Chunk, chunk)) {
7330×
                        texts.push((ObjectType::Chunk, chunk.to_vec()));
7340×
                    }
735
                }
7360×
                texts.push((ObjectType::Blob, t.blob.encode()));
737
            }
738106×
            changes.push(Value::Array(vec![Value::Bytes(bytes), sigs_value(s)]));
739
        }
740108×
        Value::map([
741108×
            (0, Value::Array(changes)),
742108×
            (
743108×
                1,
744108×
                Value::Array(b.attests.iter().map(attest_value).collect()),
745108×
            ),
746
            (
747
                2,
748
                Value::Array(
749108×
                    b.objects
750108×
                        .iter()
751108×
                        .chain(&texts)
752108×
                        .map(|(t, body)| {
75378×
                            Value::Array(vec![
75478×
                                Value::Text(t.name().into()),
75578×
                                Value::Bytes(body.clone()),
75678×
                            ])
75778×
                        })
758108×
                        .collect(),
759
                ),
760
            ),
761108×
            (
762108×
                3,
763108×
                Value::Array(b.policies.iter().map(policy_value).collect()),
764108×
            ),
765
        ])
766108×
    }
767
768100×
    pub fn bundle_from_value(v: &Value) -> Result<Bundle> {
769100×
        let m = map(v, "bundle")?;
770100×
        let mut b = Bundle::default();
771100×
        for ob in o::array(field(m, 2, "objects")?, "objects")? {
77271×
            let pair = o::array(ob, "object")?;
77371×
            if pair.len() != 2 {
7740×
                return Err(schema("object: expected [type, body]"));
77571×
            }
77671×
            let ty = ObjectType::from_name(o::text(&pair[0], "object type")?)
77771×
                .ok_or_else(|| schema("unknown object type"))?;
77871×
            b.objects
77971×
                .push((ty, o::bytes(&pair[1], "object body")?.to_vec()));
780
        }
781
        // Stored inserts are read from the bundle's own objects.
782100×
        let mut by_ref: Option<std::collections::HashMap<ObjectRef, usize>> = None;
783100×
        for c in o::array(field(m, 0, "changes")?, "changes")? {
78491×
            let pair = o::array(c, "change entry")?;
78591×
            if pair.len() != 2 {
7860×
                return Err(schema("change entry: expected [change, sigs]"));
78791×
            }
78891×
            let encoded = o::bytes(&pair[0], "change")?;
78991×
            b.hashes
79091×
                .push(crate::hash::hash_object(ObjectType::Change, encoded));
79191×
            let change = Change::decode_with(encoded, &mut |text, count, form| {
7920×
                let by_ref = by_ref.get_or_insert_with(|| {
7930×
                    b.objects
7940×
                        .iter()
7950×
                        .enumerate()
7960×
                        .map(|(i, (ty, body))| (crate::hash::hash_object(*ty, body), i))
7970×
                        .collect()
7980×
                });
7990×
                let get =
8000×
                    |r: &ObjectRef, want: ObjectType| match by_ref.get(r).map(|i| &b.objects[*i]) {
8010×
                        Some((ty, body)) if *ty == want => Ok(body),
8020×
                        _ => Err(ObjectError::Schema(format!(
8030×
                            "the bundle lacks {} {}",
8040×
                            want.name(),
8050×
                            r.short(12)
8060×
                        ))),
8070×
                    };
8080×
                let blob = crate::objects::Blob::decode(get(text, ObjectType::Blob)?)?;
8090×
                let mut content = Vec::with_capacity(blob.length as usize);
8100×
                for chunk in &blob.chunks {
8110×
                    content.extend_from_slice(get(chunk, ObjectType::Chunk)?);
812
                }
8130×
                crate::objects::text_lines(&content, count, form)
8140×
            })?;
81591×
            b.changes.push((change, sigs_from(&pair[1])?));
816
        }
817100×
        for a in o::array(field(m, 1, "attests")?, "attests")? {
81810×
            b.attests.push(attest_from(a)?);
819
        }
820100×
        if let Some(ps) = m.get(&3) {
821100×
            for p in o::array(ps, "policies")? {
8222×
                b.policies.push(policy_from(p)?);
823
            }
8240×
        }
825100×
        Ok(b)
826100×
    }
827
82877×
    pub fn encode_bundle(b: &Bundle) -> Vec<u8> {
82977×
        cbor::encode(&bundle_value(b))
83077×
    }
83173×
    pub fn decode_bundle(bytes: &[u8]) -> Result<Bundle> {
83273×
        bundle_from_value(&cbor::decode(bytes).map_err(ObjectError::from)?)
83373×
    }
834
835117×
    pub fn encode_capabilities(id: [u8; 16]) -> Vec<u8> {
836117×
        cbor::encode(&Value::map([
837117×
            (0, Value::Array(vec![Value::Uint(PROTOCOL_VERSION)])),
838117×
            (1, Value::Bytes(id.to_vec())),
839117×
            (2, Value::Array(vec![Value::Text("seal".into())])),
840117×
        ]))
841117×
    }
842117×
    pub fn decode_capabilities(bytes: &[u8]) -> Result<[u8; 16]> {
843117×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
844117×
        let m = map(&v, "capabilities")?;
845117×
        let versions = o::array(field(m, 0, "versions")?, "versions")?;
846117×
        if !versions
847117×
            .iter()
848117×
            .any(|x| x.as_uint() == Some(PROTOCOL_VERSION))
849
        {
8500×
            return Err(RepoError::Msg(
8510×
                "remote does not speak protocol version 1".into(),
8520×
            ));
853117×
        }
854117×
        o::bytes(field(m, 1, "repo id")?, "repo id")?
855117×
            .try_into()
856117×
            .map_err(|_| schema("repo id: expected 16 bytes"))
857117×
    }
858
859172×
    fn tags_value(tags: &[TagRef]) -> Value {
860
        Value::Array(
861172×
            tags.iter()
862172×
                .map(|t| {
8637×
                    Value::map([
8647×
                        (0, Value::Text(t.name.clone())),
8657×
                        (1, Value::Bytes(t.state.0.to_vec())),
8667×
                        (2, hashes_value(&t.heads)),
8677×
                        (3, opt_attest_value(&t.attestation)),
8687×
                    ])
8697×
                })
870172×
                .collect(),
871
        )
872172×
    }
873211×
    fn tags_from(v: &Value) -> Result<Vec<TagRef>> {
874211×
        let mut out = Vec::new();
875211×
        for t in o::array(v, "tags")? {
87623×
            let tm = map(t, "tag")?;
87723×
            out.push(TagRef {
87823×
                name: o::text(field(tm, 0, "name")?, "name")?.to_owned(),
87923×
                state: o::oref(field(tm, 1, "state")?, "state")?,
88023×
                heads: hashes_from(field(tm, 2, "heads")?)?,
88123×
                attestation: opt_attest_from(field(tm, 3, "attestation")?)?,
882
            });
883
        }
884211×
        Ok(out)
885211×
    }
886
887141×
    pub fn encode_refs(id: [u8; 16], resp: &RefsResponse) -> Vec<u8> {
888141×
        cbor::encode(&Value::map([
889
            (
890
                0,
891
                Value::Array(
892141×
                    resp.refs
893141×
                        .iter()
894145×
                        .map(|r| {
895145×
                            Value::map([
896145×
                                (0, Value::Text(r.name.clone())),
897145×
                                (1, Value::Bytes(r.state.0.to_vec())),
898145×
                                (2, hashes_value(&r.heads)),
899145×
                                (3, opt_attest_value(&r.attestation)),
900145×
                                (4, r.last_serial.map(Value::Uint).unwrap_or(Value::Null)),
901145×
                            ])
902145×
                        })
903141×
                        .collect(),
904
                ),
905
            ),
906141×
            (1, Value::Bytes(id.to_vec())),
907141×
            (2, opt_policy_value(resp.policy.as_ref())),
908141×
            (3, tags_value(&resp.tags)),
909141×
            (
910141×
                4,
911141×
                Value::Array(resp.history.iter().map(policy_value).collect()),
912141×
            ),
913141×
            (
914141×
                5,
915141×
                resp.default_bookmark
916141×
                    .clone()
917141×
                    .map(Value::Text)
918141×
                    .unwrap_or(Value::Null),
919141×
            ),
920
        ]))
921141×
    }
922184×
    pub fn decode_refs(bytes: &[u8]) -> Result<([u8; 16], RefsResponse)> {
923184×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
924184×
        let m = map(&v, "refs")?;
925184×
        let id: [u8; 16] = o::bytes(field(m, 1, "repo id")?, "repo id")?
926184×
            .try_into()
927184×
            .map_err(|_| schema("repo id: expected 16 bytes"))?;
928184×
        let mut refs = Vec::new();
929188×
        for r in o::array(field(m, 0, "refs")?, "refs")? {
930188×
            let rm = map(r, "ref")?;
931188×
            let ls = field(rm, 4, "last serial")?;
932188×
            refs.push(RemoteRef {
933188×
                name: o::text(field(rm, 0, "name")?, "name")?.to_owned(),
934188×
                state: o::oref(field(rm, 1, "state")?, "state")?,
935188×
                heads: hashes_from(field(rm, 2, "heads")?)?,
936188×
                attestation: opt_attest_from(field(rm, 3, "attestation")?)?,
937188×
                last_serial: if ls.is_null() {
938172×
                    None
939
                } else {
94016×
                    Some(o::uint(ls, "last serial")?)
941
                },
942
            });
943
        }
944184×
        let policy = match m.get(&2) {
945184×
            Some(p) => opt_policy_from(p)?,
9460×
            None => None,
947
        };
948184×
        let tags = match m.get(&3) {
949184×
            Some(t) => tags_from(t)?,
9500×
            None => Vec::new(),
951
        };
952184×
        let mut history = Vec::new();
953184×
        if let Some(h) = m.get(&4) {
954184×
            for p in o::array(h, "history")? {
9551×
                history.push(policy_from(p)?);
956
            }
9570×
        }
958184×
        let default_bookmark = match m.get(&5) {
959115×
            Some(Value::Text(t)) => Some(t.clone()),
96069×
            _ => None,
961
        };
962184×
        Ok((
963184×
            id,
964184×
            RefsResponse {
965184×
                refs,
966184×
                policy,
967184×
                tags,
968184×
                history,
969184×
                default_bookmark,
970184×
            },
971184×
        ))
972184×
    }
973
97445×
    pub fn encode_negotiate(have: &[ChangeHash], want: &[ChangeHash]) -> Vec<u8> {
97545×
        cbor::encode(&Value::map([
97645×
            (0, hashes_value(have)),
97745×
            (1, hashes_value(want)),
97845×
        ]))
97945×
    }
98045×
    pub fn decode_negotiate(bytes: &[u8]) -> Result<(Vec<ChangeHash>, Vec<ChangeHash>)> {
98145×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
98245×
        let m = map(&v, "negotiate")?;
983
        Ok((
98445×
            hashes_from(field(m, 0, "have")?)?,
98545×
            hashes_from(field(m, 1, "want")?)?,
986
        ))
98745×
    }
988
989
    /// `fetch` request: `{0: [changes], 1: max blob size or null}`.
99046×
    pub fn encode_fetch(hs: &[ChangeHash], max_blob: Option<u64>) -> Vec<u8> {
99146×
        cbor::encode(&Value::map([
99246×
            (0, hashes_value(hs)),
99346×
            (1, max_blob.map(Value::Uint).unwrap_or(Value::Null)),
99446×
        ]))
99546×
    }
99647×
    pub fn decode_fetch(bytes: &[u8]) -> Result<(Vec<ChangeHash>, Option<u64>)> {
99747×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
99847×
        let m = map(&v, "fetch")?;
99947×
        let max = match m.get(&1) {
100046×
            Some(x) if !x.is_null() => Some(o::uint(x, "max blob")?),
100145×
            _ => None,
1002
        };
100347×
        Ok((hashes_from(field(m, 0, "changes")?)?, max))
100447×
    }
1005
1006
    /// `shallow` request: `{0: [heads], 1: depth}`.
10071×
    pub fn encode_shallow(hs: &[ChangeHash], depth: u32) -> Vec<u8> {
10081×
        cbor::encode(&Value::map([
10091×
            (0, hashes_value(hs)),
10101×
            (1, Value::Uint(depth as u64)),
10111×
        ]))
10121×
    }
10131×
    pub fn decode_shallow(bytes: &[u8]) -> Result<(Vec<ChangeHash>, u32)> {
10141×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
10151×
        let m = map(&v, "shallow")?;
1016
        Ok((
10171×
            hashes_from(field(m, 0, "heads")?)?,
10181×
            o::u32_(field(m, 1, "depth")?, "depth")?,
1019
        ))
10201×
    }
1021
102247×
    pub fn encode_hashes(hs: &[ChangeHash]) -> Vec<u8> {
102347×
        cbor::encode(&Value::map([(0, hashes_value(hs))]))
102447×
    }
102546×
    pub fn decode_hashes(bytes: &[u8]) -> Result<Vec<ChangeHash>> {
102646×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
102746×
        hashes_from(field(map(&v, "hashes")?, 0, "hashes")?)
102846×
    }
1029
103031×
    pub fn encode_push(
103131×
        bundle: &Bundle,
103231×
        updates: &[RefUpdate],
103331×
        policy: Option<&SignedPolicy>,
103431×
        tags: &[TagRef],
103531×
    ) -> Vec<u8> {
103631×
        cbor::encode(&Value::map([
103731×
            (0, bundle_value(bundle)),
103831×
            (2, opt_policy_value(policy)),
103931×
            (3, tags_value(tags)),
1040
            (
1041
                1,
1042
                Value::Array(
104331×
                    updates
104431×
                        .iter()
104531×
                        .map(|u| {
104631×
                            Value::map([
104731×
                                (0, Value::Text(u.name.clone())),
104831×
                                (1, Value::Bytes(u.old_state.0.to_vec())),
104931×
                                (2, Value::Bytes(u.new_state.0.to_vec())),
105031×
                                (3, Value::Bool(u.force)),
105131×
                                (4, opt_attest_value(&u.attestation)),
105231×
                            ])
105331×
                        })
105431×
                        .collect(),
1055
                ),
1056
            ),
1057
        ]))
105831×
    }
1059
    /// A decoded push: bundle, bookmark updates, policy, tags.
1060
    pub type PushParts = (Bundle, Vec<RefUpdate>, Option<SignedPolicy>, Vec<TagRef>);
1061
106227×
    pub fn decode_push(bytes: &[u8]) -> Result<PushParts> {
106327×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
106427×
        let m = map(&v, "push")?;
106527×
        let bundle = bundle_from_value(field(m, 0, "bundle")?)?;
106627×
        let mut updates = Vec::new();
106727×
        for u in o::array(field(m, 1, "updates")?, "updates")? {
106827×
            let um = map(u, "update")?;
106927×
            updates.push(RefUpdate {
107027×
                name: o::text(field(um, 0, "name")?, "name")?.to_owned(),
107127×
                old_state: o::oref(field(um, 1, "old_state")?, "old_state")?,
107227×
                new_state: o::oref(field(um, 2, "new_state")?, "new_state")?,
107327×
                force: field(um, 3, "force")?
107427×
                    .as_bool()
107527×
                    .ok_or_else(|| schema("force: expected bool"))?,
107627×
                attestation: opt_attest_from(field(um, 4, "attestation")?)?,
1077
            });
1078
        }
107927×
        let policy = match m.get(&2) {
108027×
            Some(p) => opt_policy_from(p)?,
10810×
            None => None,
1082
        };
108327×
        let tags = match m.get(&3) {
108427×
            Some(t) => tags_from(t)?,
10850×
            None => Vec::new(),
1086
        };
108727×
        Ok((bundle, updates, policy, tags))
108827×
    }
1089
109027×
    pub fn encode_push_response(results: &[RefResult]) -> Vec<u8> {
109127×
        cbor::encode(&Value::map([(
1092
            0,
1093
            Value::Array(
109427×
                results
109527×
                    .iter()
109628×
                    .map(|r| {
109728×
                        Value::map([
109828×
                            (0, Value::Text(r.name.clone())),
109928×
                            (1, Value::Bool(r.ok)),
110028×
                            (2, Value::Text(r.reason.clone())),
110128×
                        ])
110228×
                    })
110327×
                    .collect(),
1104
            ),
1105
        )]))
110627×
    }
110727×
    pub fn decode_push_response(bytes: &[u8]) -> Result<Vec<RefResult>> {
110827×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
110927×
        let m = map(&v, "push response")?;
111027×
        let mut out = Vec::new();
111128×
        for r in o::array(field(m, 0, "results")?, "results")? {
111228×
            let rm = map(r, "result")?;
111328×
            out.push(RefResult {
111428×
                name: o::text(field(rm, 0, "name")?, "name")?.to_owned(),
111528×
                ok: field(rm, 1, "ok")?
111628×
                    .as_bool()
111728×
                    .ok_or_else(|| schema("ok: expected bool"))?,
111828×
                reason: o::text(field(rm, 2, "reason")?, "reason")?.to_owned(),
1119
            });
1120
        }
112127×
        Ok(out)
112227×
    }
1123
}
1124
1125
#[cfg(test)]
1126
mod tests {
1127
    use super::*;
1128
    use crate::attest::AttestBody;
1129
    use crate::objects::Hlc;
1130
1131
    #[test]
11321×
    fn wire_round_trips() {
11331×
        let c = crate::objects::tests::sample_change();
11341×
        let sk = crate::identity::SecretKey {
11351×
            ed_seed: [1; 32],
11361×
            ml_seed: [2; 32],
11371×
        };
11381×
        let id = sk.identity("a", "b", 0);
11391×
        let key = id.hash();
11401×
        let sig = sk.sign(crate::identity::Domain::Change, &key, &c.hash());
11411×
        let seal = Attest::seal([3; 16], vec![c.hash()]);
11421×
        let seal_sig = sk.sign(crate::identity::Domain::Attest, &key, &seal.hash());
11431×
        let policy = Policy::single_root([3; 16], id.clone(), 99);
11441×
        let psig = sk.sign(crate::identity::Domain::Policy, &key, &policy.hash());
11451×
        let bundle = Bundle {
11461×
            changes: vec![(c.clone(), vec![sig.clone()])],
11471×
            attests: vec![SignedAttest {
11481×
                attest: seal.clone(),
11491×
                sigs: vec![seal_sig],
11501×
            }],
11511×
            objects: vec![
11521×
                (ObjectType::Identity, id.encode()),
11531×
                (ObjectType::Chunk, b"xyz".to_vec()),
11541×
            ],
11551×
            policies: vec![SignedPolicy {
11561×
                policy: policy.clone(),
11571×
                sigs: vec![psig.clone()],
11581×
            }],
11591×
            hashes: vec![],
11601×
            raw_changes: vec![],
11611×
        };
11621×
        let d = wire::decode_bundle(&wire::encode_bundle(&bundle)).unwrap();
11631×
        assert_eq!(
1164
            d.hashes,
11651×
            vec![c.hash()],
1166
            "the receiver hashes what it was sent"
1167
        );
11681×
        assert_eq!(d.changes, bundle.changes);
11691×
        assert_eq!(d.attests, bundle.attests);
11701×
        assert_eq!(d.objects, bundle.objects);
11711×
        assert_eq!(d.policies, bundle.policies);
1172
11731×
        let att = Attest {
11741×
            repo: [3; 16],
11751×
            hlc: Hlc::default(),
11761×
            body: AttestBody::Ref {
11771×
                name: "main".into(),
11781×
                old_state: ObjectRef([1; 32]),
11791×
                new_state: ObjectRef([2; 32]),
11801×
                serial: 4,
11811×
            },
11821×
        };
11831×
        let refs = vec![
11841×
            RemoteRef {
11851×
                name: "main".into(),
11861×
                state: ObjectRef([2; 32]),
11871×
                heads: vec![c.hash()],
11881×
                attestation: Some(SignedAttest {
11891×
                    attest: att.clone(),
11901×
                    sigs: vec![sig.clone()],
11911×
                }),
11921×
                last_serial: Some(4),
11931×
            },
11941×
            RemoteRef {
11951×
                name: "dev".into(),
11961×
                state: ObjectRef([5; 32]),
11971×
                heads: vec![],
11981×
                attestation: None,
11991×
                last_serial: None,
12001×
            },
1201
        ];
12021×
        let tag = TagRef {
12031×
            name: "v1".into(),
12041×
            state: ObjectRef([2; 32]),
12051×
            heads: vec![c.hash()],
12061×
            attestation: None,
12071×
        };
12081×
        let resp = RefsResponse {
12091×
            refs,
12101×
            policy: Some(SignedPolicy {
12111×
                policy: policy.clone(),
12121×
                sigs: vec![psig.clone()],
12131×
            }),
12141×
            tags: vec![tag.clone()],
12151×
            history: vec![SignedPolicy {
12161×
                policy: policy.clone(),
12171×
                sigs: vec![],
12181×
            }],
12191×
            default_bookmark: Some("develop".into()),
12201×
        };
12211×
        let (id_back, back) = wire::decode_refs(&wire::encode_refs([3; 16], &resp)).unwrap();
12221×
        assert_eq!(id_back, [3; 16]);
12231×
        assert_eq!(back.refs.len(), 2);
12241×
        assert_eq!(back.refs[0].attestation.as_ref().unwrap().attest, att);
12251×
        assert_eq!(back.refs[1].last_serial, None);
12261×
        assert_eq!(back.policy.as_ref().unwrap().policy, policy);
12271×
        assert_eq!(back.history, resp.history);
12281×
        assert_eq!(back.tags, vec![tag.clone()]);
1229
12301×
        let (h, w) = wire::decode_negotiate(&wire::encode_negotiate(
12311×
            &[ObjectRef([1; 32])],
12321×
            &[ObjectRef([2; 32])],
12331×
        ))
12341×
        .unwrap();
12351×
        assert_eq!((h, w), (vec![ObjectRef([1; 32])], vec![ObjectRef([2; 32])]));
12361×
        assert_eq!(
12371×
            wire::decode_hashes(&wire::encode_hashes(&[c.hash()])).unwrap(),
12381×
            vec![c.hash()]
1239
        );
12401×
        assert_eq!(
12411×
            wire::decode_fetch(&wire::encode_fetch(&[c.hash()], Some(4096))).unwrap(),
12421×
            (vec![c.hash()], Some(4096))
1243
        );
12441×
        assert_eq!(
12451×
            wire::decode_fetch(&wire::encode_fetch(&[], None)).unwrap(),
12461×
            (vec![], None)
1247
        );
12481×
        assert_eq!(
12491×
            wire::decode_shallow(&wire::encode_shallow(&[c.hash()], 3)).unwrap(),
12501×
            (vec![c.hash()], 3)
1251
        );
1252
        // An old-style fetch request without the filter field still decodes.
12531×
        assert_eq!(
12541×
            wire::decode_fetch(&wire::encode_hashes(&[c.hash()])).unwrap(),
12551×
            (vec![c.hash()], None)
1256
        );
1257
12581×
        let up = RefUpdate {
12591×
            name: "main".into(),
12601×
            old_state: ObjectRef([1; 32]),
12611×
            new_state: ObjectRef([2; 32]),
12621×
            force: true,
12631×
            attestation: Some(SignedAttest {
12641×
                attest: att,
12651×
                sigs: vec![sig],
12661×
            }),
12671×
        };
12681×
        let sp = SignedPolicy {
12691×
            policy,
12701×
            sigs: vec![psig],
12711×
        };
12721×
        let (b2, ups, pol, tags) = wire::decode_push(&wire::encode_push(
12731×
            &bundle,
12741×
            std::slice::from_ref(&up),
12751×
            Some(&sp),
12761×
            std::slice::from_ref(&tag),
12771×
        ))
12781×
        .unwrap();
12791×
        assert_eq!(pol, Some(sp));
12801×
        assert_eq!(tags, vec![tag]);
12811×
        assert_eq!(b2.changes.len(), 1);
12821×
        assert_eq!(ups[0].name, "main");
12831×
        assert!(ups[0].force);
12841×
        assert_eq!(ups[0].attestation, up.attestation);
12851×
        let res = vec![RefResult {
12861×
            name: "main".into(),
12871×
            ok: false,
12881×
            reason: "stale".into(),
12891×
        }];
12901×
        assert_eq!(
12911×
            wire::decode_push_response(&wire::encode_push_response(&res)).unwrap(),
1292
            res
1293
        );
12941×
        assert_eq!(
12951×
            wire::decode_capabilities(&wire::encode_capabilities([7; 16])).unwrap(),
1296
            [7; 16]
1297
        );
12981×
    }
1299
}