OXYGENHUB

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

933 of 1100 lines run, 149 of 232 functions · run #360 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
    /// The host's latest transparency-log checkpoint, a signed note (spec
60
    /// §14.8), against which `RemoteRef::logged` proofs are made (key 6,
61
    /// only when the host keeps a log).
62
    pub log: Option<String>,
63
    /// The witnesses the host asks to cosign its checkpoints: each one's
64
    /// name in cosignatures and its identity's bytes (key 7, only when it
65
    /// has any), which a client pins (spec §14.8, *Integrated time*).
66
    pub witnesses: Vec<(String, Vec<u8>)>,
67
}
68
69
/// Where a reference attestation sits in the host's transparency log
70
/// (spec §14.8): its entry number, the entry, and the inclusion proof
71
/// against the checkpoint served beside it.
72
#[derive(Clone, Debug, PartialEq, Eq)]
73
pub struct Logged {
74
    pub index: u64,
75
    pub entry: Vec<u8>,
76
    pub proof: Vec<[u8; 32]>,
77
}
78
79
/// A checkpoint witnesses cosigned that includes a logged entry (spec
80
/// §14.8, *Integrated time*): the cosigned note, and the entry's inclusion
81
/// proof against it.
82
#[derive(Clone, Debug, PartialEq, Eq)]
83
pub struct Integration {
84
    pub note: String,
85
    pub proof: Vec<[u8; 32]>,
86
}
87
88
/// A tag as a remote reports it (spec §10.1).
89
#[derive(Clone, Debug, PartialEq, Eq)]
90
pub struct TagRef {
91
    pub name: String,
92
    pub state: ObjectRef,
93
    pub heads: Vec<ChangeHash>,
94
    pub attestation: Option<SignedAttest>,
95
}
96
97
/// One reference as a remote reports it.
98
#[derive(Clone, Debug)]
99
pub struct RemoteRef {
100
    pub name: String,
101
    pub state: ObjectRef,
102
    pub heads: Vec<ChangeHash>,
103
    /// The latest attestation, only when it describes `state`. An unattested
104
    /// push (accepted while no trust policy exists) leaves it `None`.
105
    pub attestation: Option<SignedAttest>,
106
    /// Serial of the latest attestation ever recorded, stale or not, so the
107
    /// next attestation continues the sequence.
108
    pub last_serial: Option<u64>,
109
    /// The host's acceptance of `attestation` when a short-lived key signed
110
    /// it (spec §14.7): the time its certificate is checked at.
111
    pub accepted: Option<SignedAttest>,
112
    /// The attestation's place in the host's transparency log (key 6, only
113
    /// when it has one).
114
    pub logged: Option<Logged>,
115
    /// The cosigned checkpoints that first included `logged`'s entry (key
116
    /// 7, only when there are any): what its integrated time is read from.
117
    pub integration: Vec<Integration>,
118
}
119
120
/// Everything needed to add a set of changes to a repository.
121
#[derive(Clone, Debug, Default)]
122
pub struct Bundle {
123
    /// In dependency order, each with its individual signatures.
124
    pub changes: Vec<(Change, Vec<Signature>)>,
125
    /// Seals covering the changes.
126
    pub attests: Vec<SignedAttest>,
127
    /// Chunks, blobs, identities, and state objects referenced by the changes.
128
    pub objects: Vec<(ObjectType, Vec<u8>)>,
129
    /// Policies between the receiver's and the one sent with the push,
130
    /// ascending by serial (spec §14.5).
131
    pub policies: Vec<SignedPolicy>,
132
    /// Each change's hash, in the order of `changes`, when whoever made
133
    /// the bundle knows it: the store it came from, or the bytes it was
134
    /// decoded from. Never read from the wire. Empty when unknown.
135
    pub hashes: Vec<ChangeHash>,
136
    /// Changes as stored, with their signatures, in dependency order, for a
137
    /// fetch between repositories on one machine: their text blobs and
138
    /// chunks are among `objects`. Never on the wire.
139
    pub raw_changes: Vec<(Vec<u8>, Vec<Signature>)>,
140
    /// Certificates of short-lived keys that signed what the bundle carries
141
    /// (spec §14.7), their issuers' identities among `objects`.
142
    pub certificates: Vec<crate::cert::SignedCertificate>,
143
}
144
145
impl Bundle {
14627×
    pub fn is_empty(&self) -> bool {
14727×
        self.changes.is_empty() && self.attests.is_empty() && self.objects.is_empty()
14827×
    }
149
}
150
151
/// A requested bookmark move (spec §10.2, §16.3).
152
#[derive(Clone, Debug)]
153
pub struct RefUpdate {
154
    pub name: String,
155
    pub old_state: ObjectRef,
156
    pub new_state: ObjectRef,
157
    pub force: bool,
158
    pub attestation: Option<SignedAttest>,
159
}
160
161
#[derive(Clone, Debug, PartialEq, Eq)]
162
pub struct RefResult {
163
    pub name: String,
164
    pub ok: bool,
165
    pub reason: String,
166
}
167
168
pub trait Remote {
169
    fn repo_id(&self) -> Result<[u8; 16]>;
170
    fn refs(&self) -> Result<RefsResponse>;
171
    /// Changes in the closure of `want` but not of `have`, in dependency order.
172
    fn negotiate(&self, have: &[ChangeHash], want: &[ChangeHash]) -> Result<Vec<ChangeHash>>;
173
    /// The changes with their signatures, seals, identities, and blobs; blobs
174
    /// larger than `max_blob` bytes are left out for lazy fetching (spec §13.5).
175
    fn fetch(&self, changes: &[ChangeHash], max_blob: Option<u64>) -> Result<Bundle>;
176
    /// Individual objects by reference (spec §16.1 `objects`); a blob comes
177
    /// with its chunks.
178
    fn objects(&self, refs: &[ObjectRef]) -> Result<Vec<(ObjectType, Vec<u8>)>>;
179
    /// A checkpoint of exactly `heads` (spec §16.1 `checkpoint`): the
180
    /// checkpoint object, its payload blob, and the blob's chunks.
181
    fn checkpoint(&self, heads: &[ChangeHash]) -> Result<Bundle>;
182
    /// The changes within `depth` dependency steps of `heads` (spec §17).
183
    fn shallow(&self, heads: &[ChangeHash], depth: u32) -> Result<Vec<ChangeHash>>;
184
    /// Push changes, bookmark updates, new tags, and optionally a newer
185
    /// policy. The policy is applied first; a result named `policy` reports
186
    /// it, and each tag reports as `tags/<name>`.
187
    fn push(
188
        &self,
189
        bundle: Bundle,
190
        updates: Vec<RefUpdate>,
191
        policy: Option<SignedPolicy>,
192
        tags: Vec<TagRef>,
193
    ) -> Result<Vec<RefResult>>;
194
}
195
196
// ---------------------------------------------------------------- local
197
198
/// Another repository on this machine, served in-process.
199
pub struct LocalRemote {
200
    pub repo: Repo,
201
    /// The pushing repository's id, which binds an unbound target on the
202
    /// first push, as `Oxy-Repo-Id` does over HTTP.
203
    pub claimed_id: Option<[u8; 16]>,
204
}
205
206
impl LocalRemote {
2071082×
    pub fn open(path: &Path) -> Result<LocalRemote> {
208
        Ok(LocalRemote {
2091082×
            repo: Repo::open(path)?,
2101082×
            claimed_id: None,
211
        })
2121082×
    }
213
}
214
215
impl Remote for LocalRemote {
216850×
    fn repo_id(&self) -> Result<[u8; 16]> {
217850×
        self.repo.id()
218850×
    }
219848×
    fn refs(&self) -> Result<RefsResponse> {
220848×
        self.repo.remote_refs()
221848×
    }
222338×
    fn negotiate(&self, have: &[ChangeHash], want: &[ChangeHash]) -> Result<Vec<ChangeHash>> {
223338×
        self.repo.negotiate(have, want)
224338×
    }
225342×
    fn fetch(&self, changes: &[ChangeHash], max_blob: Option<u64>) -> Result<Bundle> {
226342×
        self.repo.bundle_raw_for(changes, max_blob)
227342×
    }
2283×
    fn objects(&self, refs: &[ObjectRef]) -> Result<Vec<(ObjectType, Vec<u8>)>> {
2293×
        self.repo.objects_for(refs)
2303×
    }
2311×
    fn checkpoint(&self, heads: &[ChangeHash]) -> Result<Bundle> {
2321×
        self.repo.checkpoint_bundle_for(heads)
2331×
    }
2343×
    fn shallow(&self, heads: &[ChangeHash], depth: u32) -> Result<Vec<ChangeHash>> {
2353×
        self.repo.shallow_changes(heads, depth)
2363×
    }
237256×
    fn push(
238256×
        &self,
239256×
        bundle: Bundle,
240256×
        updates: Vec<RefUpdate>,
241256×
        policy: Option<SignedPolicy>,
242256×
        tags: Vec<TagRef>,
243256×
    ) -> Result<Vec<RefResult>> {
244256×
        if self.repo.is_unbound() {
24513×
            match self.claimed_id {
24613×
                Some(id) => self.repo.bind_id(id)?,
247
                None => {
2480×
                    return Err(RepoError::Msg(
2490×
                        "the remote is unbound and this client did not say which repository it is"
2500×
                            .into(),
2510×
                    ))
252
                }
253
            }
254243×
        }
255256×
        self.repo.receive_push(bundle, updates, policy, tags)
256256×
    }
257
}
258
259
// ---------------------------------------------------------------- http
260
261
/// How to reach a remote: credentials and trust.
262
#[derive(Clone, Debug, Default)]
263
pub struct RemoteOptions {
264
    /// Bearer token for pushes.
265
    pub token: Option<String>,
266
    /// PEM file with extra root certificates to trust for `https://` remotes
267
    /// (self-hosted servers); the system web roots are always trusted.
268
    pub ca: Option<PathBuf>,
269
    /// The local repository's id, sent as `Oxy-Repo-Id` so an unbound
270
    /// hosted repository can adopt it on the first push (spec §16.1).
271
    pub repo_id: Option<[u8; 16]>,
272
    /// Where a remote kept on a store (`dir://`, `s3://`, …) keeps its
273
    /// mirror and what it has seen: the remote's directory under
274
    /// `.oxy/remotes`. None (a clone, before there is a repository) means
275
    /// a temporary directory.
276
    pub cache_dir: Option<PathBuf>,
277
    /// Other tokens for the same hub, tried in turn when `token` is
278
    /// refused (401, 403 or 404): those of enclosing checkouts, when
279
    /// `token` came from the credential store rather than from this
280
    /// remote's own configuration (oxygen#112).
281
    pub fallback_tokens: Vec<String>,
282
}
283
284
/// Opens a store for a URL it understands, or passes (`None`). Stores that
285
/// need more than the standard library (the cloud ones) are added by the
286
/// program that links them, with [`register_store_opener`].
287
pub type StoreOpener =
288
    fn(&str, &RemoteOptions) -> Option<crate::strata::Result<Box<dyn crate::strata::Store>>>;
289
290
static STORE_OPENERS: Mutex<Vec<StoreOpener>> = Mutex::new(Vec::new());
291
292155×
pub fn register_store_opener(opener: StoreOpener) {
293155×
    STORE_OPENERS
294155×
        .lock()
295155×
        .unwrap_or_else(|p| p.into_inner())
296155×
        .push(opener);
297155×
}
298
299
/// A store for `url`, from `dir://` or any registered opener.
3001141×
pub fn open_store(
3011141×
    url: &str,
3021141×
    options: &RemoteOptions,
3031141×
) -> Option<crate::strata::Result<Box<dyn crate::strata::Store>>> {
3041141×
    if let Some(path) = url.strip_prefix("dir://") {
305
        return Some(
30659×
            crate::strata::LocalStore::open(path)
30759×
                .map(|s| Box::new(s) as Box<dyn crate::strata::Store>),
308
        );
3091082×
    }
3101082×
    let openers = STORE_OPENERS.lock().unwrap_or_else(|p| p.into_inner());
3111082×
    openers.iter().find_map(|open| open(url, options))
3121141×
}
313
314
/// The request header carrying the client's repository id.
315
pub const REPO_ID_HEADER: &str = "Oxy-Repo-Id";
316
317
/// The id of a hosted repository that has not adopted one yet.
318
pub const UNBOUND_ID: [u8; 16] = [0; 16];
319
320
/// A remote served by `oxy-server` at `<base>/oxy/v1/...`.
321
pub struct HttpRemote {
322
    base: String,
323
    /// The token in use, and those still to try when it is refused.
324
    token: Mutex<Option<String>>,
325
    fallbacks: Mutex<Vec<String>>,
326
    repo_id: Option<[u8; 16]>,
327
    agent: ureq::Agent,
328
}
329
330
/// A TLS client configuration trusting the web roots plus `ca`, if given:
331
/// the trust every oxy connection uses, shared with tools that call hub APIs.
332159×
pub fn tls_client_config(ca: Option<&Path>) -> Result<Arc<rustls::ClientConfig>> {
333159×
    let mut roots = rustls::RootCertStore::empty();
334159×
    roots.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
335159×
    if let Some(path) = ca {
33655×
        let pem = std::fs::read(path)
33755×
            .map_err(|e| RepoError::Msg(format!("reading CA file {}: {e}", path.display())))?;
33855×
        let certs = rustls_pemfile::certs(&mut pem.as_slice())
33955×
            .collect::<std::result::Result<Vec<_>, _>>()
34055×
            .map_err(|e| RepoError::Msg(format!("parsing CA file {}: {e}", path.display())))?;
34155×
        if certs.is_empty() {
3420×
            return Err(RepoError::Msg(format!(
3430×
                "CA file {} holds no certificates",
3440×
                path.display()
3450×
            )));
34655×
        }
34755×
        for c in certs {
34855×
            roots
34955×
                .add(c)
35055×
                .map_err(|e| RepoError::Msg(format!("CA file {}: {e}", path.display())))?;
351
        }
352104×
    }
353159×
    let cfg = rustls::ClientConfig::builder_with_provider(Arc::new(
354159×
        rustls::crypto::ring::default_provider(),
355
    ))
356159×
    .with_safe_default_protocol_versions()
357159×
    .map_err(|e| RepoError::Msg(e.to_string()))?
358159×
    .with_root_certificates(roots)
359159×
    .with_no_client_auth();
360159×
    Ok(Arc::new(cfg))
361159×
}
362
363
impl HttpRemote {
364155×
    pub fn new(base: &str, options: &RemoteOptions) -> Result<HttpRemote> {
365155×
        refuse_plain_token(base, options)?;
366155×
        let agent = ureq::AgentBuilder::new()
367155×
            .tls_config(tls_client_config(options.ca.as_deref())?)
368155×
            .build();
369155×
        Ok(HttpRemote {
370155×
            base: base.trim_end_matches('/').to_string(),
371155×
            token: Mutex::new(options.token.clone()),
372155×
            fallbacks: Mutex::new(options.fallback_tokens.iter().rev().cloned().collect()),
373155×
            repo_id: options.repo_id,
374155×
            agent,
375155×
        })
376155×
    }
377
378
    /// A request, tried again with the next fallback token while the
379
    /// hub refuses the one in use (oxygen#112).
380397×
    fn call(&self, post: bool, endpoint: &str, body: Option<&[u8]>) -> Result<Vec<u8>> {
381
        loop {
382398×
            let token = self.token.lock().unwrap_or_else(|p| p.into_inner()).clone();
383398×
            match self.call_once(post, endpoint, body, token.as_deref()) {
38412×
                Err(RepoError::Msg(m)) if token.is_some() && refused(&m) => {
3853×
                    let next = self
3863×
                        .fallbacks
3873×
                        .lock()
3883×
                        .unwrap_or_else(|p| p.into_inner())
3893×
                        .pop();
3903×
                    let Some(next) = next else {
3912×
                        return Err(RepoError::Msg(m));
392
                    };
3931×
                    crate::credentials::warn_once(&format!(
3941×
                        "{}: the stored token was refused; using the one an enclosing checkout has for this hub",
3951×
                        self.base
3961×
                    ));
3971×
                    *self.token.lock().unwrap_or_else(|p| p.into_inner()) = Some(next);
398
                }
399395×
                other => return other,
400
            }
401
        }
402397×
    }
403
404398×
    fn call_once(
405398×
        &self,
406398×
        post: bool,
407398×
        endpoint: &str,
408398×
        body: Option<&[u8]>,
409398×
        token: Option<&str>,
410398×
    ) -> Result<Vec<u8>> {
411398×
        let url = format!("{}/oxy/v1/{endpoint}", self.base);
412398×
        let mut req = if post {
413139×
            self.agent.post(&url)
414
        } else {
415259×
            self.agent.get(&url)
416
        };
417398×
        req = req.set("Accept", CONTENT_TYPE);
418398×
        if let Some(t) = token {
41922×
            req = req.set("Authorization", &format!("Bearer {t}"));
420376×
        }
421398×
        if let Some(id) = &self.repo_id {
422373×
            req = req.set(REPO_ID_HEADER, &hex::encode(id));
423373×
        }
424398×
        let resp = match body {
425139×
            Some(b) => req.set("Content-Type", CONTENT_TYPE).send_bytes(b),
426259×
            None => req.call(),
427
        };
42812×
        match resp {
429386×
            Ok(r) => {
430386×
                let mut out = Vec::new();
431386×
                r.into_reader()
432386×
                    .read_to_end(&mut out)
433386×
                    .map_err(|e| RepoError::Msg(format!("{url}: {e}")))?;
434386×
                Ok(out)
435
            }
4369×
            Err(ureq::Error::Status(code, r)) => {
4379×
                let text = r.into_string().unwrap_or_default();
438
                // The hint comes from the status alone: the server's text
439
                // (a host's reason for refusing a push, several lines
440
                // perhaps) is shown as it is, never read for hints.
4419×
                let status = format!("{url}: HTTP {code}");
4429×
                let msg = format!("{status}: {}", text.trim());
4439×
                Err(RepoError::Msg(match hint_for(&status) {
4448×
                    Some(h) => format!("{msg}\n  hint: {h}"),
4451×
                    None => msg,
446
                }))
447
            }
448
            // The transport error already names the URL.
4493×
            Err(e) => Err(RepoError::Msg(with_hint(e.to_string()))),
450
        }
451398×
    }
452
}
453
454
/// Whether a failed request's message says the hub refused its token:
455
/// HTTP 401, 403, or 404 (a hub hides a private repository from a token
456
/// that may not read it).
4574×
fn refused(message: &str) -> bool {
4584×
    [": HTTP 401", ": HTTP 403", ": HTTP 404"]
4594×
        .iter()
4606×
        .any(|c| message.contains(c))
4614×
}
462
463
/// Refuse to send a token where anyone on the way could read it: plain
464
/// `http` to another machine (see [`crate::credentials::token_allowed`]).
465155×
fn refuse_plain_token(url: &str, options: &RemoteOptions) -> Result<()> {
466155×
    if options.token.is_some() && !crate::credentials::token_allowed(url) {
4670×
        return Err(RepoError::Msg(format!(
4680×
            "{url}: refusing to send a token over plain http; use https"
4690×
        )));
470155×
    }
471155×
    Ok(())
472155×
}
473
474
/// What to do about a failed request, recognised from its message.
47520×
pub fn hint_for(message: &str) -> Option<&'static str> {
47620×
    let m = message.to_ascii_lowercase();
47720×
    let hint = if m.contains("http 401") {
4786×
        "the hub needs you signed in, or did not accept the token: run `oxy auth login HUB` (pushing needs repo:write)"
47914×
    } else if m.contains("http 403") {
4801×
        "the token or account lacks permission: pushing needs a token with repo:write and write access to the repository"
48113×
    } else if m.contains("http 404") {
4824×
        "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`)"
4839×
    } else if m.contains("unknownissuer")
4847×
        || m.contains("unknown issuer")
4857×
        || m.contains("certificate")
4866×
        || m.contains("invalidcertificate")
487
    {
4883×
        "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`"
4896×
    } else if m.contains("connection refused") {
4903×
        "nothing is listening there: check the URL and port, and that the server is running"
4913×
    } else if m.contains("dns")
4922×
        || m.contains("failed to lookup")
4932×
        || m.contains("name or service not known")
494
    {
4951×
        "the host name does not resolve: check the URL"
4962×
    } else if m.contains("timed out") || m.contains("timeout") {
4970×
        "the server did not answer in time: check the network, or try again"
498
    } else {
4992×
        return None;
500
    };
50118×
    Some(hint)
50220×
}
503
504
/// `message`, followed by what to do about it when that is known.
5053×
pub fn with_hint(message: String) -> String {
5063×
    match hint_for(&message) {
5073×
        Some(h) => format!("{message}\n  hint: {h}"),
5080×
        None => message,
509
    }
5103×
}
511
512
/// A JSON request to a hub API (`GET`, `POST` or `DELETE`), with the same
513
/// TLS trust and token rules as remotes. Returns the status and body, an
514
/// error status included; only transport failures are errors.
5150×
pub fn http_json(
5160×
    method: &str,
5170×
    url: &str,
5180×
    body: Option<&str>,
5190×
    options: &RemoteOptions,
5200×
) -> Result<(u16, String)> {
5210×
    refuse_plain_token(url, options)?;
5220×
    let agent = ureq::AgentBuilder::new()
5230×
        .tls_config(tls_client_config(options.ca.as_deref())?)
5240×
        .timeout(std::time::Duration::from_secs(60))
5250×
        .build();
5260×
    let mut req = agent.request(method, url).set("Accept", "application/json");
5270×
    if let Some(t) = &options.token {
5280×
        req = req.set("Authorization", &format!("Bearer {t}"));
5290×
    }
5300×
    let resp = match body {
5310×
        Some(b) => req.set("Content-Type", "application/json").send_string(b),
5320×
        None => req.call(),
533
    };
5340×
    match resp {
5350×
        Ok(r) => {
5360×
            let code = r.status();
5370×
            Ok((code, r.into_string().unwrap_or_default()))
538
        }
5390×
        Err(ureq::Error::Status(code, r)) => Ok((code, r.into_string().unwrap_or_default())),
5400×
        Err(e) => Err(RepoError::Msg(with_hint(e.to_string()))),
541
    }
5420×
}
543
544
/// An authenticated GET of any URL on a host, with the same TLS trust and
545
/// token as remotes use (for hub APIs: proposals). Returns the body.
5460×
pub fn http_get(url: &str, options: &RemoteOptions) -> Result<Vec<u8>> {
5470×
    refuse_plain_token(url, options)?;
5480×
    let agent = ureq::AgentBuilder::new()
5490×
        .tls_config(tls_client_config(options.ca.as_deref())?)
5500×
        .build();
5510×
    let mut req = agent.get(url).set("Accept", "application/json");
5520×
    if let Some(t) = &options.token {
5530×
        req = req.set("Authorization", &format!("Bearer {t}"));
5540×
    }
5550×
    match req.call() {
5560×
        Ok(r) => {
5570×
            let mut out = Vec::new();
5580×
            r.into_reader()
5590×
                .read_to_end(&mut out)
5600×
                .map_err(|e| RepoError::Msg(format!("{url}: {e}")))?;
5610×
            Ok(out)
562
        }
5630×
        Err(ureq::Error::Status(code, r)) => {
5640×
            let text = r.into_string().unwrap_or_default();
5650×
            Err(RepoError::Msg(with_hint(format!(
5660×
                "{url}: HTTP {code}: {}",
5670×
                text.trim()
5680×
            ))))
569
        }
570
        // The transport error already names the URL.
5710×
        Err(e) => Err(RepoError::Msg(with_hint(e.to_string()))),
572
    }
5730×
}
574
575
impl Remote for HttpRemote {
576134×
    fn repo_id(&self) -> Result<[u8; 16]> {
577134×
        wire::decode_capabilities(&self.call(false, "capabilities", None)?)
578134×
    }
579125×
    fn refs(&self) -> Result<RefsResponse> {
580125×
        Ok(wire::decode_refs(&self.call(false, "refs", None)?)?.1)
581125×
    }
58249×
    fn negotiate(&self, have: &[ChangeHash], want: &[ChangeHash]) -> Result<Vec<ChangeHash>> {
58349×
        wire::decode_hashes(&self.call(
584
            true,
58549×
            "negotiate",
58649×
            Some(&wire::encode_negotiate(have, want)),
5870×
        )?)
58849×
    }
58949×
    fn fetch(&self, changes: &[ChangeHash], max_blob: Option<u64>) -> Result<Bundle> {
59049×
        wire::decode_bundle(&self.call(
591
            true,
59249×
            "fetch",
59349×
            Some(&wire::encode_fetch(changes, max_blob)),
5940×
        )?)
59549×
    }
5961×
    fn objects(&self, refs: &[ObjectRef]) -> Result<Vec<(ObjectType, Vec<u8>)>> {
597
        Ok(
5981×
            wire::decode_bundle(&self.call(true, "objects", Some(&wire::encode_hashes(refs)))?)?
599
                .objects,
600
        )
6011×
    }
6020×
    fn checkpoint(&self, heads: &[ChangeHash]) -> Result<Bundle> {
6030×
        wire::decode_bundle(&self.call(true, "checkpoint", Some(&wire::encode_hashes(heads)))?)
6040×
    }
6050×
    fn shallow(&self, heads: &[ChangeHash], depth: u32) -> Result<Vec<ChangeHash>> {
6060×
        wire::decode_hashes(&self.call(
607
            true,
6080×
            "shallow",
6090×
            Some(&wire::encode_shallow(heads, depth)),
6100×
        )?)
6110×
    }
61239×
    fn push(
61339×
        &self,
61439×
        bundle: Bundle,
61539×
        updates: Vec<RefUpdate>,
61639×
        policy: Option<SignedPolicy>,
61739×
        tags: Vec<TagRef>,
61839×
    ) -> Result<Vec<RefResult>> {
61939×
        wire::decode_push_response(&self.call(
620
            true,
62139×
            "push",
62239×
            Some(&wire::encode_push(
62339×
                &bundle,
62439×
                &updates,
62539×
                policy.as_ref(),
62639×
                &tags,
62739×
            )),
6285×
        )?)
62939×
    }
630
}
631
632
/// A remote's URL as it is stored: an `http(s)://` URL as given, a local
633
/// path made absolute (with its `file://` kept), so it still names the same
634
/// repository from inside the clone (oxygen#57).
635263×
pub fn stored_url(url: &str) -> String {
636
    // Only a path is made absolute: a plain one, or one behind file:// or
637
    // dir://. Every other URL (a hub, a bucket) is kept as written.
638263×
    let (prefix, path) = match (url.strip_prefix("file://"), url.strip_prefix("dir://")) {
6391×
        (Some(p), _) => ("file://", p),
64011×
        (_, Some(p)) => ("dir://", p),
641251×
        _ if url.contains("://") => return url.to_string(),
642228×
        _ => ("", url),
643
    };
644240×
    match std::path::absolute(path) {
645240×
        Ok(abs) => format!("{prefix}{}", abs.display()),
6460×
        Err(_) => url.to_string(),
647
    }
648263×
}
649
650
/// Open a remote by URL: a local path (optionally `file://`), `http(s)://`
651
/// (a hub), or a store (`dir://`, and whatever openers are registered).
6521284×
pub fn open_remote(url: &str, options: &RemoteOptions) -> Result<Box<dyn Remote>> {
6531284×
    if url.starts_with("http://") || url.starts_with("https://") {
654155×
        return Ok(Box::new(HttpRemote::new(url, options)?));
6551129×
    }
6561129×
    if let Some(store) = open_store(url, options) {
65748×
        return crate::repo::strata::open_store_remote(store?, options);
6581081×
    }
6591081×
    let path = url.strip_prefix("file://").unwrap_or(url);
6601081×
    if path.contains("://") {
6610×
        return Err(RepoError::Msg(format!("unsupported remote URL {url:?}")));
6621081×
    }
6631081×
    let mut local = LocalRemote::open(Path::new(path))?;
6641081×
    local.claimed_id = options.repo_id;
6651081×
    Ok(Box::new(local))
6661284×
}
667
668
// ---------------------------------------------------------------- wire
669
670
/// CBOR encodings of the protocol messages (spec §16.1).
671
pub mod wire {
672
    use super::*;
673
6740×
    fn schema(msg: &str) -> RepoError {
6750×
        RepoError::Object(ObjectError::Schema(msg.into()))
6760×
    }
677155×
    fn sigs_value(sigs: &[Signature]) -> Value {
678155×
        Value::Array(sigs.iter().map(|s| s.to_value()).collect())
679155×
    }
680150×
    fn sigs_from(v: &Value) -> Result<Vec<Signature>> {
681150×
        Ok(o::array(v, "signatures")?
682150×
            .iter()
683150×
            .map(Signature::from_value)
684150×
            .collect::<std::result::Result<Vec<_>, _>>()?)
685150×
    }
686371×
    fn hashes_value(hs: &[ObjectRef]) -> Value {
687534×
        Value::Array(hs.iter().map(|h| Value::Bytes(h.0.to_vec())).collect())
688371×
    }
689430×
    fn hashes_from(v: &Value) -> Result<Vec<ObjectRef>> {
690430×
        Ok(o::array(v, "hashes")?
691430×
            .iter()
692594×
            .map(|h| o::oref(h, "hash"))
693430×
            .collect::<std::result::Result<Vec<_>, _>>()?)
694430×
    }
69525×
    fn attest_value(sa: &SignedAttest) -> Value {
69625×
        Value::Array(vec![Value::Bytes(sa.attest.encode()), sigs_value(&sa.sigs)])
69725×
    }
69839×
    fn attest_from(v: &Value) -> Result<SignedAttest> {
69939×
        let a = o::array(v, "signed attest")?;
70039×
        if a.len() != 2 {
7010×
            return Err(schema("signed attest: expected [attest, sigs]"));
70239×
        }
703
        Ok(SignedAttest {
70439×
            attest: Attest::decode(o::bytes(&a[0], "attest")?)?,
70539×
            sigs: sigs_from(&a[1])?,
706
        })
70739×
    }
708207×
    fn opt_attest_value(sa: &Option<SignedAttest>) -> Value {
709207×
        sa.as_ref().map(attest_value).unwrap_or(Value::Null)
710207×
    }
711262×
    fn opt_attest_from(v: &Value) -> Result<Option<SignedAttest>> {
712262×
        if v.is_null() {
713234×
            Ok(None)
714
        } else {
71528×
            attest_from(v).map(Some)
716
        }
717262×
    }
718
    /// `[policy bytes, [signature]]`: also the format of a policy proposal
719
    /// file exchanged between root holders (spec §14.5).
72012×
    pub fn policy_value(sp: &SignedPolicy) -> Value {
72112×
        Value::Array(vec![Value::Bytes(sp.policy.encode()), sigs_value(&sp.sigs)])
72212×
    }
72310×
    pub fn policy_from(v: &Value) -> Result<SignedPolicy> {
72410×
        let a = o::array(v, "signed policy")?;
72510×
        if a.len() != 2 {
7260×
            return Err(schema("signed policy: expected [policy, sigs]"));
72710×
        }
728
        Ok(SignedPolicy {
72910×
            policy: Policy::decode(o::bytes(&a[0], "policy")?)?,
73010×
            sigs: sigs_from(&a[1])?,
731
        })
73210×
    }
733194×
    fn opt_policy_value(sp: Option<&SignedPolicy>) -> Value {
734194×
        sp.map(policy_value).unwrap_or(Value::Null)
735194×
    }
736233×
    fn opt_policy_from(v: &Value) -> Result<Option<SignedPolicy>> {
737233×
        if v.is_null() {
738229×
            Ok(None)
739
        } else {
7404×
            policy_from(v).map(Some)
741
        }
742233×
    }
743964×
    fn map<'a>(v: &'a Value, what: &str) -> Result<&'a o::Map> {
744964×
        Ok(o::map(v, what)?)
745964×
    }
7462703×
    fn field<'a>(m: &'a o::Map, k: u64, what: &str) -> Result<&'a Value> {
7472703×
        Ok(o::field(m, k, what)?)
7482703×
    }
749
750
    /// A bundle's value. Each change's text blobs and their chunks (spec
751
    /// §6.1) are added to its objects when they are not already there, so a
752
    /// bundle can always be read on its own.
753125×
    pub fn bundle_value(b: &Bundle) -> Value {
754125×
        let mut changes = Vec::with_capacity(b.raw_changes.len() + b.changes.len());
755
        // Changes as stored are already their encoding, their texts among
756
        // the objects.
757125×
        for (bytes, s) in &b.raw_changes {
7580×
            changes.push(Value::Array(vec![
7590×
                Value::Bytes(bytes.clone()),
7600×
                sigs_value(s),
7610×
            ]));
7620×
        }
763125×
        let mut texts: Vec<(ObjectType, Vec<u8>)> = Vec::new();
764125×
        let mut listed: Option<std::collections::HashSet<ObjectRef>> = None;
765125×
        for (c, s) in &b.changes {
766118×
            let (bytes, stored) = c.encode_parts();
767118×
            for t in stored {
7680×
                let listed = listed.get_or_insert_with(|| {
7690×
                    b.objects
7700×
                        .iter()
7710×
                        .map(|(ty, body)| crate::hash::hash_object(*ty, body))
7720×
                        .collect()
7730×
                });
7740×
                if !listed.insert(t.blob.hash()) {
7750×
                    continue;
7760×
                }
7770×
                for chunk in crate::chunk::chunks(&t.content) {
7780×
                    if listed.insert(crate::hash::hash_object(ObjectType::Chunk, chunk)) {
7790×
                        texts.push((ObjectType::Chunk, chunk.to_vec()));
7800×
                    }
781
                }
7820×
                texts.push((ObjectType::Blob, t.blob.encode()));
783
            }
784118×
            changes.push(Value::Array(vec![Value::Bytes(bytes), sigs_value(s)]));
785
        }
786125×
        let mut v = Value::map([
787125×
            (0, Value::Array(changes)),
788125×
            (
789125×
                1,
790125×
                Value::Array(b.attests.iter().map(attest_value).collect()),
791125×
            ),
792
            (
793
                2,
794
                Value::Array(
795125×
                    b.objects
796125×
                        .iter()
797125×
                        .chain(&texts)
798125×
                        .map(|(t, body)| {
79994×
                            Value::Array(vec![
80094×
                                Value::Text(t.name().into()),
80194×
                                Value::Bytes(body.clone()),
80294×
                            ])
80394×
                        })
804125×
                        .collect(),
805
                ),
806
            ),
807125×
            (
808125×
                3,
809125×
                Value::Array(b.policies.iter().map(policy_value).collect()),
810125×
            ),
811
        ]);
812
        // Only when there are any; older peers ignore the field.
813125×
        if !b.certificates.is_empty() {
8141×
            if let Value::Map(m) = &mut v {
8151×
                m.insert(
816
                    4,
817
                    Value::Array(
8181×
                        b.certificates
8191×
                            .iter()
8201×
                            .map(|c| Value::Bytes(c.encode()))
8211×
                            .collect(),
822
                    ),
823
                );
8240×
            }
825124×
        }
826125×
        v
827125×
    }
828
829115×
    pub fn bundle_from_value(v: &Value) -> Result<Bundle> {
830115×
        let m = map(v, "bundle")?;
831115×
        let mut b = Bundle::default();
832115×
        for ob in o::array(field(m, 2, "objects")?, "objects")? {
83383×
            let pair = o::array(ob, "object")?;
83483×
            if pair.len() != 2 {
8350×
                return Err(schema("object: expected [type, body]"));
83683×
            }
83783×
            let ty = ObjectType::from_name(o::text(&pair[0], "object type")?)
83883×
                .ok_or_else(|| schema("unknown object type"))?;
83983×
            b.objects
84083×
                .push((ty, o::bytes(&pair[1], "object body")?.to_vec()));
841
        }
842
        // Stored inserts are read from the bundle's own objects.
843115×
        let mut by_ref: Option<std::collections::HashMap<ObjectRef, usize>> = None;
844115×
        for c in o::array(field(m, 0, "changes")?, "changes")? {
845101×
            let pair = o::array(c, "change entry")?;
846101×
            if pair.len() != 2 {
8470×
                return Err(schema("change entry: expected [change, sigs]"));
848101×
            }
849101×
            let encoded = o::bytes(&pair[0], "change")?;
850101×
            b.hashes
851101×
                .push(crate::hash::hash_object(ObjectType::Change, encoded));
852101×
            let change = Change::decode_with(encoded, &mut |text, count, form| {
8530×
                let by_ref = by_ref.get_or_insert_with(|| {
8540×
                    b.objects
8550×
                        .iter()
8560×
                        .enumerate()
8570×
                        .map(|(i, (ty, body))| (crate::hash::hash_object(*ty, body), i))
8580×
                        .collect()
8590×
                });
8600×
                let get =
8610×
                    |r: &ObjectRef, want: ObjectType| match by_ref.get(r).map(|i| &b.objects[*i]) {
8620×
                        Some((ty, body)) if *ty == want => Ok(body),
8630×
                        _ => Err(ObjectError::Schema(format!(
8640×
                            "the bundle lacks {} {}",
8650×
                            want.name(),
8660×
                            r.short(12)
8670×
                        ))),
8680×
                    };
8690×
                let blob = crate::objects::Blob::decode(get(text, ObjectType::Blob)?)?;
8700×
                let mut content = Vec::with_capacity(blob.length as usize);
8710×
                for chunk in &blob.chunks {
8720×
                    content.extend_from_slice(get(chunk, ObjectType::Chunk)?);
873
                }
8740×
                crate::objects::text_lines(&content, count, form)
8750×
            })?;
876101×
            b.changes.push((change, sigs_from(&pair[1])?));
877
        }
878115×
        for a in o::array(field(m, 1, "attests")?, "attests")? {
87911×
            b.attests.push(attest_from(a)?);
880
        }
881115×
        if let Some(ps) = m.get(&3) {
882115×
            for p in o::array(ps, "policies")? {
8833×
                b.policies.push(policy_from(p)?);
884
            }
8850×
        }
886115×
        if let Some(cs) = m.get(&4) {
8871×
            for c in o::array(cs, "certificates")? {
8881×
                b.certificates.push(
8891×
                    crate::cert::SignedCertificate::decode(o::bytes(c, "certificate")?)
8901×
                        .map_err(|e| schema(&format!("certificate: {e}")))?,
891
                );
892
            }
893114×
        }
894115×
        Ok(b)
895115×
    }
896
89785×
    pub fn encode_bundle(b: &Bundle) -> Vec<u8> {
89885×
        cbor::encode(&bundle_value(b))
89985×
    }
90079×
    pub fn decode_bundle(bytes: &[u8]) -> Result<Bundle> {
90179×
        bundle_from_value(&cbor::decode(bytes).map_err(ObjectError::from)?)
90279×
    }
903
904129×
    pub fn encode_capabilities(id: [u8; 16]) -> Vec<u8> {
905129×
        cbor::encode(&Value::map([
906129×
            (0, Value::Array(vec![Value::Uint(PROTOCOL_VERSION)])),
907129×
            (1, Value::Bytes(id.to_vec())),
908129×
            (2, Value::Array(vec![Value::Text("seal".into())])),
909129×
        ]))
910129×
    }
911129×
    pub fn decode_capabilities(bytes: &[u8]) -> Result<[u8; 16]> {
912129×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
913129×
        let m = map(&v, "capabilities")?;
914129×
        let versions = o::array(field(m, 0, "versions")?, "versions")?;
915129×
        if !versions
916129×
            .iter()
917129×
            .any(|x| x.as_uint() == Some(PROTOCOL_VERSION))
918
        {
9190×
            return Err(RepoError::Msg(
9200×
                "remote does not speak protocol version 1".into(),
9210×
            ));
922129×
        }
923129×
        o::bytes(field(m, 1, "repo id")?, "repo id")?
924129×
            .try_into()
925129×
            .map_err(|_| schema("repo id: expected 16 bytes"))
926129×
    }
927
928194×
    fn tags_value(tags: &[TagRef]) -> Value {
929
        Value::Array(
930194×
            tags.iter()
931194×
                .map(|t| {
9328×
                    Value::map([
9338×
                        (0, Value::Text(t.name.clone())),
9348×
                        (1, Value::Bytes(t.state.0.to_vec())),
9358×
                        (2, hashes_value(&t.heads)),
9368×
                        (3, opt_attest_value(&t.attestation)),
9378×
                    ])
9388×
                })
939194×
                .collect(),
940
        )
941194×
    }
942233×
    fn tags_from(v: &Value) -> Result<Vec<TagRef>> {
943233×
        let mut out = Vec::new();
944233×
        for t in o::array(v, "tags")? {
94524×
            let tm = map(t, "tag")?;
94624×
            out.push(TagRef {
94724×
                name: o::text(field(tm, 0, "name")?, "name")?.to_owned(),
94824×
                state: o::oref(field(tm, 1, "state")?, "state")?,
94924×
                heads: hashes_from(field(tm, 2, "heads")?)?,
95024×
                attestation: opt_attest_from(field(tm, 3, "attestation")?)?,
951
            });
952
        }
953233×
        Ok(out)
954233×
    }
955
956154×
    pub fn encode_refs(id: [u8; 16], resp: &RefsResponse) -> Vec<u8> {
957154×
        let mut v = Value::map([
958
            (
959
                0,
960
                Value::Array(
961154×
                    resp.refs
962154×
                        .iter()
963159×
                        .map(|r| {
964159×
                            let mut v = Value::map([
965159×
                                (0, Value::Text(r.name.clone())),
966159×
                                (1, Value::Bytes(r.state.0.to_vec())),
967159×
                                (2, hashes_value(&r.heads)),
968159×
                                (3, opt_attest_value(&r.attestation)),
969159×
                                (4, r.last_serial.map(Value::Uint).unwrap_or(Value::Null)),
970159×
                            ]);
971
                            // Only when there is one; older peers ignore it.
972159×
                            if let Value::Map(m) = &mut v {
973159×
                                if r.accepted.is_some() {
9740×
                                    m.insert(5, opt_attest_value(&r.accepted));
975159×
                                }
976159×
                                if let Some(l) = &r.logged {
9771×
                                    m.insert(
9781×
                                        6,
9791×
                                        Value::Array(vec![
9801×
                                            Value::Uint(l.index),
9811×
                                            Value::Bytes(l.entry.clone()),
9821×
                                            proof_value(&l.proof),
9831×
                                        ]),
9841×
                                    );
985158×
                                }
986159×
                                if !r.integration.is_empty() {
9871×
                                    m.insert(
988
                                        7,
989
                                        Value::Array(
9901×
                                            r.integration
9911×
                                                .iter()
9921×
                                                .map(|i| {
9931×
                                                    Value::Array(vec![
9941×
                                                        Value::Text(i.note.clone()),
9951×
                                                        proof_value(&i.proof),
9961×
                                                    ])
9971×
                                                })
9981×
                                                .collect(),
999
                                        ),
1000
                                    );
1001158×
                                }
10020×
                            }
1003159×
                            v
1004159×
                        })
1005154×
                        .collect(),
1006
                ),
1007
            ),
1008154×
            (1, Value::Bytes(id.to_vec())),
1009154×
            (2, opt_policy_value(resp.policy.as_ref())),
1010154×
            (3, tags_value(&resp.tags)),
1011154×
            (
1012154×
                4,
1013154×
                Value::Array(resp.history.iter().map(policy_value).collect()),
1014154×
            ),
1015154×
            (
1016154×
                5,
1017154×
                resp.default_bookmark
1018154×
                    .clone()
1019154×
                    .map(Value::Text)
1020154×
                    .unwrap_or(Value::Null),
1021154×
            ),
1022
        ]);
1023154×
        if let Value::Map(m) = &mut v {
1024154×
            if let Some(log) = &resp.log {
10252×
                m.insert(6, Value::Text(log.clone()));
1026152×
            }
1027154×
            if !resp.witnesses.is_empty() {
10281×
                m.insert(
1029
                    7,
1030
                    Value::Array(
10311×
                        resp.witnesses
10321×
                            .iter()
10331×
                            .map(|(name, id)| {
10341×
                                Value::Array(vec![
10351×
                                    Value::Text(name.clone()),
10361×
                                    Value::Bytes(id.clone()),
10371×
                                ])
10381×
                            })
10391×
                            .collect(),
1040
                    ),
1041
                );
1042153×
            }
10430×
        }
1044154×
        cbor::encode(&v)
1045154×
    }
1046197×
    pub fn decode_refs(bytes: &[u8]) -> Result<([u8; 16], RefsResponse)> {
1047197×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
1048197×
        let m = map(&v, "refs")?;
1049197×
        let id: [u8; 16] = o::bytes(field(m, 1, "repo id")?, "repo id")?
1050197×
            .try_into()
1051197×
            .map_err(|_| schema("repo id: expected 16 bytes"))?;
1052197×
        let mut refs = Vec::new();
1053202×
        for r in o::array(field(m, 0, "refs")?, "refs")? {
1054202×
            let rm = map(r, "ref")?;
1055202×
            let ls = field(rm, 4, "last serial")?;
1056202×
            refs.push(RemoteRef {
1057202×
                name: o::text(field(rm, 0, "name")?, "name")?.to_owned(),
1058202×
                state: o::oref(field(rm, 1, "state")?, "state")?,
1059202×
                heads: hashes_from(field(rm, 2, "heads")?)?,
1060202×
                attestation: opt_attest_from(field(rm, 3, "attestation")?)?,
1061202×
                last_serial: if ls.is_null() {
1062185×
                    None
1063
                } else {
106417×
                    Some(o::uint(ls, "last serial")?)
1065
                },
1066202×
                accepted: match rm.get(&5) {
10670×
                    Some(a) => opt_attest_from(a)?,
1068202×
                    None => None,
1069
                },
1070202×
                logged: match rm.get(&6) {
10711×
                    Some(l) => {
10721×
                        let a = o::array(l, "logged")?;
10731×
                        if a.len() != 3 {
10740×
                            return Err(schema("logged: expected [index, entry, proof]"));
10751×
                        }
1076
                        Some(Logged {
10771×
                            index: o::uint(&a[0], "index")?,
10781×
                            entry: o::bytes(&a[1], "entry")?.to_vec(),
10791×
                            proof: proof_from(&a[2])?,
1080
                        })
1081
                    }
1082201×
                    None => None,
1083
                },
1084202×
                integration: match rm.get(&7) {
10851×
                    Some(l) => {
10861×
                        let mut out = Vec::new();
10871×
                        for i in o::array(l, "integration")? {
10881×
                            let a = o::array(i, "integration")?;
10891×
                            if a.len() != 2 {
10900×
                                return Err(schema("integration: expected [note, proof]"));
10911×
                            }
10921×
                            out.push(Integration {
10931×
                                note: o::text(&a[0], "note")?.to_owned(),
10941×
                                proof: proof_from(&a[1])?,
1095
                            });
1096
                        }
10971×
                        out
1098
                    }
1099201×
                    None => Vec::new(),
1100
                },
1101
            });
1102
        }
1103197×
        let policy = match m.get(&2) {
1104197×
            Some(p) => opt_policy_from(p)?,
11050×
            None => None,
1106
        };
1107197×
        let tags = match m.get(&3) {
1108197×
            Some(t) => tags_from(t)?,
11090×
            None => Vec::new(),
1110
        };
1111197×
        let mut history = Vec::new();
1112197×
        if let Some(h) = m.get(&4) {
1113197×
            for p in o::array(h, "history")? {
11142×
                history.push(policy_from(p)?);
1115
            }
11160×
        }
1117197×
        let default_bookmark = match m.get(&5) {
1118128×
            Some(Value::Text(t)) => Some(t.clone()),
111969×
            _ => None,
1120
        };
1121197×
        let log = match m.get(&6) {
11222×
            Some(Value::Text(t)) => Some(t.clone()),
1123195×
            _ => None,
1124
        };
1125197×
        let mut witnesses = Vec::new();
1126197×
        if let Some(w) = m.get(&7) {
11271×
            for x in o::array(w, "witnesses")? {
11281×
                let a = o::array(x, "witness")?;
11291×
                if a.len() != 2 {
11300×
                    return Err(schema("witness: expected [name, identity]"));
11311×
                }
11321×
                witnesses.push((
11331×
                    o::text(&a[0], "witness name")?.to_owned(),
11341×
                    o::bytes(&a[1], "witness identity")?.to_vec(),
1135
                ));
1136
            }
1137196×
        }
1138197×
        Ok((
1139197×
            id,
1140197×
            RefsResponse {
1141197×
                refs,
1142197×
                policy,
1143197×
                tags,
1144197×
                history,
1145197×
                default_bookmark,
1146197×
                log,
1147197×
                witnesses,
1148197×
            },
1149197×
        ))
1150197×
    }
1151
1152
    /// A proof's hashes, from the leaf upwards (spec §14.8).
11532×
    fn proof_value(proof: &[[u8; 32]]) -> Value {
11543×
        Value::Array(proof.iter().map(|h| Value::Bytes(h.to_vec())).collect())
11552×
    }
1156
11572×
    fn proof_from(v: &Value) -> Result<Vec<[u8; 32]>> {
11582×
        let mut proof = Vec::new();
11593×
        for h in o::array(v, "proof")? {
11603×
            proof.push(
11613×
                o::bytes(h, "proof hash")?
11623×
                    .try_into()
11633×
                    .map_err(|_| schema("proof hash: expected 32 bytes"))?,
1164
            );
1165
        }
11662×
        Ok(proof)
11672×
    }
1168
116950×
    pub fn encode_negotiate(have: &[ChangeHash], want: &[ChangeHash]) -> Vec<u8> {
117050×
        cbor::encode(&Value::map([
117150×
            (0, hashes_value(have)),
117250×
            (1, hashes_value(want)),
117350×
        ]))
117450×
    }
117550×
    pub fn decode_negotiate(bytes: &[u8]) -> Result<(Vec<ChangeHash>, Vec<ChangeHash>)> {
117650×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
117750×
        let m = map(&v, "negotiate")?;
1178
        Ok((
117950×
            hashes_from(field(m, 0, "have")?)?,
118050×
            hashes_from(field(m, 1, "want")?)?,
1181
        ))
118250×
    }
1183
1184
    /// `fetch` request: `{0: [changes], 1: max blob size or null}`.
118551×
    pub fn encode_fetch(hs: &[ChangeHash], max_blob: Option<u64>) -> Vec<u8> {
118651×
        cbor::encode(&Value::map([
118751×
            (0, hashes_value(hs)),
118851×
            (1, max_blob.map(Value::Uint).unwrap_or(Value::Null)),
118951×
        ]))
119051×
    }
119152×
    pub fn decode_fetch(bytes: &[u8]) -> Result<(Vec<ChangeHash>, Option<u64>)> {
119252×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
119352×
        let m = map(&v, "fetch")?;
119452×
        let max = match m.get(&1) {
119551×
            Some(x) if !x.is_null() => Some(o::uint(x, "max blob")?),
119650×
            _ => None,
1197
        };
119852×
        Ok((hashes_from(field(m, 0, "changes")?)?, max))
119952×
    }
1200
1201
    /// `shallow` request: `{0: [heads], 1: depth}`.
12021×
    pub fn encode_shallow(hs: &[ChangeHash], depth: u32) -> Vec<u8> {
12031×
        cbor::encode(&Value::map([
12041×
            (0, hashes_value(hs)),
12051×
            (1, Value::Uint(depth as u64)),
12061×
        ]))
12071×
    }
12081×
    pub fn decode_shallow(bytes: &[u8]) -> Result<(Vec<ChangeHash>, u32)> {
12091×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
12101×
        let m = map(&v, "shallow")?;
1211
        Ok((
12121×
            hashes_from(field(m, 0, "heads")?)?,
12131×
            o::u32_(field(m, 1, "depth")?, "depth")?,
1214
        ))
12151×
    }
1216
121752×
    pub fn encode_hashes(hs: &[ChangeHash]) -> Vec<u8> {
121852×
        cbor::encode(&Value::map([(0, hashes_value(hs))]))
121952×
    }
122051×
    pub fn decode_hashes(bytes: &[u8]) -> Result<Vec<ChangeHash>> {
122151×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
122251×
        hashes_from(field(map(&v, "hashes")?, 0, "hashes")?)
122351×
    }
1224
122540×
    pub fn encode_push(
122640×
        bundle: &Bundle,
122740×
        updates: &[RefUpdate],
122840×
        policy: Option<&SignedPolicy>,
122940×
        tags: &[TagRef],
123040×
    ) -> Vec<u8> {
123140×
        cbor::encode(&Value::map([
123240×
            (0, bundle_value(bundle)),
123340×
            (2, opt_policy_value(policy)),
123440×
            (3, tags_value(tags)),
1235
            (
1236
                1,
1237
                Value::Array(
123840×
                    updates
123940×
                        .iter()
124040×
                        .map(|u| {
124140×
                            Value::map([
124240×
                                (0, Value::Text(u.name.clone())),
124340×
                                (1, Value::Bytes(u.old_state.0.to_vec())),
124440×
                                (2, Value::Bytes(u.new_state.0.to_vec())),
124540×
                                (3, Value::Bool(u.force)),
124640×
                                (4, opt_attest_value(&u.attestation)),
124740×
                            ])
124840×
                        })
124940×
                        .collect(),
1250
                ),
1251
            ),
1252
        ]))
125340×
    }
1254
    /// A decoded push: bundle, bookmark updates, policy, tags.
1255
    pub type PushParts = (Bundle, Vec<RefUpdate>, Option<SignedPolicy>, Vec<TagRef>);
1256
125736×
    pub fn decode_push(bytes: &[u8]) -> Result<PushParts> {
125836×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
125936×
        let m = map(&v, "push")?;
126036×
        let bundle = bundle_from_value(field(m, 0, "bundle")?)?;
126136×
        let mut updates = Vec::new();
126236×
        for u in o::array(field(m, 1, "updates")?, "updates")? {
126336×
            let um = map(u, "update")?;
126436×
            updates.push(RefUpdate {
126536×
                name: o::text(field(um, 0, "name")?, "name")?.to_owned(),
126636×
                old_state: o::oref(field(um, 1, "old_state")?, "old_state")?,
126736×
                new_state: o::oref(field(um, 2, "new_state")?, "new_state")?,
126836×
                force: field(um, 3, "force")?
126936×
                    .as_bool()
127036×
                    .ok_or_else(|| schema("force: expected bool"))?,
127136×
                attestation: opt_attest_from(field(um, 4, "attestation")?)?,
1272
            });
1273
        }
127436×
        let policy = match m.get(&2) {
127536×
            Some(p) => opt_policy_from(p)?,
12760×
            None => None,
1277
        };
127836×
        let tags = match m.get(&3) {
127936×
            Some(t) => tags_from(t)?,
12800×
            None => Vec::new(),
1281
        };
128236×
        Ok((bundle, updates, policy, tags))
128336×
    }
1284
128535×
    pub fn encode_push_response(results: &[RefResult]) -> Vec<u8> {
128635×
        cbor::encode(&Value::map([(
1287
            0,
1288
            Value::Array(
128935×
                results
129035×
                    .iter()
129136×
                    .map(|r| {
129236×
                        Value::map([
129336×
                            (0, Value::Text(r.name.clone())),
129436×
                            (1, Value::Bool(r.ok)),
129536×
                            (2, Value::Text(r.reason.clone())),
129636×
                        ])
129736×
                    })
129835×
                    .collect(),
1299
            ),
1300
        )]))
130135×
    }
130235×
    pub fn decode_push_response(bytes: &[u8]) -> Result<Vec<RefResult>> {
130335×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
130435×
        let m = map(&v, "push response")?;
130535×
        let mut out = Vec::new();
130636×
        for r in o::array(field(m, 0, "results")?, "results")? {
130736×
            let rm = map(r, "result")?;
130836×
            out.push(RefResult {
130936×
                name: o::text(field(rm, 0, "name")?, "name")?.to_owned(),
131036×
                ok: field(rm, 1, "ok")?
131136×
                    .as_bool()
131236×
                    .ok_or_else(|| schema("ok: expected bool"))?,
131336×
                reason: o::text(field(rm, 2, "reason")?, "reason")?.to_owned(),
1314
            });
1315
        }
131635×
        Ok(out)
131735×
    }
1318
}
1319
1320
#[cfg(test)]
1321
mod tests {
1322
    use super::*;
1323
    use crate::attest::AttestBody;
1324
    use crate::objects::Hlc;
1325
1326
    #[test]
13271×
    fn wire_round_trips() {
13281×
        let c = crate::objects::tests::sample_change();
13291×
        let sk = crate::identity::SecretKey {
13301×
            ed_seed: [1; 32],
13311×
            ml_seed: [2; 32],
13321×
        };
13331×
        let id = sk.identity("a", "b", 0);
13341×
        let key = id.hash();
13351×
        let sig = sk.sign(crate::identity::Domain::Change, &key, &c.hash());
13361×
        let seal = Attest::seal([3; 16], vec![c.hash()]);
13371×
        let seal_sig = sk.sign(crate::identity::Domain::Attest, &key, &seal.hash());
13381×
        let policy = Policy::single_root([3; 16], id.clone(), 99);
13391×
        let psig = sk.sign(crate::identity::Domain::Policy, &key, &policy.hash());
13401×
        let bundle = Bundle {
13411×
            changes: vec![(c.clone(), vec![sig.clone()])],
13421×
            attests: vec![SignedAttest {
13431×
                attest: seal.clone(),
13441×
                sigs: vec![seal_sig],
13451×
            }],
13461×
            objects: vec![
13471×
                (ObjectType::Identity, id.encode()),
13481×
                (ObjectType::Chunk, b"xyz".to_vec()),
13491×
            ],
13501×
            policies: vec![SignedPolicy {
13511×
                policy: policy.clone(),
13521×
                sigs: vec![psig.clone()],
13531×
            }],
13541×
            hashes: vec![],
13551×
            raw_changes: vec![],
13561×
            certificates: vec![],
13571×
        };
13581×
        let d = wire::decode_bundle(&wire::encode_bundle(&bundle)).unwrap();
13591×
        assert_eq!(
1360
            d.hashes,
13611×
            vec![c.hash()],
1362
            "the receiver hashes what it was sent"
1363
        );
13641×
        assert_eq!(d.changes, bundle.changes);
13651×
        assert_eq!(d.attests, bundle.attests);
13661×
        assert_eq!(d.objects, bundle.objects);
13671×
        assert_eq!(d.policies, bundle.policies);
13681×
        assert!(d.certificates.is_empty());
1369
        // Certificates (keyless, oxygenhub#241) travel as field 4, only
1370
        // when there are any: a bundle without them encodes as before.
13711×
        let plain = wire::encode_bundle(&bundle);
13721×
        let mut with = bundle.clone();
13731×
        let issuer_sk = crate::identity::SecretKey::generate();
13741×
        let issuer = issuer_sk.identity("hub", "h@x", 1);
13751×
        with.certificates.push(crate::cert::SignedCertificate::sign(
13761×
            crate::cert::Certificate {
13771×
                key: id.clone(),
13781×
                issuer: issuer.hash(),
13791×
                subject: "agent:a@b".into(),
13801×
                claims: vec![],
13811×
                scope: crate::identity::Scope::CHANGES,
13821×
                not_before: 1,
13831×
                expires: 2,
13841×
                grant: None,
13851×
            },
13861×
            &issuer,
13871×
            &issuer_sk,
1388
        ));
13891×
        let encoded = wire::encode_bundle(&with);
13901×
        assert_ne!(encoded, plain);
13911×
        assert_eq!(
13921×
            wire::decode_bundle(&encoded).unwrap().certificates,
1393
            with.certificates
1394
        );
13951×
        with.certificates.clear();
13961×
        assert_eq!(wire::encode_bundle(&with), plain);
1397
13981×
        let att = Attest {
13991×
            repo: [3; 16],
14001×
            hlc: Hlc::default(),
14011×
            body: AttestBody::Ref {
14021×
                name: "main".into(),
14031×
                old_state: ObjectRef([1; 32]),
14041×
                new_state: ObjectRef([2; 32]),
14051×
                serial: 4,
14061×
            },
14071×
        };
14081×
        let refs = vec![
14091×
            RemoteRef {
14101×
                name: "main".into(),
14111×
                state: ObjectRef([2; 32]),
14121×
                heads: vec![c.hash()],
14131×
                attestation: Some(SignedAttest {
14141×
                    attest: att.clone(),
14151×
                    sigs: vec![sig.clone()],
14161×
                }),
14171×
                last_serial: Some(4),
14181×
                accepted: None,
14191×
                logged: None,
14201×
                integration: vec![],
14211×
            },
14221×
            RemoteRef {
14231×
                name: "dev".into(),
14241×
                state: ObjectRef([5; 32]),
14251×
                heads: vec![],
14261×
                attestation: None,
14271×
                last_serial: None,
14281×
                accepted: None,
14291×
                logged: None,
14301×
                integration: vec![],
14311×
            },
1432
        ];
14331×
        let tag = TagRef {
14341×
            name: "v1".into(),
14351×
            state: ObjectRef([2; 32]),
14361×
            heads: vec![c.hash()],
14371×
            attestation: None,
14381×
        };
14391×
        let mut resp = RefsResponse {
14401×
            refs,
14411×
            policy: Some(SignedPolicy {
14421×
                policy: policy.clone(),
14431×
                sigs: vec![psig.clone()],
14441×
            }),
14451×
            tags: vec![tag.clone()],
14461×
            history: vec![SignedPolicy {
14471×
                policy: policy.clone(),
14481×
                sigs: vec![],
14491×
            }],
14501×
            default_bookmark: Some("develop".into()),
14511×
            log: Some("hub.example/log\n2\nroot\n\n- sig\n".into()),
14521×
            witnesses: vec![],
14531×
        };
1454
        // Without integrated times (spec §14.8) nothing is added: an old
1455
        // peer's answer, and what it reads.
14561×
        let old = wire::encode_refs([3; 16], &resp);
14571×
        let back = wire::decode_refs(&old).unwrap().1;
14582×
        assert!(back.witnesses.is_empty() && back.refs.iter().all(|r| r.integration.is_empty()));
14591×
        resp.refs[1].logged = Some(Logged {
14601×
            index: 41,
14611×
            entry: vec![1, 2, 3],
14621×
            proof: vec![[9; 32], [8; 32]],
14631×
        });
14641×
        resp.refs[1].integration = vec![Integration {
14651×
            note: "hub.example/log\n42\nroot\n\n- sig\n".into(),
14661×
            proof: vec![[7; 32]],
14671×
        }];
14681×
        resp.witnesses = vec![("w.example".into(), vec![4, 5, 6])];
14691×
        let new = wire::encode_refs([3; 16], &resp);
14701×
        let (id_back, back) = wire::decode_refs(&new).unwrap();
14711×
        assert_eq!(back.log, resp.log);
14721×
        assert_eq!(back.refs[1].logged, resp.refs[1].logged);
14731×
        assert_eq!(back.refs[1].integration, resp.refs[1].integration);
14741×
        assert_eq!(back.witnesses, resp.witnesses);
14751×
        assert_eq!(back.refs[0].logged, None);
1476
        // The new keys are 7s an old reader never asks for.
14771×
        let crate::cbor::Value::Map(m) = crate::cbor::decode(&new).unwrap() else {
14780×
            panic!()
1479
        };
14801×
        assert!(m.contains_key(&7));
14811×
        assert_eq!(id_back, [3; 16]);
14821×
        assert_eq!(back.refs.len(), 2);
14831×
        assert_eq!(back.refs[0].attestation.as_ref().unwrap().attest, att);
14841×
        assert_eq!(back.refs[1].last_serial, None);
14851×
        assert_eq!(back.policy.as_ref().unwrap().policy, policy);
14861×
        assert_eq!(back.history, resp.history);
14871×
        assert_eq!(back.tags, vec![tag.clone()]);
1488
14891×
        let (h, w) = wire::decode_negotiate(&wire::encode_negotiate(
14901×
            &[ObjectRef([1; 32])],
14911×
            &[ObjectRef([2; 32])],
14921×
        ))
14931×
        .unwrap();
14941×
        assert_eq!((h, w), (vec![ObjectRef([1; 32])], vec![ObjectRef([2; 32])]));
14951×
        assert_eq!(
14961×
            wire::decode_hashes(&wire::encode_hashes(&[c.hash()])).unwrap(),
14971×
            vec![c.hash()]
1498
        );
14991×
        assert_eq!(
15001×
            wire::decode_fetch(&wire::encode_fetch(&[c.hash()], Some(4096))).unwrap(),
15011×
            (vec![c.hash()], Some(4096))
1502
        );
15031×
        assert_eq!(
15041×
            wire::decode_fetch(&wire::encode_fetch(&[], None)).unwrap(),
15051×
            (vec![], None)
1506
        );
15071×
        assert_eq!(
15081×
            wire::decode_shallow(&wire::encode_shallow(&[c.hash()], 3)).unwrap(),
15091×
            (vec![c.hash()], 3)
1510
        );
1511
        // An old-style fetch request without the filter field still decodes.
15121×
        assert_eq!(
15131×
            wire::decode_fetch(&wire::encode_hashes(&[c.hash()])).unwrap(),
15141×
            (vec![c.hash()], None)
1515
        );
1516
15171×
        let up = RefUpdate {
15181×
            name: "main".into(),
15191×
            old_state: ObjectRef([1; 32]),
15201×
            new_state: ObjectRef([2; 32]),
15211×
            force: true,
15221×
            attestation: Some(SignedAttest {
15231×
                attest: att,
15241×
                sigs: vec![sig],
15251×
            }),
15261×
        };
15271×
        let sp = SignedPolicy {
15281×
            policy,
15291×
            sigs: vec![psig],
15301×
        };
15311×
        let (b2, ups, pol, tags) = wire::decode_push(&wire::encode_push(
15321×
            &bundle,
15331×
            std::slice::from_ref(&up),
15341×
            Some(&sp),
15351×
            std::slice::from_ref(&tag),
15361×
        ))
15371×
        .unwrap();
15381×
        assert_eq!(pol, Some(sp));
15391×
        assert_eq!(tags, vec![tag]);
15401×
        assert_eq!(b2.changes.len(), 1);
15411×
        assert_eq!(ups[0].name, "main");
15421×
        assert!(ups[0].force);
15431×
        assert_eq!(ups[0].attestation, up.attestation);
15441×
        let res = vec![RefResult {
15451×
            name: "main".into(),
15461×
            ok: false,
15471×
            reason: "stale".into(),
15481×
        }];
15491×
        assert_eq!(
15501×
            wire::decode_push_response(&wire::encode_push_response(&res)).unwrap(),
1551
            res
1552
        );
15531×
        assert_eq!(
15541×
            wire::decode_capabilities(&wire::encode_capabilities([7; 16])).unwrap(),
1555
            [7; 16]
1556
        );
15571×
    }
1558
}