OXYGENHUB

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

1056 of 1212 lines run, 169 of 253 functions · run #364 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
    /// The acceptance of `attestation` by its signer's certificate issuer
96
    /// when a short-lived key signed it (spec §14.7; key 4, only when there
97
    /// is one): the time a fetch checks the certificate at.
98
    pub accepted: Option<SignedAttest>,
99
    /// The attestation's place in the host's transparency log (key 5,
100
    /// only when it has one), as a bookmark's.
101
    pub logged: Option<Logged>,
102
    /// The cosigned checkpoints that first included `logged`'s entry (key
103
    /// 6, only when there are any).
104
    pub integration: Vec<Integration>,
105
}
106
107
impl TagRef {
108
    /// A tag with no acceptance or log place (yet).
109120×
    pub fn new(
110120×
        name: String,
111120×
        state: ObjectRef,
112120×
        heads: Vec<ChangeHash>,
113120×
        attestation: Option<SignedAttest>,
114120×
    ) -> TagRef {
115120×
        TagRef {
116120×
            name,
117120×
            state,
118120×
            heads,
119120×
            attestation,
120120×
            accepted: None,
121120×
            logged: None,
122120×
            integration: vec![],
123120×
        }
124120×
    }
125
}
126
127
/// One reference as a remote reports it.
128
#[derive(Clone, Debug)]
129
pub struct RemoteRef {
130
    pub name: String,
131
    pub state: ObjectRef,
132
    pub heads: Vec<ChangeHash>,
133
    /// The latest attestation, only when it describes `state`. An unattested
134
    /// push (accepted while no trust policy exists) leaves it `None`.
135
    pub attestation: Option<SignedAttest>,
136
    /// Serial of the latest attestation ever recorded, stale or not, so the
137
    /// next attestation continues the sequence.
138
    pub last_serial: Option<u64>,
139
    /// The host's acceptance of `attestation` when a short-lived key signed
140
    /// it (spec §14.7): the time its certificate is checked at.
141
    pub accepted: Option<SignedAttest>,
142
    /// The attestation's place in the host's transparency log (key 6, only
143
    /// when it has one).
144
    pub logged: Option<Logged>,
145
    /// The cosigned checkpoints that first included `logged`'s entry (key
146
    /// 7, only when there are any): what its integrated time is read from.
147
    pub integration: Vec<Integration>,
148
}
149
150
/// Everything needed to add a set of changes to a repository.
151
#[derive(Clone, Debug, Default)]
152
pub struct Bundle {
153
    /// In dependency order, each with its individual signatures.
154
    pub changes: Vec<(Change, Vec<Signature>)>,
155
    /// Seals covering the changes.
156
    pub attests: Vec<SignedAttest>,
157
    /// Chunks, blobs, identities, and state objects referenced by the changes.
158
    pub objects: Vec<(ObjectType, Vec<u8>)>,
159
    /// Policies between the receiver's and the one sent with the push,
160
    /// ascending by serial (spec §14.5).
161
    pub policies: Vec<SignedPolicy>,
162
    /// Each change's hash, in the order of `changes`, when whoever made
163
    /// the bundle knows it: the store it came from, or the bytes it was
164
    /// decoded from. Never read from the wire. Empty when unknown.
165
    pub hashes: Vec<ChangeHash>,
166
    /// Changes as stored, with their signatures, in dependency order, for a
167
    /// fetch between repositories on one machine: their text blobs and
168
    /// chunks are among `objects`. Never on the wire.
169
    pub raw_changes: Vec<(Vec<u8>, Vec<Signature>)>,
170
    /// Certificates of short-lived keys that signed what the bundle carries
171
    /// (spec §14.7), their issuers' identities among `objects`.
172
    pub certificates: Vec<crate::cert::SignedCertificate>,
173
}
174
175
impl Bundle {
17627×
    pub fn is_empty(&self) -> bool {
17727×
        self.changes.is_empty() && self.attests.is_empty() && self.objects.is_empty()
17827×
    }
179
}
180
181
/// A requested bookmark move (spec §10.2, §16.3).
182
#[derive(Clone, Debug)]
183
pub struct RefUpdate {
184
    pub name: String,
185
    pub old_state: ObjectRef,
186
    pub new_state: ObjectRef,
187
    pub force: bool,
188
    pub attestation: Option<SignedAttest>,
189
}
190
191
#[derive(Clone, Debug, PartialEq, Eq)]
192
pub struct RefResult {
193
    pub name: String,
194
    pub ok: bool,
195
    pub reason: String,
196
}
197
198
pub trait Remote {
199
    fn repo_id(&self) -> Result<[u8; 16]>;
200
    fn refs(&self) -> Result<RefsResponse>;
201
    /// Changes in the closure of `want` but not of `have`, in dependency order.
202
    fn negotiate(&self, have: &[ChangeHash], want: &[ChangeHash]) -> Result<Vec<ChangeHash>>;
203
    /// The changes with their signatures, seals, identities, and blobs; blobs
204
    /// larger than `max_blob` bytes are left out for lazy fetching (spec §13.5).
205
    fn fetch(&self, changes: &[ChangeHash], max_blob: Option<u64>) -> Result<Bundle>;
206
    /// Individual objects by reference (spec §16.1 `objects`); a blob comes
207
    /// with its chunks.
208
    fn objects(&self, refs: &[ObjectRef]) -> Result<Vec<(ObjectType, Vec<u8>)>>;
209
    /// A checkpoint of exactly `heads` (spec §16.1 `checkpoint`): the
210
    /// checkpoint object, its payload blob, and the blob's chunks.
211
    fn checkpoint(&self, heads: &[ChangeHash]) -> Result<Bundle>;
212
    /// The changes within `depth` dependency steps of `heads` (spec §17).
213
    fn shallow(&self, heads: &[ChangeHash], depth: u32) -> Result<Vec<ChangeHash>>;
214
    /// Push changes, bookmark updates, new tags, and optionally a newer
215
    /// policy. The policy is applied first; a result named `policy` reports
216
    /// it, and each tag reports as `tags/<name>`.
217
    fn push(
218
        &self,
219
        bundle: Bundle,
220
        updates: Vec<RefUpdate>,
221
        policy: Option<SignedPolicy>,
222
        tags: Vec<TagRef>,
223
    ) -> Result<Vec<RefResult>>;
224
}
225
226
// ---------------------------------------------------------------- local
227
228
/// Another repository on this machine, served in-process.
229
pub struct LocalRemote {
230
    pub repo: Repo,
231
    /// The pushing repository's id, which binds an unbound target on the
232
    /// first push, as `Oxy-Repo-Id` does over HTTP.
233
    pub claimed_id: Option<[u8; 16]>,
234
}
235
236
impl LocalRemote {
2371132×
    pub fn open(path: &Path) -> Result<LocalRemote> {
238
        Ok(LocalRemote {
2391132×
            repo: Repo::open(path)?,
2401132×
            claimed_id: None,
241
        })
2421132×
    }
243
}
244
245
impl Remote for LocalRemote {
246890×
    fn repo_id(&self) -> Result<[u8; 16]> {
247890×
        self.repo.id()
248890×
    }
249888×
    fn refs(&self) -> Result<RefsResponse> {
250888×
        self.repo.remote_refs()
251888×
    }
252353×
    fn negotiate(&self, have: &[ChangeHash], want: &[ChangeHash]) -> Result<Vec<ChangeHash>> {
253353×
        self.repo.negotiate(have, want)
254353×
    }
255357×
    fn fetch(&self, changes: &[ChangeHash], max_blob: Option<u64>) -> Result<Bundle> {
256357×
        self.repo.bundle_raw_for(changes, max_blob)
257357×
    }
2583×
    fn objects(&self, refs: &[ObjectRef]) -> Result<Vec<(ObjectType, Vec<u8>)>> {
2593×
        self.repo.objects_for(refs)
2603×
    }
2611×
    fn checkpoint(&self, heads: &[ChangeHash]) -> Result<Bundle> {
2621×
        self.repo.checkpoint_bundle_for(heads)
2631×
    }
2643×
    fn shallow(&self, heads: &[ChangeHash], depth: u32) -> Result<Vec<ChangeHash>> {
2653×
        self.repo.shallow_changes(heads, depth)
2663×
    }
267267×
    fn push(
268267×
        &self,
269267×
        bundle: Bundle,
270267×
        updates: Vec<RefUpdate>,
271267×
        policy: Option<SignedPolicy>,
272267×
        tags: Vec<TagRef>,
273267×
    ) -> Result<Vec<RefResult>> {
274267×
        if self.repo.is_unbound() {
27513×
            match self.claimed_id {
27613×
                Some(id) => self.repo.bind_id(id)?,
277
                None => {
2780×
                    return Err(RepoError::Msg(
2790×
                        "the remote is unbound and this client did not say which repository it is"
2800×
                            .into(),
2810×
                    ))
282
                }
283
            }
284254×
        }
285267×
        self.repo.receive_push(bundle, updates, policy, tags)
286267×
    }
287
}
288
289
// ---------------------------------------------------------------- http
290
291
/// How to reach a remote: credentials and trust.
292
#[derive(Clone, Debug, Default)]
293
pub struct RemoteOptions {
294
    /// Bearer token for pushes.
295
    pub token: Option<String>,
296
    /// PEM file with extra root certificates to trust for `https://` remotes
297
    /// (self-hosted servers); the system web roots are always trusted.
298
    pub ca: Option<PathBuf>,
299
    /// The local repository's id, sent as `Oxy-Repo-Id` so an unbound
300
    /// hosted repository can adopt it on the first push (spec §16.1).
301
    pub repo_id: Option<[u8; 16]>,
302
    /// Where a remote kept on a store (`dir://`, `s3://`, …) keeps its
303
    /// mirror and what it has seen: the remote's directory under
304
    /// `.oxy/remotes`. None (a clone, before there is a repository) means
305
    /// a temporary directory.
306
    pub cache_dir: Option<PathBuf>,
307
    /// Other tokens for the same hub, tried in turn when `token` is
308
    /// refused (401, 403 or 404): those of enclosing checkouts, when
309
    /// `token` came from the credential store rather than from this
310
    /// remote's own configuration (oxygen#112).
311
    pub fallback_tokens: Vec<String>,
312
}
313
314
/// Opens a store for a URL it understands, or passes (`None`). Stores that
315
/// need more than the standard library (the cloud ones) are added by the
316
/// program that links them, with [`register_store_opener`].
317
pub type StoreOpener =
318
    fn(&str, &RemoteOptions) -> Option<crate::strata::Result<Box<dyn crate::strata::Store>>>;
319
320
static STORE_OPENERS: Mutex<Vec<StoreOpener>> = Mutex::new(Vec::new());
321
322155×
pub fn register_store_opener(opener: StoreOpener) {
323155×
    STORE_OPENERS
324155×
        .lock()
325155×
        .unwrap_or_else(|p| p.into_inner())
326155×
        .push(opener);
327155×
}
328
329
/// A store for `url`, from `dir://` or any registered opener.
3301191×
pub fn open_store(
3311191×
    url: &str,
3321191×
    options: &RemoteOptions,
3331191×
) -> Option<crate::strata::Result<Box<dyn crate::strata::Store>>> {
3341191×
    if let Some(path) = url.strip_prefix("dir://") {
335
        return Some(
33659×
            crate::strata::LocalStore::open(path)
33759×
                .map(|s| Box::new(s) as Box<dyn crate::strata::Store>),
338
        );
3391132×
    }
3401132×
    let openers = STORE_OPENERS.lock().unwrap_or_else(|p| p.into_inner());
3411132×
    openers.iter().find_map(|open| open(url, options))
3421191×
}
343
344
/// The request header carrying the client's repository id.
345
pub const REPO_ID_HEADER: &str = "Oxy-Repo-Id";
346
347
/// The id of a hosted repository that has not adopted one yet.
348
pub const UNBOUND_ID: [u8; 16] = [0; 16];
349
350
/// The request header in which a client declares the protocol features it
351
/// understands beyond the 0.5.0-era set: a comma-separated list, which a
352
/// server may tailor its answers to (docs/protocol.md, *Client
353
/// capabilities*). A request without it is a client of that era.
354
pub const FEATURES_HEADER: &str = "Oxy-Features";
355
356
/// The feature of a client that authorizes a tag signed by a short-lived,
357
/// certified key by its certificate at the time the host accepted it
358
/// (oxygen#129). A client without it refuses such a tag, and with it the
359
/// whole fetch, so servers leave those tags out of its `refs` (oxygen#131).
360
pub const FEATURE_CERTIFIED_TAGS: &str = "certified-tags";
361
362
/// The features this client declares in [`FEATURES_HEADER`].
363
pub const CLIENT_FEATURES: &[&str] = &[FEATURE_CERTIFIED_TAGS];
364
365
/// The `User-Agent` every request of this client sends: `oxy/<version>`.
366176×
pub fn user_agent() -> String {
367176×
    format!("oxy/{}", env!("CARGO_PKG_VERSION"))
368176×
}
369
370
/// Whether a [`FEATURES_HEADER`] value (absent: `None`) declares `feature`.
371
/// Entries are comma-separated, compared without surrounding blanks and
372
/// regardless of case; unknown ones are ignored.
373147×
pub fn declares_feature(header: Option<&str>, feature: &str) -> bool {
374147×
    header.is_some_and(|h| h.split(',').any(|f| f.trim().eq_ignore_ascii_case(feature)))
375147×
}
376
377
/// A remote served by `oxy-server` at `<base>/oxy/v1/...`.
378
pub struct HttpRemote {
379
    base: String,
380
    /// The token in use, and those still to try when it is refused.
381
    token: Mutex<Option<String>>,
382
    fallbacks: Mutex<Vec<String>>,
383
    repo_id: Option<[u8; 16]>,
384
    agent: ureq::Agent,
385
}
386
387
/// A TLS client configuration trusting the web roots plus `ca`, if given:
388
/// the trust every oxy connection uses, shared with tools that call hub APIs.
389179×
pub fn tls_client_config(ca: Option<&Path>) -> Result<Arc<rustls::ClientConfig>> {
390179×
    let mut roots = rustls::RootCertStore::empty();
391179×
    roots.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
392179×
    if let Some(path) = ca {
3939×
        let pem = std::fs::read(path)
3949×
            .map_err(|e| RepoError::Msg(format!("reading CA file {}: {e}", path.display())))?;
3959×
        let certs = rustls_pemfile::certs(&mut pem.as_slice())
3969×
            .collect::<std::result::Result<Vec<_>, _>>()
3979×
            .map_err(|e| RepoError::Msg(format!("parsing CA file {}: {e}", path.display())))?;
3989×
        if certs.is_empty() {
3990×
            return Err(RepoError::Msg(format!(
4000×
                "CA file {} holds no certificates",
4010×
                path.display()
4020×
            )));
4039×
        }
4049×
        for c in certs {
4059×
            roots
4069×
                .add(c)
4079×
                .map_err(|e| RepoError::Msg(format!("CA file {}: {e}", path.display())))?;
408
        }
409170×
    }
410179×
    let cfg = rustls::ClientConfig::builder_with_provider(Arc::new(
411179×
        rustls::crypto::ring::default_provider(),
412
    ))
413179×
    .with_safe_default_protocol_versions()
414179×
    .map_err(|e| RepoError::Msg(e.to_string()))?
415179×
    .with_root_certificates(roots)
416179×
    .with_no_client_auth();
417179×
    Ok(Arc::new(cfg))
418179×
}
419
420
impl HttpRemote {
421173×
    pub fn new(base: &str, options: &RemoteOptions) -> Result<HttpRemote> {
422173×
        refuse_plain_token(base, options)?;
423173×
        let agent = ureq::AgentBuilder::new()
424173×
            .tls_config(tls_client_config(options.ca.as_deref())?)
425173×
            .user_agent(&user_agent())
426173×
            .build();
427173×
        Ok(HttpRemote {
428173×
            base: base.trim_end_matches('/').to_string(),
429173×
            token: Mutex::new(options.token.clone()),
430173×
            fallbacks: Mutex::new(options.fallback_tokens.iter().rev().cloned().collect()),
431173×
            repo_id: options.repo_id,
432173×
            agent,
433173×
        })
434173×
    }
435
436
    /// A request, tried again with the next fallback token while the
437
    /// hub refuses the one in use (oxygen#112).
438434×
    fn call(&self, post: bool, endpoint: &str, body: Option<&[u8]>) -> Result<Vec<u8>> {
439
        loop {
440435×
            let token = self.token.lock().unwrap_or_else(|p| p.into_inner()).clone();
441435×
            match self.call_once(post, endpoint, body, token.as_deref()) {
44212×
                Err(RepoError::Msg(m)) if token.is_some() && refused(&m) => {
4433×
                    let next = self
4443×
                        .fallbacks
4453×
                        .lock()
4463×
                        .unwrap_or_else(|p| p.into_inner())
4473×
                        .pop();
4483×
                    let Some(next) = next else {
4492×
                        return Err(RepoError::Msg(m));
450
                    };
4511×
                    crate::credentials::warn_once(&format!(
4521×
                        "{}: the stored token was refused; using the one an enclosing checkout has for this hub",
4531×
                        self.base
4541×
                    ));
4551×
                    *self.token.lock().unwrap_or_else(|p| p.into_inner()) = Some(next);
456
                }
457432×
                other => return other,
458
            }
459
        }
460434×
    }
461
462435×
    fn call_once(
463435×
        &self,
464435×
        post: bool,
465435×
        endpoint: &str,
466435×
        body: Option<&[u8]>,
467435×
        token: Option<&str>,
468435×
    ) -> Result<Vec<u8>> {
469435×
        let url = format!("{}/oxy/v1/{endpoint}", self.base);
470435×
        let mut req = if post {
471150×
            self.agent.post(&url)
472
        } else {
473285×
            self.agent.get(&url)
474
        };
475435×
        req = req
476435×
            .set("Accept", CONTENT_TYPE)
477435×
            .set(FEATURES_HEADER, &CLIENT_FEATURES.join(","));
478435×
        if let Some(t) = token {
47922×
            req = req.set("Authorization", &format!("Bearer {t}"));
480413×
        }
481435×
        if let Some(id) = &self.repo_id {
482404×
            req = req.set(REPO_ID_HEADER, &hex::encode(id));
483404×
        }
484435×
        let resp = match body {
485150×
            Some(b) => req.set("Content-Type", CONTENT_TYPE).send_bytes(b),
486285×
            None => req.call(),
487
        };
48812×
        match resp {
489423×
            Ok(r) => {
490423×
                let mut out = Vec::new();
491423×
                r.into_reader()
492423×
                    .read_to_end(&mut out)
493423×
                    .map_err(|e| RepoError::Msg(format!("{url}: {e}")))?;
494423×
                Ok(out)
495
            }
4969×
            Err(ureq::Error::Status(code, r)) => {
4979×
                let text = r.into_string().unwrap_or_default();
498
                // The hint comes from the status alone: the server's text
499
                // (a host's reason for refusing a push, several lines
500
                // perhaps) is shown as it is, never read for hints.
5019×
                let status = format!("{url}: HTTP {code}");
5029×
                let msg = format!("{status}: {}", text.trim());
5039×
                Err(RepoError::Msg(match hint_for(&status) {
5048×
                    Some(h) => format!("{msg}\n  hint: {h}"),
5051×
                    None => msg,
506
                }))
507
            }
508
            // The transport error already names the URL.
5093×
            Err(e) => Err(RepoError::Msg(with_hint(e.to_string()))),
510
        }
511435×
    }
512
}
513
514
/// Whether a failed request's message says the hub refused its token:
515
/// HTTP 401, 403, or 404 (a hub hides a private repository from a token
516
/// that may not read it).
5174×
fn refused(message: &str) -> bool {
5184×
    [": HTTP 401", ": HTTP 403", ": HTTP 404"]
5194×
        .iter()
5206×
        .any(|c| message.contains(c))
5214×
}
522
523
/// Refuse to send a token where anyone on the way could read it: plain
524
/// `http` to another machine (see [`crate::credentials::token_allowed`]).
525175×
fn refuse_plain_token(url: &str, options: &RemoteOptions) -> Result<()> {
526175×
    if options.token.is_some() && !crate::credentials::token_allowed(url) {
5270×
        return Err(RepoError::Msg(format!(
5280×
            "{url}: refusing to send a token over plain http; use https"
5290×
        )));
530175×
    }
531175×
    Ok(())
532175×
}
533
534
/// What to do about a failed request, recognised from its message.
53520×
pub fn hint_for(message: &str) -> Option<&'static str> {
53620×
    let m = message.to_ascii_lowercase();
53720×
    let hint = if m.contains("http 401") {
5386×
        "the hub needs you signed in, or did not accept the token: run `oxy auth login HUB` (pushing needs repo:write)"
53914×
    } else if m.contains("http 403") {
5401×
        "the token or account lacks permission: pushing needs a token with repo:write and write access to the repository"
54113×
    } else if m.contains("http 404") {
5424×
        "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`)"
5439×
    } else if m.contains("unknownissuer")
5447×
        || m.contains("unknown issuer")
5457×
        || m.contains("certificate")
5466×
        || m.contains("invalidcertificate")
547
    {
5483×
        "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`"
5496×
    } else if m.contains("connection refused") {
5503×
        "nothing is listening there: check the URL and port, and that the server is running"
5513×
    } else if m.contains("dns")
5522×
        || m.contains("failed to lookup")
5532×
        || m.contains("name or service not known")
554
    {
5551×
        "the host name does not resolve: check the URL"
5562×
    } else if m.contains("timed out") || m.contains("timeout") {
5570×
        "the server did not answer in time: check the network, or try again"
558
    } else {
5592×
        return None;
560
    };
56118×
    Some(hint)
56220×
}
563
564
/// `message`, followed by what to do about it when that is known.
5653×
pub fn with_hint(message: String) -> String {
5663×
    match hint_for(&message) {
5673×
        Some(h) => format!("{message}\n  hint: {h}"),
5680×
        None => message,
569
    }
5703×
}
571
572
/// A JSON request to a hub API (`GET`, `POST` or `DELETE`), with the same
573
/// TLS trust and token rules as remotes. Returns the status and body, an
574
/// error status included; only transport failures are errors.
5750×
pub fn http_json(
5760×
    method: &str,
5770×
    url: &str,
5780×
    body: Option<&str>,
5790×
    options: &RemoteOptions,
5800×
) -> Result<(u16, String)> {
5810×
    refuse_plain_token(url, options)?;
5820×
    let agent = ureq::AgentBuilder::new()
5830×
        .tls_config(tls_client_config(options.ca.as_deref())?)
5840×
        .timeout(std::time::Duration::from_secs(60))
5850×
        .user_agent(&user_agent())
5860×
        .build();
5870×
    let mut req = agent.request(method, url).set("Accept", "application/json");
5880×
    if let Some(t) = &options.token {
5890×
        req = req.set("Authorization", &format!("Bearer {t}"));
5900×
    }
5910×
    let resp = match body {
5920×
        Some(b) => req.set("Content-Type", "application/json").send_string(b),
5930×
        None => req.call(),
594
    };
5950×
    match resp {
5960×
        Ok(r) => {
5970×
            let code = r.status();
5980×
            Ok((code, r.into_string().unwrap_or_default()))
599
        }
6000×
        Err(ureq::Error::Status(code, r)) => Ok((code, r.into_string().unwrap_or_default())),
6010×
        Err(e) => Err(RepoError::Msg(with_hint(e.to_string()))),
602
    }
6030×
}
604
605
/// An authenticated GET of any URL on a host, with the same TLS trust and
606
/// token as remotes use (for hub APIs: proposals). Returns the body.
6072×
pub fn http_get(url: &str, options: &RemoteOptions) -> Result<Vec<u8>> {
6082×
    refuse_plain_token(url, options)?;
6092×
    let agent = ureq::AgentBuilder::new()
6102×
        .tls_config(tls_client_config(options.ca.as_deref())?)
6112×
        .user_agent(&user_agent())
6122×
        .build();
6132×
    let mut req = agent.get(url).set("Accept", "application/json");
6142×
    if let Some(t) = &options.token {
6150×
        req = req.set("Authorization", &format!("Bearer {t}"));
6162×
    }
6172×
    match req.call() {
6182×
        Ok(r) => {
6192×
            let mut out = Vec::new();
6202×
            r.into_reader()
6212×
                .read_to_end(&mut out)
6222×
                .map_err(|e| RepoError::Msg(format!("{url}: {e}")))?;
6232×
            Ok(out)
624
        }
6250×
        Err(ureq::Error::Status(code, r)) => {
6260×
            let text = r.into_string().unwrap_or_default();
6270×
            Err(RepoError::Msg(with_hint(format!(
6280×
                "{url}: HTTP {code}: {}",
6290×
                text.trim()
6300×
            ))))
631
        }
632
        // The transport error already names the URL.
6330×
        Err(e) => Err(RepoError::Msg(with_hint(e.to_string()))),
634
    }
6352×
}
636
637
impl Remote for HttpRemote {
638146×
    fn repo_id(&self) -> Result<[u8; 16]> {
639146×
        wire::decode_capabilities(&self.call(false, "capabilities", None)?)
640146×
    }
641139×
    fn refs(&self) -> Result<RefsResponse> {
642139×
        Ok(wire::decode_refs(&self.call(false, "refs", None)?)?.1)
643139×
    }
64454×
    fn negotiate(&self, have: &[ChangeHash], want: &[ChangeHash]) -> Result<Vec<ChangeHash>> {
64554×
        wire::decode_hashes(&self.call(
646
            true,
64754×
            "negotiate",
64854×
            Some(&wire::encode_negotiate(have, want)),
6490×
        )?)
65054×
    }
65154×
    fn fetch(&self, changes: &[ChangeHash], max_blob: Option<u64>) -> Result<Bundle> {
65254×
        wire::decode_bundle(&self.call(
653
            true,
65454×
            "fetch",
65554×
            Some(&wire::encode_fetch(changes, max_blob)),
6560×
        )?)
65754×
    }
6581×
    fn objects(&self, refs: &[ObjectRef]) -> Result<Vec<(ObjectType, Vec<u8>)>> {
659
        Ok(
6601×
            wire::decode_bundle(&self.call(true, "objects", Some(&wire::encode_hashes(refs)))?)?
661
                .objects,
662
        )
6631×
    }
6640×
    fn checkpoint(&self, heads: &[ChangeHash]) -> Result<Bundle> {
6650×
        wire::decode_bundle(&self.call(true, "checkpoint", Some(&wire::encode_hashes(heads)))?)
6660×
    }
6670×
    fn shallow(&self, heads: &[ChangeHash], depth: u32) -> Result<Vec<ChangeHash>> {
6680×
        wire::decode_hashes(&self.call(
669
            true,
6700×
            "shallow",
6710×
            Some(&wire::encode_shallow(heads, depth)),
6720×
        )?)
6730×
    }
67440×
    fn push(
67540×
        &self,
67640×
        bundle: Bundle,
67740×
        updates: Vec<RefUpdate>,
67840×
        policy: Option<SignedPolicy>,
67940×
        tags: Vec<TagRef>,
68040×
    ) -> Result<Vec<RefResult>> {
68140×
        wire::decode_push_response(&self.call(
682
            true,
68340×
            "push",
68440×
            Some(&wire::encode_push(
68540×
                &bundle,
68640×
                &updates,
68740×
                policy.as_ref(),
68840×
                &tags,
68940×
            )),
6905×
        )?)
69140×
    }
692
}
693
694
/// A remote's URL as it is stored: an `http(s)://` URL as given, a local
695
/// path made absolute (with its `file://` kept), so it still names the same
696
/// repository from inside the clone (oxygen#57).
697277×
pub fn stored_url(url: &str) -> String {
698
    // Only a path is made absolute: a plain one, or one behind file:// or
699
    // dir://. Every other URL (a hub, a bucket) is kept as written.
700277×
    let (prefix, path) = match (url.strip_prefix("file://"), url.strip_prefix("dir://")) {
7011×
        (Some(p), _) => ("file://", p),
70211×
        (_, Some(p)) => ("dir://", p),
703265×
        _ if url.contains("://") => return url.to_string(),
704238×
        _ => ("", url),
705
    };
706250×
    match std::path::absolute(path) {
707250×
        Ok(abs) => format!("{prefix}{}", abs.display()),
7080×
        Err(_) => url.to_string(),
709
    }
710277×
}
711
712
/// Open a remote by URL: a local path (optionally `file://`), `http(s)://`
713
/// (a hub), or a store (`dir://`, and whatever openers are registered).
7141352×
pub fn open_remote(url: &str, options: &RemoteOptions) -> Result<Box<dyn Remote>> {
7151352×
    if url.starts_with("http://") || url.starts_with("https://") {
716173×
        return Ok(Box::new(HttpRemote::new(url, options)?));
7171179×
    }
7181179×
    if let Some(store) = open_store(url, options) {
71948×
        return crate::repo::strata::open_store_remote(store?, options);
7201131×
    }
7211131×
    let path = url.strip_prefix("file://").unwrap_or(url);
7221131×
    if path.contains("://") {
7230×
        return Err(RepoError::Msg(format!("unsupported remote URL {url:?}")));
7241131×
    }
7251131×
    let mut local = LocalRemote::open(Path::new(path))?;
7261131×
    local.claimed_id = options.repo_id;
7271131×
    Ok(Box::new(local))
7281352×
}
729
730
// ---------------------------------------------------------------- wire
731
732
/// CBOR encodings of the protocol messages (spec §16.1).
733
pub mod wire {
734
    use super::*;
735
7360×
    fn schema(msg: &str) -> RepoError {
7370×
        RepoError::Object(ObjectError::Schema(msg.into()))
7380×
    }
739256×
    fn sigs_value(sigs: &[Signature]) -> Value {
740256×
        Value::Array(sigs.iter().map(|s| s.to_value()).collect())
741256×
    }
742252×
    fn sigs_from(v: &Value) -> Result<Vec<Signature>> {
743252×
        Ok(o::array(v, "signatures")?
744252×
            .iter()
745252×
            .map(Signature::from_value)
746252×
            .collect::<std::result::Result<Vec<_>, _>>()?)
747252×
    }
748435×
    fn hashes_value(hs: &[ObjectRef]) -> Value {
749585×
        Value::Array(hs.iter().map(|h| Value::Bytes(h.0.to_vec())).collect())
750435×
    }
751496×
    fn hashes_from(v: &Value) -> Result<Vec<ObjectRef>> {
752496×
        Ok(o::array(v, "hashes")?
753496×
            .iter()
754647×
            .map(|h| o::oref(h, "hash"))
755496×
            .collect::<std::result::Result<Vec<_>, _>>()?)
756496×
    }
75791×
    fn attest_value(sa: &SignedAttest) -> Value {
75891×
        Value::Array(vec![Value::Bytes(sa.attest.encode()), sigs_value(&sa.sigs)])
75991×
    }
760106×
    fn attest_from(v: &Value) -> Result<SignedAttest> {
761106×
        let a = o::array(v, "signed attest")?;
762106×
        if a.len() != 2 {
7630×
            return Err(schema("signed attest: expected [attest, sigs]"));
764106×
        }
765
        Ok(SignedAttest {
766106×
            attest: Attest::decode(o::bytes(&a[0], "attest")?)?,
767106×
            sigs: sigs_from(&a[1])?,
768
        })
769106×
    }
770269×
    fn opt_attest_value(sa: &Option<SignedAttest>) -> Value {
771269×
        sa.as_ref().map(attest_value).unwrap_or(Value::Null)
772269×
    }
773326×
    fn opt_attest_from(v: &Value) -> Result<Option<SignedAttest>> {
774326×
        if v.is_null() {
775236×
            Ok(None)
776
        } else {
77790×
            attest_from(v).map(Some)
778
        }
779326×
    }
780
    /// `[policy bytes, [signature]]`: also the format of a policy proposal
781
    /// file exchanged between root holders (spec §14.5).
78245×
    pub fn policy_value(sp: &SignedPolicy) -> Value {
78345×
        Value::Array(vec![Value::Bytes(sp.policy.encode()), sigs_value(&sp.sigs)])
78445×
    }
78543×
    pub fn policy_from(v: &Value) -> Result<SignedPolicy> {
78643×
        let a = o::array(v, "signed policy")?;
78743×
        if a.len() != 2 {
7880×
            return Err(schema("signed policy: expected [policy, sigs]"));
78943×
        }
790
        Ok(SignedPolicy {
79143×
            policy: Policy::decode(o::bytes(&a[0], "policy")?)?,
79243×
            sigs: sigs_from(&a[1])?,
793
        })
79443×
    }
795213×
    fn opt_policy_value(sp: Option<&SignedPolicy>) -> Value {
796213×
        sp.map(policy_value).unwrap_or(Value::Null)
797213×
    }
798252×
    fn opt_policy_from(v: &Value) -> Result<Option<SignedPolicy>> {
799252×
        if v.is_null() {
800230×
            Ok(None)
801
        } else {
80222×
            policy_from(v).map(Some)
803
        }
804252×
    }
8051072×
    fn map<'a>(v: &'a Value, what: &str) -> Result<&'a o::Map> {
8061072×
        Ok(o::map(v, what)?)
8071072×
    }
8083033×
    fn field<'a>(m: &'a o::Map, k: u64, what: &str) -> Result<&'a Value> {
8093033×
        Ok(o::field(m, k, what)?)
8103033×
    }
811
812
    /// A bundle's value. Each change's text blobs and their chunks (spec
813
    /// §6.1) are added to its objects when they are not already there, so a
814
    /// bundle can always be read on its own.
815132×
    pub fn bundle_value(b: &Bundle) -> Value {
816132×
        let mut changes = Vec::with_capacity(b.raw_changes.len() + b.changes.len());
817
        // Changes as stored are already their encoding, their texts among
818
        // the objects.
819132×
        for (bytes, s) in &b.raw_changes {
8200×
            changes.push(Value::Array(vec![
8210×
                Value::Bytes(bytes.clone()),
8220×
                sigs_value(s),
8230×
            ]));
8240×
        }
825132×
        let mut texts: Vec<(ObjectType, Vec<u8>)> = Vec::new();
826132×
        let mut listed: Option<std::collections::HashSet<ObjectRef>> = None;
827132×
        for (c, s) in &b.changes {
828120×
            let (bytes, stored) = c.encode_parts();
829120×
            for t in stored {
8300×
                let listed = listed.get_or_insert_with(|| {
8310×
                    b.objects
8320×
                        .iter()
8330×
                        .map(|(ty, body)| crate::hash::hash_object(*ty, body))
8340×
                        .collect()
8350×
                });
8360×
                if !listed.insert(t.blob.hash()) {
8370×
                    continue;
8380×
                }
8390×
                for chunk in crate::chunk::chunks(&t.content) {
8400×
                    if listed.insert(crate::hash::hash_object(ObjectType::Chunk, chunk)) {
8410×
                        texts.push((ObjectType::Chunk, chunk.to_vec()));
8420×
                    }
843
                }
8440×
                texts.push((ObjectType::Blob, t.blob.encode()));
845
            }
846120×
            changes.push(Value::Array(vec![Value::Bytes(bytes), sigs_value(s)]));
847
        }
848132×
        let mut v = Value::map([
849132×
            (0, Value::Array(changes)),
850132×
            (
851132×
                1,
852132×
                Value::Array(b.attests.iter().map(attest_value).collect()),
853132×
            ),
854
            (
855
                2,
856
                Value::Array(
857132×
                    b.objects
858132×
                        .iter()
859132×
                        .chain(&texts)
860132×
                        .map(|(t, body)| {
861118×
                            Value::Array(vec![
862118×
                                Value::Text(t.name().into()),
863118×
                                Value::Bytes(body.clone()),
864118×
                            ])
865118×
                        })
866132×
                        .collect(),
867
                ),
868
            ),
869132×
            (
870132×
                3,
871132×
                Value::Array(b.policies.iter().map(policy_value).collect()),
872132×
            ),
873
        ]);
874
        // Only when there are any; older peers ignore the field.
875132×
        if !b.certificates.is_empty() {
8767×
            if let Value::Map(m) = &mut v {
8777×
                m.insert(
878
                    4,
879
                    Value::Array(
8807×
                        b.certificates
8817×
                            .iter()
8827×
                            .map(|c| Value::Bytes(c.encode()))
8837×
                            .collect(),
884
                    ),
885
                );
8860×
            }
887125×
        }
888132×
        v
889132×
    }
890
891122×
    pub fn bundle_from_value(v: &Value) -> Result<Bundle> {
892122×
        let m = map(v, "bundle")?;
893122×
        let mut b = Bundle::default();
894122×
        for ob in o::array(field(m, 2, "objects")?, "objects")? {
895107×
            let pair = o::array(ob, "object")?;
896107×
            if pair.len() != 2 {
8970×
                return Err(schema("object: expected [type, body]"));
898107×
            }
899107×
            let ty = ObjectType::from_name(o::text(&pair[0], "object type")?)
900107×
                .ok_or_else(|| schema("unknown object type"))?;
901107×
            b.objects
902107×
                .push((ty, o::bytes(&pair[1], "object body")?.to_vec()));
903
        }
904
        // Stored inserts are read from the bundle's own objects.
905122×
        let mut by_ref: Option<std::collections::HashMap<ObjectRef, usize>> = None;
906122×
        for c in o::array(field(m, 0, "changes")?, "changes")? {
907103×
            let pair = o::array(c, "change entry")?;
908103×
            if pair.len() != 2 {
9090×
                return Err(schema("change entry: expected [change, sigs]"));
910103×
            }
911103×
            let encoded = o::bytes(&pair[0], "change")?;
912103×
            b.hashes
913103×
                .push(crate::hash::hash_object(ObjectType::Change, encoded));
914103×
            let change = Change::decode_with(encoded, &mut |text, count, form| {
9150×
                let by_ref = by_ref.get_or_insert_with(|| {
9160×
                    b.objects
9170×
                        .iter()
9180×
                        .enumerate()
9190×
                        .map(|(i, (ty, body))| (crate::hash::hash_object(*ty, body), i))
9200×
                        .collect()
9210×
                });
9220×
                let get =
9230×
                    |r: &ObjectRef, want: ObjectType| match by_ref.get(r).map(|i| &b.objects[*i]) {
9240×
                        Some((ty, body)) if *ty == want => Ok(body),
9250×
                        _ => Err(ObjectError::Schema(format!(
9260×
                            "the bundle lacks {} {}",
9270×
                            want.name(),
9280×
                            r.short(12)
9290×
                        ))),
9300×
                    };
9310×
                let blob = crate::objects::Blob::decode(get(text, ObjectType::Blob)?)?;
9320×
                let mut content = Vec::with_capacity(blob.length as usize);
9330×
                for chunk in &blob.chunks {
9340×
                    content.extend_from_slice(get(chunk, ObjectType::Chunk)?);
935
                }
9360×
                crate::objects::text_lines(&content, count, form)
9370×
            })?;
938103×
            b.changes.push((change, sigs_from(&pair[1])?));
939
        }
940122×
        for a in o::array(field(m, 1, "attests")?, "attests")? {
94116×
            b.attests.push(attest_from(a)?);
942
        }
943122×
        if let Some(ps) = m.get(&3) {
944122×
            for p in o::array(ps, "policies")? {
9453×
                b.policies.push(policy_from(p)?);
946
            }
9470×
        }
948122×
        if let Some(cs) = m.get(&4) {
9497×
            for c in o::array(cs, "certificates")? {
9507×
                b.certificates.push(
9517×
                    crate::cert::SignedCertificate::decode(o::bytes(c, "certificate")?)
9527×
                        .map_err(|e| schema(&format!("certificate: {e}")))?,
953
                );
954
            }
955115×
        }
956122×
        Ok(b)
957122×
    }
958
95990×
    pub fn encode_bundle(b: &Bundle) -> Vec<u8> {
96090×
        cbor::encode(&bundle_value(b))
96190×
    }
96284×
    pub fn decode_bundle(bytes: &[u8]) -> Result<Bundle> {
96384×
        bundle_from_value(&cbor::decode(bytes).map_err(ObjectError::from)?)
96484×
    }
965
966141×
    pub fn encode_capabilities(id: [u8; 16]) -> Vec<u8> {
967141×
        cbor::encode(&Value::map([
968141×
            (0, Value::Array(vec![Value::Uint(PROTOCOL_VERSION)])),
969141×
            (1, Value::Bytes(id.to_vec())),
970141×
            (2, Value::Array(vec![Value::Text("seal".into())])),
971141×
        ]))
972141×
    }
973141×
    pub fn decode_capabilities(bytes: &[u8]) -> Result<[u8; 16]> {
974141×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
975141×
        let m = map(&v, "capabilities")?;
976141×
        let versions = o::array(field(m, 0, "versions")?, "versions")?;
977141×
        if !versions
978141×
            .iter()
979141×
            .any(|x| x.as_uint() == Some(PROTOCOL_VERSION))
980
        {
9810×
            return Err(RepoError::Msg(
9820×
                "remote does not speak protocol version 1".into(),
9830×
            ));
984141×
        }
985141×
        o::bytes(field(m, 1, "repo id")?, "repo id")?
986141×
            .try_into()
987141×
            .map_err(|_| schema("repo id: expected 16 bytes"))
988141×
    }
989
990213×
    fn tags_value(tags: &[TagRef]) -> Value {
991
        Value::Array(
992213×
            tags.iter()
993213×
                .map(|t| {
99434×
                    let mut v = Value::map([
99534×
                        (0, Value::Text(t.name.clone())),
99634×
                        (1, Value::Bytes(t.state.0.to_vec())),
99734×
                        (2, hashes_value(&t.heads)),
99834×
                        (3, opt_attest_value(&t.attestation)),
99934×
                    ]);
1000
                    // Only when there is one; older peers ignore them
1001
                    // (oxygen#129).
100234×
                    if let Value::Map(m) = &mut v {
100334×
                        if t.accepted.is_some() {
10048×
                            m.insert(4, opt_attest_value(&t.accepted));
100526×
                        }
100634×
                        if let Some(l) = &t.logged {
10072×
                            m.insert(5, logged_value(l));
100832×
                        }
100934×
                        if !t.integration.is_empty() {
10102×
                            m.insert(6, integration_value(&t.integration));
101132×
                        }
10120×
                    }
101334×
                    v
101434×
                })
1015213×
                .collect(),
1016
        )
1017213×
    }
1018252×
    fn tags_from(v: &Value) -> Result<Vec<TagRef>> {
1019252×
        let mut out = Vec::new();
1020252×
        for t in o::array(v, "tags")? {
102150×
            let tm = map(t, "tag")?;
102250×
            out.push(TagRef {
102350×
                name: o::text(field(tm, 0, "name")?, "name")?.to_owned(),
102450×
                state: o::oref(field(tm, 1, "state")?, "state")?,
102550×
                heads: hashes_from(field(tm, 2, "heads")?)?,
102650×
                attestation: opt_attest_from(field(tm, 3, "attestation")?)?,
102750×
                accepted: match tm.get(&4) {
10288×
                    Some(a) => opt_attest_from(a)?,
102942×
                    None => None,
1030
                },
103150×
                logged: tm.get(&5).map(logged_from).transpose()?,
103250×
                integration: match tm.get(&6) {
10332×
                    Some(l) => integration_from(l)?,
103448×
                    None => Vec::new(),
1035
                },
1036
            });
1037
        }
1038252×
        Ok(out)
1039252×
    }
1040
1041
    /// The tags of a refs answer as oxy 0.5.0 read them (and the runners
1042
    /// built with it), keys 0 to 3 only: what an older reader makes of an
1043
    /// answer with keys 4 to 6.
1044
    #[cfg(test)]
10451×
    pub(super) fn tags_as_0_5_read_them(bytes: &[u8]) -> Result<Vec<TagRef>> {
10461×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
10471×
        let m = map(&v, "refs")?;
10481×
        let mut out = Vec::new();
10492×
        for t in o::array(field(m, 3, "tags")?, "tags")? {
10502×
            let tm = map(t, "tag")?;
10512×
            out.push(TagRef::new(
10522×
                o::text(field(tm, 0, "name")?, "name")?.to_owned(),
10532×
                o::oref(field(tm, 1, "state")?, "state")?,
10542×
                hashes_from(field(tm, 2, "heads")?)?,
10552×
                opt_attest_from(field(tm, 3, "attestation")?)?,
1056
            ));
1057
        }
10581×
        Ok(out)
10591×
    }
1060
1061
    /// A log place, `[entry number, entry bytes, [proof hash]]` (spec §14.8).
10624×
    fn logged_value(l: &Logged) -> Value {
10634×
        Value::Array(vec![
10644×
            Value::Uint(l.index),
10654×
            Value::Bytes(l.entry.clone()),
10664×
            proof_value(&l.proof),
10674×
        ])
10684×
    }
10694×
    fn logged_from(v: &Value) -> Result<Logged> {
10704×
        let a = o::array(v, "logged")?;
10714×
        if a.len() != 3 {
10720×
            return Err(schema("logged: expected [index, entry, proof]"));
10734×
        }
1074
        Ok(Logged {
10754×
            index: o::uint(&a[0], "index")?,
10764×
            entry: o::bytes(&a[1], "entry")?.to_vec(),
10774×
            proof: proof_from(&a[2])?,
1078
        })
10794×
    }
1080
1081
    /// Cosigned checkpoints holding an entry, `[[note, [proof hash]]]`.
10824×
    fn integration_value(integration: &[Integration]) -> Value {
1083
        Value::Array(
10844×
            integration
10854×
                .iter()
10864×
                .map(|i| Value::Array(vec![Value::Text(i.note.clone()), proof_value(&i.proof)]))
10874×
                .collect(),
1088
        )
10894×
    }
10904×
    fn integration_from(v: &Value) -> Result<Vec<Integration>> {
10914×
        let mut out = Vec::new();
10924×
        for i in o::array(v, "integration")? {
10934×
            let a = o::array(i, "integration")?;
10944×
            if a.len() != 2 {
10950×
                return Err(schema("integration: expected [note, proof]"));
10964×
            }
10974×
            out.push(Integration {
10984×
                note: o::text(&a[0], "note")?.to_owned(),
10994×
                proof: proof_from(&a[1])?,
1100
            });
1101
        }
11024×
        Ok(out)
11034×
    }
1104
1105171×
    pub fn encode_refs(id: [u8; 16], resp: &RefsResponse) -> Vec<u8> {
1106171×
        let mut v = Value::map([
1107
            (
1108
                0,
1109
                Value::Array(
1110171×
                    resp.refs
1111171×
                        .iter()
1112177×
                        .map(|r| {
1113177×
                            let mut v = Value::map([
1114177×
                                (0, Value::Text(r.name.clone())),
1115177×
                                (1, Value::Bytes(r.state.0.to_vec())),
1116177×
                                (2, hashes_value(&r.heads)),
1117177×
                                (3, opt_attest_value(&r.attestation)),
1118177×
                                (4, r.last_serial.map(Value::Uint).unwrap_or(Value::Null)),
1119177×
                            ]);
1120
                            // Only when there is one; older peers ignore it.
1121177×
                            if let Value::Map(m) = &mut v {
1122177×
                                if r.accepted.is_some() {
11239×
                                    m.insert(5, opt_attest_value(&r.accepted));
1124168×
                                }
1125177×
                                if let Some(l) = &r.logged {
11262×
                                    m.insert(6, logged_value(l));
1127175×
                                }
1128177×
                                if !r.integration.is_empty() {
11292×
                                    m.insert(7, integration_value(&r.integration));
1130175×
                                }
11310×
                            }
1132177×
                            v
1133177×
                        })
1134171×
                        .collect(),
1135
                ),
1136
            ),
1137171×
            (1, Value::Bytes(id.to_vec())),
1138171×
            (2, opt_policy_value(resp.policy.as_ref())),
1139171×
            (3, tags_value(&resp.tags)),
1140171×
            (
1141171×
                4,
1142171×
                Value::Array(resp.history.iter().map(policy_value).collect()),
1143171×
            ),
1144171×
            (
1145171×
                5,
1146171×
                resp.default_bookmark
1147171×
                    .clone()
1148171×
                    .map(Value::Text)
1149171×
                    .unwrap_or(Value::Null),
1150171×
            ),
1151
        ]);
1152171×
        if let Value::Map(m) = &mut v {
1153171×
            if let Some(log) = &resp.log {
11543×
                m.insert(6, Value::Text(log.clone()));
1155168×
            }
1156171×
            if !resp.witnesses.is_empty() {
11572×
                m.insert(
1158
                    7,
1159
                    Value::Array(
11602×
                        resp.witnesses
11612×
                            .iter()
11622×
                            .map(|(name, id)| {
11632×
                                Value::Array(vec![
11642×
                                    Value::Text(name.clone()),
11652×
                                    Value::Bytes(id.clone()),
11662×
                                ])
11672×
                            })
11682×
                            .collect(),
1169
                    ),
1170
                );
1171169×
            }
11720×
        }
1173171×
        cbor::encode(&v)
1174171×
    }
1175214×
    pub fn decode_refs(bytes: &[u8]) -> Result<([u8; 16], RefsResponse)> {
1176214×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
1177214×
        let m = map(&v, "refs")?;
1178214×
        let id: [u8; 16] = o::bytes(field(m, 1, "repo id")?, "repo id")?
1179214×
            .try_into()
1180214×
            .map_err(|_| schema("repo id: expected 16 bytes"))?;
1181214×
        let mut refs = Vec::new();
1182220×
        for r in o::array(field(m, 0, "refs")?, "refs")? {
1183220×
            let rm = map(r, "ref")?;
1184220×
            let ls = field(rm, 4, "last serial")?;
1185220×
            refs.push(RemoteRef {
1186220×
                name: o::text(field(rm, 0, "name")?, "name")?.to_owned(),
1187220×
                state: o::oref(field(rm, 1, "state")?, "state")?,
1188220×
                heads: hashes_from(field(rm, 2, "heads")?)?,
1189220×
                attestation: opt_attest_from(field(rm, 3, "attestation")?)?,
1190220×
                last_serial: if ls.is_null() {
1191187×
                    None
1192
                } else {
119333×
                    Some(o::uint(ls, "last serial")?)
1194
                },
1195220×
                accepted: match rm.get(&5) {
11969×
                    Some(a) => opt_attest_from(a)?,
1197211×
                    None => None,
1198
                },
1199220×
                logged: rm.get(&6).map(logged_from).transpose()?,
1200220×
                integration: match rm.get(&7) {
12012×
                    Some(l) => integration_from(l)?,
1202218×
                    None => Vec::new(),
1203
                },
1204
            });
1205
        }
1206214×
        let policy = match m.get(&2) {
1207214×
            Some(p) => opt_policy_from(p)?,
12080×
            None => None,
1209
        };
1210214×
        let tags = match m.get(&3) {
1211214×
            Some(t) => tags_from(t)?,
12120×
            None => Vec::new(),
1213
        };
1214214×
        let mut history = Vec::new();
1215214×
        if let Some(h) = m.get(&4) {
1216214×
            for p in o::array(h, "history")? {
121717×
                history.push(policy_from(p)?);
1218
            }
12190×
        }
1220214×
        let default_bookmark = match m.get(&5) {
1221145×
            Some(Value::Text(t)) => Some(t.clone()),
122269×
            _ => None,
1223
        };
1224214×
        let log = match m.get(&6) {
12253×
            Some(Value::Text(t)) => Some(t.clone()),
1226211×
            _ => None,
1227
        };
1228214×
        let mut witnesses = Vec::new();
1229214×
        if let Some(w) = m.get(&7) {
12302×
            for x in o::array(w, "witnesses")? {
12312×
                let a = o::array(x, "witness")?;
12322×
                if a.len() != 2 {
12330×
                    return Err(schema("witness: expected [name, identity]"));
12342×
                }
12352×
                witnesses.push((
12362×
                    o::text(&a[0], "witness name")?.to_owned(),
12372×
                    o::bytes(&a[1], "witness identity")?.to_vec(),
1238
                ));
1239
            }
1240212×
        }
1241214×
        Ok((
1242214×
            id,
1243214×
            RefsResponse {
1244214×
                refs,
1245214×
                policy,
1246214×
                tags,
1247214×
                history,
1248214×
                default_bookmark,
1249214×
                log,
1250214×
                witnesses,
1251214×
            },
1252214×
        ))
1253214×
    }
1254
1255
    /// A proof's hashes, from the leaf upwards (spec §14.8).
12568×
    fn proof_value(proof: &[[u8; 32]]) -> Value {
12578×
        Value::Array(proof.iter().map(|h| Value::Bytes(h.to_vec())).collect())
12588×
    }
1259
12608×
    fn proof_from(v: &Value) -> Result<Vec<[u8; 32]>> {
12618×
        let mut proof = Vec::new();
12628×
        for h in o::array(v, "proof")? {
12638×
            proof.push(
12648×
                o::bytes(h, "proof hash")?
12658×
                    .try_into()
12668×
                    .map_err(|_| schema("proof hash: expected 32 bytes"))?,
1267
            );
1268
        }
12698×
        Ok(proof)
12708×
    }
1271
127255×
    pub fn encode_negotiate(have: &[ChangeHash], want: &[ChangeHash]) -> Vec<u8> {
127355×
        cbor::encode(&Value::map([
127455×
            (0, hashes_value(have)),
127555×
            (1, hashes_value(want)),
127655×
        ]))
127755×
    }
127855×
    pub fn decode_negotiate(bytes: &[u8]) -> Result<(Vec<ChangeHash>, Vec<ChangeHash>)> {
127955×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
128055×
        let m = map(&v, "negotiate")?;
1281
        Ok((
128255×
            hashes_from(field(m, 0, "have")?)?,
128355×
            hashes_from(field(m, 1, "want")?)?,
1284
        ))
128555×
    }
1286
1287
    /// `fetch` request: `{0: [changes], 1: max blob size or null}`.
128856×
    pub fn encode_fetch(hs: &[ChangeHash], max_blob: Option<u64>) -> Vec<u8> {
128956×
        cbor::encode(&Value::map([
129056×
            (0, hashes_value(hs)),
129156×
            (1, max_blob.map(Value::Uint).unwrap_or(Value::Null)),
129256×
        ]))
129356×
    }
129457×
    pub fn decode_fetch(bytes: &[u8]) -> Result<(Vec<ChangeHash>, Option<u64>)> {
129557×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
129657×
        let m = map(&v, "fetch")?;
129757×
        let max = match m.get(&1) {
129856×
            Some(x) if !x.is_null() => Some(o::uint(x, "max blob")?),
129955×
            _ => None,
1300
        };
130157×
        Ok((hashes_from(field(m, 0, "changes")?)?, max))
130257×
    }
1303
1304
    /// `shallow` request: `{0: [heads], 1: depth}`.
13051×
    pub fn encode_shallow(hs: &[ChangeHash], depth: u32) -> Vec<u8> {
13061×
        cbor::encode(&Value::map([
13071×
            (0, hashes_value(hs)),
13081×
            (1, Value::Uint(depth as u64)),
13091×
        ]))
13101×
    }
13111×
    pub fn decode_shallow(bytes: &[u8]) -> Result<(Vec<ChangeHash>, u32)> {
13121×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
13131×
        let m = map(&v, "shallow")?;
1314
        Ok((
13151×
            hashes_from(field(m, 0, "heads")?)?,
13161×
            o::u32_(field(m, 1, "depth")?, "depth")?,
1317
        ))
13181×
    }
1319
132057×
    pub fn encode_hashes(hs: &[ChangeHash]) -> Vec<u8> {
132157×
        cbor::encode(&Value::map([(0, hashes_value(hs))]))
132257×
    }
132356×
    pub fn decode_hashes(bytes: &[u8]) -> Result<Vec<ChangeHash>> {
132456×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
132556×
        hashes_from(field(map(&v, "hashes")?, 0, "hashes")?)
132656×
    }
1327
132842×
    pub fn encode_push(
132942×
        bundle: &Bundle,
133042×
        updates: &[RefUpdate],
133142×
        policy: Option<&SignedPolicy>,
133242×
        tags: &[TagRef],
133342×
    ) -> Vec<u8> {
133442×
        cbor::encode(&Value::map([
133542×
            (0, bundle_value(bundle)),
133642×
            (2, opt_policy_value(policy)),
133742×
            (3, tags_value(tags)),
1338
            (
1339
                1,
1340
                Value::Array(
134142×
                    updates
134242×
                        .iter()
134342×
                        .map(|u| {
134441×
                            Value::map([
134541×
                                (0, Value::Text(u.name.clone())),
134641×
                                (1, Value::Bytes(u.old_state.0.to_vec())),
134741×
                                (2, Value::Bytes(u.new_state.0.to_vec())),
134841×
                                (3, Value::Bool(u.force)),
134941×
                                (4, opt_attest_value(&u.attestation)),
135041×
                            ])
135141×
                        })
135242×
                        .collect(),
1353
                ),
1354
            ),
1355
        ]))
135642×
    }
1357
    /// A decoded push: bundle, bookmark updates, policy, tags.
1358
    pub type PushParts = (Bundle, Vec<RefUpdate>, Option<SignedPolicy>, Vec<TagRef>);
1359
136038×
    pub fn decode_push(bytes: &[u8]) -> Result<PushParts> {
136138×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
136238×
        let m = map(&v, "push")?;
136338×
        let bundle = bundle_from_value(field(m, 0, "bundle")?)?;
136438×
        let mut updates = Vec::new();
136538×
        for u in o::array(field(m, 1, "updates")?, "updates")? {
136637×
            let um = map(u, "update")?;
136737×
            updates.push(RefUpdate {
136837×
                name: o::text(field(um, 0, "name")?, "name")?.to_owned(),
136937×
                old_state: o::oref(field(um, 1, "old_state")?, "old_state")?,
137037×
                new_state: o::oref(field(um, 2, "new_state")?, "new_state")?,
137137×
                force: field(um, 3, "force")?
137237×
                    .as_bool()
137337×
                    .ok_or_else(|| schema("force: expected bool"))?,
137437×
                attestation: opt_attest_from(field(um, 4, "attestation")?)?,
1375
            });
1376
        }
137738×
        let policy = match m.get(&2) {
137838×
            Some(p) => opt_policy_from(p)?,
13790×
            None => None,
1380
        };
138138×
        let tags = match m.get(&3) {
138238×
            Some(t) => tags_from(t)?,
13830×
            None => Vec::new(),
1384
        };
138538×
        Ok((bundle, updates, policy, tags))
138638×
    }
1387
138836×
    pub fn encode_push_response(results: &[RefResult]) -> Vec<u8> {
138936×
        cbor::encode(&Value::map([(
1390
            0,
1391
            Value::Array(
139236×
                results
139336×
                    .iter()
139442×
                    .map(|r| {
139542×
                        Value::map([
139642×
                            (0, Value::Text(r.name.clone())),
139742×
                            (1, Value::Bool(r.ok)),
139842×
                            (2, Value::Text(r.reason.clone())),
139942×
                        ])
140042×
                    })
140136×
                    .collect(),
1402
            ),
1403
        )]))
140436×
    }
140536×
    pub fn decode_push_response(bytes: &[u8]) -> Result<Vec<RefResult>> {
140636×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
140736×
        let m = map(&v, "push response")?;
140836×
        let mut out = Vec::new();
140942×
        for r in o::array(field(m, 0, "results")?, "results")? {
141042×
            let rm = map(r, "result")?;
141142×
            out.push(RefResult {
141242×
                name: o::text(field(rm, 0, "name")?, "name")?.to_owned(),
141342×
                ok: field(rm, 1, "ok")?
141442×
                    .as_bool()
141542×
                    .ok_or_else(|| schema("ok: expected bool"))?,
141642×
                reason: o::text(field(rm, 2, "reason")?, "reason")?.to_owned(),
1417
            });
1418
        }
141936×
        Ok(out)
142036×
    }
1421
}
1422
1423
#[cfg(test)]
1424
mod tests {
1425
    use super::*;
1426
    use crate::attest::AttestBody;
1427
    use crate::objects::Hlc;
1428
1429
    #[test]
14301×
    fn client_features_are_declared_and_read() {
14311×
        assert_eq!(CLIENT_FEATURES.join(","), "certified-tags");
14321×
        assert!(user_agent().starts_with("oxy/"));
14331×
        assert!(declares_feature(
14341×
            Some("certified-tags"),
14351×
            FEATURE_CERTIFIED_TAGS
1436
        ));
14371×
        assert!(declares_feature(
14381×
            Some("later-thing, Certified-Tags ,x"),
14391×
            FEATURE_CERTIFIED_TAGS
1440
        ));
14411×
        assert!(!declares_feature(
14421×
            Some("certified-tags-v2"),
14431×
            FEATURE_CERTIFIED_TAGS
14441×
        ));
14451×
        assert!(!declares_feature(Some(""), FEATURE_CERTIFIED_TAGS));
14461×
        assert!(!declares_feature(None, FEATURE_CERTIFIED_TAGS));
14471×
    }
1448
1449
    #[test]
14501×
    fn wire_round_trips() {
14511×
        let c = crate::objects::tests::sample_change();
14521×
        let sk = crate::identity::SecretKey {
14531×
            ed_seed: [1; 32],
14541×
            ml_seed: [2; 32],
14551×
        };
14561×
        let id = sk.identity("a", "b", 0);
14571×
        let key = id.hash();
14581×
        let sig = sk.sign(crate::identity::Domain::Change, &key, &c.hash());
14591×
        let seal = Attest::seal([3; 16], vec![c.hash()]);
14601×
        let seal_sig = sk.sign(crate::identity::Domain::Attest, &key, &seal.hash());
14611×
        let policy = Policy::single_root([3; 16], id.clone(), 99);
14621×
        let psig = sk.sign(crate::identity::Domain::Policy, &key, &policy.hash());
14631×
        let bundle = Bundle {
14641×
            changes: vec![(c.clone(), vec![sig.clone()])],
14651×
            attests: vec![SignedAttest {
14661×
                attest: seal.clone(),
14671×
                sigs: vec![seal_sig],
14681×
            }],
14691×
            objects: vec![
14701×
                (ObjectType::Identity, id.encode()),
14711×
                (ObjectType::Chunk, b"xyz".to_vec()),
14721×
            ],
14731×
            policies: vec![SignedPolicy {
14741×
                policy: policy.clone(),
14751×
                sigs: vec![psig.clone()],
14761×
            }],
14771×
            hashes: vec![],
14781×
            raw_changes: vec![],
14791×
            certificates: vec![],
14801×
        };
14811×
        let d = wire::decode_bundle(&wire::encode_bundle(&bundle)).unwrap();
14821×
        assert_eq!(
1483
            d.hashes,
14841×
            vec![c.hash()],
1485
            "the receiver hashes what it was sent"
1486
        );
14871×
        assert_eq!(d.changes, bundle.changes);
14881×
        assert_eq!(d.attests, bundle.attests);
14891×
        assert_eq!(d.objects, bundle.objects);
14901×
        assert_eq!(d.policies, bundle.policies);
14911×
        assert!(d.certificates.is_empty());
1492
        // Certificates (keyless, oxygenhub#241) travel as field 4, only
1493
        // when there are any: a bundle without them encodes as before.
14941×
        let plain = wire::encode_bundle(&bundle);
14951×
        let mut with = bundle.clone();
14961×
        let issuer_sk = crate::identity::SecretKey::generate();
14971×
        let issuer = issuer_sk.identity("hub", "h@x", 1);
14981×
        with.certificates.push(crate::cert::SignedCertificate::sign(
14991×
            crate::cert::Certificate {
15001×
                key: id.clone(),
15011×
                issuer: issuer.hash(),
15021×
                subject: "agent:a@b".into(),
15031×
                claims: vec![],
15041×
                scope: crate::identity::Scope::CHANGES,
15051×
                not_before: 1,
15061×
                expires: 2,
15071×
                grant: None,
15081×
            },
15091×
            &issuer,
15101×
            &issuer_sk,
1511
        ));
15121×
        let encoded = wire::encode_bundle(&with);
15131×
        assert_ne!(encoded, plain);
15141×
        assert_eq!(
15151×
            wire::decode_bundle(&encoded).unwrap().certificates,
1516
            with.certificates
1517
        );
15181×
        with.certificates.clear();
15191×
        assert_eq!(wire::encode_bundle(&with), plain);
1520
15211×
        let att = Attest {
15221×
            repo: [3; 16],
15231×
            hlc: Hlc::default(),
15241×
            body: AttestBody::Ref {
15251×
                name: "main".into(),
15261×
                old_state: ObjectRef([1; 32]),
15271×
                new_state: ObjectRef([2; 32]),
15281×
                serial: 4,
15291×
            },
15301×
        };
15311×
        let refs = vec![
15321×
            RemoteRef {
15331×
                name: "main".into(),
15341×
                state: ObjectRef([2; 32]),
15351×
                heads: vec![c.hash()],
15361×
                attestation: Some(SignedAttest {
15371×
                    attest: att.clone(),
15381×
                    sigs: vec![sig.clone()],
15391×
                }),
15401×
                last_serial: Some(4),
15411×
                accepted: None,
15421×
                logged: None,
15431×
                integration: vec![],
15441×
            },
15451×
            RemoteRef {
15461×
                name: "dev".into(),
15471×
                state: ObjectRef([5; 32]),
15481×
                heads: vec![],
15491×
                attestation: None,
15501×
                last_serial: None,
15511×
                accepted: None,
15521×
                logged: None,
15531×
                integration: vec![],
15541×
            },
1555
        ];
15561×
        let tag = TagRef::new("v1".into(), ObjectRef([2; 32]), vec![c.hash()], None);
15571×
        let mut resp = RefsResponse {
15581×
            refs,
15591×
            policy: Some(SignedPolicy {
15601×
                policy: policy.clone(),
15611×
                sigs: vec![psig.clone()],
15621×
            }),
15631×
            tags: vec![tag.clone()],
15641×
            history: vec![SignedPolicy {
15651×
                policy: policy.clone(),
15661×
                sigs: vec![],
15671×
            }],
15681×
            default_bookmark: Some("develop".into()),
15691×
            log: Some("hub.example/log\n2\nroot\n\n- sig\n".into()),
15701×
            witnesses: vec![],
15711×
        };
1572
        // Without integrated times (spec §14.8) nothing is added: an old
1573
        // peer's answer, and what it reads.
15741×
        let old = wire::encode_refs([3; 16], &resp);
15751×
        let back = wire::decode_refs(&old).unwrap().1;
15762×
        assert!(back.witnesses.is_empty() && back.refs.iter().all(|r| r.integration.is_empty()));
15771×
        resp.refs[1].logged = Some(Logged {
15781×
            index: 41,
15791×
            entry: vec![1, 2, 3],
15801×
            proof: vec![[9; 32], [8; 32]],
15811×
        });
15821×
        resp.refs[1].integration = vec![Integration {
15831×
            note: "hub.example/log\n42\nroot\n\n- sig\n".into(),
15841×
            proof: vec![[7; 32]],
15851×
        }];
15861×
        resp.witnesses = vec![("w.example".into(), vec![4, 5, 6])];
15871×
        let new = wire::encode_refs([3; 16], &resp);
15881×
        let (id_back, back) = wire::decode_refs(&new).unwrap();
15891×
        assert_eq!(back.log, resp.log);
15901×
        assert_eq!(back.refs[1].logged, resp.refs[1].logged);
15911×
        assert_eq!(back.refs[1].integration, resp.refs[1].integration);
15921×
        assert_eq!(back.witnesses, resp.witnesses);
15931×
        assert_eq!(back.refs[0].logged, None);
1594
        // The new keys are 7s an old reader never asks for.
15951×
        let crate::cbor::Value::Map(m) = crate::cbor::decode(&new).unwrap() else {
15960×
            panic!()
1597
        };
15981×
        assert!(m.contains_key(&7));
15991×
        assert_eq!(id_back, [3; 16]);
16001×
        assert_eq!(back.refs.len(), 2);
16011×
        assert_eq!(back.refs[0].attestation.as_ref().unwrap().attest, att);
16021×
        assert_eq!(back.refs[1].last_serial, None);
16031×
        assert_eq!(back.policy.as_ref().unwrap().policy, policy);
16041×
        assert_eq!(back.history, resp.history);
16051×
        assert_eq!(back.tags, vec![tag.clone()]);
1606
1607
        // A tag's acceptance and log place (oxygen#129): keys 4 to 6, only
1608
        // when there are any, so a tag without them encodes as before.
16091×
        let crate::cbor::Value::Map(m) = crate::cbor::decode(&new).unwrap() else {
16100×
            panic!()
1611
        };
16121×
        let crate::cbor::Value::Array(tags) = &m[&3] else {
16130×
            panic!()
1614
        };
16151×
        let crate::cbor::Value::Map(plain) = &tags[0] else {
16160×
            panic!()
1617
        };
16181×
        assert_eq!(plain.keys().copied().collect::<Vec<_>>(), vec![0, 1, 2, 3]);
16191×
        let mut full = tag.clone();
16201×
        full.name = "v2".into();
16211×
        full.attestation = Some(SignedAttest {
16221×
            attest: att.clone(),
16231×
            sigs: vec![sig.clone()],
16241×
        });
16251×
        full.accepted = full.attestation.clone();
16261×
        full.logged = Some(Logged {
16271×
            index: 7,
16281×
            entry: vec![4],
16291×
            proof: vec![[3; 32]],
16301×
        });
16311×
        full.integration = vec![Integration {
16321×
            note: "hub.example/log\n8\nroot\n\n- sig\n".into(),
16331×
            proof: vec![],
16341×
        }];
16351×
        resp.tags = vec![full.clone(), tag.clone()];
16361×
        let bytes = wire::encode_refs([3; 16], &resp);
16371×
        assert_eq!(wire::decode_refs(&bytes).unwrap().1.tags, resp.tags);
1638
        // In a push too.
16391×
        let pushed = wire::encode_push(&Bundle::default(), &[], None, &resp.tags);
16401×
        assert_eq!(wire::decode_push(&pushed).unwrap().3, resp.tags);
1641
        // A reader that knows only keys 0 to 3 (oxy 0.5.0 and older, and
1642
        // the runners built with it) reads the same tags from the new answer.
16431×
        let stripped: Vec<TagRef> = resp
16441×
            .tags
16451×
            .iter()
16462×
            .map(|t| {
16472×
                TagRef::new(
16482×
                    t.name.clone(),
16492×
                    t.state,
16502×
                    t.heads.clone(),
16512×
                    t.attestation.clone(),
1652
                )
16532×
            })
16541×
            .collect();
16551×
        assert_eq!(wire::tags_as_0_5_read_them(&bytes).unwrap(), stripped);
1656
16571×
        let (h, w) = wire::decode_negotiate(&wire::encode_negotiate(
16581×
            &[ObjectRef([1; 32])],
16591×
            &[ObjectRef([2; 32])],
16601×
        ))
16611×
        .unwrap();
16621×
        assert_eq!((h, w), (vec![ObjectRef([1; 32])], vec![ObjectRef([2; 32])]));
16631×
        assert_eq!(
16641×
            wire::decode_hashes(&wire::encode_hashes(&[c.hash()])).unwrap(),
16651×
            vec![c.hash()]
1666
        );
16671×
        assert_eq!(
16681×
            wire::decode_fetch(&wire::encode_fetch(&[c.hash()], Some(4096))).unwrap(),
16691×
            (vec![c.hash()], Some(4096))
1670
        );
16711×
        assert_eq!(
16721×
            wire::decode_fetch(&wire::encode_fetch(&[], None)).unwrap(),
16731×
            (vec![], None)
1674
        );
16751×
        assert_eq!(
16761×
            wire::decode_shallow(&wire::encode_shallow(&[c.hash()], 3)).unwrap(),
16771×
            (vec![c.hash()], 3)
1678
        );
1679
        // An old-style fetch request without the filter field still decodes.
16801×
        assert_eq!(
16811×
            wire::decode_fetch(&wire::encode_hashes(&[c.hash()])).unwrap(),
16821×
            (vec![c.hash()], None)
1683
        );
1684
16851×
        let up = RefUpdate {
16861×
            name: "main".into(),
16871×
            old_state: ObjectRef([1; 32]),
16881×
            new_state: ObjectRef([2; 32]),
16891×
            force: true,
16901×
            attestation: Some(SignedAttest {
16911×
                attest: att,
16921×
                sigs: vec![sig],
16931×
            }),
16941×
        };
16951×
        let sp = SignedPolicy {
16961×
            policy,
16971×
            sigs: vec![psig],
16981×
        };
16991×
        let (b2, ups, pol, tags) = wire::decode_push(&wire::encode_push(
17001×
            &bundle,
17011×
            std::slice::from_ref(&up),
17021×
            Some(&sp),
17031×
            std::slice::from_ref(&tag),
17041×
        ))
17051×
        .unwrap();
17061×
        assert_eq!(pol, Some(sp));
17071×
        assert_eq!(tags, vec![tag]);
17081×
        assert_eq!(b2.changes.len(), 1);
17091×
        assert_eq!(ups[0].name, "main");
17101×
        assert!(ups[0].force);
17111×
        assert_eq!(ups[0].attestation, up.attestation);
17121×
        let res = vec![RefResult {
17131×
            name: "main".into(),
17141×
            ok: false,
17151×
            reason: "stale".into(),
17161×
        }];
17171×
        assert_eq!(
17181×
            wire::decode_push_response(&wire::encode_push_response(&res)).unwrap(),
1719
            res
1720
        );
17211×
        assert_eq!(
17221×
            wire::decode_capabilities(&wire::encode_capabilities([7; 16])).unwrap(),
1723
            [7; 16]
1724
        );
17251×
    }
1726
}