OXYGENHUB

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

732 of 885 lines run, 136 of 203 functions · run #253 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 {
168986×
    pub fn open(path: &Path) -> Result<LocalRemote> {
169
        Ok(LocalRemote {
170986×
            repo: Repo::open(path)?,
171986×
            claimed_id: None,
172
        })
173986×
    }
174
}
175
176
impl Remote for LocalRemote {
177776×
    fn repo_id(&self) -> Result<[u8; 16]> {
178776×
        self.repo.id()
179776×
    }
180775×
    fn refs(&self) -> Result<RefsResponse> {
181775×
        self.repo.remote_refs()
182775×
    }
183291×
    fn negotiate(&self, have: &[ChangeHash], want: &[ChangeHash]) -> Result<Vec<ChangeHash>> {
184291×
        self.repo.negotiate(have, want)
185291×
    }
186294×
    fn fetch(&self, changes: &[ChangeHash], max_blob: Option<u64>) -> Result<Bundle> {
187294×
        self.repo.bundle_raw_for(changes, max_blob)
188294×
    }
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×
    }
198221×
    fn push(
199221×
        &self,
200221×
        bundle: Bundle,
201221×
        updates: Vec<RefUpdate>,
202221×
        policy: Option<SignedPolicy>,
203221×
        tags: Vec<TagRef>,
204221×
    ) -> Result<Vec<RefResult>> {
205221×
        if self.repo.is_unbound() {
2068×
            match self.claimed_id {
2078×
                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
            }
215213×
        }
216221×
        self.repo.receive_push(bundle, updates, policy, tags)
217221×
    }
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
}
239
240
/// Opens a store for a URL it understands, or passes (`None`). Stores that
241
/// need more than the standard library (the cloud ones) are added by the
242
/// program that links them, with [`register_store_opener`].
243
pub type StoreOpener =
244
    fn(&str, &RemoteOptions) -> Option<crate::strata::Result<Box<dyn crate::strata::Store>>>;
245
246
static STORE_OPENERS: Mutex<Vec<StoreOpener>> = Mutex::new(Vec::new());
247
248143×
pub fn register_store_opener(opener: StoreOpener) {
249143×
    STORE_OPENERS
250143×
        .lock()
251143×
        .unwrap_or_else(|p| p.into_inner())
252143×
        .push(opener);
253143×
}
254
255
/// A store for `url`, from `dir://` or any registered opener.
2561046×
pub fn open_store(
2571046×
    url: &str,
2581046×
    options: &RemoteOptions,
2591046×
) -> Option<crate::strata::Result<Box<dyn crate::strata::Store>>> {
2601046×
    if let Some(path) = url.strip_prefix("dir://") {
261
        return Some(
26259×
            crate::strata::LocalStore::open(path)
26359×
                .map(|s| Box::new(s) as Box<dyn crate::strata::Store>),
264
        );
265987×
    }
266987×
    let openers = STORE_OPENERS.lock().unwrap_or_else(|p| p.into_inner());
267987×
    openers.iter().find_map(|open| open(url, options))
2681046×
}
269
270
/// The request header carrying the client's repository id.
271
pub const REPO_ID_HEADER: &str = "Oxy-Repo-Id";
272
273
/// The id of a hosted repository that has not adopted one yet.
274
pub const UNBOUND_ID: [u8; 16] = [0; 16];
275
276
/// A remote served by `oxy-server` at `<base>/oxy/v1/...`.
277
pub struct HttpRemote {
278
    base: String,
279
    token: Option<String>,
280
    repo_id: Option<[u8; 16]>,
281
    agent: ureq::Agent,
282
}
283
284
/// A TLS client configuration trusting the web roots plus `ca`, if given:
285
/// the trust every oxy connection uses, shared with tools that call hub APIs.
286143×
pub fn tls_client_config(ca: Option<&Path>) -> Result<Arc<rustls::ClientConfig>> {
287143×
    let mut roots = rustls::RootCertStore::empty();
288143×
    roots.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
289143×
    if let Some(path) = ca {
29077×
        let pem = std::fs::read(path)
29177×
            .map_err(|e| RepoError::Msg(format!("reading CA file {}: {e}", path.display())))?;
29277×
        let certs = rustls_pemfile::certs(&mut pem.as_slice())
29377×
            .collect::<std::result::Result<Vec<_>, _>>()
29477×
            .map_err(|e| RepoError::Msg(format!("parsing CA file {}: {e}", path.display())))?;
29577×
        if certs.is_empty() {
2960×
            return Err(RepoError::Msg(format!(
2970×
                "CA file {} holds no certificates",
2980×
                path.display()
2990×
            )));
30077×
        }
30177×
        for c in certs {
30277×
            roots
30377×
                .add(c)
30477×
                .map_err(|e| RepoError::Msg(format!("CA file {}: {e}", path.display())))?;
305
        }
30666×
    }
307143×
    let cfg = rustls::ClientConfig::builder_with_provider(Arc::new(
308143×
        rustls::crypto::ring::default_provider(),
309
    ))
310143×
    .with_safe_default_protocol_versions()
311143×
    .map_err(|e| RepoError::Msg(e.to_string()))?
312143×
    .with_root_certificates(roots)
313143×
    .with_no_client_auth();
314143×
    Ok(Arc::new(cfg))
315143×
}
316
317
impl HttpRemote {
318141×
    pub fn new(base: &str, options: &RemoteOptions) -> Result<HttpRemote> {
319141×
        refuse_plain_token(base, options)?;
320141×
        let agent = ureq::AgentBuilder::new()
321141×
            .tls_config(tls_client_config(options.ca.as_deref())?)
322141×
            .build();
323141×
        Ok(HttpRemote {
324141×
            base: base.trim_end_matches('/').to_string(),
325141×
            token: options.token.clone(),
326141×
            repo_id: options.repo_id,
327141×
            agent,
328141×
        })
329141×
    }
330
331362×
    fn call(&self, post: bool, endpoint: &str, body: Option<&[u8]>) -> Result<Vec<u8>> {
332362×
        let url = format!("{}/oxy/v1/{endpoint}", self.base);
333362×
        let mut req = if post {
334127×
            self.agent.post(&url)
335
        } else {
336235×
            self.agent.get(&url)
337
        };
338362×
        req = req.set("Accept", CONTENT_TYPE);
339362×
        if let Some(t) = &self.token {
34010×
            req = req.set("Authorization", &format!("Bearer {t}"));
341352×
        }
342362×
        if let Some(id) = &self.repo_id {
343339×
            req = req.set(REPO_ID_HEADER, &hex::encode(id));
344339×
        }
345362×
        let resp = match body {
346127×
            Some(b) => req.set("Content-Type", CONTENT_TYPE).send_bytes(b),
347235×
            None => req.call(),
348
        };
3499×
        match resp {
350353×
            Ok(r) => {
351353×
                let mut out = Vec::new();
352353×
                r.into_reader()
353353×
                    .read_to_end(&mut out)
354353×
                    .map_err(|e| RepoError::Msg(format!("{url}: {e}")))?;
355353×
                Ok(out)
356
            }
3576×
            Err(ureq::Error::Status(code, r)) => {
3586×
                let text = r.into_string().unwrap_or_default();
3596×
                let msg = format!("{url}: HTTP {code}: {}", text.trim());
3606×
                Err(RepoError::Msg(with_hint(msg)))
361
            }
362
            // The transport error already names the URL.
3633×
            Err(e) => Err(RepoError::Msg(with_hint(e.to_string()))),
364
        }
365362×
    }
366
}
367
368
/// Refuse to send a token where anyone on the way could read it: plain
369
/// `http` to another machine (see [`crate::credentials::token_allowed`]).
370141×
fn refuse_plain_token(url: &str, options: &RemoteOptions) -> Result<()> {
371141×
    if options.token.is_some() && !crate::credentials::token_allowed(url) {
3720×
        return Err(RepoError::Msg(format!(
3730×
            "{url}: refusing to send a token over plain http; use https"
3740×
        )));
375141×
    }
376141×
    Ok(())
377141×
}
378
379
/// What to do about a failed request, recognised from its message.
38017×
pub fn hint_for(message: &str) -> Option<&'static str> {
38117×
    let m = message.to_ascii_lowercase();
38217×
    let hint = if m.contains("http 401") {
3834×
        "the hub needs you signed in, or did not accept the token: run `oxy auth login HUB` (pushing needs repo:write)"
38413×
    } else if m.contains("http 403") {
3851×
        "the token or account lacks permission: pushing needs a token with repo:write and write access to the repository"
38612×
    } else if m.contains("http 404") {
3874×
        "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`)"
3888×
    } else if m.contains("unknownissuer")
3896×
        || m.contains("unknown issuer")
3906×
        || m.contains("certificate")
3915×
        || m.contains("invalidcertificate")
392
    {
3933×
        "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`"
3945×
    } else if m.contains("connection refused") {
3953×
        "nothing is listening there: check the URL and port, and that the server is running"
3962×
    } else if m.contains("dns")
3971×
        || m.contains("failed to lookup")
3981×
        || m.contains("name or service not known")
399
    {
4001×
        "the host name does not resolve: check the URL"
4011×
    } else if m.contains("timed out") || m.contains("timeout") {
4020×
        "the server did not answer in time: check the network, or try again"
403
    } else {
4041×
        return None;
405
    };
40616×
    Some(hint)
40717×
}
408
409
/// `message`, followed by what to do about it when that is known.
4109×
pub fn with_hint(message: String) -> String {
4119×
    match hint_for(&message) {
4129×
        Some(h) => format!("{message}\n  hint: {h}"),
4130×
        None => message,
414
    }
4159×
}
416
417
/// A JSON request to a hub API (`GET`, `POST` or `DELETE`), with the same
418
/// TLS trust and token rules as remotes. Returns the status and body, an
419
/// error status included; only transport failures are errors.
4200×
pub fn http_json(
4210×
    method: &str,
4220×
    url: &str,
4230×
    body: Option<&str>,
4240×
    options: &RemoteOptions,
4250×
) -> Result<(u16, String)> {
4260×
    refuse_plain_token(url, options)?;
4270×
    let agent = ureq::AgentBuilder::new()
4280×
        .tls_config(tls_client_config(options.ca.as_deref())?)
4290×
        .timeout(std::time::Duration::from_secs(60))
4300×
        .build();
4310×
    let mut req = agent.request(method, url).set("Accept", "application/json");
4320×
    if let Some(t) = &options.token {
4330×
        req = req.set("Authorization", &format!("Bearer {t}"));
4340×
    }
4350×
    let resp = match body {
4360×
        Some(b) => req.set("Content-Type", "application/json").send_string(b),
4370×
        None => req.call(),
438
    };
4390×
    match resp {
4400×
        Ok(r) => {
4410×
            let code = r.status();
4420×
            Ok((code, r.into_string().unwrap_or_default()))
443
        }
4440×
        Err(ureq::Error::Status(code, r)) => Ok((code, r.into_string().unwrap_or_default())),
4450×
        Err(e) => Err(RepoError::Msg(with_hint(e.to_string()))),
446
    }
4470×
}
448
449
/// An authenticated GET of any URL on a host, with the same TLS trust and
450
/// token as remotes use (for hub APIs: proposals). Returns the body.
4510×
pub fn http_get(url: &str, options: &RemoteOptions) -> Result<Vec<u8>> {
4520×
    refuse_plain_token(url, options)?;
4530×
    let agent = ureq::AgentBuilder::new()
4540×
        .tls_config(tls_client_config(options.ca.as_deref())?)
4550×
        .build();
4560×
    let mut req = agent.get(url).set("Accept", "application/json");
4570×
    if let Some(t) = &options.token {
4580×
        req = req.set("Authorization", &format!("Bearer {t}"));
4590×
    }
4600×
    match req.call() {
4610×
        Ok(r) => {
4620×
            let mut out = Vec::new();
4630×
            r.into_reader()
4640×
                .read_to_end(&mut out)
4650×
                .map_err(|e| RepoError::Msg(format!("{url}: {e}")))?;
4660×
            Ok(out)
467
        }
4680×
        Err(ureq::Error::Status(code, r)) => {
4690×
            let text = r.into_string().unwrap_or_default();
4700×
            Err(RepoError::Msg(with_hint(format!(
4710×
                "{url}: HTTP {code}: {}",
4720×
                text.trim()
4730×
            ))))
474
        }
475
        // The transport error already names the URL.
4760×
        Err(e) => Err(RepoError::Msg(with_hint(e.to_string()))),
477
    }
4780×
}
479
480
impl Remote for HttpRemote {
481122×
    fn repo_id(&self) -> Result<[u8; 16]> {
482122×
        wire::decode_capabilities(&self.call(false, "capabilities", None)?)
483122×
    }
484113×
    fn refs(&self) -> Result<RefsResponse> {
485113×
        Ok(wire::decode_refs(&self.call(false, "refs", None)?)?.1)
486113×
    }
48745×
    fn negotiate(&self, have: &[ChangeHash], want: &[ChangeHash]) -> Result<Vec<ChangeHash>> {
48845×
        wire::decode_hashes(&self.call(
489
            true,
49045×
            "negotiate",
49145×
            Some(&wire::encode_negotiate(have, want)),
4920×
        )?)
49345×
    }
49445×
    fn fetch(&self, changes: &[ChangeHash], max_blob: Option<u64>) -> Result<Bundle> {
49545×
        wire::decode_bundle(&self.call(
496
            true,
49745×
            "fetch",
49845×
            Some(&wire::encode_fetch(changes, max_blob)),
4990×
        )?)
50045×
    }
5011×
    fn objects(&self, refs: &[ObjectRef]) -> Result<Vec<(ObjectType, Vec<u8>)>> {
502
        Ok(
5031×
            wire::decode_bundle(&self.call(true, "objects", Some(&wire::encode_hashes(refs)))?)?
504
                .objects,
505
        )
5061×
    }
5070×
    fn checkpoint(&self, heads: &[ChangeHash]) -> Result<Bundle> {
5080×
        wire::decode_bundle(&self.call(true, "checkpoint", Some(&wire::encode_hashes(heads)))?)
5090×
    }
5100×
    fn shallow(&self, heads: &[ChangeHash], depth: u32) -> Result<Vec<ChangeHash>> {
5110×
        wire::decode_hashes(&self.call(
512
            true,
5130×
            "shallow",
5140×
            Some(&wire::encode_shallow(heads, depth)),
5150×
        )?)
5160×
    }
51736×
    fn push(
51836×
        &self,
51936×
        bundle: Bundle,
52036×
        updates: Vec<RefUpdate>,
52136×
        policy: Option<SignedPolicy>,
52236×
        tags: Vec<TagRef>,
52336×
    ) -> Result<Vec<RefResult>> {
52436×
        wire::decode_push_response(&self.call(
525
            true,
52636×
            "push",
52736×
            Some(&wire::encode_push(
52836×
                &bundle,
52936×
                &updates,
53036×
                policy.as_ref(),
53136×
                &tags,
53236×
            )),
5333×
        )?)
53436×
    }
535
}
536
537
/// A remote's URL as it is stored: an `http(s)://` URL as given, a local
538
/// path made absolute (with its `file://` kept), so it still names the same
539
/// repository from inside the clone (oxygen#57).
540239×
pub fn stored_url(url: &str) -> String {
541
    // Only a path is made absolute: a plain one, or one behind file:// or
542
    // dir://. Every other URL (a hub, a bucket) is kept as written.
543239×
    let (prefix, path) = match (url.strip_prefix("file://"), url.strip_prefix("dir://")) {
5441×
        (Some(p), _) => ("file://", p),
54511×
        (_, Some(p)) => ("dir://", p),
546227×
        _ if url.contains("://") => return url.to_string(),
547206×
        _ => ("", url),
548
    };
549218×
    match std::path::absolute(path) {
550218×
        Ok(abs) => format!("{prefix}{}", abs.display()),
5510×
        Err(_) => url.to_string(),
552
    }
553239×
}
554
555
/// Open a remote by URL: a local path (optionally `file://`), `http(s)://`
556
/// (a hub), or a store (`dir://`, and whatever openers are registered).
5571175×
pub fn open_remote(url: &str, options: &RemoteOptions) -> Result<Box<dyn Remote>> {
5581175×
    if url.starts_with("http://") || url.starts_with("https://") {
559141×
        return Ok(Box::new(HttpRemote::new(url, options)?));
5601034×
    }
5611034×
    if let Some(store) = open_store(url, options) {
56248×
        return crate::repo::strata::open_store_remote(store?, options);
563986×
    }
564986×
    let path = url.strip_prefix("file://").unwrap_or(url);
565986×
    if path.contains("://") {
5660×
        return Err(RepoError::Msg(format!("unsupported remote URL {url:?}")));
567986×
    }
568986×
    let mut local = LocalRemote::open(Path::new(path))?;
569986×
    local.claimed_id = options.repo_id;
570986×
    Ok(Box::new(local))
5711175×
}
572
573
// ---------------------------------------------------------------- wire
574
575
/// CBOR encodings of the protocol messages (spec §16.1).
576
pub mod wire {
577
    use super::*;
578
5790×
    fn schema(msg: &str) -> RepoError {
5800×
        RepoError::Object(ObjectError::Schema(msg.into()))
5810×
    }
582140×
    fn sigs_value(sigs: &[Signature]) -> Value {
583140×
        Value::Array(sigs.iter().map(|s| s.to_value()).collect())
584140×
    }
585142×
    fn sigs_from(v: &Value) -> Result<Vec<Signature>> {
586142×
        Ok(o::array(v, "signatures")?
587142×
            .iter()
588142×
            .map(Signature::from_value)
589142×
            .collect::<std::result::Result<Vec<_>, _>>()?)
590142×
    }
591340×
    fn hashes_value(hs: &[ObjectRef]) -> Value {
592500×
        Value::Array(hs.iter().map(|h| Value::Bytes(h.0.to_vec())).collect())
593340×
    }
594399×
    fn hashes_from(v: &Value) -> Result<Vec<ObjectRef>> {
595399×
        Ok(o::array(v, "hashes")?
596399×
            .iter()
597560×
            .map(|h| o::oref(h, "hash"))
598399×
            .collect::<std::result::Result<Vec<_>, _>>()?)
599399×
    }
60021×
    fn attest_value(sa: &SignedAttest) -> Value {
60121×
        Value::Array(vec![Value::Bytes(sa.attest.encode()), sigs_value(&sa.sigs)])
60221×
    }
60337×
    fn attest_from(v: &Value) -> Result<SignedAttest> {
60437×
        let a = o::array(v, "signed attest")?;
60537×
        if a.len() != 2 {
6060×
            return Err(schema("signed attest: expected [attest, sigs]"));
60737×
        }
608
        Ok(SignedAttest {
60937×
            attest: Attest::decode(o::bytes(&a[0], "attest")?)?,
61037×
            sigs: sigs_from(&a[1])?,
611
        })
61237×
    }
613189×
    fn opt_attest_value(sa: &Option<SignedAttest>) -> Value {
614189×
        sa.as_ref().map(attest_value).unwrap_or(Value::Null)
615189×
    }
616245×
    fn opt_attest_from(v: &Value) -> Result<Option<SignedAttest>> {
617245×
        if v.is_null() {
618218×
            Ok(None)
619
        } else {
62027×
            attest_from(v).map(Some)
621
        }
622245×
    }
623
    /// `[policy bytes, [signature]]`: also the format of a policy proposal
624
    /// file exchanged between root holders (spec §14.5).
6257×
    pub fn policy_value(sp: &SignedPolicy) -> Value {
6267×
        Value::Array(vec![Value::Bytes(sp.policy.encode()), sigs_value(&sp.sigs)])
6277×
    }
6287×
    pub fn policy_from(v: &Value) -> Result<SignedPolicy> {
6297×
        let a = o::array(v, "signed policy")?;
6307×
        if a.len() != 2 {
6310×
            return Err(schema("signed policy: expected [policy, sigs]"));
6327×
        }
633
        Ok(SignedPolicy {
6347×
            policy: Policy::decode(o::bytes(&a[0], "policy")?)?,
6357×
            sigs: sigs_from(&a[1])?,
636
        })
6377×
    }
638178×
    fn opt_policy_value(sp: Option<&SignedPolicy>) -> Value {
639178×
        sp.map(policy_value).unwrap_or(Value::Null)
640178×
    }
641218×
    fn opt_policy_from(v: &Value) -> Result<Option<SignedPolicy>> {
642218×
        if v.is_null() {
643215×
            Ok(None)
644
        } else {
6453×
            policy_from(v).map(Some)
646
        }
647218×
    }
648899×
    fn map<'a>(v: &'a Value, what: &str) -> Result<&'a o::Map> {
649899×
        Ok(o::map(v, what)?)
650899×
    }
6512524×
    fn field<'a>(m: &'a o::Map, k: u64, what: &str) -> Result<&'a Value> {
6522524×
        Ok(o::field(m, k, what)?)
6532524×
    }
654
655
    /// A bundle's value. Each change's text blobs and their chunks (spec
656
    /// §6.1) are added to its objects when they are not already there, so a
657
    /// bundle can always be read on its own.
658115×
    pub fn bundle_value(b: &Bundle) -> Value {
659115×
        let mut changes = Vec::with_capacity(b.raw_changes.len() + b.changes.len());
660
        // Changes as stored are already their encoding, their texts among
661
        // the objects.
662115×
        for (bytes, s) in &b.raw_changes {
6630×
            changes.push(Value::Array(vec![
6640×
                Value::Bytes(bytes.clone()),
6650×
                sigs_value(s),
6660×
            ]));
6670×
        }
668115×
        let mut texts: Vec<(ObjectType, Vec<u8>)> = Vec::new();
669115×
        let mut listed: Option<std::collections::HashSet<ObjectRef>> = None;
670115×
        for (c, s) in &b.changes {
671112×
            let (bytes, stored) = c.encode_parts();
672112×
            for t in stored {
6730×
                let listed = listed.get_or_insert_with(|| {
6740×
                    b.objects
6750×
                        .iter()
6760×
                        .map(|(ty, body)| crate::hash::hash_object(*ty, body))
6770×
                        .collect()
6780×
                });
6790×
                if !listed.insert(t.blob.hash()) {
6800×
                    continue;
6810×
                }
6820×
                for chunk in crate::chunk::chunks(&t.content) {
6830×
                    if listed.insert(crate::hash::hash_object(ObjectType::Chunk, chunk)) {
6840×
                        texts.push((ObjectType::Chunk, chunk.to_vec()));
6850×
                    }
686
                }
6870×
                texts.push((ObjectType::Blob, t.blob.encode()));
688
            }
689112×
            changes.push(Value::Array(vec![Value::Bytes(bytes), sigs_value(s)]));
690
        }
691115×
        Value::map([
692115×
            (0, Value::Array(changes)),
693115×
            (
694115×
                1,
695115×
                Value::Array(b.attests.iter().map(attest_value).collect()),
696115×
            ),
697
            (
698
                2,
699
                Value::Array(
700115×
                    b.objects
701115×
                        .iter()
702115×
                        .chain(&texts)
703115×
                        .map(|(t, body)| {
70484×
                            Value::Array(vec![
70584×
                                Value::Text(t.name().into()),
70684×
                                Value::Bytes(body.clone()),
70784×
                            ])
70884×
                        })
709115×
                        .collect(),
710
                ),
711
            ),
712115×
            (
713115×
                3,
714115×
                Value::Array(b.policies.iter().map(policy_value).collect()),
715115×
            ),
716
        ])
717115×
    }
718
719108×
    pub fn bundle_from_value(v: &Value) -> Result<Bundle> {
720108×
        let m = map(v, "bundle")?;
721108×
        let mut b = Bundle::default();
722108×
        for ob in o::array(field(m, 2, "objects")?, "objects")? {
72378×
            let pair = o::array(ob, "object")?;
72478×
            if pair.len() != 2 {
7250×
                return Err(schema("object: expected [type, body]"));
72678×
            }
72778×
            let ty = ObjectType::from_name(o::text(&pair[0], "object type")?)
72878×
                .ok_or_else(|| schema("unknown object type"))?;
72978×
            b.objects
73078×
                .push((ty, o::bytes(&pair[1], "object body")?.to_vec()));
731
        }
732
        // Stored inserts are read from the bundle's own objects.
733108×
        let mut by_ref: Option<std::collections::HashMap<ObjectRef, usize>> = None;
734108×
        for c in o::array(field(m, 0, "changes")?, "changes")? {
73598×
            let pair = o::array(c, "change entry")?;
73698×
            if pair.len() != 2 {
7370×
                return Err(schema("change entry: expected [change, sigs]"));
73898×
            }
73998×
            let encoded = o::bytes(&pair[0], "change")?;
74098×
            b.hashes
74198×
                .push(crate::hash::hash_object(ObjectType::Change, encoded));
74298×
            let change = Change::decode_with(encoded, &mut |text, count, form| {
7430×
                let by_ref = by_ref.get_or_insert_with(|| {
7440×
                    b.objects
7450×
                        .iter()
7460×
                        .enumerate()
7470×
                        .map(|(i, (ty, body))| (crate::hash::hash_object(*ty, body), i))
7480×
                        .collect()
7490×
                });
7500×
                let get =
7510×
                    |r: &ObjectRef, want: ObjectType| match by_ref.get(r).map(|i| &b.objects[*i]) {
7520×
                        Some((ty, body)) if *ty == want => Ok(body),
7530×
                        _ => Err(ObjectError::Schema(format!(
7540×
                            "the bundle lacks {} {}",
7550×
                            want.name(),
7560×
                            r.short(12)
7570×
                        ))),
7580×
                    };
7590×
                let blob = crate::objects::Blob::decode(get(text, ObjectType::Blob)?)?;
7600×
                let mut content = Vec::with_capacity(blob.length as usize);
7610×
                for chunk in &blob.chunks {
7620×
                    content.extend_from_slice(get(chunk, ObjectType::Chunk)?);
763
                }
7640×
                crate::objects::text_lines(&content, count, form)
7650×
            })?;
76698×
            b.changes.push((change, sigs_from(&pair[1])?));
767
        }
768108×
        for a in o::array(field(m, 1, "attests")?, "attests")? {
76910×
            b.attests.push(attest_from(a)?);
770
        }
771108×
        if let Some(ps) = m.get(&3) {
772108×
            for p in o::array(ps, "policies")? {
7732×
                b.policies.push(policy_from(p)?);
774
            }
7750×
        }
776108×
        Ok(b)
777108×
    }
778
77978×
    pub fn encode_bundle(b: &Bundle) -> Vec<u8> {
78078×
        cbor::encode(&bundle_value(b))
78178×
    }
78274×
    pub fn decode_bundle(bytes: &[u8]) -> Result<Bundle> {
78374×
        bundle_from_value(&cbor::decode(bytes).map_err(ObjectError::from)?)
78474×
    }
785
786117×
    pub fn encode_capabilities(id: [u8; 16]) -> Vec<u8> {
787117×
        cbor::encode(&Value::map([
788117×
            (0, Value::Array(vec![Value::Uint(PROTOCOL_VERSION)])),
789117×
            (1, Value::Bytes(id.to_vec())),
790117×
            (2, Value::Array(vec![Value::Text("seal".into())])),
791117×
        ]))
792117×
    }
793117×
    pub fn decode_capabilities(bytes: &[u8]) -> Result<[u8; 16]> {
794117×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
795117×
        let m = map(&v, "capabilities")?;
796117×
        let versions = o::array(field(m, 0, "versions")?, "versions")?;
797117×
        if !versions
798117×
            .iter()
799117×
            .any(|x| x.as_uint() == Some(PROTOCOL_VERSION))
800
        {
8010×
            return Err(RepoError::Msg(
8020×
                "remote does not speak protocol version 1".into(),
8030×
            ));
804117×
        }
805117×
        o::bytes(field(m, 1, "repo id")?, "repo id")?
806117×
            .try_into()
807117×
            .map_err(|_| schema("repo id: expected 16 bytes"))
808117×
    }
809
810178×
    fn tags_value(tags: &[TagRef]) -> Value {
811
        Value::Array(
812178×
            tags.iter()
813178×
                .map(|t| {
8147×
                    Value::map([
8157×
                        (0, Value::Text(t.name.clone())),
8167×
                        (1, Value::Bytes(t.state.0.to_vec())),
8177×
                        (2, hashes_value(&t.heads)),
8187×
                        (3, opt_attest_value(&t.attestation)),
8197×
                    ])
8207×
                })
821178×
                .collect(),
822
        )
823178×
    }
824218×
    fn tags_from(v: &Value) -> Result<Vec<TagRef>> {
825218×
        let mut out = Vec::new();
826218×
        for t in o::array(v, "tags")? {
82723×
            let tm = map(t, "tag")?;
82823×
            out.push(TagRef {
82923×
                name: o::text(field(tm, 0, "name")?, "name")?.to_owned(),
83023×
                state: o::oref(field(tm, 1, "state")?, "state")?,
83123×
                heads: hashes_from(field(tm, 2, "heads")?)?,
83223×
                attestation: opt_attest_from(field(tm, 3, "attestation")?)?,
833
            });
834
        }
835218×
        Ok(out)
836218×
    }
837
838141×
    pub fn encode_refs(id: [u8; 16], resp: &RefsResponse) -> Vec<u8> {
839141×
        cbor::encode(&Value::map([
840
            (
841
                0,
842
                Value::Array(
843141×
                    resp.refs
844141×
                        .iter()
845145×
                        .map(|r| {
846145×
                            Value::map([
847145×
                                (0, Value::Text(r.name.clone())),
848145×
                                (1, Value::Bytes(r.state.0.to_vec())),
849145×
                                (2, hashes_value(&r.heads)),
850145×
                                (3, opt_attest_value(&r.attestation)),
851145×
                                (4, r.last_serial.map(Value::Uint).unwrap_or(Value::Null)),
852145×
                            ])
853145×
                        })
854141×
                        .collect(),
855
                ),
856
            ),
857141×
            (1, Value::Bytes(id.to_vec())),
858141×
            (2, opt_policy_value(resp.policy.as_ref())),
859141×
            (3, tags_value(&resp.tags)),
860141×
            (
861141×
                4,
862141×
                Value::Array(resp.history.iter().map(policy_value).collect()),
863141×
            ),
864141×
            (
865141×
                5,
866141×
                resp.default_bookmark
867141×
                    .clone()
868141×
                    .map(Value::Text)
869141×
                    .unwrap_or(Value::Null),
870141×
            ),
871
        ]))
872141×
    }
873184×
    pub fn decode_refs(bytes: &[u8]) -> Result<([u8; 16], RefsResponse)> {
874184×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
875184×
        let m = map(&v, "refs")?;
876184×
        let id: [u8; 16] = o::bytes(field(m, 1, "repo id")?, "repo id")?
877184×
            .try_into()
878184×
            .map_err(|_| schema("repo id: expected 16 bytes"))?;
879184×
        let mut refs = Vec::new();
880188×
        for r in o::array(field(m, 0, "refs")?, "refs")? {
881188×
            let rm = map(r, "ref")?;
882188×
            let ls = field(rm, 4, "last serial")?;
883188×
            refs.push(RemoteRef {
884188×
                name: o::text(field(rm, 0, "name")?, "name")?.to_owned(),
885188×
                state: o::oref(field(rm, 1, "state")?, "state")?,
886188×
                heads: hashes_from(field(rm, 2, "heads")?)?,
887188×
                attestation: opt_attest_from(field(rm, 3, "attestation")?)?,
888188×
                last_serial: if ls.is_null() {
889172×
                    None
890
                } else {
89116×
                    Some(o::uint(ls, "last serial")?)
892
                },
893
            });
894
        }
895184×
        let policy = match m.get(&2) {
896184×
            Some(p) => opt_policy_from(p)?,
8970×
            None => None,
898
        };
899184×
        let tags = match m.get(&3) {
900184×
            Some(t) => tags_from(t)?,
9010×
            None => Vec::new(),
902
        };
903184×
        let mut history = Vec::new();
904184×
        if let Some(h) = m.get(&4) {
905184×
            for p in o::array(h, "history")? {
9061×
                history.push(policy_from(p)?);
907
            }
9080×
        }
909184×
        let default_bookmark = match m.get(&5) {
910115×
            Some(Value::Text(t)) => Some(t.clone()),
91169×
            _ => None,
912
        };
913184×
        Ok((
914184×
            id,
915184×
            RefsResponse {
916184×
                refs,
917184×
                policy,
918184×
                tags,
919184×
                history,
920184×
                default_bookmark,
921184×
            },
922184×
        ))
923184×
    }
924
92546×
    pub fn encode_negotiate(have: &[ChangeHash], want: &[ChangeHash]) -> Vec<u8> {
92646×
        cbor::encode(&Value::map([
92746×
            (0, hashes_value(have)),
92846×
            (1, hashes_value(want)),
92946×
        ]))
93046×
    }
93146×
    pub fn decode_negotiate(bytes: &[u8]) -> Result<(Vec<ChangeHash>, Vec<ChangeHash>)> {
93246×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
93346×
        let m = map(&v, "negotiate")?;
934
        Ok((
93546×
            hashes_from(field(m, 0, "have")?)?,
93646×
            hashes_from(field(m, 1, "want")?)?,
937
        ))
93846×
    }
939
940
    /// `fetch` request: `{0: [changes], 1: max blob size or null}`.
94147×
    pub fn encode_fetch(hs: &[ChangeHash], max_blob: Option<u64>) -> Vec<u8> {
94247×
        cbor::encode(&Value::map([
94347×
            (0, hashes_value(hs)),
94447×
            (1, max_blob.map(Value::Uint).unwrap_or(Value::Null)),
94547×
        ]))
94647×
    }
94748×
    pub fn decode_fetch(bytes: &[u8]) -> Result<(Vec<ChangeHash>, Option<u64>)> {
94848×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
94948×
        let m = map(&v, "fetch")?;
95048×
        let max = match m.get(&1) {
95147×
            Some(x) if !x.is_null() => Some(o::uint(x, "max blob")?),
95246×
            _ => None,
953
        };
95448×
        Ok((hashes_from(field(m, 0, "changes")?)?, max))
95548×
    }
956
957
    /// `shallow` request: `{0: [heads], 1: depth}`.
9581×
    pub fn encode_shallow(hs: &[ChangeHash], depth: u32) -> Vec<u8> {
9591×
        cbor::encode(&Value::map([
9601×
            (0, hashes_value(hs)),
9611×
            (1, Value::Uint(depth as u64)),
9621×
        ]))
9631×
    }
9641×
    pub fn decode_shallow(bytes: &[u8]) -> Result<(Vec<ChangeHash>, u32)> {
9651×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
9661×
        let m = map(&v, "shallow")?;
967
        Ok((
9681×
            hashes_from(field(m, 0, "heads")?)?,
9691×
            o::u32_(field(m, 1, "depth")?, "depth")?,
970
        ))
9711×
    }
972
97348×
    pub fn encode_hashes(hs: &[ChangeHash]) -> Vec<u8> {
97448×
        cbor::encode(&Value::map([(0, hashes_value(hs))]))
97548×
    }
97647×
    pub fn decode_hashes(bytes: &[u8]) -> Result<Vec<ChangeHash>> {
97747×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
97847×
        hashes_from(field(map(&v, "hashes")?, 0, "hashes")?)
97947×
    }
980
98137×
    pub fn encode_push(
98237×
        bundle: &Bundle,
98337×
        updates: &[RefUpdate],
98437×
        policy: Option<&SignedPolicy>,
98537×
        tags: &[TagRef],
98637×
    ) -> Vec<u8> {
98737×
        cbor::encode(&Value::map([
98837×
            (0, bundle_value(bundle)),
98937×
            (2, opt_policy_value(policy)),
99037×
            (3, tags_value(tags)),
991
            (
992
                1,
993
                Value::Array(
99437×
                    updates
99537×
                        .iter()
99637×
                        .map(|u| {
99737×
                            Value::map([
99837×
                                (0, Value::Text(u.name.clone())),
99937×
                                (1, Value::Bytes(u.old_state.0.to_vec())),
100037×
                                (2, Value::Bytes(u.new_state.0.to_vec())),
100137×
                                (3, Value::Bool(u.force)),
100237×
                                (4, opt_attest_value(&u.attestation)),
100337×
                            ])
100437×
                        })
100537×
                        .collect(),
1006
                ),
1007
            ),
1008
        ]))
100937×
    }
1010
    /// A decoded push: bundle, bookmark updates, policy, tags.
1011
    pub type PushParts = (Bundle, Vec<RefUpdate>, Option<SignedPolicy>, Vec<TagRef>);
1012
101334×
    pub fn decode_push(bytes: &[u8]) -> Result<PushParts> {
101434×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
101534×
        let m = map(&v, "push")?;
101634×
        let bundle = bundle_from_value(field(m, 0, "bundle")?)?;
101734×
        let mut updates = Vec::new();
101834×
        for u in o::array(field(m, 1, "updates")?, "updates")? {
101934×
            let um = map(u, "update")?;
102034×
            updates.push(RefUpdate {
102134×
                name: o::text(field(um, 0, "name")?, "name")?.to_owned(),
102234×
                old_state: o::oref(field(um, 1, "old_state")?, "old_state")?,
102334×
                new_state: o::oref(field(um, 2, "new_state")?, "new_state")?,
102434×
                force: field(um, 3, "force")?
102534×
                    .as_bool()
102634×
                    .ok_or_else(|| schema("force: expected bool"))?,
102734×
                attestation: opt_attest_from(field(um, 4, "attestation")?)?,
1028
            });
1029
        }
103034×
        let policy = match m.get(&2) {
103134×
            Some(p) => opt_policy_from(p)?,
10320×
            None => None,
1033
        };
103434×
        let tags = match m.get(&3) {
103534×
            Some(t) => tags_from(t)?,
10360×
            None => Vec::new(),
1037
        };
103834×
        Ok((bundle, updates, policy, tags))
103934×
    }
1040
104134×
    pub fn encode_push_response(results: &[RefResult]) -> Vec<u8> {
104234×
        cbor::encode(&Value::map([(
1043
            0,
1044
            Value::Array(
104534×
                results
104634×
                    .iter()
104735×
                    .map(|r| {
104835×
                        Value::map([
104935×
                            (0, Value::Text(r.name.clone())),
105035×
                            (1, Value::Bool(r.ok)),
105135×
                            (2, Value::Text(r.reason.clone())),
105235×
                        ])
105335×
                    })
105434×
                    .collect(),
1055
            ),
1056
        )]))
105734×
    }
105834×
    pub fn decode_push_response(bytes: &[u8]) -> Result<Vec<RefResult>> {
105934×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
106034×
        let m = map(&v, "push response")?;
106134×
        let mut out = Vec::new();
106235×
        for r in o::array(field(m, 0, "results")?, "results")? {
106335×
            let rm = map(r, "result")?;
106435×
            out.push(RefResult {
106535×
                name: o::text(field(rm, 0, "name")?, "name")?.to_owned(),
106635×
                ok: field(rm, 1, "ok")?
106735×
                    .as_bool()
106835×
                    .ok_or_else(|| schema("ok: expected bool"))?,
106935×
                reason: o::text(field(rm, 2, "reason")?, "reason")?.to_owned(),
1070
            });
1071
        }
107234×
        Ok(out)
107334×
    }
1074
}
1075
1076
#[cfg(test)]
1077
mod tests {
1078
    use super::*;
1079
    use crate::attest::AttestBody;
1080
    use crate::objects::Hlc;
1081
1082
    #[test]
10831×
    fn wire_round_trips() {
10841×
        let c = crate::objects::tests::sample_change();
10851×
        let sk = crate::identity::SecretKey {
10861×
            ed_seed: [1; 32],
10871×
            ml_seed: [2; 32],
10881×
        };
10891×
        let id = sk.identity("a", "b", 0);
10901×
        let key = id.hash();
10911×
        let sig = sk.sign(crate::identity::Domain::Change, &key, &c.hash());
10921×
        let seal = Attest::seal([3; 16], vec![c.hash()]);
10931×
        let seal_sig = sk.sign(crate::identity::Domain::Attest, &key, &seal.hash());
10941×
        let policy = Policy::single_root([3; 16], id.clone(), 99);
10951×
        let psig = sk.sign(crate::identity::Domain::Policy, &key, &policy.hash());
10961×
        let bundle = Bundle {
10971×
            changes: vec![(c.clone(), vec![sig.clone()])],
10981×
            attests: vec![SignedAttest {
10991×
                attest: seal.clone(),
11001×
                sigs: vec![seal_sig],
11011×
            }],
11021×
            objects: vec![
11031×
                (ObjectType::Identity, id.encode()),
11041×
                (ObjectType::Chunk, b"xyz".to_vec()),
11051×
            ],
11061×
            policies: vec![SignedPolicy {
11071×
                policy: policy.clone(),
11081×
                sigs: vec![psig.clone()],
11091×
            }],
11101×
            hashes: vec![],
11111×
            raw_changes: vec![],
11121×
        };
11131×
        let d = wire::decode_bundle(&wire::encode_bundle(&bundle)).unwrap();
11141×
        assert_eq!(
1115
            d.hashes,
11161×
            vec![c.hash()],
1117
            "the receiver hashes what it was sent"
1118
        );
11191×
        assert_eq!(d.changes, bundle.changes);
11201×
        assert_eq!(d.attests, bundle.attests);
11211×
        assert_eq!(d.objects, bundle.objects);
11221×
        assert_eq!(d.policies, bundle.policies);
1123
11241×
        let att = Attest {
11251×
            repo: [3; 16],
11261×
            hlc: Hlc::default(),
11271×
            body: AttestBody::Ref {
11281×
                name: "main".into(),
11291×
                old_state: ObjectRef([1; 32]),
11301×
                new_state: ObjectRef([2; 32]),
11311×
                serial: 4,
11321×
            },
11331×
        };
11341×
        let refs = vec![
11351×
            RemoteRef {
11361×
                name: "main".into(),
11371×
                state: ObjectRef([2; 32]),
11381×
                heads: vec![c.hash()],
11391×
                attestation: Some(SignedAttest {
11401×
                    attest: att.clone(),
11411×
                    sigs: vec![sig.clone()],
11421×
                }),
11431×
                last_serial: Some(4),
11441×
            },
11451×
            RemoteRef {
11461×
                name: "dev".into(),
11471×
                state: ObjectRef([5; 32]),
11481×
                heads: vec![],
11491×
                attestation: None,
11501×
                last_serial: None,
11511×
            },
1152
        ];
11531×
        let tag = TagRef {
11541×
            name: "v1".into(),
11551×
            state: ObjectRef([2; 32]),
11561×
            heads: vec![c.hash()],
11571×
            attestation: None,
11581×
        };
11591×
        let resp = RefsResponse {
11601×
            refs,
11611×
            policy: Some(SignedPolicy {
11621×
                policy: policy.clone(),
11631×
                sigs: vec![psig.clone()],
11641×
            }),
11651×
            tags: vec![tag.clone()],
11661×
            history: vec![SignedPolicy {
11671×
                policy: policy.clone(),
11681×
                sigs: vec![],
11691×
            }],
11701×
            default_bookmark: Some("develop".into()),
11711×
        };
11721×
        let (id_back, back) = wire::decode_refs(&wire::encode_refs([3; 16], &resp)).unwrap();
11731×
        assert_eq!(id_back, [3; 16]);
11741×
        assert_eq!(back.refs.len(), 2);
11751×
        assert_eq!(back.refs[0].attestation.as_ref().unwrap().attest, att);
11761×
        assert_eq!(back.refs[1].last_serial, None);
11771×
        assert_eq!(back.policy.as_ref().unwrap().policy, policy);
11781×
        assert_eq!(back.history, resp.history);
11791×
        assert_eq!(back.tags, vec![tag.clone()]);
1180
11811×
        let (h, w) = wire::decode_negotiate(&wire::encode_negotiate(
11821×
            &[ObjectRef([1; 32])],
11831×
            &[ObjectRef([2; 32])],
11841×
        ))
11851×
        .unwrap();
11861×
        assert_eq!((h, w), (vec![ObjectRef([1; 32])], vec![ObjectRef([2; 32])]));
11871×
        assert_eq!(
11881×
            wire::decode_hashes(&wire::encode_hashes(&[c.hash()])).unwrap(),
11891×
            vec![c.hash()]
1190
        );
11911×
        assert_eq!(
11921×
            wire::decode_fetch(&wire::encode_fetch(&[c.hash()], Some(4096))).unwrap(),
11931×
            (vec![c.hash()], Some(4096))
1194
        );
11951×
        assert_eq!(
11961×
            wire::decode_fetch(&wire::encode_fetch(&[], None)).unwrap(),
11971×
            (vec![], None)
1198
        );
11991×
        assert_eq!(
12001×
            wire::decode_shallow(&wire::encode_shallow(&[c.hash()], 3)).unwrap(),
12011×
            (vec![c.hash()], 3)
1202
        );
1203
        // An old-style fetch request without the filter field still decodes.
12041×
        assert_eq!(
12051×
            wire::decode_fetch(&wire::encode_hashes(&[c.hash()])).unwrap(),
12061×
            (vec![c.hash()], None)
1207
        );
1208
12091×
        let up = RefUpdate {
12101×
            name: "main".into(),
12111×
            old_state: ObjectRef([1; 32]),
12121×
            new_state: ObjectRef([2; 32]),
12131×
            force: true,
12141×
            attestation: Some(SignedAttest {
12151×
                attest: att,
12161×
                sigs: vec![sig],
12171×
            }),
12181×
        };
12191×
        let sp = SignedPolicy {
12201×
            policy,
12211×
            sigs: vec![psig],
12221×
        };
12231×
        let (b2, ups, pol, tags) = wire::decode_push(&wire::encode_push(
12241×
            &bundle,
12251×
            std::slice::from_ref(&up),
12261×
            Some(&sp),
12271×
            std::slice::from_ref(&tag),
12281×
        ))
12291×
        .unwrap();
12301×
        assert_eq!(pol, Some(sp));
12311×
        assert_eq!(tags, vec![tag]);
12321×
        assert_eq!(b2.changes.len(), 1);
12331×
        assert_eq!(ups[0].name, "main");
12341×
        assert!(ups[0].force);
12351×
        assert_eq!(ups[0].attestation, up.attestation);
12361×
        let res = vec![RefResult {
12371×
            name: "main".into(),
12381×
            ok: false,
12391×
            reason: "stale".into(),
12401×
        }];
12411×
        assert_eq!(
12421×
            wire::decode_push_response(&wire::encode_push_response(&res)).unwrap(),
1243
            res
1244
        );
12451×
        assert_eq!(
12461×
            wire::decode_capabilities(&wire::encode_capabilities([7; 16])).unwrap(),
1247
            [7; 16]
1248
        );
12491×
    }
1250
}