OXYGENHUB

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

930 of 1097 lines run, 149 of 232 functions · run #358 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 {
2071076×
    pub fn open(path: &Path) -> Result<LocalRemote> {
208
        Ok(LocalRemote {
2091076×
            repo: Repo::open(path)?,
2101076×
            claimed_id: None,
211
        })
2121076×
    }
213
}
214
215
impl Remote for LocalRemote {
216845×
    fn repo_id(&self) -> Result<[u8; 16]> {
217845×
        self.repo.id()
218845×
    }
219843×
    fn refs(&self) -> Result<RefsResponse> {
220843×
        self.repo.remote_refs()
221843×
    }
222336×
    fn negotiate(&self, have: &[ChangeHash], want: &[ChangeHash]) -> Result<Vec<ChangeHash>> {
223336×
        self.repo.negotiate(have, want)
224336×
    }
225340×
    fn fetch(&self, changes: &[ChangeHash], max_blob: Option<u64>) -> Result<Bundle> {
226340×
        self.repo.bundle_raw_for(changes, max_blob)
227340×
    }
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×
    }
237253×
    fn push(
238253×
        &self,
239253×
        bundle: Bundle,
240253×
        updates: Vec<RefUpdate>,
241253×
        policy: Option<SignedPolicy>,
242253×
        tags: Vec<TagRef>,
243253×
    ) -> Result<Vec<RefResult>> {
244253×
        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
            }
254240×
        }
255253×
        self.repo.receive_push(bundle, updates, policy, tags)
256253×
    }
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.
3001135×
pub fn open_store(
3011135×
    url: &str,
3021135×
    options: &RemoteOptions,
3031135×
) -> Option<crate::strata::Result<Box<dyn crate::strata::Store>>> {
3041135×
    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
        );
3091076×
    }
3101076×
    let openers = STORE_OPENERS.lock().unwrap_or_else(|p| p.into_inner());
3111076×
    openers.iter().find_map(|open| open(url, options))
3121135×
}
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.
332149×
pub fn tls_client_config(ca: Option<&Path>) -> Result<Arc<rustls::ClientConfig>> {
333149×
    let mut roots = rustls::RootCertStore::empty();
334149×
    roots.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
335149×
    if let Some(path) = ca {
33634×
        let pem = std::fs::read(path)
33734×
            .map_err(|e| RepoError::Msg(format!("reading CA file {}: {e}", path.display())))?;
33834×
        let certs = rustls_pemfile::certs(&mut pem.as_slice())
33934×
            .collect::<std::result::Result<Vec<_>, _>>()
34034×
            .map_err(|e| RepoError::Msg(format!("parsing CA file {}: {e}", path.display())))?;
34134×
        if certs.is_empty() {
3420×
            return Err(RepoError::Msg(format!(
3430×
                "CA file {} holds no certificates",
3440×
                path.display()
3450×
            )));
34634×
        }
34734×
        for c in certs {
34834×
            roots
34934×
                .add(c)
35034×
                .map_err(|e| RepoError::Msg(format!("CA file {}: {e}", path.display())))?;
351
        }
352115×
    }
353149×
    let cfg = rustls::ClientConfig::builder_with_provider(Arc::new(
354149×
        rustls::crypto::ring::default_provider(),
355
    ))
356149×
    .with_safe_default_protocol_versions()
357149×
    .map_err(|e| RepoError::Msg(e.to_string()))?
358149×
    .with_root_certificates(roots)
359149×
    .with_no_client_auth();
360149×
    Ok(Arc::new(cfg))
361149×
}
362
363
impl HttpRemote {
364145×
    pub fn new(base: &str, options: &RemoteOptions) -> Result<HttpRemote> {
365145×
        refuse_plain_token(base, options)?;
366145×
        let agent = ureq::AgentBuilder::new()
367145×
            .tls_config(tls_client_config(options.ca.as_deref())?)
368145×
            .build();
369145×
        Ok(HttpRemote {
370145×
            base: base.trim_end_matches('/').to_string(),
371145×
            token: Mutex::new(options.token.clone()),
372145×
            fallbacks: Mutex::new(options.fallback_tokens.iter().rev().cloned().collect()),
373145×
            repo_id: options.repo_id,
374145×
            agent,
375145×
        })
376145×
    }
377
378
    /// A request, tried again with the next fallback token while the
379
    /// hub refuses the one in use (oxygen#112).
380365×
    fn call(&self, post: bool, endpoint: &str, body: Option<&[u8]>) -> Result<Vec<u8>> {
381
        loop {
382366×
            let token = self.token.lock().unwrap_or_else(|p| p.into_inner()).clone();
383366×
            match self.call_once(post, endpoint, body, token.as_deref()) {
38411×
                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
                }
399363×
                other => return other,
400
            }
401
        }
402365×
    }
403
404366×
    fn call_once(
405366×
        &self,
406366×
        post: bool,
407366×
        endpoint: &str,
408366×
        body: Option<&[u8]>,
409366×
        token: Option<&str>,
410366×
    ) -> Result<Vec<u8>> {
411366×
        let url = format!("{}/oxy/v1/{endpoint}", self.base);
412366×
        let mut req = if post {
413127×
            self.agent.post(&url)
414
        } else {
415239×
            self.agent.get(&url)
416
        };
417366×
        req = req.set("Accept", CONTENT_TYPE);
418366×
        if let Some(t) = token {
41922×
            req = req.set("Authorization", &format!("Bearer {t}"));
420344×
        }
421366×
        if let Some(id) = &self.repo_id {
422341×
            req = req.set(REPO_ID_HEADER, &hex::encode(id));
423341×
        }
424366×
        let resp = match body {
425127×
            Some(b) => req.set("Content-Type", CONTENT_TYPE).send_bytes(b),
426239×
            None => req.call(),
427
        };
42811×
        match resp {
429355×
            Ok(r) => {
430355×
                let mut out = Vec::new();
431355×
                r.into_reader()
432355×
                    .read_to_end(&mut out)
433355×
                    .map_err(|e| RepoError::Msg(format!("{url}: {e}")))?;
434355×
                Ok(out)
435
            }
4368×
            Err(ureq::Error::Status(code, r)) => {
4378×
                let text = r.into_string().unwrap_or_default();
4388×
                let msg = format!("{url}: HTTP {code}: {}", text.trim());
4398×
                Err(RepoError::Msg(with_hint(msg)))
440
            }
441
            // The transport error already names the URL.
4423×
            Err(e) => Err(RepoError::Msg(with_hint(e.to_string()))),
443
        }
444366×
    }
445
}
446
447
/// Whether a failed request's message says the hub refused its token:
448
/// HTTP 401, 403, or 404 (a hub hides a private repository from a token
449
/// that may not read it).
4504×
fn refused(message: &str) -> bool {
4514×
    [": HTTP 401", ": HTTP 403", ": HTTP 404"]
4524×
        .iter()
4536×
        .any(|c| message.contains(c))
4544×
}
455
456
/// Refuse to send a token where anyone on the way could read it: plain
457
/// `http` to another machine (see [`crate::credentials::token_allowed`]).
458145×
fn refuse_plain_token(url: &str, options: &RemoteOptions) -> Result<()> {
459145×
    if options.token.is_some() && !crate::credentials::token_allowed(url) {
4600×
        return Err(RepoError::Msg(format!(
4610×
            "{url}: refusing to send a token over plain http; use https"
4620×
        )));
463145×
    }
464145×
    Ok(())
465145×
}
466
467
/// What to do about a failed request, recognised from its message.
46819×
pub fn hint_for(message: &str) -> Option<&'static str> {
46919×
    let m = message.to_ascii_lowercase();
47019×
    let hint = if m.contains("http 401") {
4716×
        "the hub needs you signed in, or did not accept the token: run `oxy auth login HUB` (pushing needs repo:write)"
47213×
    } else if m.contains("http 403") {
4731×
        "the token or account lacks permission: pushing needs a token with repo:write and write access to the repository"
47412×
    } else if m.contains("http 404") {
4754×
        "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`)"
4768×
    } else if m.contains("unknownissuer")
4776×
        || m.contains("unknown issuer")
4786×
        || m.contains("certificate")
4795×
        || m.contains("invalidcertificate")
480
    {
4813×
        "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`"
4825×
    } else if m.contains("connection refused") {
4833×
        "nothing is listening there: check the URL and port, and that the server is running"
4842×
    } else if m.contains("dns")
4851×
        || m.contains("failed to lookup")
4861×
        || m.contains("name or service not known")
487
    {
4881×
        "the host name does not resolve: check the URL"
4891×
    } else if m.contains("timed out") || m.contains("timeout") {
4900×
        "the server did not answer in time: check the network, or try again"
491
    } else {
4921×
        return None;
493
    };
49418×
    Some(hint)
49519×
}
496
497
/// `message`, followed by what to do about it when that is known.
49811×
pub fn with_hint(message: String) -> String {
49911×
    match hint_for(&message) {
50011×
        Some(h) => format!("{message}\n  hint: {h}"),
5010×
        None => message,
502
    }
50311×
}
504
505
/// A JSON request to a hub API (`GET`, `POST` or `DELETE`), with the same
506
/// TLS trust and token rules as remotes. Returns the status and body, an
507
/// error status included; only transport failures are errors.
5080×
pub fn http_json(
5090×
    method: &str,
5100×
    url: &str,
5110×
    body: Option<&str>,
5120×
    options: &RemoteOptions,
5130×
) -> Result<(u16, String)> {
5140×
    refuse_plain_token(url, options)?;
5150×
    let agent = ureq::AgentBuilder::new()
5160×
        .tls_config(tls_client_config(options.ca.as_deref())?)
5170×
        .timeout(std::time::Duration::from_secs(60))
5180×
        .build();
5190×
    let mut req = agent.request(method, url).set("Accept", "application/json");
5200×
    if let Some(t) = &options.token {
5210×
        req = req.set("Authorization", &format!("Bearer {t}"));
5220×
    }
5230×
    let resp = match body {
5240×
        Some(b) => req.set("Content-Type", "application/json").send_string(b),
5250×
        None => req.call(),
526
    };
5270×
    match resp {
5280×
        Ok(r) => {
5290×
            let code = r.status();
5300×
            Ok((code, r.into_string().unwrap_or_default()))
531
        }
5320×
        Err(ureq::Error::Status(code, r)) => Ok((code, r.into_string().unwrap_or_default())),
5330×
        Err(e) => Err(RepoError::Msg(with_hint(e.to_string()))),
534
    }
5350×
}
536
537
/// An authenticated GET of any URL on a host, with the same TLS trust and
538
/// token as remotes use (for hub APIs: proposals). Returns the body.
5390×
pub fn http_get(url: &str, options: &RemoteOptions) -> Result<Vec<u8>> {
5400×
    refuse_plain_token(url, options)?;
5410×
    let agent = ureq::AgentBuilder::new()
5420×
        .tls_config(tls_client_config(options.ca.as_deref())?)
5430×
        .build();
5440×
    let mut req = agent.get(url).set("Accept", "application/json");
5450×
    if let Some(t) = &options.token {
5460×
        req = req.set("Authorization", &format!("Bearer {t}"));
5470×
    }
5480×
    match req.call() {
5490×
        Ok(r) => {
5500×
            let mut out = Vec::new();
5510×
            r.into_reader()
5520×
                .read_to_end(&mut out)
5530×
                .map_err(|e| RepoError::Msg(format!("{url}: {e}")))?;
5540×
            Ok(out)
555
        }
5560×
        Err(ureq::Error::Status(code, r)) => {
5570×
            let text = r.into_string().unwrap_or_default();
5580×
            Err(RepoError::Msg(with_hint(format!(
5590×
                "{url}: HTTP {code}: {}",
5600×
                text.trim()
5610×
            ))))
562
        }
563
        // The transport error already names the URL.
5640×
        Err(e) => Err(RepoError::Msg(with_hint(e.to_string()))),
565
    }
5660×
}
567
568
impl Remote for HttpRemote {
569124×
    fn repo_id(&self) -> Result<[u8; 16]> {
570124×
        wire::decode_capabilities(&self.call(false, "capabilities", None)?)
571124×
    }
572115×
    fn refs(&self) -> Result<RefsResponse> {
573115×
        Ok(wire::decode_refs(&self.call(false, "refs", None)?)?.1)
574115×
    }
57545×
    fn negotiate(&self, have: &[ChangeHash], want: &[ChangeHash]) -> Result<Vec<ChangeHash>> {
57645×
        wire::decode_hashes(&self.call(
577
            true,
57845×
            "negotiate",
57945×
            Some(&wire::encode_negotiate(have, want)),
5800×
        )?)
58145×
    }
58245×
    fn fetch(&self, changes: &[ChangeHash], max_blob: Option<u64>) -> Result<Bundle> {
58345×
        wire::decode_bundle(&self.call(
584
            true,
58545×
            "fetch",
58645×
            Some(&wire::encode_fetch(changes, max_blob)),
5870×
        )?)
58845×
    }
5891×
    fn objects(&self, refs: &[ObjectRef]) -> Result<Vec<(ObjectType, Vec<u8>)>> {
590
        Ok(
5911×
            wire::decode_bundle(&self.call(true, "objects", Some(&wire::encode_hashes(refs)))?)?
592
                .objects,
593
        )
5941×
    }
5950×
    fn checkpoint(&self, heads: &[ChangeHash]) -> Result<Bundle> {
5960×
        wire::decode_bundle(&self.call(true, "checkpoint", Some(&wire::encode_hashes(heads)))?)
5970×
    }
5980×
    fn shallow(&self, heads: &[ChangeHash], depth: u32) -> Result<Vec<ChangeHash>> {
5990×
        wire::decode_hashes(&self.call(
600
            true,
6010×
            "shallow",
6020×
            Some(&wire::encode_shallow(heads, depth)),
6030×
        )?)
6040×
    }
60535×
    fn push(
60635×
        &self,
60735×
        bundle: Bundle,
60835×
        updates: Vec<RefUpdate>,
60935×
        policy: Option<SignedPolicy>,
61035×
        tags: Vec<TagRef>,
61135×
    ) -> Result<Vec<RefResult>> {
61235×
        wire::decode_push_response(&self.call(
613
            true,
61435×
            "push",
61535×
            Some(&wire::encode_push(
61635×
                &bundle,
61735×
                &updates,
61835×
                policy.as_ref(),
61935×
                &tags,
62035×
            )),
6214×
        )?)
62235×
    }
623
}
624
625
/// A remote's URL as it is stored: an `http(s)://` URL as given, a local
626
/// path made absolute (with its `file://` kept), so it still names the same
627
/// repository from inside the clone (oxygen#57).
628262×
pub fn stored_url(url: &str) -> String {
629
    // Only a path is made absolute: a plain one, or one behind file:// or
630
    // dir://. Every other URL (a hub, a bucket) is kept as written.
631262×
    let (prefix, path) = match (url.strip_prefix("file://"), url.strip_prefix("dir://")) {
6321×
        (Some(p), _) => ("file://", p),
63311×
        (_, Some(p)) => ("dir://", p),
634250×
        _ if url.contains("://") => return url.to_string(),
635227×
        _ => ("", url),
636
    };
637239×
    match std::path::absolute(path) {
638239×
        Ok(abs) => format!("{prefix}{}", abs.display()),
6390×
        Err(_) => url.to_string(),
640
    }
641262×
}
642
643
/// Open a remote by URL: a local path (optionally `file://`), `http(s)://`
644
/// (a hub), or a store (`dir://`, and whatever openers are registered).
6451268×
pub fn open_remote(url: &str, options: &RemoteOptions) -> Result<Box<dyn Remote>> {
6461268×
    if url.starts_with("http://") || url.starts_with("https://") {
647145×
        return Ok(Box::new(HttpRemote::new(url, options)?));
6481123×
    }
6491123×
    if let Some(store) = open_store(url, options) {
65048×
        return crate::repo::strata::open_store_remote(store?, options);
6511075×
    }
6521075×
    let path = url.strip_prefix("file://").unwrap_or(url);
6531075×
    if path.contains("://") {
6540×
        return Err(RepoError::Msg(format!("unsupported remote URL {url:?}")));
6551075×
    }
6561075×
    let mut local = LocalRemote::open(Path::new(path))?;
6571075×
    local.claimed_id = options.repo_id;
6581075×
    Ok(Box::new(local))
6591268×
}
660
661
// ---------------------------------------------------------------- wire
662
663
/// CBOR encodings of the protocol messages (spec §16.1).
664
pub mod wire {
665
    use super::*;
666
6670×
    fn schema(msg: &str) -> RepoError {
6680×
        RepoError::Object(ObjectError::Schema(msg.into()))
6690×
    }
670151×
    fn sigs_value(sigs: &[Signature]) -> Value {
671151×
        Value::Array(sigs.iter().map(|s| s.to_value()).collect())
672151×
    }
673146×
    fn sigs_from(v: &Value) -> Result<Vec<Signature>> {
674146×
        Ok(o::array(v, "signatures")?
675146×
            .iter()
676146×
            .map(Signature::from_value)
677146×
            .collect::<std::result::Result<Vec<_>, _>>()?)
678146×
    }
679345×
    fn hashes_value(hs: &[ObjectRef]) -> Value {
680469×
        Value::Array(hs.iter().map(|h| Value::Bytes(h.0.to_vec())).collect())
681345×
    }
682404×
    fn hashes_from(v: &Value) -> Result<Vec<ObjectRef>> {
683404×
        Ok(o::array(v, "hashes")?
684404×
            .iter()
685529×
            .map(|h| o::oref(h, "hash"))
686404×
            .collect::<std::result::Result<Vec<_>, _>>()?)
687404×
    }
68825×
    fn attest_value(sa: &SignedAttest) -> Value {
68925×
        Value::Array(vec![Value::Bytes(sa.attest.encode()), sigs_value(&sa.sigs)])
69025×
    }
69139×
    fn attest_from(v: &Value) -> Result<SignedAttest> {
69239×
        let a = o::array(v, "signed attest")?;
69339×
        if a.len() != 2 {
6940×
            return Err(schema("signed attest: expected [attest, sigs]"));
69539×
        }
696
        Ok(SignedAttest {
69739×
            attest: Attest::decode(o::bytes(&a[0], "attest")?)?,
69839×
            sigs: sigs_from(&a[1])?,
699
        })
70039×
    }
701193×
    fn opt_attest_value(sa: &Option<SignedAttest>) -> Value {
702193×
        sa.as_ref().map(attest_value).unwrap_or(Value::Null)
703193×
    }
704248×
    fn opt_attest_from(v: &Value) -> Result<Option<SignedAttest>> {
705248×
        if v.is_null() {
706220×
            Ok(None)
707
        } else {
70828×
            attest_from(v).map(Some)
709
        }
710248×
    }
711
    /// `[policy bytes, [signature]]`: also the format of a policy proposal
712
    /// file exchanged between root holders (spec §14.5).
71312×
    pub fn policy_value(sp: &SignedPolicy) -> Value {
71412×
        Value::Array(vec![Value::Bytes(sp.policy.encode()), sigs_value(&sp.sigs)])
71512×
    }
71610×
    pub fn policy_from(v: &Value) -> Result<SignedPolicy> {
71710×
        let a = o::array(v, "signed policy")?;
71810×
        if a.len() != 2 {
7190×
            return Err(schema("signed policy: expected [policy, sigs]"));
72010×
        }
721
        Ok(SignedPolicy {
72210×
            policy: Policy::decode(o::bytes(&a[0], "policy")?)?,
72310×
            sigs: sigs_from(&a[1])?,
724
        })
72510×
    }
726180×
    fn opt_policy_value(sp: Option<&SignedPolicy>) -> Value {
727180×
        sp.map(policy_value).unwrap_or(Value::Null)
728180×
    }
729219×
    fn opt_policy_from(v: &Value) -> Result<Option<SignedPolicy>> {
730219×
        if v.is_null() {
731215×
            Ok(None)
732
        } else {
7334×
            policy_from(v).map(Some)
734
        }
735219×
    }
736900×
    fn map<'a>(v: &'a Value, what: &str) -> Result<&'a o::Map> {
737900×
        Ok(o::map(v, what)?)
738900×
    }
7392533×
    fn field<'a>(m: &'a o::Map, k: u64, what: &str) -> Result<&'a Value> {
7402533×
        Ok(o::field(m, k, what)?)
7412533×
    }
742
743
    /// A bundle's value. Each change's text blobs and their chunks (spec
744
    /// §6.1) are added to its objects when they are not already there, so a
745
    /// bundle can always be read on its own.
746117×
    pub fn bundle_value(b: &Bundle) -> Value {
747117×
        let mut changes = Vec::with_capacity(b.raw_changes.len() + b.changes.len());
748
        // Changes as stored are already their encoding, their texts among
749
        // the objects.
750117×
        for (bytes, s) in &b.raw_changes {
7510×
            changes.push(Value::Array(vec![
7520×
                Value::Bytes(bytes.clone()),
7530×
                sigs_value(s),
7540×
            ]));
7550×
        }
756117×
        let mut texts: Vec<(ObjectType, Vec<u8>)> = Vec::new();
757117×
        let mut listed: Option<std::collections::HashSet<ObjectRef>> = None;
758117×
        for (c, s) in &b.changes {
759114×
            let (bytes, stored) = c.encode_parts();
760114×
            for t in stored {
7610×
                let listed = listed.get_or_insert_with(|| {
7620×
                    b.objects
7630×
                        .iter()
7640×
                        .map(|(ty, body)| crate::hash::hash_object(*ty, body))
7650×
                        .collect()
7660×
                });
7670×
                if !listed.insert(t.blob.hash()) {
7680×
                    continue;
7690×
                }
7700×
                for chunk in crate::chunk::chunks(&t.content) {
7710×
                    if listed.insert(crate::hash::hash_object(ObjectType::Chunk, chunk)) {
7720×
                        texts.push((ObjectType::Chunk, chunk.to_vec()));
7730×
                    }
774
                }
7750×
                texts.push((ObjectType::Blob, t.blob.encode()));
776
            }
777114×
            changes.push(Value::Array(vec![Value::Bytes(bytes), sigs_value(s)]));
778
        }
779117×
        let mut v = Value::map([
780117×
            (0, Value::Array(changes)),
781117×
            (
782117×
                1,
783117×
                Value::Array(b.attests.iter().map(attest_value).collect()),
784117×
            ),
785
            (
786
                2,
787
                Value::Array(
788117×
                    b.objects
789117×
                        .iter()
790117×
                        .chain(&texts)
791117×
                        .map(|(t, body)| {
79290×
                            Value::Array(vec![
79390×
                                Value::Text(t.name().into()),
79490×
                                Value::Bytes(body.clone()),
79590×
                            ])
79690×
                        })
797117×
                        .collect(),
798
                ),
799
            ),
800117×
            (
801117×
                3,
802117×
                Value::Array(b.policies.iter().map(policy_value).collect()),
803117×
            ),
804
        ]);
805
        // Only when there are any; older peers ignore the field.
806117×
        if !b.certificates.is_empty() {
8071×
            if let Value::Map(m) = &mut v {
8081×
                m.insert(
809
                    4,
810
                    Value::Array(
8111×
                        b.certificates
8121×
                            .iter()
8131×
                            .map(|c| Value::Bytes(c.encode()))
8141×
                            .collect(),
815
                    ),
816
                );
8170×
            }
818116×
        }
819117×
        v
820117×
    }
821
822107×
    pub fn bundle_from_value(v: &Value) -> Result<Bundle> {
823107×
        let m = map(v, "bundle")?;
824107×
        let mut b = Bundle::default();
825107×
        for ob in o::array(field(m, 2, "objects")?, "objects")? {
82679×
            let pair = o::array(ob, "object")?;
82779×
            if pair.len() != 2 {
8280×
                return Err(schema("object: expected [type, body]"));
82979×
            }
83079×
            let ty = ObjectType::from_name(o::text(&pair[0], "object type")?)
83179×
                .ok_or_else(|| schema("unknown object type"))?;
83279×
            b.objects
83379×
                .push((ty, o::bytes(&pair[1], "object body")?.to_vec()));
834
        }
835
        // Stored inserts are read from the bundle's own objects.
836107×
        let mut by_ref: Option<std::collections::HashMap<ObjectRef, usize>> = None;
837107×
        for c in o::array(field(m, 0, "changes")?, "changes")? {
83897×
            let pair = o::array(c, "change entry")?;
83997×
            if pair.len() != 2 {
8400×
                return Err(schema("change entry: expected [change, sigs]"));
84197×
            }
84297×
            let encoded = o::bytes(&pair[0], "change")?;
84397×
            b.hashes
84497×
                .push(crate::hash::hash_object(ObjectType::Change, encoded));
84597×
            let change = Change::decode_with(encoded, &mut |text, count, form| {
8460×
                let by_ref = by_ref.get_or_insert_with(|| {
8470×
                    b.objects
8480×
                        .iter()
8490×
                        .enumerate()
8500×
                        .map(|(i, (ty, body))| (crate::hash::hash_object(*ty, body), i))
8510×
                        .collect()
8520×
                });
8530×
                let get =
8540×
                    |r: &ObjectRef, want: ObjectType| match by_ref.get(r).map(|i| &b.objects[*i]) {
8550×
                        Some((ty, body)) if *ty == want => Ok(body),
8560×
                        _ => Err(ObjectError::Schema(format!(
8570×
                            "the bundle lacks {} {}",
8580×
                            want.name(),
8590×
                            r.short(12)
8600×
                        ))),
8610×
                    };
8620×
                let blob = crate::objects::Blob::decode(get(text, ObjectType::Blob)?)?;
8630×
                let mut content = Vec::with_capacity(blob.length as usize);
8640×
                for chunk in &blob.chunks {
8650×
                    content.extend_from_slice(get(chunk, ObjectType::Chunk)?);
866
                }
8670×
                crate::objects::text_lines(&content, count, form)
8680×
            })?;
86997×
            b.changes.push((change, sigs_from(&pair[1])?));
870
        }
871107×
        for a in o::array(field(m, 1, "attests")?, "attests")? {
87211×
            b.attests.push(attest_from(a)?);
873
        }
874107×
        if let Some(ps) = m.get(&3) {
875107×
            for p in o::array(ps, "policies")? {
8763×
                b.policies.push(policy_from(p)?);
877
            }
8780×
        }
879107×
        if let Some(cs) = m.get(&4) {
8801×
            for c in o::array(cs, "certificates")? {
8811×
                b.certificates.push(
8821×
                    crate::cert::SignedCertificate::decode(o::bytes(c, "certificate")?)
8831×
                        .map_err(|e| schema(&format!("certificate: {e}")))?,
884
                );
885
            }
886106×
        }
887107×
        Ok(b)
888107×
    }
889
89081×
    pub fn encode_bundle(b: &Bundle) -> Vec<u8> {
89181×
        cbor::encode(&bundle_value(b))
89281×
    }
89375×
    pub fn decode_bundle(bytes: &[u8]) -> Result<Bundle> {
89475×
        bundle_from_value(&cbor::decode(bytes).map_err(ObjectError::from)?)
89575×
    }
896
897119×
    pub fn encode_capabilities(id: [u8; 16]) -> Vec<u8> {
898119×
        cbor::encode(&Value::map([
899119×
            (0, Value::Array(vec![Value::Uint(PROTOCOL_VERSION)])),
900119×
            (1, Value::Bytes(id.to_vec())),
901119×
            (2, Value::Array(vec![Value::Text("seal".into())])),
902119×
        ]))
903119×
    }
904119×
    pub fn decode_capabilities(bytes: &[u8]) -> Result<[u8; 16]> {
905119×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
906119×
        let m = map(&v, "capabilities")?;
907119×
        let versions = o::array(field(m, 0, "versions")?, "versions")?;
908119×
        if !versions
909119×
            .iter()
910119×
            .any(|x| x.as_uint() == Some(PROTOCOL_VERSION))
911
        {
9120×
            return Err(RepoError::Msg(
9130×
                "remote does not speak protocol version 1".into(),
9140×
            ));
915119×
        }
916119×
        o::bytes(field(m, 1, "repo id")?, "repo id")?
917119×
            .try_into()
918119×
            .map_err(|_| schema("repo id: expected 16 bytes"))
919119×
    }
920
921180×
    fn tags_value(tags: &[TagRef]) -> Value {
922
        Value::Array(
923180×
            tags.iter()
924180×
                .map(|t| {
9258×
                    Value::map([
9268×
                        (0, Value::Text(t.name.clone())),
9278×
                        (1, Value::Bytes(t.state.0.to_vec())),
9288×
                        (2, hashes_value(&t.heads)),
9298×
                        (3, opt_attest_value(&t.attestation)),
9308×
                    ])
9318×
                })
932180×
                .collect(),
933
        )
934180×
    }
935219×
    fn tags_from(v: &Value) -> Result<Vec<TagRef>> {
936219×
        let mut out = Vec::new();
937219×
        for t in o::array(v, "tags")? {
93824×
            let tm = map(t, "tag")?;
93924×
            out.push(TagRef {
94024×
                name: o::text(field(tm, 0, "name")?, "name")?.to_owned(),
94124×
                state: o::oref(field(tm, 1, "state")?, "state")?,
94224×
                heads: hashes_from(field(tm, 2, "heads")?)?,
94324×
                attestation: opt_attest_from(field(tm, 3, "attestation")?)?,
944
            });
945
        }
946219×
        Ok(out)
947219×
    }
948
949144×
    pub fn encode_refs(id: [u8; 16], resp: &RefsResponse) -> Vec<u8> {
950144×
        let mut v = Value::map([
951
            (
952
                0,
953
                Value::Array(
954144×
                    resp.refs
955144×
                        .iter()
956149×
                        .map(|r| {
957149×
                            let mut v = Value::map([
958149×
                                (0, Value::Text(r.name.clone())),
959149×
                                (1, Value::Bytes(r.state.0.to_vec())),
960149×
                                (2, hashes_value(&r.heads)),
961149×
                                (3, opt_attest_value(&r.attestation)),
962149×
                                (4, r.last_serial.map(Value::Uint).unwrap_or(Value::Null)),
963149×
                            ]);
964
                            // Only when there is one; older peers ignore it.
965149×
                            if let Value::Map(m) = &mut v {
966149×
                                if r.accepted.is_some() {
9670×
                                    m.insert(5, opt_attest_value(&r.accepted));
968149×
                                }
969149×
                                if let Some(l) = &r.logged {
9701×
                                    m.insert(
9711×
                                        6,
9721×
                                        Value::Array(vec![
9731×
                                            Value::Uint(l.index),
9741×
                                            Value::Bytes(l.entry.clone()),
9751×
                                            proof_value(&l.proof),
9761×
                                        ]),
9771×
                                    );
978148×
                                }
979149×
                                if !r.integration.is_empty() {
9801×
                                    m.insert(
981
                                        7,
982
                                        Value::Array(
9831×
                                            r.integration
9841×
                                                .iter()
9851×
                                                .map(|i| {
9861×
                                                    Value::Array(vec![
9871×
                                                        Value::Text(i.note.clone()),
9881×
                                                        proof_value(&i.proof),
9891×
                                                    ])
9901×
                                                })
9911×
                                                .collect(),
992
                                        ),
993
                                    );
994148×
                                }
9950×
                            }
996149×
                            v
997149×
                        })
998144×
                        .collect(),
999
                ),
1000
            ),
1001144×
            (1, Value::Bytes(id.to_vec())),
1002144×
            (2, opt_policy_value(resp.policy.as_ref())),
1003144×
            (3, tags_value(&resp.tags)),
1004144×
            (
1005144×
                4,
1006144×
                Value::Array(resp.history.iter().map(policy_value).collect()),
1007144×
            ),
1008144×
            (
1009144×
                5,
1010144×
                resp.default_bookmark
1011144×
                    .clone()
1012144×
                    .map(Value::Text)
1013144×
                    .unwrap_or(Value::Null),
1014144×
            ),
1015
        ]);
1016144×
        if let Value::Map(m) = &mut v {
1017144×
            if let Some(log) = &resp.log {
10182×
                m.insert(6, Value::Text(log.clone()));
1019142×
            }
1020144×
            if !resp.witnesses.is_empty() {
10211×
                m.insert(
1022
                    7,
1023
                    Value::Array(
10241×
                        resp.witnesses
10251×
                            .iter()
10261×
                            .map(|(name, id)| {
10271×
                                Value::Array(vec![
10281×
                                    Value::Text(name.clone()),
10291×
                                    Value::Bytes(id.clone()),
10301×
                                ])
10311×
                            })
10321×
                            .collect(),
1033
                    ),
1034
                );
1035143×
            }
10360×
        }
1037144×
        cbor::encode(&v)
1038144×
    }
1039187×
    pub fn decode_refs(bytes: &[u8]) -> Result<([u8; 16], RefsResponse)> {
1040187×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
1041187×
        let m = map(&v, "refs")?;
1042187×
        let id: [u8; 16] = o::bytes(field(m, 1, "repo id")?, "repo id")?
1043187×
            .try_into()
1044187×
            .map_err(|_| schema("repo id: expected 16 bytes"))?;
1045187×
        let mut refs = Vec::new();
1046192×
        for r in o::array(field(m, 0, "refs")?, "refs")? {
1047192×
            let rm = map(r, "ref")?;
1048192×
            let ls = field(rm, 4, "last serial")?;
1049192×
            refs.push(RemoteRef {
1050192×
                name: o::text(field(rm, 0, "name")?, "name")?.to_owned(),
1051192×
                state: o::oref(field(rm, 1, "state")?, "state")?,
1052192×
                heads: hashes_from(field(rm, 2, "heads")?)?,
1053192×
                attestation: opt_attest_from(field(rm, 3, "attestation")?)?,
1054192×
                last_serial: if ls.is_null() {
1055175×
                    None
1056
                } else {
105717×
                    Some(o::uint(ls, "last serial")?)
1058
                },
1059192×
                accepted: match rm.get(&5) {
10600×
                    Some(a) => opt_attest_from(a)?,
1061192×
                    None => None,
1062
                },
1063192×
                logged: match rm.get(&6) {
10641×
                    Some(l) => {
10651×
                        let a = o::array(l, "logged")?;
10661×
                        if a.len() != 3 {
10670×
                            return Err(schema("logged: expected [index, entry, proof]"));
10681×
                        }
1069
                        Some(Logged {
10701×
                            index: o::uint(&a[0], "index")?,
10711×
                            entry: o::bytes(&a[1], "entry")?.to_vec(),
10721×
                            proof: proof_from(&a[2])?,
1073
                        })
1074
                    }
1075191×
                    None => None,
1076
                },
1077192×
                integration: match rm.get(&7) {
10781×
                    Some(l) => {
10791×
                        let mut out = Vec::new();
10801×
                        for i in o::array(l, "integration")? {
10811×
                            let a = o::array(i, "integration")?;
10821×
                            if a.len() != 2 {
10830×
                                return Err(schema("integration: expected [note, proof]"));
10841×
                            }
10851×
                            out.push(Integration {
10861×
                                note: o::text(&a[0], "note")?.to_owned(),
10871×
                                proof: proof_from(&a[1])?,
1088
                            });
1089
                        }
10901×
                        out
1091
                    }
1092191×
                    None => Vec::new(),
1093
                },
1094
            });
1095
        }
1096187×
        let policy = match m.get(&2) {
1097187×
            Some(p) => opt_policy_from(p)?,
10980×
            None => None,
1099
        };
1100187×
        let tags = match m.get(&3) {
1101187×
            Some(t) => tags_from(t)?,
11020×
            None => Vec::new(),
1103
        };
1104187×
        let mut history = Vec::new();
1105187×
        if let Some(h) = m.get(&4) {
1106187×
            for p in o::array(h, "history")? {
11072×
                history.push(policy_from(p)?);
1108
            }
11090×
        }
1110187×
        let default_bookmark = match m.get(&5) {
1111118×
            Some(Value::Text(t)) => Some(t.clone()),
111269×
            _ => None,
1113
        };
1114187×
        let log = match m.get(&6) {
11152×
            Some(Value::Text(t)) => Some(t.clone()),
1116185×
            _ => None,
1117
        };
1118187×
        let mut witnesses = Vec::new();
1119187×
        if let Some(w) = m.get(&7) {
11201×
            for x in o::array(w, "witnesses")? {
11211×
                let a = o::array(x, "witness")?;
11221×
                if a.len() != 2 {
11230×
                    return Err(schema("witness: expected [name, identity]"));
11241×
                }
11251×
                witnesses.push((
11261×
                    o::text(&a[0], "witness name")?.to_owned(),
11271×
                    o::bytes(&a[1], "witness identity")?.to_vec(),
1128
                ));
1129
            }
1130186×
        }
1131187×
        Ok((
1132187×
            id,
1133187×
            RefsResponse {
1134187×
                refs,
1135187×
                policy,
1136187×
                tags,
1137187×
                history,
1138187×
                default_bookmark,
1139187×
                log,
1140187×
                witnesses,
1141187×
            },
1142187×
        ))
1143187×
    }
1144
1145
    /// A proof's hashes, from the leaf upwards (spec §14.8).
11462×
    fn proof_value(proof: &[[u8; 32]]) -> Value {
11473×
        Value::Array(proof.iter().map(|h| Value::Bytes(h.to_vec())).collect())
11482×
    }
1149
11502×
    fn proof_from(v: &Value) -> Result<Vec<[u8; 32]>> {
11512×
        let mut proof = Vec::new();
11523×
        for h in o::array(v, "proof")? {
11533×
            proof.push(
11543×
                o::bytes(h, "proof hash")?
11553×
                    .try_into()
11563×
                    .map_err(|_| schema("proof hash: expected 32 bytes"))?,
1157
            );
1158
        }
11592×
        Ok(proof)
11602×
    }
1161
116246×
    pub fn encode_negotiate(have: &[ChangeHash], want: &[ChangeHash]) -> Vec<u8> {
116346×
        cbor::encode(&Value::map([
116446×
            (0, hashes_value(have)),
116546×
            (1, hashes_value(want)),
116646×
        ]))
116746×
    }
116846×
    pub fn decode_negotiate(bytes: &[u8]) -> Result<(Vec<ChangeHash>, Vec<ChangeHash>)> {
116946×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
117046×
        let m = map(&v, "negotiate")?;
1171
        Ok((
117246×
            hashes_from(field(m, 0, "have")?)?,
117346×
            hashes_from(field(m, 1, "want")?)?,
1174
        ))
117546×
    }
1176
1177
    /// `fetch` request: `{0: [changes], 1: max blob size or null}`.
117847×
    pub fn encode_fetch(hs: &[ChangeHash], max_blob: Option<u64>) -> Vec<u8> {
117947×
        cbor::encode(&Value::map([
118047×
            (0, hashes_value(hs)),
118147×
            (1, max_blob.map(Value::Uint).unwrap_or(Value::Null)),
118247×
        ]))
118347×
    }
118448×
    pub fn decode_fetch(bytes: &[u8]) -> Result<(Vec<ChangeHash>, Option<u64>)> {
118548×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
118648×
        let m = map(&v, "fetch")?;
118748×
        let max = match m.get(&1) {
118847×
            Some(x) if !x.is_null() => Some(o::uint(x, "max blob")?),
118946×
            _ => None,
1190
        };
119148×
        Ok((hashes_from(field(m, 0, "changes")?)?, max))
119248×
    }
1193
1194
    /// `shallow` request: `{0: [heads], 1: depth}`.
11951×
    pub fn encode_shallow(hs: &[ChangeHash], depth: u32) -> Vec<u8> {
11961×
        cbor::encode(&Value::map([
11971×
            (0, hashes_value(hs)),
11981×
            (1, Value::Uint(depth as u64)),
11991×
        ]))
12001×
    }
12011×
    pub fn decode_shallow(bytes: &[u8]) -> Result<(Vec<ChangeHash>, u32)> {
12021×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
12031×
        let m = map(&v, "shallow")?;
1204
        Ok((
12051×
            hashes_from(field(m, 0, "heads")?)?,
12061×
            o::u32_(field(m, 1, "depth")?, "depth")?,
1207
        ))
12081×
    }
1209
121048×
    pub fn encode_hashes(hs: &[ChangeHash]) -> Vec<u8> {
121148×
        cbor::encode(&Value::map([(0, hashes_value(hs))]))
121248×
    }
121347×
    pub fn decode_hashes(bytes: &[u8]) -> Result<Vec<ChangeHash>> {
121447×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
121547×
        hashes_from(field(map(&v, "hashes")?, 0, "hashes")?)
121647×
    }
1217
121836×
    pub fn encode_push(
121936×
        bundle: &Bundle,
122036×
        updates: &[RefUpdate],
122136×
        policy: Option<&SignedPolicy>,
122236×
        tags: &[TagRef],
122336×
    ) -> Vec<u8> {
122436×
        cbor::encode(&Value::map([
122536×
            (0, bundle_value(bundle)),
122636×
            (2, opt_policy_value(policy)),
122736×
            (3, tags_value(tags)),
1228
            (
1229
                1,
1230
                Value::Array(
123136×
                    updates
123236×
                        .iter()
123336×
                        .map(|u| {
123436×
                            Value::map([
123536×
                                (0, Value::Text(u.name.clone())),
123636×
                                (1, Value::Bytes(u.old_state.0.to_vec())),
123736×
                                (2, Value::Bytes(u.new_state.0.to_vec())),
123836×
                                (3, Value::Bool(u.force)),
123936×
                                (4, opt_attest_value(&u.attestation)),
124036×
                            ])
124136×
                        })
124236×
                        .collect(),
1243
                ),
1244
            ),
1245
        ]))
124636×
    }
1247
    /// A decoded push: bundle, bookmark updates, policy, tags.
1248
    pub type PushParts = (Bundle, Vec<RefUpdate>, Option<SignedPolicy>, Vec<TagRef>);
1249
125032×
    pub fn decode_push(bytes: &[u8]) -> Result<PushParts> {
125132×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
125232×
        let m = map(&v, "push")?;
125332×
        let bundle = bundle_from_value(field(m, 0, "bundle")?)?;
125432×
        let mut updates = Vec::new();
125532×
        for u in o::array(field(m, 1, "updates")?, "updates")? {
125632×
            let um = map(u, "update")?;
125732×
            updates.push(RefUpdate {
125832×
                name: o::text(field(um, 0, "name")?, "name")?.to_owned(),
125932×
                old_state: o::oref(field(um, 1, "old_state")?, "old_state")?,
126032×
                new_state: o::oref(field(um, 2, "new_state")?, "new_state")?,
126132×
                force: field(um, 3, "force")?
126232×
                    .as_bool()
126332×
                    .ok_or_else(|| schema("force: expected bool"))?,
126432×
                attestation: opt_attest_from(field(um, 4, "attestation")?)?,
1265
            });
1266
        }
126732×
        let policy = match m.get(&2) {
126832×
            Some(p) => opt_policy_from(p)?,
12690×
            None => None,
1270
        };
127132×
        let tags = match m.get(&3) {
127232×
            Some(t) => tags_from(t)?,
12730×
            None => Vec::new(),
1274
        };
127532×
        Ok((bundle, updates, policy, tags))
127632×
    }
1277
127832×
    pub fn encode_push_response(results: &[RefResult]) -> Vec<u8> {
127932×
        cbor::encode(&Value::map([(
1280
            0,
1281
            Value::Array(
128232×
                results
128332×
                    .iter()
128433×
                    .map(|r| {
128533×
                        Value::map([
128633×
                            (0, Value::Text(r.name.clone())),
128733×
                            (1, Value::Bool(r.ok)),
128833×
                            (2, Value::Text(r.reason.clone())),
128933×
                        ])
129033×
                    })
129132×
                    .collect(),
1292
            ),
1293
        )]))
129432×
    }
129532×
    pub fn decode_push_response(bytes: &[u8]) -> Result<Vec<RefResult>> {
129632×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
129732×
        let m = map(&v, "push response")?;
129832×
        let mut out = Vec::new();
129933×
        for r in o::array(field(m, 0, "results")?, "results")? {
130033×
            let rm = map(r, "result")?;
130133×
            out.push(RefResult {
130233×
                name: o::text(field(rm, 0, "name")?, "name")?.to_owned(),
130333×
                ok: field(rm, 1, "ok")?
130433×
                    .as_bool()
130533×
                    .ok_or_else(|| schema("ok: expected bool"))?,
130633×
                reason: o::text(field(rm, 2, "reason")?, "reason")?.to_owned(),
1307
            });
1308
        }
130932×
        Ok(out)
131032×
    }
1311
}
1312
1313
#[cfg(test)]
1314
mod tests {
1315
    use super::*;
1316
    use crate::attest::AttestBody;
1317
    use crate::objects::Hlc;
1318
1319
    #[test]
13201×
    fn wire_round_trips() {
13211×
        let c = crate::objects::tests::sample_change();
13221×
        let sk = crate::identity::SecretKey {
13231×
            ed_seed: [1; 32],
13241×
            ml_seed: [2; 32],
13251×
        };
13261×
        let id = sk.identity("a", "b", 0);
13271×
        let key = id.hash();
13281×
        let sig = sk.sign(crate::identity::Domain::Change, &key, &c.hash());
13291×
        let seal = Attest::seal([3; 16], vec![c.hash()]);
13301×
        let seal_sig = sk.sign(crate::identity::Domain::Attest, &key, &seal.hash());
13311×
        let policy = Policy::single_root([3; 16], id.clone(), 99);
13321×
        let psig = sk.sign(crate::identity::Domain::Policy, &key, &policy.hash());
13331×
        let bundle = Bundle {
13341×
            changes: vec![(c.clone(), vec![sig.clone()])],
13351×
            attests: vec![SignedAttest {
13361×
                attest: seal.clone(),
13371×
                sigs: vec![seal_sig],
13381×
            }],
13391×
            objects: vec![
13401×
                (ObjectType::Identity, id.encode()),
13411×
                (ObjectType::Chunk, b"xyz".to_vec()),
13421×
            ],
13431×
            policies: vec![SignedPolicy {
13441×
                policy: policy.clone(),
13451×
                sigs: vec![psig.clone()],
13461×
            }],
13471×
            hashes: vec![],
13481×
            raw_changes: vec![],
13491×
            certificates: vec![],
13501×
        };
13511×
        let d = wire::decode_bundle(&wire::encode_bundle(&bundle)).unwrap();
13521×
        assert_eq!(
1353
            d.hashes,
13541×
            vec![c.hash()],
1355
            "the receiver hashes what it was sent"
1356
        );
13571×
        assert_eq!(d.changes, bundle.changes);
13581×
        assert_eq!(d.attests, bundle.attests);
13591×
        assert_eq!(d.objects, bundle.objects);
13601×
        assert_eq!(d.policies, bundle.policies);
13611×
        assert!(d.certificates.is_empty());
1362
        // Certificates (keyless, oxygenhub#241) travel as field 4, only
1363
        // when there are any: a bundle without them encodes as before.
13641×
        let plain = wire::encode_bundle(&bundle);
13651×
        let mut with = bundle.clone();
13661×
        let issuer_sk = crate::identity::SecretKey::generate();
13671×
        let issuer = issuer_sk.identity("hub", "h@x", 1);
13681×
        with.certificates.push(crate::cert::SignedCertificate::sign(
13691×
            crate::cert::Certificate {
13701×
                key: id.clone(),
13711×
                issuer: issuer.hash(),
13721×
                subject: "agent:a@b".into(),
13731×
                claims: vec![],
13741×
                scope: crate::identity::Scope::CHANGES,
13751×
                not_before: 1,
13761×
                expires: 2,
13771×
                grant: None,
13781×
            },
13791×
            &issuer,
13801×
            &issuer_sk,
1381
        ));
13821×
        let encoded = wire::encode_bundle(&with);
13831×
        assert_ne!(encoded, plain);
13841×
        assert_eq!(
13851×
            wire::decode_bundle(&encoded).unwrap().certificates,
1386
            with.certificates
1387
        );
13881×
        with.certificates.clear();
13891×
        assert_eq!(wire::encode_bundle(&with), plain);
1390
13911×
        let att = Attest {
13921×
            repo: [3; 16],
13931×
            hlc: Hlc::default(),
13941×
            body: AttestBody::Ref {
13951×
                name: "main".into(),
13961×
                old_state: ObjectRef([1; 32]),
13971×
                new_state: ObjectRef([2; 32]),
13981×
                serial: 4,
13991×
            },
14001×
        };
14011×
        let refs = vec![
14021×
            RemoteRef {
14031×
                name: "main".into(),
14041×
                state: ObjectRef([2; 32]),
14051×
                heads: vec![c.hash()],
14061×
                attestation: Some(SignedAttest {
14071×
                    attest: att.clone(),
14081×
                    sigs: vec![sig.clone()],
14091×
                }),
14101×
                last_serial: Some(4),
14111×
                accepted: None,
14121×
                logged: None,
14131×
                integration: vec![],
14141×
            },
14151×
            RemoteRef {
14161×
                name: "dev".into(),
14171×
                state: ObjectRef([5; 32]),
14181×
                heads: vec![],
14191×
                attestation: None,
14201×
                last_serial: None,
14211×
                accepted: None,
14221×
                logged: None,
14231×
                integration: vec![],
14241×
            },
1425
        ];
14261×
        let tag = TagRef {
14271×
            name: "v1".into(),
14281×
            state: ObjectRef([2; 32]),
14291×
            heads: vec![c.hash()],
14301×
            attestation: None,
14311×
        };
14321×
        let mut resp = RefsResponse {
14331×
            refs,
14341×
            policy: Some(SignedPolicy {
14351×
                policy: policy.clone(),
14361×
                sigs: vec![psig.clone()],
14371×
            }),
14381×
            tags: vec![tag.clone()],
14391×
            history: vec![SignedPolicy {
14401×
                policy: policy.clone(),
14411×
                sigs: vec![],
14421×
            }],
14431×
            default_bookmark: Some("develop".into()),
14441×
            log: Some("hub.example/log\n2\nroot\n\n- sig\n".into()),
14451×
            witnesses: vec![],
14461×
        };
1447
        // Without integrated times (spec §14.8) nothing is added: an old
1448
        // peer's answer, and what it reads.
14491×
        let old = wire::encode_refs([3; 16], &resp);
14501×
        let back = wire::decode_refs(&old).unwrap().1;
14512×
        assert!(back.witnesses.is_empty() && back.refs.iter().all(|r| r.integration.is_empty()));
14521×
        resp.refs[1].logged = Some(Logged {
14531×
            index: 41,
14541×
            entry: vec![1, 2, 3],
14551×
            proof: vec![[9; 32], [8; 32]],
14561×
        });
14571×
        resp.refs[1].integration = vec![Integration {
14581×
            note: "hub.example/log\n42\nroot\n\n- sig\n".into(),
14591×
            proof: vec![[7; 32]],
14601×
        }];
14611×
        resp.witnesses = vec![("w.example".into(), vec![4, 5, 6])];
14621×
        let new = wire::encode_refs([3; 16], &resp);
14631×
        let (id_back, back) = wire::decode_refs(&new).unwrap();
14641×
        assert_eq!(back.log, resp.log);
14651×
        assert_eq!(back.refs[1].logged, resp.refs[1].logged);
14661×
        assert_eq!(back.refs[1].integration, resp.refs[1].integration);
14671×
        assert_eq!(back.witnesses, resp.witnesses);
14681×
        assert_eq!(back.refs[0].logged, None);
1469
        // The new keys are 7s an old reader never asks for.
14701×
        let crate::cbor::Value::Map(m) = crate::cbor::decode(&new).unwrap() else {
14710×
            panic!()
1472
        };
14731×
        assert!(m.contains_key(&7));
14741×
        assert_eq!(id_back, [3; 16]);
14751×
        assert_eq!(back.refs.len(), 2);
14761×
        assert_eq!(back.refs[0].attestation.as_ref().unwrap().attest, att);
14771×
        assert_eq!(back.refs[1].last_serial, None);
14781×
        assert_eq!(back.policy.as_ref().unwrap().policy, policy);
14791×
        assert_eq!(back.history, resp.history);
14801×
        assert_eq!(back.tags, vec![tag.clone()]);
1481
14821×
        let (h, w) = wire::decode_negotiate(&wire::encode_negotiate(
14831×
            &[ObjectRef([1; 32])],
14841×
            &[ObjectRef([2; 32])],
14851×
        ))
14861×
        .unwrap();
14871×
        assert_eq!((h, w), (vec![ObjectRef([1; 32])], vec![ObjectRef([2; 32])]));
14881×
        assert_eq!(
14891×
            wire::decode_hashes(&wire::encode_hashes(&[c.hash()])).unwrap(),
14901×
            vec![c.hash()]
1491
        );
14921×
        assert_eq!(
14931×
            wire::decode_fetch(&wire::encode_fetch(&[c.hash()], Some(4096))).unwrap(),
14941×
            (vec![c.hash()], Some(4096))
1495
        );
14961×
        assert_eq!(
14971×
            wire::decode_fetch(&wire::encode_fetch(&[], None)).unwrap(),
14981×
            (vec![], None)
1499
        );
15001×
        assert_eq!(
15011×
            wire::decode_shallow(&wire::encode_shallow(&[c.hash()], 3)).unwrap(),
15021×
            (vec![c.hash()], 3)
1503
        );
1504
        // An old-style fetch request without the filter field still decodes.
15051×
        assert_eq!(
15061×
            wire::decode_fetch(&wire::encode_hashes(&[c.hash()])).unwrap(),
15071×
            (vec![c.hash()], None)
1508
        );
1509
15101×
        let up = RefUpdate {
15111×
            name: "main".into(),
15121×
            old_state: ObjectRef([1; 32]),
15131×
            new_state: ObjectRef([2; 32]),
15141×
            force: true,
15151×
            attestation: Some(SignedAttest {
15161×
                attest: att,
15171×
                sigs: vec![sig],
15181×
            }),
15191×
        };
15201×
        let sp = SignedPolicy {
15211×
            policy,
15221×
            sigs: vec![psig],
15231×
        };
15241×
        let (b2, ups, pol, tags) = wire::decode_push(&wire::encode_push(
15251×
            &bundle,
15261×
            std::slice::from_ref(&up),
15271×
            Some(&sp),
15281×
            std::slice::from_ref(&tag),
15291×
        ))
15301×
        .unwrap();
15311×
        assert_eq!(pol, Some(sp));
15321×
        assert_eq!(tags, vec![tag]);
15331×
        assert_eq!(b2.changes.len(), 1);
15341×
        assert_eq!(ups[0].name, "main");
15351×
        assert!(ups[0].force);
15361×
        assert_eq!(ups[0].attestation, up.attestation);
15371×
        let res = vec![RefResult {
15381×
            name: "main".into(),
15391×
            ok: false,
15401×
            reason: "stale".into(),
15411×
        }];
15421×
        assert_eq!(
15431×
            wire::decode_push_response(&wire::encode_push_response(&res)).unwrap(),
1544
            res
1545
        );
15461×
        assert_eq!(
15471×
            wire::decode_capabilities(&wire::encode_capabilities([7; 16])).unwrap(),
1548
            [7; 16]
1549
        );
15501×
    }
1551
}