OXYGENHUB

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

1100 of 1278 lines run, 179 of 272 functions · run #399 on proposal/150 · 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
    /// Tags withdrawn here (spec §10.1; key 8, only when there are any):
68
    /// each with its `untag` attestation as `attestation`, and that
69
    /// attestation's acceptance as `accepted` when a short-lived key
70
    /// signed it. Older clients ignore them and keep the tag they have.
71
    pub withdrawn: Vec<TagRef>,
72
}
73
74
/// Where a reference attestation sits in the host's transparency log
75
/// (spec §14.8): its entry number, the entry, and the inclusion proof
76
/// against the checkpoint served beside it.
77
#[derive(Clone, Debug, PartialEq, Eq)]
78
pub struct Logged {
79
    pub index: u64,
80
    pub entry: Vec<u8>,
81
    pub proof: Vec<[u8; 32]>,
82
}
83
84
/// A checkpoint witnesses cosigned that includes a logged entry (spec
85
/// §14.8, *Integrated time*): the cosigned note, and the entry's inclusion
86
/// proof against it.
87
#[derive(Clone, Debug, PartialEq, Eq)]
88
pub struct Integration {
89
    pub note: String,
90
    pub proof: Vec<[u8; 32]>,
91
}
92
93
/// A tag as a remote reports it (spec §10.1).
94
#[derive(Clone, Debug, PartialEq, Eq)]
95
pub struct TagRef {
96
    pub name: String,
97
    pub state: ObjectRef,
98
    pub heads: Vec<ChangeHash>,
99
    pub attestation: Option<SignedAttest>,
100
    /// The acceptance of `attestation` by its signer's certificate issuer
101
    /// when a short-lived key signed it (spec §14.7; key 4, only when there
102
    /// is one): the time a fetch checks the certificate at.
103
    pub accepted: Option<SignedAttest>,
104
    /// The attestation's place in the host's transparency log (key 5,
105
    /// only when it has one), as a bookmark's.
106
    pub logged: Option<Logged>,
107
    /// The cosigned checkpoints that first included `logged`'s entry (key
108
    /// 6, only when there are any).
109
    pub integration: Vec<Integration>,
110
}
111
112
impl TagRef {
113
    /// Whether this is a tag's withdrawal (its attestation an `untag`), as
114
    /// a push carries one (oxygenhub#301).
11525×
    pub fn is_withdrawal(&self) -> bool {
11625×
        self.attestation
11725×
            .as_ref()
11825×
            .is_some_and(|a| matches!(a.attest.body, crate::attest::AttestBody::Untag { .. }))
11925×
    }
120
121
    /// A tag with no acceptance or log place (yet).
122148×
    pub fn new(
123148×
        name: String,
124148×
        state: ObjectRef,
125148×
        heads: Vec<ChangeHash>,
126148×
        attestation: Option<SignedAttest>,
127148×
    ) -> TagRef {
128148×
        TagRef {
129148×
            name,
130148×
            state,
131148×
            heads,
132148×
            attestation,
133148×
            accepted: None,
134148×
            logged: None,
135148×
            integration: vec![],
136148×
        }
137148×
    }
138
}
139
140
/// One reference as a remote reports it.
141
#[derive(Clone, Debug)]
142
pub struct RemoteRef {
143
    pub name: String,
144
    pub state: ObjectRef,
145
    pub heads: Vec<ChangeHash>,
146
    /// The latest attestation, only when it describes `state`. An unattested
147
    /// push (accepted while no trust policy exists) leaves it `None`.
148
    pub attestation: Option<SignedAttest>,
149
    /// Serial of the latest attestation ever recorded, stale or not, so the
150
    /// next attestation continues the sequence.
151
    pub last_serial: Option<u64>,
152
    /// The host's acceptance of `attestation` when a short-lived key signed
153
    /// it (spec §14.7): the time its certificate is checked at.
154
    pub accepted: Option<SignedAttest>,
155
    /// The attestation's place in the host's transparency log (key 6, only
156
    /// when it has one).
157
    pub logged: Option<Logged>,
158
    /// The cosigned checkpoints that first included `logged`'s entry (key
159
    /// 7, only when there are any): what its integrated time is read from.
160
    pub integration: Vec<Integration>,
161
}
162
163
/// Everything needed to add a set of changes to a repository.
164
#[derive(Clone, Debug, Default)]
165
pub struct Bundle {
166
    /// In dependency order, each with its individual signatures.
167
    pub changes: Vec<(Change, Vec<Signature>)>,
168
    /// Seals covering the changes.
169
    pub attests: Vec<SignedAttest>,
170
    /// Chunks, blobs, identities, and state objects referenced by the changes.
171
    pub objects: Vec<(ObjectType, Vec<u8>)>,
172
    /// Policies between the receiver's and the one sent with the push,
173
    /// ascending by serial (spec §14.5).
174
    pub policies: Vec<SignedPolicy>,
175
    /// Each change's hash, in the order of `changes`, when whoever made
176
    /// the bundle knows it: the store it came from, or the bytes it was
177
    /// decoded from. Never read from the wire. Empty when unknown.
178
    pub hashes: Vec<ChangeHash>,
179
    /// Changes as stored, with their signatures, in dependency order, for a
180
    /// fetch between repositories on one machine: their text blobs and
181
    /// chunks are among `objects`. Never on the wire.
182
    pub raw_changes: Vec<(Vec<u8>, Vec<Signature>)>,
183
    /// Certificates of short-lived keys that signed what the bundle carries
184
    /// (spec §14.7), their issuers' identities among `objects`.
185
    pub certificates: Vec<crate::cert::SignedCertificate>,
186
}
187
188
impl Bundle {
18927×
    pub fn is_empty(&self) -> bool {
19027×
        self.changes.is_empty() && self.attests.is_empty() && self.objects.is_empty()
19127×
    }
192
}
193
194
/// A requested bookmark move (spec §10.2, §16.3).
195
#[derive(Clone, Debug)]
196
pub struct RefUpdate {
197
    pub name: String,
198
    pub old_state: ObjectRef,
199
    pub new_state: ObjectRef,
200
    pub force: bool,
201
    pub attestation: Option<SignedAttest>,
202
}
203
204
#[derive(Clone, Debug, PartialEq, Eq)]
205
pub struct RefResult {
206
    pub name: String,
207
    pub ok: bool,
208
    pub reason: String,
209
}
210
211
pub trait Remote {
212
    fn repo_id(&self) -> Result<[u8; 16]>;
213
    fn refs(&self) -> Result<RefsResponse>;
214
    /// Changes in the closure of `want` but not of `have`, in dependency order.
215
    fn negotiate(&self, have: &[ChangeHash], want: &[ChangeHash]) -> Result<Vec<ChangeHash>>;
216
    /// The changes with their signatures, seals, identities, and blobs; blobs
217
    /// larger than `max_blob` bytes are left out for lazy fetching (spec §13.5).
218
    fn fetch(&self, changes: &[ChangeHash], max_blob: Option<u64>) -> Result<Bundle>;
219
    /// Individual objects by reference (spec §16.1 `objects`); a blob comes
220
    /// with its chunks.
221
    fn objects(&self, refs: &[ObjectRef]) -> Result<Vec<(ObjectType, Vec<u8>)>>;
222
    /// A checkpoint of exactly `heads` (spec §16.1 `checkpoint`): the
223
    /// checkpoint object, its payload blob, and the blob's chunks.
224
    fn checkpoint(&self, heads: &[ChangeHash]) -> Result<Bundle>;
225
    /// A checkpoint of exactly `heads` without its graph blobs (spec §16.1
226
    /// `checkpoint-index`, oxygen#137), which the client then asks for in
227
    /// parts with `objects`. A remote that cannot answer it sends the
228
    /// whole checkpoint, which does as well.
2290×
    fn checkpoint_index(&self, heads: &[ChangeHash]) -> Result<Bundle> {
2300×
        self.checkpoint(heads)
2310×
    }
232
    /// The changes within `depth` dependency steps of `heads` (spec §17).
233
    fn shallow(&self, heads: &[ChangeHash], depth: u32) -> Result<Vec<ChangeHash>>;
234
    /// Push changes, bookmark updates, new tags, and optionally a newer
235
    /// policy. The policy is applied first; a result named `policy` reports
236
    /// it, and each tag reports as `tags/<name>`.
237
    fn push(
238
        &self,
239
        bundle: Bundle,
240
        updates: Vec<RefUpdate>,
241
        policy: Option<SignedPolicy>,
242
        tags: Vec<TagRef>,
243
    ) -> Result<Vec<RefResult>>;
244
}
245
246
// ---------------------------------------------------------------- local
247
248
/// Another repository on this machine, served in-process.
249
pub struct LocalRemote {
250
    pub repo: Repo,
251
    /// The pushing repository's id, which binds an unbound target on the
252
    /// first push, as `Oxy-Repo-Id` does over HTTP.
253
    pub claimed_id: Option<[u8; 16]>,
254
}
255
256
impl LocalRemote {
2571183×
    pub fn open(path: &Path) -> Result<LocalRemote> {
258
        Ok(LocalRemote {
2591183×
            repo: Repo::open(path)?,
2601183×
            claimed_id: None,
261
        })
2621183×
    }
263
}
264
265
impl Remote for LocalRemote {
266926×
    fn repo_id(&self) -> Result<[u8; 16]> {
267926×
        self.repo.id()
268926×
    }
269925×
    fn refs(&self) -> Result<RefsResponse> {
270925×
        self.repo.remote_refs()
271925×
    }
272365×
    fn negotiate(&self, have: &[ChangeHash], want: &[ChangeHash]) -> Result<Vec<ChangeHash>> {
273365×
        self.repo.negotiate(have, want)
274365×
    }
275369×
    fn fetch(&self, changes: &[ChangeHash], max_blob: Option<u64>) -> Result<Bundle> {
276369×
        self.repo.bundle_raw_for(changes, max_blob)
277369×
    }
2785×
    fn objects(&self, refs: &[ObjectRef]) -> Result<Vec<(ObjectType, Vec<u8>)>> {
2795×
        self.repo.objects_for(refs)
2805×
    }
2810×
    fn checkpoint(&self, heads: &[ChangeHash]) -> Result<Bundle> {
2820×
        self.repo.checkpoint_bundle_for(heads)
2830×
    }
2843×
    fn checkpoint_index(&self, heads: &[ChangeHash]) -> Result<Bundle> {
2853×
        self.repo.checkpoint_index_for(heads)
2863×
    }
2873×
    fn shallow(&self, heads: &[ChangeHash], depth: u32) -> Result<Vec<ChangeHash>> {
2883×
        self.repo.shallow_changes(heads, depth)
2893×
    }
290281×
    fn push(
291281×
        &self,
292281×
        bundle: Bundle,
293281×
        updates: Vec<RefUpdate>,
294281×
        policy: Option<SignedPolicy>,
295281×
        tags: Vec<TagRef>,
296281×
    ) -> Result<Vec<RefResult>> {
297281×
        if self.repo.is_unbound() {
29815×
            match self.claimed_id {
29915×
                Some(id) => self.repo.bind_id(id)?,
300
                None => {
3010×
                    return Err(RepoError::Msg(
3020×
                        "the remote is unbound and this client did not say which repository it is"
3030×
                            .into(),
3040×
                    ))
305
                }
306
            }
307266×
        }
308281×
        self.repo.receive_push(bundle, updates, policy, tags)
309281×
    }
310
}
311
312
// ---------------------------------------------------------------- http
313
314
/// How to reach a remote: credentials and trust.
315
#[derive(Clone, Debug, Default)]
316
pub struct RemoteOptions {
317
    /// Bearer token for pushes.
318
    pub token: Option<String>,
319
    /// PEM file with extra root certificates to trust for `https://` remotes
320
    /// (self-hosted servers); the system web roots are always trusted.
321
    pub ca: Option<PathBuf>,
322
    /// The local repository's id, sent as `Oxy-Repo-Id` so an unbound
323
    /// hosted repository can adopt it on the first push (spec §16.1).
324
    pub repo_id: Option<[u8; 16]>,
325
    /// Where a remote kept on a store (`dir://`, `s3://`, …) keeps its
326
    /// mirror and what it has seen: the remote's directory under
327
    /// `.oxy/remotes`. None (a clone, before there is a repository) means
328
    /// a temporary directory.
329
    pub cache_dir: Option<PathBuf>,
330
    /// Other tokens for the same hub, tried in turn when `token` is
331
    /// refused (401, 403 or 404): those of enclosing checkouts, when
332
    /// `token` came from the credential store rather than from this
333
    /// remote's own configuration (oxygen#112).
334
    pub fallback_tokens: Vec<String>,
335
}
336
337
/// Opens a store for a URL it understands, or passes (`None`). Stores that
338
/// need more than the standard library (the cloud ones) are added by the
339
/// program that links them, with [`register_store_opener`].
340
pub type StoreOpener =
341
    fn(&str, &RemoteOptions) -> Option<crate::strata::Result<Box<dyn crate::strata::Store>>>;
342
343
static STORE_OPENERS: Mutex<Vec<StoreOpener>> = Mutex::new(Vec::new());
344
345155×
pub fn register_store_opener(opener: StoreOpener) {
346155×
    STORE_OPENERS
347155×
        .lock()
348155×
        .unwrap_or_else(|p| p.into_inner())
349155×
        .push(opener);
350155×
}
351
352
/// A store for `url`, from `dir://` or any registered opener.
3531242×
pub fn open_store(
3541242×
    url: &str,
3551242×
    options: &RemoteOptions,
3561242×
) -> Option<crate::strata::Result<Box<dyn crate::strata::Store>>> {
3571242×
    if let Some(path) = url.strip_prefix("dir://") {
358
        return Some(
35959×
            crate::strata::LocalStore::open(path)
36059×
                .map(|s| Box::new(s) as Box<dyn crate::strata::Store>),
361
        );
3621183×
    }
3631183×
    let openers = STORE_OPENERS.lock().unwrap_or_else(|p| p.into_inner());
3641183×
    openers.iter().find_map(|open| open(url, options))
3651242×
}
366
367
/// The request header carrying the client's repository id.
368
pub const REPO_ID_HEADER: &str = "Oxy-Repo-Id";
369
370
/// The id of a hosted repository that has not adopted one yet.
371
pub const UNBOUND_ID: [u8; 16] = [0; 16];
372
373
/// The request header in which a client declares the protocol features it
374
/// understands beyond the 0.5.0-era set: a comma-separated list, which a
375
/// server may tailor its answers to (docs/protocol.md, *Client
376
/// capabilities*). A request without it is a client of that era.
377
pub const FEATURES_HEADER: &str = "Oxy-Features";
378
379
/// The feature of a client that authorizes a tag signed by a short-lived,
380
/// certified key by its certificate at the time the host accepted it
381
/// (oxygen#129). A client without it refuses such a tag, and with it the
382
/// whole fetch, so servers leave those tags out of its `refs` (oxygen#131).
383
pub const FEATURE_CERTIFIED_TAGS: &str = "certified-tags";
384
385
/// The features this client declares in [`FEATURES_HEADER`].
386
pub const CLIENT_FEATURES: &[&str] = &[FEATURE_CERTIFIED_TAGS];
387
388
/// The `User-Agent` every request of this client sends: `oxy/<version>`.
389187×
pub fn user_agent() -> String {
390187×
    format!("oxy/{}", env!("CARGO_PKG_VERSION"))
391187×
}
392
393
/// Whether a [`FEATURES_HEADER`] value (absent: `None`) declares `feature`.
394
/// Entries are comma-separated, compared without surrounding blanks and
395
/// regardless of case; unknown ones are ignored.
396156×
pub fn declares_feature(header: Option<&str>, feature: &str) -> bool {
397156×
    header.is_some_and(|h| h.split(',').any(|f| f.trim().eq_ignore_ascii_case(feature)))
398156×
}
399
400
/// A remote served by `oxy-server` at `<base>/oxy/v1/...`.
401
pub struct HttpRemote {
402
    base: String,
403
    /// The token in use, and those still to try when it is refused.
404
    token: Mutex<Option<String>>,
405
    fallbacks: Mutex<Vec<String>>,
406
    repo_id: Option<[u8; 16]>,
407
    agent: ureq::Agent,
408
}
409
410
/// A TLS client configuration trusting the web roots plus `ca`, if given:
411
/// the trust every oxy connection uses, shared with tools that call hub APIs.
412190×
pub fn tls_client_config(ca: Option<&Path>) -> Result<Arc<rustls::ClientConfig>> {
413190×
    let mut roots = rustls::RootCertStore::empty();
414190×
    roots.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
415190×
    if let Some(path) = ca {
4165×
        let pem = std::fs::read(path)
4175×
            .map_err(|e| RepoError::Msg(format!("reading CA file {}: {e}", path.display())))?;
4185×
        let certs = rustls_pemfile::certs(&mut pem.as_slice())
4195×
            .collect::<std::result::Result<Vec<_>, _>>()
4205×
            .map_err(|e| RepoError::Msg(format!("parsing CA file {}: {e}", path.display())))?;
4215×
        if certs.is_empty() {
4220×
            return Err(RepoError::Msg(format!(
4230×
                "CA file {} holds no certificates",
4240×
                path.display()
4250×
            )));
4265×
        }
4275×
        for c in certs {
4285×
            roots
4295×
                .add(c)
4305×
                .map_err(|e| RepoError::Msg(format!("CA file {}: {e}", path.display())))?;
431
        }
432185×
    }
433190×
    let cfg = rustls::ClientConfig::builder_with_provider(Arc::new(
434190×
        rustls::crypto::ring::default_provider(),
435
    ))
436190×
    .with_safe_default_protocol_versions()
437190×
    .map_err(|e| RepoError::Msg(e.to_string()))?
438190×
    .with_root_certificates(roots)
439190×
    .with_no_client_auth();
440190×
    Ok(Arc::new(cfg))
441190×
}
442
443
impl HttpRemote {
444184×
    pub fn new(base: &str, options: &RemoteOptions) -> Result<HttpRemote> {
445184×
        refuse_plain_token(base, options)?;
446184×
        let agent = ureq::AgentBuilder::new()
447184×
            .tls_config(tls_client_config(options.ca.as_deref())?)
448184×
            .user_agent(&user_agent())
449184×
            .build();
450184×
        Ok(HttpRemote {
451184×
            base: base.trim_end_matches('/').to_string(),
452184×
            token: Mutex::new(options.token.clone()),
453184×
            fallbacks: Mutex::new(options.fallback_tokens.iter().rev().cloned().collect()),
454184×
            repo_id: options.repo_id,
455184×
            agent,
456184×
        })
457184×
    }
458
459
    /// A request, tried again with the next fallback token while the
460
    /// hub refuses the one in use (oxygen#112).
461464×
    fn call(&self, post: bool, endpoint: &str, body: Option<&[u8]>) -> Result<Vec<u8>> {
462
        loop {
463465×
            let token = self.token.lock().unwrap_or_else(|p| p.into_inner()).clone();
464465×
            match self.call_once(post, endpoint, body, token.as_deref()) {
46512×
                Err(RepoError::Msg(m)) if token.is_some() && refused(&m) => {
4663×
                    let next = self
4673×
                        .fallbacks
4683×
                        .lock()
4693×
                        .unwrap_or_else(|p| p.into_inner())
4703×
                        .pop();
4713×
                    let Some(next) = next else {
4722×
                        return Err(RepoError::Msg(m));
473
                    };
4741×
                    crate::credentials::warn_once(&format!(
4751×
                        "{}: the stored token was refused; using the one an enclosing checkout has for this hub",
4761×
                        self.base
4771×
                    ));
4781×
                    *self.token.lock().unwrap_or_else(|p| p.into_inner()) = Some(next);
479
                }
480462×
                other => return other,
481
            }
482
        }
483464×
    }
484
485465×
    fn call_once(
486465×
        &self,
487465×
        post: bool,
488465×
        endpoint: &str,
489465×
        body: Option<&[u8]>,
490465×
        token: Option<&str>,
491465×
    ) -> Result<Vec<u8>> {
492465×
        let url = format!("{}/oxy/v1/{endpoint}", self.base);
493465×
        let mut req = if post {
494162×
            self.agent.post(&url)
495
        } else {
496303×
            self.agent.get(&url)
497
        };
498465×
        req = req
499465×
            .set("Accept", CONTENT_TYPE)
500465×
            .set(FEATURES_HEADER, &CLIENT_FEATURES.join(","));
501465×
        if let Some(t) = token {
50222×
            req = req.set("Authorization", &format!("Bearer {t}"));
503443×
        }
504465×
        if let Some(id) = &self.repo_id {
505432×
            req = req.set(REPO_ID_HEADER, &hex::encode(id));
506432×
        }
507465×
        let resp = match body {
508162×
            Some(b) => req.set("Content-Type", CONTENT_TYPE).send_bytes(b),
509303×
            None => req.call(),
510
        };
51112×
        match resp {
512453×
            Ok(r) => {
513453×
                let mut out = Vec::new();
514453×
                r.into_reader()
515453×
                    .read_to_end(&mut out)
516453×
                    .map_err(|e| RepoError::Msg(format!("{url}: {e}")))?;
517453×
                Ok(out)
518
            }
5199×
            Err(ureq::Error::Status(code, r)) => {
5209×
                let text = r.into_string().unwrap_or_default();
521
                // The hint comes from the status alone: the server's text
522
                // (a host's reason for refusing a push, several lines
523
                // perhaps) is shown as it is, never read for hints. A
524
                // proxy's HTML error page is shown by its title only
525
                // (oxygen#133).
5269×
                let status = format!("{url}: HTTP {code}");
5279×
                let msg = format!("{status}: {}", plain_error_text(&text));
5289×
                Err(RepoError::Msg(match hint_for(&status) {
5298×
                    Some(h) => format!("{msg}\n  hint: {h}"),
5301×
                    None => msg,
531
                }))
532
            }
533
            // The transport error already names the URL.
5343×
            Err(e) => Err(RepoError::Msg(with_hint(e.to_string()))),
535
        }
536465×
    }
537
}
538
539
/// Whether a failed request's message says the hub refused its token:
540
/// HTTP 401, 403, or 404 (a hub hides a private repository from a token
541
/// that may not read it).
5424×
fn refused(message: &str) -> bool {
5434×
    [": HTTP 401", ": HTTP 403", ": HTTP 404"]
5444×
        .iter()
5456×
        .any(|c| message.contains(c))
5464×
}
547
548
/// Refuse to send a token where anyone on the way could read it: plain
549
/// `http` to another machine (see [`crate::credentials::token_allowed`]).
550186×
fn refuse_plain_token(url: &str, options: &RemoteOptions) -> Result<()> {
551186×
    if options.token.is_some() && !crate::credentials::token_allowed(url) {
5520×
        return Err(RepoError::Msg(format!(
5530×
            "{url}: refusing to send a token over plain http; use https"
5540×
        )));
555186×
    }
556186×
    Ok(())
557186×
}
558
559
/// What to do about a failed request, recognised from its message.
56021×
pub fn hint_for(message: &str) -> Option<&'static str> {
56121×
    let m = message.to_ascii_lowercase();
56221×
    let hint = if m.contains("http 401") {
5636×
        "the hub needs you signed in, or did not accept the token: run `oxy auth login HUB` (pushing needs repo:write)"
56415×
    } else if m.contains("http 403") {
5651×
        "the token or account lacks permission: pushing needs a token with repo:write and write access to the repository"
56614×
    } else if m.contains("http 413") {
5671×
        "the request was larger than the server, or a proxy in front of it, takes at once (Cloudflare's limit is 100 MB): push in smaller parts with `oxy config push.batch-bytes 33554432`, then push again"
56813×
    } else if m.contains("http 404") {
5694×
        "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`)"
5709×
    } else if m.contains("unknownissuer")
5717×
        || m.contains("unknown issuer")
5727×
        || m.contains("certificate")
5736×
        || m.contains("invalidcertificate")
574
    {
5753×
        "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`"
5766×
    } else if m.contains("connection refused") {
5773×
        "nothing is listening there: check the URL and port, and that the server is running"
5783×
    } else if m.contains("dns")
5792×
        || m.contains("failed to lookup")
5802×
        || m.contains("name or service not known")
581
    {
5821×
        "the host name does not resolve: check the URL"
5832×
    } else if m.contains("timed out") || m.contains("timeout") {
5840×
        "the server did not answer in time: check the network, or try again"
585
    } else {
5862×
        return None;
587
    };
58819×
    Some(hint)
58921×
}
590
591
/// An error response's text as it is, unless it is an HTML page (a proxy's,
592
/// such as Cloudflare's 413): then its title, or a note that it was one.
59311×
fn plain_error_text(text: &str) -> String {
59411×
    let t = text.trim();
59511×
    let lower = t.to_ascii_lowercase();
59611×
    if !(lower.starts_with("<!doctype html") || lower.starts_with("<html")) {
59710×
        return t.to_string();
5981×
    }
5991×
    let title = lower
6001×
        .find("<title>")
6011×
        .and_then(|i| {
6021×
            lower[i + 7..]
6031×
                .find("</title>")
6041×
                .map(|j| t[i + 7..i + 7 + j].trim())
6051×
        })
6061×
        .filter(|s| !s.is_empty());
6071×
    match title {
6081×
        Some(s) => format!("{s} (an HTML error page, from a proxy in front of the server perhaps)"),
6090×
        None => "an HTML error page (from a proxy in front of the server perhaps)".into(),
610
    }
61111×
}
612
613
/// `message`, followed by what to do about it when that is known.
6143×
pub fn with_hint(message: String) -> String {
6153×
    match hint_for(&message) {
6163×
        Some(h) => format!("{message}\n  hint: {h}"),
6170×
        None => message,
618
    }
6193×
}
620
621
/// A JSON request to a hub API (`GET`, `POST` or `DELETE`), with the same
622
/// TLS trust and token rules as remotes. Returns the status and body, an
623
/// error status included; only transport failures are errors.
6240×
pub fn http_json(
6250×
    method: &str,
6260×
    url: &str,
6270×
    body: Option<&str>,
6280×
    options: &RemoteOptions,
6290×
) -> Result<(u16, String)> {
6300×
    refuse_plain_token(url, options)?;
6310×
    let agent = ureq::AgentBuilder::new()
6320×
        .tls_config(tls_client_config(options.ca.as_deref())?)
6330×
        .timeout(std::time::Duration::from_secs(60))
6340×
        .user_agent(&user_agent())
6350×
        .build();
6360×
    let mut req = agent.request(method, url).set("Accept", "application/json");
6370×
    if let Some(t) = &options.token {
6380×
        req = req.set("Authorization", &format!("Bearer {t}"));
6390×
    }
6400×
    let resp = match body {
6410×
        Some(b) => req.set("Content-Type", "application/json").send_string(b),
6420×
        None => req.call(),
643
    };
6440×
    match resp {
6450×
        Ok(r) => {
6460×
            let code = r.status();
6470×
            Ok((code, r.into_string().unwrap_or_default()))
648
        }
6490×
        Err(ureq::Error::Status(code, r)) => Ok((code, r.into_string().unwrap_or_default())),
6500×
        Err(e) => Err(RepoError::Msg(with_hint(e.to_string()))),
651
    }
6520×
}
653
654
/// An authenticated GET of any URL on a host, with the same TLS trust and
655
/// token as remotes use (for hub APIs: proposals). Returns the body.
6562×
pub fn http_get(url: &str, options: &RemoteOptions) -> Result<Vec<u8>> {
6572×
    refuse_plain_token(url, options)?;
6582×
    let agent = ureq::AgentBuilder::new()
6592×
        .tls_config(tls_client_config(options.ca.as_deref())?)
6602×
        .user_agent(&user_agent())
6612×
        .build();
6622×
    let mut req = agent.get(url).set("Accept", "application/json");
6632×
    if let Some(t) = &options.token {
6640×
        req = req.set("Authorization", &format!("Bearer {t}"));
6652×
    }
6662×
    match req.call() {
6672×
        Ok(r) => {
6682×
            let mut out = Vec::new();
6692×
            r.into_reader()
6702×
                .read_to_end(&mut out)
6712×
                .map_err(|e| RepoError::Msg(format!("{url}: {e}")))?;
6722×
            Ok(out)
673
        }
6740×
        Err(ureq::Error::Status(code, r)) => {
6750×
            let text = r.into_string().unwrap_or_default();
6760×
            Err(RepoError::Msg(with_hint(format!(
6770×
                "{url}: HTTP {code}: {}",
6780×
                text.trim()
6790×
            ))))
680
        }
681
        // The transport error already names the URL.
6820×
        Err(e) => Err(RepoError::Msg(with_hint(e.to_string()))),
683
    }
6842×
}
685
686
impl Remote for HttpRemote {
687155×
    fn repo_id(&self) -> Result<[u8; 16]> {
688155×
        wire::decode_capabilities(&self.call(false, "capabilities", None)?)
689155×
    }
690148×
    fn refs(&self) -> Result<RefsResponse> {
691148×
        Ok(wire::decode_refs(&self.call(false, "refs", None)?)?.1)
692148×
    }
69357×
    fn negotiate(&self, have: &[ChangeHash], want: &[ChangeHash]) -> Result<Vec<ChangeHash>> {
69457×
        wire::decode_hashes(&self.call(
695
            true,
69657×
            "negotiate",
69757×
            Some(&wire::encode_negotiate(have, want)),
6980×
        )?)
69957×
    }
70057×
    fn fetch(&self, changes: &[ChangeHash], max_blob: Option<u64>) -> Result<Bundle> {
70157×
        wire::decode_bundle(&self.call(
702
            true,
70357×
            "fetch",
70457×
            Some(&wire::encode_fetch(changes, max_blob)),
7050×
        )?)
70657×
    }
7071×
    fn objects(&self, refs: &[ObjectRef]) -> Result<Vec<(ObjectType, Vec<u8>)>> {
708
        Ok(
7091×
            wire::decode_bundle(&self.call(true, "objects", Some(&wire::encode_hashes(refs)))?)?
710
                .objects,
711
        )
7121×
    }
7130×
    fn checkpoint(&self, heads: &[ChangeHash]) -> Result<Bundle> {
7140×
        let body = {
7150×
            let _t = crate::timing::phase("remote: checkpoint answer");
7160×
            self.call(true, "checkpoint", Some(&wire::encode_hashes(heads)))?
717
        };
7180×
        let _t = crate::timing::phase("remote: decode the checkpoint");
7190×
        wire::decode_bundle(&body)
7200×
    }
7210×
    fn checkpoint_index(&self, heads: &[ChangeHash]) -> Result<Bundle> {
7220×
        let body = {
7230×
            let _t = crate::timing::phase("remote: checkpoint index");
7240×
            match self.call(true, "checkpoint-index", Some(&wire::encode_hashes(heads))) {
7250×
                Ok(b) => b,
726
                // A server from before checkpoint-index: the whole answer.
7270×
                Err(RepoError::Msg(m)) if m.contains("HTTP 404") => return self.checkpoint(heads),
7280×
                Err(e) => return Err(e),
729
            }
730
        };
7310×
        wire::decode_bundle(&body)
7320×
    }
7330×
    fn shallow(&self, heads: &[ChangeHash], depth: u32) -> Result<Vec<ChangeHash>> {
7340×
        wire::decode_hashes(&self.call(
735
            true,
7360×
            "shallow",
7370×
            Some(&wire::encode_shallow(heads, depth)),
7380×
        )?)
7390×
    }
74046×
    fn push(
74146×
        &self,
74246×
        bundle: Bundle,
74346×
        updates: Vec<RefUpdate>,
74446×
        policy: Option<SignedPolicy>,
74546×
        tags: Vec<TagRef>,
74646×
    ) -> Result<Vec<RefResult>> {
74746×
        wire::decode_push_response(&self.call(
748
            true,
74946×
            "push",
75046×
            Some(&wire::encode_push(
75146×
                &bundle,
75246×
                &updates,
75346×
                policy.as_ref(),
75446×
                &tags,
75546×
            )),
7565×
        )?)
75746×
    }
758
}
759
760
/// A remote's URL as it is stored: an `http(s)://` URL as given, a local
761
/// path made absolute (with its `file://` kept), so it still names the same
762
/// repository from inside the clone (oxygen#57).
763292×
pub fn stored_url(url: &str) -> String {
764
    // Only a path is made absolute: a plain one, or one behind file:// or
765
    // dir://. Every other URL (a hub, a bucket) is kept as written.
766292×
    let (prefix, path) = match (url.strip_prefix("file://"), url.strip_prefix("dir://")) {
7671×
        (Some(p), _) => ("file://", p),
76811×
        (_, Some(p)) => ("dir://", p),
769280×
        _ if url.contains("://") => return url.to_string(),
770251×
        _ => ("", url),
771
    };
772263×
    match std::path::absolute(path) {
773263×
        Ok(abs) => format!("{prefix}{}", abs.display()),
7740×
        Err(_) => url.to_string(),
775
    }
776292×
}
777
778
/// Open a remote by URL: a local path (optionally `file://`), `http(s)://`
779
/// (a hub), or a store (`dir://`, and whatever openers are registered).
7801414×
pub fn open_remote(url: &str, options: &RemoteOptions) -> Result<Box<dyn Remote>> {
7811414×
    if url.starts_with("http://") || url.starts_with("https://") {
782184×
        return Ok(Box::new(HttpRemote::new(url, options)?));
7831230×
    }
7841230×
    if let Some(store) = open_store(url, options) {
78548×
        return crate::repo::strata::open_store_remote(store?, options);
7861182×
    }
7871182×
    let path = url.strip_prefix("file://").unwrap_or(url);
7881182×
    if path.contains("://") {
7890×
        return Err(RepoError::Msg(format!("unsupported remote URL {url:?}")));
7901182×
    }
7911182×
    let mut local = LocalRemote::open(Path::new(path))?;
7921182×
    local.claimed_id = options.repo_id;
7931182×
    Ok(Box::new(local))
7941414×
}
795
796
// ---------------------------------------------------------------- wire
797
798
/// CBOR encodings of the protocol messages (spec §16.1).
799
pub mod wire {
800
    use super::*;
801
8020×
    fn schema(msg: &str) -> RepoError {
8030×
        RepoError::Object(ObjectError::Schema(msg.into()))
8040×
    }
805262×
    fn sigs_value(sigs: &[Signature]) -> Value {
806262×
        Value::Array(sigs.iter().map(|s| s.to_value()).collect())
807262×
    }
808258×
    fn sigs_from(v: &Value) -> Result<Vec<Signature>> {
809258×
        Ok(o::array(v, "signatures")?
810258×
            .iter()
811258×
            .map(Signature::from_value)
812258×
            .collect::<std::result::Result<Vec<_>, _>>()?)
813258×
    }
814456×
    fn hashes_value(hs: &[ObjectRef]) -> Value {
815605×
        Value::Array(hs.iter().map(|h| Value::Bytes(h.0.to_vec())).collect())
816456×
    }
817517×
    fn hashes_from(v: &Value) -> Result<Vec<ObjectRef>> {
818517×
        Ok(o::array(v, "hashes")?
819517×
            .iter()
820667×
            .map(|h| o::oref(h, "hash"))
821517×
            .collect::<std::result::Result<Vec<_>, _>>()?)
822517×
    }
82391×
    fn attest_value(sa: &SignedAttest) -> Value {
82491×
        Value::Array(vec![Value::Bytes(sa.attest.encode()), sigs_value(&sa.sigs)])
82591×
    }
826106×
    fn attest_from(v: &Value) -> Result<SignedAttest> {
827106×
        let a = o::array(v, "signed attest")?;
828106×
        if a.len() != 2 {
8290×
            return Err(schema("signed attest: expected [attest, sigs]"));
830106×
        }
831
        Ok(SignedAttest {
832106×
            attest: Attest::decode(o::bytes(&a[0], "attest")?)?,
833106×
            sigs: sigs_from(&a[1])?,
834
        })
835106×
    }
836284×
    fn opt_attest_value(sa: &Option<SignedAttest>) -> Value {
837284×
        sa.as_ref().map(attest_value).unwrap_or(Value::Null)
838284×
    }
839341×
    fn opt_attest_from(v: &Value) -> Result<Option<SignedAttest>> {
840341×
        if v.is_null() {
841251×
            Ok(None)
842
        } else {
84390×
            attest_from(v).map(Some)
844
        }
845341×
    }
846
    /// `[policy bytes, [signature]]`: also the format of a policy proposal
847
    /// file exchanged between root holders (spec §14.5).
84845×
    pub fn policy_value(sp: &SignedPolicy) -> Value {
84945×
        Value::Array(vec![Value::Bytes(sp.policy.encode()), sigs_value(&sp.sigs)])
85045×
    }
85143×
    pub fn policy_from(v: &Value) -> Result<SignedPolicy> {
85243×
        let a = o::array(v, "signed policy")?;
85343×
        if a.len() != 2 {
8540×
            return Err(schema("signed policy: expected [policy, sigs]"));
85543×
        }
856
        Ok(SignedPolicy {
85743×
            policy: Policy::decode(o::bytes(&a[0], "policy")?)?,
85843×
            sigs: sigs_from(&a[1])?,
859
        })
86043×
    }
861228×
    fn opt_policy_value(sp: Option<&SignedPolicy>) -> Value {
862228×
        sp.map(policy_value).unwrap_or(Value::Null)
863228×
    }
864267×
    fn opt_policy_from(v: &Value) -> Result<Option<SignedPolicy>> {
865267×
        if v.is_null() {
866245×
            Ok(None)
867
        } else {
86822×
            policy_from(v).map(Some)
869
        }
870267×
    }
8711141×
    fn map<'a>(v: &'a Value, what: &str) -> Result<&'a o::Map> {
8721141×
        Ok(o::map(v, what)?)
8731141×
    }
8743219×
    fn field<'a>(m: &'a o::Map, k: u64, what: &str) -> Result<&'a Value> {
8753219×
        Ok(o::field(m, k, what)?)
8763219×
    }
877
878
    /// A bundle's value. Each change's text blobs and their chunks (spec
879
    /// §6.1) are added to its objects when they are not already there, so a
880
    /// bundle can always be read on its own.
881141×
    pub fn bundle_value(b: &Bundle) -> Value {
882141×
        let mut changes = Vec::with_capacity(b.raw_changes.len() + b.changes.len());
883
        // Changes as stored are already their encoding, their texts among
884
        // the objects.
885141×
        for (bytes, s) in &b.raw_changes {
8860×
            changes.push(Value::Array(vec![
8870×
                Value::Bytes(bytes.clone()),
8880×
                sigs_value(s),
8890×
            ]));
8900×
        }
891141×
        let mut texts: Vec<(ObjectType, Vec<u8>)> = Vec::new();
892141×
        let mut listed: Option<std::collections::HashSet<ObjectRef>> = None;
893141×
        for (c, s) in &b.changes {
894126×
            let (bytes, stored) = c.encode_parts();
895126×
            for t in stored {
8960×
                let listed = listed.get_or_insert_with(|| {
8970×
                    b.objects
8980×
                        .iter()
8990×
                        .map(|(ty, body)| crate::hash::hash_object(*ty, body))
9000×
                        .collect()
9010×
                });
9020×
                if !listed.insert(t.blob.hash()) {
9030×
                    continue;
9040×
                }
9050×
                for chunk in crate::chunk::chunks(&t.content) {
9060×
                    if listed.insert(crate::hash::hash_object(ObjectType::Chunk, chunk)) {
9070×
                        texts.push((ObjectType::Chunk, chunk.to_vec()));
9080×
                    }
909
                }
9100×
                texts.push((ObjectType::Blob, t.blob.encode()));
911
            }
912126×
            changes.push(Value::Array(vec![Value::Bytes(bytes), sigs_value(s)]));
913
        }
914141×
        let mut v = Value::map([
915141×
            (0, Value::Array(changes)),
916141×
            (
917141×
                1,
918141×
                Value::Array(b.attests.iter().map(attest_value).collect()),
919141×
            ),
920
            (
921
                2,
922
                Value::Array(
923141×
                    b.objects
924141×
                        .iter()
925141×
                        .chain(&texts)
926204×
                        .map(|(t, body)| {
927204×
                            Value::Array(vec![
928204×
                                Value::Text(t.name().into()),
929204×
                                Value::Bytes(body.clone()),
930204×
                            ])
931204×
                        })
932141×
                        .collect(),
933
                ),
934
            ),
935141×
            (
936141×
                3,
937141×
                Value::Array(b.policies.iter().map(policy_value).collect()),
938141×
            ),
939
        ]);
940
        // Only when there are any; older peers ignore the field.
941141×
        if !b.certificates.is_empty() {
9427×
            if let Value::Map(m) = &mut v {
9437×
                m.insert(
944
                    4,
945
                    Value::Array(
9467×
                        b.certificates
9477×
                            .iter()
9487×
                            .map(|c| Value::Bytes(c.encode()))
9497×
                            .collect(),
950
                    ),
951
                );
9520×
            }
953134×
        }
954141×
        v
955141×
    }
956
957131×
    pub fn bundle_from_value(v: &Value) -> Result<Bundle> {
958131×
        let m = map(v, "bundle")?;
959131×
        let mut b = Bundle::default();
960193×
        for ob in o::array(field(m, 2, "objects")?, "objects")? {
961193×
            let pair = o::array(ob, "object")?;
962193×
            if pair.len() != 2 {
9630×
                return Err(schema("object: expected [type, body]"));
964193×
            }
965193×
            let ty = ObjectType::from_name(o::text(&pair[0], "object type")?)
966193×
                .ok_or_else(|| schema("unknown object type"))?;
967193×
            b.objects
968193×
                .push((ty, o::bytes(&pair[1], "object body")?.to_vec()));
969
        }
970
        // Stored inserts are read from the bundle's own objects.
971131×
        let mut by_ref: Option<std::collections::HashMap<ObjectRef, usize>> = None;
972131×
        for c in o::array(field(m, 0, "changes")?, "changes")? {
973109×
            let pair = o::array(c, "change entry")?;
974109×
            if pair.len() != 2 {
9750×
                return Err(schema("change entry: expected [change, sigs]"));
976109×
            }
977109×
            let encoded = o::bytes(&pair[0], "change")?;
978109×
            b.hashes
979109×
                .push(crate::hash::hash_object(ObjectType::Change, encoded));
980109×
            let change = Change::decode_with(encoded, &mut |text, count, form| {
9810×
                let by_ref = by_ref.get_or_insert_with(|| {
9820×
                    b.objects
9830×
                        .iter()
9840×
                        .enumerate()
9850×
                        .map(|(i, (ty, body))| (crate::hash::hash_object(*ty, body), i))
9860×
                        .collect()
9870×
                });
9880×
                let get =
9890×
                    |r: &ObjectRef, want: ObjectType| match by_ref.get(r).map(|i| &b.objects[*i]) {
9900×
                        Some((ty, body)) if *ty == want => Ok(body),
9910×
                        _ => Err(ObjectError::Schema(format!(
9920×
                            "the bundle lacks {} {}",
9930×
                            want.name(),
9940×
                            r.short(12)
9950×
                        ))),
9960×
                    };
9970×
                let blob = crate::objects::Blob::decode(get(text, ObjectType::Blob)?)?;
9980×
                let mut content = Vec::with_capacity(blob.length as usize);
9990×
                for chunk in &blob.chunks {
10000×
                    content.extend_from_slice(get(chunk, ObjectType::Chunk)?);
1001
                }
10020×
                crate::objects::text_lines(&content, count, form)
10030×
            })?;
1004109×
            b.changes.push((change, sigs_from(&pair[1])?));
1005
        }
1006131×
        for a in o::array(field(m, 1, "attests")?, "attests")? {
100716×
            b.attests.push(attest_from(a)?);
1008
        }
1009131×
        if let Some(ps) = m.get(&3) {
1010131×
            for p in o::array(ps, "policies")? {
10113×
                b.policies.push(policy_from(p)?);
1012
            }
10130×
        }
1014131×
        if let Some(cs) = m.get(&4) {
10157×
            for c in o::array(cs, "certificates")? {
10167×
                b.certificates.push(
10177×
                    crate::cert::SignedCertificate::decode(o::bytes(c, "certificate")?)
10187×
                        .map_err(|e| schema(&format!("certificate: {e}")))?,
1019
                );
1020
            }
1021124×
        }
1022131×
        Ok(b)
1023131×
    }
1024
102593×
    pub fn encode_bundle(b: &Bundle) -> Vec<u8> {
102693×
        cbor::encode(&bundle_value(b))
102793×
    }
102887×
    pub fn decode_bundle(bytes: &[u8]) -> Result<Bundle> {
102987×
        bundle_from_value(&cbor::decode(bytes).map_err(ObjectError::from)?)
103087×
    }
1031
1032150×
    pub fn encode_capabilities(id: [u8; 16]) -> Vec<u8> {
1033150×
        cbor::encode(&Value::map([
1034150×
            (0, Value::Array(vec![Value::Uint(PROTOCOL_VERSION)])),
1035150×
            (1, Value::Bytes(id.to_vec())),
1036150×
            (2, Value::Array(vec![Value::Text("seal".into())])),
1037150×
        ]))
1038150×
    }
1039150×
    pub fn decode_capabilities(bytes: &[u8]) -> Result<[u8; 16]> {
1040150×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
1041150×
        let m = map(&v, "capabilities")?;
1042150×
        let versions = o::array(field(m, 0, "versions")?, "versions")?;
1043150×
        if !versions
1044150×
            .iter()
1045150×
            .any(|x| x.as_uint() == Some(PROTOCOL_VERSION))
1046
        {
10470×
            return Err(RepoError::Msg(
10480×
                "remote does not speak protocol version 1".into(),
10490×
            ));
1050150×
        }
1051150×
        o::bytes(field(m, 1, "repo id")?, "repo id")?
1052150×
            .try_into()
1053150×
            .map_err(|_| schema("repo id: expected 16 bytes"))
1054150×
    }
1055
1056228×
    fn tags_value(tags: &[TagRef]) -> Value {
1057
        Value::Array(
1058228×
            tags.iter()
1059228×
                .map(|t| {
106034×
                    let mut v = Value::map([
106134×
                        (0, Value::Text(t.name.clone())),
106234×
                        (1, Value::Bytes(t.state.0.to_vec())),
106334×
                        (2, hashes_value(&t.heads)),
106434×
                        (3, opt_attest_value(&t.attestation)),
106534×
                    ]);
1066
                    // Only when there is one; older peers ignore them
1067
                    // (oxygen#129).
106834×
                    if let Value::Map(m) = &mut v {
106934×
                        if t.accepted.is_some() {
10708×
                            m.insert(4, opt_attest_value(&t.accepted));
107126×
                        }
107234×
                        if let Some(l) = &t.logged {
10732×
                            m.insert(5, logged_value(l));
107432×
                        }
107534×
                        if !t.integration.is_empty() {
10762×
                            m.insert(6, integration_value(&t.integration));
107732×
                        }
10780×
                    }
107934×
                    v
108034×
                })
1081228×
                .collect(),
1082
        )
1083228×
    }
1084267×
    fn tags_from(v: &Value) -> Result<Vec<TagRef>> {
1085267×
        let mut out = Vec::new();
1086267×
        for t in o::array(v, "tags")? {
108750×
            let tm = map(t, "tag")?;
108850×
            out.push(TagRef {
108950×
                name: o::text(field(tm, 0, "name")?, "name")?.to_owned(),
109050×
                state: o::oref(field(tm, 1, "state")?, "state")?,
109150×
                heads: hashes_from(field(tm, 2, "heads")?)?,
109250×
                attestation: opt_attest_from(field(tm, 3, "attestation")?)?,
109350×
                accepted: match tm.get(&4) {
10948×
                    Some(a) => opt_attest_from(a)?,
109542×
                    None => None,
1096
                },
109750×
                logged: tm.get(&5).map(logged_from).transpose()?,
109850×
                integration: match tm.get(&6) {
10992×
                    Some(l) => integration_from(l)?,
110048×
                    None => Vec::new(),
1101
                },
1102
            });
1103
        }
1104267×
        Ok(out)
1105267×
    }
1106
1107
    /// The tags of a refs answer as oxy 0.5.0 read them (and the runners
1108
    /// built with it), keys 0 to 3 only: what an older reader makes of an
1109
    /// answer with keys 4 to 6.
1110
    #[cfg(test)]
11111×
    pub(super) fn tags_as_0_5_read_them(bytes: &[u8]) -> Result<Vec<TagRef>> {
11121×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
11131×
        let m = map(&v, "refs")?;
11141×
        let mut out = Vec::new();
11152×
        for t in o::array(field(m, 3, "tags")?, "tags")? {
11162×
            let tm = map(t, "tag")?;
11172×
            out.push(TagRef::new(
11182×
                o::text(field(tm, 0, "name")?, "name")?.to_owned(),
11192×
                o::oref(field(tm, 1, "state")?, "state")?,
11202×
                hashes_from(field(tm, 2, "heads")?)?,
11212×
                opt_attest_from(field(tm, 3, "attestation")?)?,
1122
            ));
1123
        }
11241×
        Ok(out)
11251×
    }
1126
1127
    /// A log place, `[entry number, entry bytes, [proof hash]]` (spec §14.8).
11284×
    fn logged_value(l: &Logged) -> Value {
11294×
        Value::Array(vec![
11304×
            Value::Uint(l.index),
11314×
            Value::Bytes(l.entry.clone()),
11324×
            proof_value(&l.proof),
11334×
        ])
11344×
    }
11354×
    fn logged_from(v: &Value) -> Result<Logged> {
11364×
        let a = o::array(v, "logged")?;
11374×
        if a.len() != 3 {
11380×
            return Err(schema("logged: expected [index, entry, proof]"));
11394×
        }
1140
        Ok(Logged {
11414×
            index: o::uint(&a[0], "index")?,
11424×
            entry: o::bytes(&a[1], "entry")?.to_vec(),
11434×
            proof: proof_from(&a[2])?,
1144
        })
11454×
    }
1146
1147
    /// Cosigned checkpoints holding an entry, `[[note, [proof hash]]]`.
11484×
    fn integration_value(integration: &[Integration]) -> Value {
1149
        Value::Array(
11504×
            integration
11514×
                .iter()
11524×
                .map(|i| Value::Array(vec![Value::Text(i.note.clone()), proof_value(&i.proof)]))
11534×
                .collect(),
1154
        )
11554×
    }
11564×
    fn integration_from(v: &Value) -> Result<Vec<Integration>> {
11574×
        let mut out = Vec::new();
11584×
        for i in o::array(v, "integration")? {
11594×
            let a = o::array(i, "integration")?;
11604×
            if a.len() != 2 {
11610×
                return Err(schema("integration: expected [note, proof]"));
11624×
            }
11634×
            out.push(Integration {
11644×
                note: o::text(&a[0], "note")?.to_owned(),
11654×
                proof: proof_from(&a[1])?,
1166
            });
1167
        }
11684×
        Ok(out)
11694×
    }
1170
1171180×
    pub fn encode_refs(id: [u8; 16], resp: &RefsResponse) -> Vec<u8> {
1172180×
        let mut v = Value::map([
1173
            (
1174
                0,
1175
                Value::Array(
1176180×
                    resp.refs
1177180×
                        .iter()
1178186×
                        .map(|r| {
1179186×
                            let mut v = Value::map([
1180186×
                                (0, Value::Text(r.name.clone())),
1181186×
                                (1, Value::Bytes(r.state.0.to_vec())),
1182186×
                                (2, hashes_value(&r.heads)),
1183186×
                                (3, opt_attest_value(&r.attestation)),
1184186×
                                (4, r.last_serial.map(Value::Uint).unwrap_or(Value::Null)),
1185186×
                            ]);
1186
                            // Only when there is one; older peers ignore it.
1187186×
                            if let Value::Map(m) = &mut v {
1188186×
                                if r.accepted.is_some() {
11899×
                                    m.insert(5, opt_attest_value(&r.accepted));
1190177×
                                }
1191186×
                                if let Some(l) = &r.logged {
11922×
                                    m.insert(6, logged_value(l));
1193184×
                                }
1194186×
                                if !r.integration.is_empty() {
11952×
                                    m.insert(7, integration_value(&r.integration));
1196184×
                                }
11970×
                            }
1198186×
                            v
1199186×
                        })
1200180×
                        .collect(),
1201
                ),
1202
            ),
1203180×
            (1, Value::Bytes(id.to_vec())),
1204180×
            (2, opt_policy_value(resp.policy.as_ref())),
1205180×
            (3, tags_value(&resp.tags)),
1206180×
            (
1207180×
                4,
1208180×
                Value::Array(resp.history.iter().map(policy_value).collect()),
1209180×
            ),
1210180×
            (
1211180×
                5,
1212180×
                resp.default_bookmark
1213180×
                    .clone()
1214180×
                    .map(Value::Text)
1215180×
                    .unwrap_or(Value::Null),
1216180×
            ),
1217
        ]);
1218180×
        if let Value::Map(m) = &mut v {
1219180×
            if let Some(log) = &resp.log {
12203×
                m.insert(6, Value::Text(log.clone()));
1221177×
            }
1222180×
            if !resp.withdrawn.is_empty() {
12230×
                m.insert(8, tags_value(&resp.withdrawn));
1224180×
            }
1225180×
            if !resp.witnesses.is_empty() {
12262×
                m.insert(
1227
                    7,
1228
                    Value::Array(
12292×
                        resp.witnesses
12302×
                            .iter()
12312×
                            .map(|(name, id)| {
12322×
                                Value::Array(vec![
12332×
                                    Value::Text(name.clone()),
12342×
                                    Value::Bytes(id.clone()),
12352×
                                ])
12362×
                            })
12372×
                            .collect(),
1238
                    ),
1239
                );
1240178×
            }
12410×
        }
1242180×
        cbor::encode(&v)
1243180×
    }
1244223×
    pub fn decode_refs(bytes: &[u8]) -> Result<([u8; 16], RefsResponse)> {
1245223×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
1246223×
        let m = map(&v, "refs")?;
1247223×
        let id: [u8; 16] = o::bytes(field(m, 1, "repo id")?, "repo id")?
1248223×
            .try_into()
1249223×
            .map_err(|_| schema("repo id: expected 16 bytes"))?;
1250223×
        let mut refs = Vec::new();
1251229×
        for r in o::array(field(m, 0, "refs")?, "refs")? {
1252229×
            let rm = map(r, "ref")?;
1253229×
            let ls = field(rm, 4, "last serial")?;
1254229×
            refs.push(RemoteRef {
1255229×
                name: o::text(field(rm, 0, "name")?, "name")?.to_owned(),
1256229×
                state: o::oref(field(rm, 1, "state")?, "state")?,
1257229×
                heads: hashes_from(field(rm, 2, "heads")?)?,
1258229×
                attestation: opt_attest_from(field(rm, 3, "attestation")?)?,
1259229×
                last_serial: if ls.is_null() {
1260196×
                    None
1261
                } else {
126233×
                    Some(o::uint(ls, "last serial")?)
1263
                },
1264229×
                accepted: match rm.get(&5) {
12659×
                    Some(a) => opt_attest_from(a)?,
1266220×
                    None => None,
1267
                },
1268229×
                logged: rm.get(&6).map(logged_from).transpose()?,
1269229×
                integration: match rm.get(&7) {
12702×
                    Some(l) => integration_from(l)?,
1271227×
                    None => Vec::new(),
1272
                },
1273
            });
1274
        }
1275223×
        let policy = match m.get(&2) {
1276223×
            Some(p) => opt_policy_from(p)?,
12770×
            None => None,
1278
        };
1279223×
        let tags = match m.get(&3) {
1280223×
            Some(t) => tags_from(t)?,
12810×
            None => Vec::new(),
1282
        };
1283223×
        let mut history = Vec::new();
1284223×
        if let Some(h) = m.get(&4) {
1285223×
            for p in o::array(h, "history")? {
128617×
                history.push(policy_from(p)?);
1287
            }
12880×
        }
1289223×
        let default_bookmark = match m.get(&5) {
1290154×
            Some(Value::Text(t)) => Some(t.clone()),
129169×
            _ => None,
1292
        };
1293223×
        let log = match m.get(&6) {
12943×
            Some(Value::Text(t)) => Some(t.clone()),
1295220×
            _ => None,
1296
        };
1297223×
        let mut witnesses = Vec::new();
1298223×
        if let Some(w) = m.get(&7) {
12992×
            for x in o::array(w, "witnesses")? {
13002×
                let a = o::array(x, "witness")?;
13012×
                if a.len() != 2 {
13020×
                    return Err(schema("witness: expected [name, identity]"));
13032×
                }
13042×
                witnesses.push((
13052×
                    o::text(&a[0], "witness name")?.to_owned(),
13062×
                    o::bytes(&a[1], "witness identity")?.to_vec(),
1307
                ));
1308
            }
1309221×
        }
1310223×
        let withdrawn = match m.get(&8) {
13110×
            Some(t) => tags_from(t)?,
1312223×
            None => Vec::new(),
1313
        };
1314223×
        Ok((
1315223×
            id,
1316223×
            RefsResponse {
1317223×
                refs,
1318223×
                policy,
1319223×
                tags,
1320223×
                history,
1321223×
                default_bookmark,
1322223×
                log,
1323223×
                witnesses,
1324223×
                withdrawn,
1325223×
            },
1326223×
        ))
1327223×
    }
1328
1329
    /// A proof's hashes, from the leaf upwards (spec §14.8).
13308×
    fn proof_value(proof: &[[u8; 32]]) -> Value {
13318×
        Value::Array(proof.iter().map(|h| Value::Bytes(h.to_vec())).collect())
13328×
    }
1333
13348×
    fn proof_from(v: &Value) -> Result<Vec<[u8; 32]>> {
13358×
        let mut proof = Vec::new();
13368×
        for h in o::array(v, "proof")? {
13378×
            proof.push(
13388×
                o::bytes(h, "proof hash")?
13398×
                    .try_into()
13408×
                    .map_err(|_| schema("proof hash: expected 32 bytes"))?,
1341
            );
1342
        }
13438×
        Ok(proof)
13448×
    }
1345
134658×
    pub fn encode_negotiate(have: &[ChangeHash], want: &[ChangeHash]) -> Vec<u8> {
134758×
        cbor::encode(&Value::map([
134858×
            (0, hashes_value(have)),
134958×
            (1, hashes_value(want)),
135058×
        ]))
135158×
    }
135258×
    pub fn decode_negotiate(bytes: &[u8]) -> Result<(Vec<ChangeHash>, Vec<ChangeHash>)> {
135358×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
135458×
        let m = map(&v, "negotiate")?;
1355
        Ok((
135658×
            hashes_from(field(m, 0, "have")?)?,
135758×
            hashes_from(field(m, 1, "want")?)?,
1358
        ))
135958×
    }
1360
1361
    /// `fetch` request: `{0: [changes], 1: max blob size or null}`.
136259×
    pub fn encode_fetch(hs: &[ChangeHash], max_blob: Option<u64>) -> Vec<u8> {
136359×
        cbor::encode(&Value::map([
136459×
            (0, hashes_value(hs)),
136559×
            (1, max_blob.map(Value::Uint).unwrap_or(Value::Null)),
136659×
        ]))
136759×
    }
136860×
    pub fn decode_fetch(bytes: &[u8]) -> Result<(Vec<ChangeHash>, Option<u64>)> {
136960×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
137060×
        let m = map(&v, "fetch")?;
137160×
        let max = match m.get(&1) {
137259×
            Some(x) if !x.is_null() => Some(o::uint(x, "max blob")?),
137358×
            _ => None,
1374
        };
137560×
        Ok((hashes_from(field(m, 0, "changes")?)?, max))
137660×
    }
1377
1378
    /// `shallow` request: `{0: [heads], 1: depth}`.
13791×
    pub fn encode_shallow(hs: &[ChangeHash], depth: u32) -> Vec<u8> {
13801×
        cbor::encode(&Value::map([
13811×
            (0, hashes_value(hs)),
13821×
            (1, Value::Uint(depth as u64)),
13831×
        ]))
13841×
    }
13851×
    pub fn decode_shallow(bytes: &[u8]) -> Result<(Vec<ChangeHash>, u32)> {
13861×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
13871×
        let m = map(&v, "shallow")?;
1388
        Ok((
13891×
            hashes_from(field(m, 0, "heads")?)?,
13901×
            o::u32_(field(m, 1, "depth")?, "depth")?,
1391
        ))
13921×
    }
1393
139460×
    pub fn encode_hashes(hs: &[ChangeHash]) -> Vec<u8> {
139560×
        cbor::encode(&Value::map([(0, hashes_value(hs))]))
139660×
    }
139759×
    pub fn decode_hashes(bytes: &[u8]) -> Result<Vec<ChangeHash>> {
139859×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
139959×
        hashes_from(field(map(&v, "hashes")?, 0, "hashes")?)
140059×
    }
1401
140248×
    pub fn encode_push(
140348×
        bundle: &Bundle,
140448×
        updates: &[RefUpdate],
140548×
        policy: Option<&SignedPolicy>,
140648×
        tags: &[TagRef],
140748×
    ) -> Vec<u8> {
140848×
        cbor::encode(&Value::map([
140948×
            (0, bundle_value(bundle)),
141048×
            (2, opt_policy_value(policy)),
141148×
            (3, tags_value(tags)),
1412
            (
1413
                1,
1414
                Value::Array(
141548×
                    updates
141648×
                        .iter()
141748×
                        .map(|u| {
141847×
                            Value::map([
141947×
                                (0, Value::Text(u.name.clone())),
142047×
                                (1, Value::Bytes(u.old_state.0.to_vec())),
142147×
                                (2, Value::Bytes(u.new_state.0.to_vec())),
142247×
                                (3, Value::Bool(u.force)),
142347×
                                (4, opt_attest_value(&u.attestation)),
142447×
                            ])
142547×
                        })
142648×
                        .collect(),
1427
                ),
1428
            ),
1429
        ]))
143048×
    }
1431
    /// A decoded push: bundle, bookmark updates, policy, tags.
1432
    pub type PushParts = (Bundle, Vec<RefUpdate>, Option<SignedPolicy>, Vec<TagRef>);
1433
143444×
    pub fn decode_push(bytes: &[u8]) -> Result<PushParts> {
143544×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
143644×
        let m = map(&v, "push")?;
143744×
        let bundle = bundle_from_value(field(m, 0, "bundle")?)?;
143844×
        let mut updates = Vec::new();
143944×
        for u in o::array(field(m, 1, "updates")?, "updates")? {
144043×
            let um = map(u, "update")?;
144143×
            updates.push(RefUpdate {
144243×
                name: o::text(field(um, 0, "name")?, "name")?.to_owned(),
144343×
                old_state: o::oref(field(um, 1, "old_state")?, "old_state")?,
144443×
                new_state: o::oref(field(um, 2, "new_state")?, "new_state")?,
144543×
                force: field(um, 3, "force")?
144643×
                    .as_bool()
144743×
                    .ok_or_else(|| schema("force: expected bool"))?,
144843×
                attestation: opt_attest_from(field(um, 4, "attestation")?)?,
1449
            });
1450
        }
145144×
        let policy = match m.get(&2) {
145244×
            Some(p) => opt_policy_from(p)?,
14530×
            None => None,
1454
        };
145544×
        let tags = match m.get(&3) {
145644×
            Some(t) => tags_from(t)?,
14570×
            None => Vec::new(),
1458
        };
145944×
        Ok((bundle, updates, policy, tags))
146044×
    }
1461
146242×
    pub fn encode_push_response(results: &[RefResult]) -> Vec<u8> {
146342×
        cbor::encode(&Value::map([(
1464
            0,
1465
            Value::Array(
146642×
                results
146742×
                    .iter()
146848×
                    .map(|r| {
146948×
                        Value::map([
147048×
                            (0, Value::Text(r.name.clone())),
147148×
                            (1, Value::Bool(r.ok)),
147248×
                            (2, Value::Text(r.reason.clone())),
147348×
                        ])
147448×
                    })
147542×
                    .collect(),
1476
            ),
1477
        )]))
147842×
    }
147942×
    pub fn decode_push_response(bytes: &[u8]) -> Result<Vec<RefResult>> {
148042×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
148142×
        let m = map(&v, "push response")?;
148242×
        let mut out = Vec::new();
148348×
        for r in o::array(field(m, 0, "results")?, "results")? {
148448×
            let rm = map(r, "result")?;
148548×
            out.push(RefResult {
148648×
                name: o::text(field(rm, 0, "name")?, "name")?.to_owned(),
148748×
                ok: field(rm, 1, "ok")?
148848×
                    .as_bool()
148948×
                    .ok_or_else(|| schema("ok: expected bool"))?,
149048×
                reason: o::text(field(rm, 2, "reason")?, "reason")?.to_owned(),
1491
            });
1492
        }
149342×
        Ok(out)
149442×
    }
1495
}
1496
1497
#[cfg(test)]
1498
mod tests {
1499
    use super::*;
1500
    use crate::attest::AttestBody;
1501
    use crate::objects::Hlc;
1502
1503
    /// oxygen#133: a proxy's HTML error page is shown by its title, and a
1504
    /// server's own text as it is; a 413 says to push in smaller parts.
1505
    #[test]
15061×
    fn html_error_pages_are_shown_by_their_title() {
15071×
        let cloudflare = "<html>\r\n<head><title>413 Request Entity Too Large</title></head>\r\n<body><center><h1>413</h1></center><hr><center>cloudflare</center></body></html>";
15081×
        assert_eq!(
15091×
            plain_error_text(cloudflare),
1510
            "413 Request Entity Too Large (an HTML error page, from a proxy in front of the server perhaps)"
1511
        );
15121×
        assert_eq!(
15131×
            plain_error_text("  refused: a secret\nat a.txt:3 "),
1514
            "refused: a secret\nat a.txt:3"
1515
        );
15161×
        assert!(hint_for("https://hub/x: HTTP 413: too large")
15171×
            .unwrap()
15181×
            .contains("push.batch-bytes"));
15191×
    }
1520
1521
    #[test]
15221×
    fn client_features_are_declared_and_read() {
15231×
        assert_eq!(CLIENT_FEATURES.join(","), "certified-tags");
15241×
        assert!(user_agent().starts_with("oxy/"));
15251×
        assert!(declares_feature(
15261×
            Some("certified-tags"),
15271×
            FEATURE_CERTIFIED_TAGS
1528
        ));
15291×
        assert!(declares_feature(
15301×
            Some("later-thing, Certified-Tags ,x"),
15311×
            FEATURE_CERTIFIED_TAGS
1532
        ));
15331×
        assert!(!declares_feature(
15341×
            Some("certified-tags-v2"),
15351×
            FEATURE_CERTIFIED_TAGS
15361×
        ));
15371×
        assert!(!declares_feature(Some(""), FEATURE_CERTIFIED_TAGS));
15381×
        assert!(!declares_feature(None, FEATURE_CERTIFIED_TAGS));
15391×
    }
1540
1541
    #[test]
15421×
    fn wire_round_trips() {
15431×
        let c = crate::objects::tests::sample_change();
15441×
        let sk = crate::identity::SecretKey {
15451×
            ed_seed: [1; 32],
15461×
            ml_seed: [2; 32],
15471×
        };
15481×
        let id = sk.identity("a", "b", 0);
15491×
        let key = id.hash();
15501×
        let sig = sk.sign(crate::identity::Domain::Change, &key, &c.hash());
15511×
        let seal = Attest::seal([3; 16], vec![c.hash()]);
15521×
        let seal_sig = sk.sign(crate::identity::Domain::Attest, &key, &seal.hash());
15531×
        let policy = Policy::single_root([3; 16], id.clone(), 99);
15541×
        let psig = sk.sign(crate::identity::Domain::Policy, &key, &policy.hash());
15551×
        let bundle = Bundle {
15561×
            changes: vec![(c.clone(), vec![sig.clone()])],
15571×
            attests: vec![SignedAttest {
15581×
                attest: seal.clone(),
15591×
                sigs: vec![seal_sig],
15601×
            }],
15611×
            objects: vec![
15621×
                (ObjectType::Identity, id.encode()),
15631×
                (ObjectType::Chunk, b"xyz".to_vec()),
15641×
            ],
15651×
            policies: vec![SignedPolicy {
15661×
                policy: policy.clone(),
15671×
                sigs: vec![psig.clone()],
15681×
            }],
15691×
            hashes: vec![],
15701×
            raw_changes: vec![],
15711×
            certificates: vec![],
15721×
        };
15731×
        let d = wire::decode_bundle(&wire::encode_bundle(&bundle)).unwrap();
15741×
        assert_eq!(
1575
            d.hashes,
15761×
            vec![c.hash()],
1577
            "the receiver hashes what it was sent"
1578
        );
15791×
        assert_eq!(d.changes, bundle.changes);
15801×
        assert_eq!(d.attests, bundle.attests);
15811×
        assert_eq!(d.objects, bundle.objects);
15821×
        assert_eq!(d.policies, bundle.policies);
15831×
        assert!(d.certificates.is_empty());
1584
        // Certificates (keyless, oxygenhub#241) travel as field 4, only
1585
        // when there are any: a bundle without them encodes as before.
15861×
        let plain = wire::encode_bundle(&bundle);
15871×
        let mut with = bundle.clone();
15881×
        let issuer_sk = crate::identity::SecretKey::generate();
15891×
        let issuer = issuer_sk.identity("hub", "h@x", 1);
15901×
        with.certificates.push(crate::cert::SignedCertificate::sign(
15911×
            crate::cert::Certificate {
15921×
                key: id.clone(),
15931×
                issuer: issuer.hash(),
15941×
                subject: "agent:a@b".into(),
15951×
                claims: vec![],
15961×
                scope: crate::identity::Scope::CHANGES,
15971×
                not_before: 1,
15981×
                expires: 2,
15991×
                grant: None,
16001×
            },
16011×
            &issuer,
16021×
            &issuer_sk,
1603
        ));
16041×
        let encoded = wire::encode_bundle(&with);
16051×
        assert_ne!(encoded, plain);
16061×
        assert_eq!(
16071×
            wire::decode_bundle(&encoded).unwrap().certificates,
1608
            with.certificates
1609
        );
16101×
        with.certificates.clear();
16111×
        assert_eq!(wire::encode_bundle(&with), plain);
1612
16131×
        let att = Attest {
16141×
            repo: [3; 16],
16151×
            hlc: Hlc::default(),
16161×
            body: AttestBody::Ref {
16171×
                name: "main".into(),
16181×
                old_state: ObjectRef([1; 32]),
16191×
                new_state: ObjectRef([2; 32]),
16201×
                serial: 4,
16211×
            },
16221×
        };
16231×
        let refs = vec![
16241×
            RemoteRef {
16251×
                name: "main".into(),
16261×
                state: ObjectRef([2; 32]),
16271×
                heads: vec![c.hash()],
16281×
                attestation: Some(SignedAttest {
16291×
                    attest: att.clone(),
16301×
                    sigs: vec![sig.clone()],
16311×
                }),
16321×
                last_serial: Some(4),
16331×
                accepted: None,
16341×
                logged: None,
16351×
                integration: vec![],
16361×
            },
16371×
            RemoteRef {
16381×
                name: "dev".into(),
16391×
                state: ObjectRef([5; 32]),
16401×
                heads: vec![],
16411×
                attestation: None,
16421×
                last_serial: None,
16431×
                accepted: None,
16441×
                logged: None,
16451×
                integration: vec![],
16461×
            },
1647
        ];
16481×
        let tag = TagRef::new("v1".into(), ObjectRef([2; 32]), vec![c.hash()], None);
16491×
        let mut resp = RefsResponse {
16501×
            refs,
16511×
            policy: Some(SignedPolicy {
16521×
                policy: policy.clone(),
16531×
                sigs: vec![psig.clone()],
16541×
            }),
16551×
            tags: vec![tag.clone()],
16561×
            history: vec![SignedPolicy {
16571×
                policy: policy.clone(),
16581×
                sigs: vec![],
16591×
            }],
16601×
            default_bookmark: Some("develop".into()),
16611×
            log: Some("hub.example/log\n2\nroot\n\n- sig\n".into()),
16621×
            witnesses: vec![],
16631×
            withdrawn: vec![],
16641×
        };
1665
        // Without integrated times (spec §14.8) nothing is added: an old
1666
        // peer's answer, and what it reads.
16671×
        let old = wire::encode_refs([3; 16], &resp);
16681×
        let back = wire::decode_refs(&old).unwrap().1;
16692×
        assert!(back.witnesses.is_empty() && back.refs.iter().all(|r| r.integration.is_empty()));
16701×
        resp.refs[1].logged = Some(Logged {
16711×
            index: 41,
16721×
            entry: vec![1, 2, 3],
16731×
            proof: vec![[9; 32], [8; 32]],
16741×
        });
16751×
        resp.refs[1].integration = vec![Integration {
16761×
            note: "hub.example/log\n42\nroot\n\n- sig\n".into(),
16771×
            proof: vec![[7; 32]],
16781×
        }];
16791×
        resp.witnesses = vec![("w.example".into(), vec![4, 5, 6])];
16801×
        let new = wire::encode_refs([3; 16], &resp);
16811×
        let (id_back, back) = wire::decode_refs(&new).unwrap();
16821×
        assert_eq!(back.log, resp.log);
16831×
        assert_eq!(back.refs[1].logged, resp.refs[1].logged);
16841×
        assert_eq!(back.refs[1].integration, resp.refs[1].integration);
16851×
        assert_eq!(back.witnesses, resp.witnesses);
16861×
        assert_eq!(back.refs[0].logged, None);
1687
        // The new keys are 7s an old reader never asks for.
16881×
        let crate::cbor::Value::Map(m) = crate::cbor::decode(&new).unwrap() else {
16890×
            panic!()
1690
        };
16911×
        assert!(m.contains_key(&7));
16921×
        assert_eq!(id_back, [3; 16]);
16931×
        assert_eq!(back.refs.len(), 2);
16941×
        assert_eq!(back.refs[0].attestation.as_ref().unwrap().attest, att);
16951×
        assert_eq!(back.refs[1].last_serial, None);
16961×
        assert_eq!(back.policy.as_ref().unwrap().policy, policy);
16971×
        assert_eq!(back.history, resp.history);
16981×
        assert_eq!(back.tags, vec![tag.clone()]);
1699
1700
        // A tag's acceptance and log place (oxygen#129): keys 4 to 6, only
1701
        // when there are any, so a tag without them encodes as before.
17021×
        let crate::cbor::Value::Map(m) = crate::cbor::decode(&new).unwrap() else {
17030×
            panic!()
1704
        };
17051×
        let crate::cbor::Value::Array(tags) = &m[&3] else {
17060×
            panic!()
1707
        };
17081×
        let crate::cbor::Value::Map(plain) = &tags[0] else {
17090×
            panic!()
1710
        };
17111×
        assert_eq!(plain.keys().copied().collect::<Vec<_>>(), vec![0, 1, 2, 3]);
17121×
        let mut full = tag.clone();
17131×
        full.name = "v2".into();
17141×
        full.attestation = Some(SignedAttest {
17151×
            attest: att.clone(),
17161×
            sigs: vec![sig.clone()],
17171×
        });
17181×
        full.accepted = full.attestation.clone();
17191×
        full.logged = Some(Logged {
17201×
            index: 7,
17211×
            entry: vec![4],
17221×
            proof: vec![[3; 32]],
17231×
        });
17241×
        full.integration = vec![Integration {
17251×
            note: "hub.example/log\n8\nroot\n\n- sig\n".into(),
17261×
            proof: vec![],
17271×
        }];
17281×
        resp.tags = vec![full.clone(), tag.clone()];
17291×
        let bytes = wire::encode_refs([3; 16], &resp);
17301×
        assert_eq!(wire::decode_refs(&bytes).unwrap().1.tags, resp.tags);
1731
        // In a push too.
17321×
        let pushed = wire::encode_push(&Bundle::default(), &[], None, &resp.tags);
17331×
        assert_eq!(wire::decode_push(&pushed).unwrap().3, resp.tags);
1734
        // A reader that knows only keys 0 to 3 (oxy 0.5.0 and older, and
1735
        // the runners built with it) reads the same tags from the new answer.
17361×
        let stripped: Vec<TagRef> = resp
17371×
            .tags
17381×
            .iter()
17392×
            .map(|t| {
17402×
                TagRef::new(
17412×
                    t.name.clone(),
17422×
                    t.state,
17432×
                    t.heads.clone(),
17442×
                    t.attestation.clone(),
1745
                )
17462×
            })
17471×
            .collect();
17481×
        assert_eq!(wire::tags_as_0_5_read_them(&bytes).unwrap(), stripped);
1749
17501×
        let (h, w) = wire::decode_negotiate(&wire::encode_negotiate(
17511×
            &[ObjectRef([1; 32])],
17521×
            &[ObjectRef([2; 32])],
17531×
        ))
17541×
        .unwrap();
17551×
        assert_eq!((h, w), (vec![ObjectRef([1; 32])], vec![ObjectRef([2; 32])]));
17561×
        assert_eq!(
17571×
            wire::decode_hashes(&wire::encode_hashes(&[c.hash()])).unwrap(),
17581×
            vec![c.hash()]
1759
        );
17601×
        assert_eq!(
17611×
            wire::decode_fetch(&wire::encode_fetch(&[c.hash()], Some(4096))).unwrap(),
17621×
            (vec![c.hash()], Some(4096))
1763
        );
17641×
        assert_eq!(
17651×
            wire::decode_fetch(&wire::encode_fetch(&[], None)).unwrap(),
17661×
            (vec![], None)
1767
        );
17681×
        assert_eq!(
17691×
            wire::decode_shallow(&wire::encode_shallow(&[c.hash()], 3)).unwrap(),
17701×
            (vec![c.hash()], 3)
1771
        );
1772
        // An old-style fetch request without the filter field still decodes.
17731×
        assert_eq!(
17741×
            wire::decode_fetch(&wire::encode_hashes(&[c.hash()])).unwrap(),
17751×
            (vec![c.hash()], None)
1776
        );
1777
17781×
        let up = RefUpdate {
17791×
            name: "main".into(),
17801×
            old_state: ObjectRef([1; 32]),
17811×
            new_state: ObjectRef([2; 32]),
17821×
            force: true,
17831×
            attestation: Some(SignedAttest {
17841×
                attest: att,
17851×
                sigs: vec![sig],
17861×
            }),
17871×
        };
17881×
        let sp = SignedPolicy {
17891×
            policy,
17901×
            sigs: vec![psig],
17911×
        };
17921×
        let (b2, ups, pol, tags) = wire::decode_push(&wire::encode_push(
17931×
            &bundle,
17941×
            std::slice::from_ref(&up),
17951×
            Some(&sp),
17961×
            std::slice::from_ref(&tag),
17971×
        ))
17981×
        .unwrap();
17991×
        assert_eq!(pol, Some(sp));
18001×
        assert_eq!(tags, vec![tag]);
18011×
        assert_eq!(b2.changes.len(), 1);
18021×
        assert_eq!(ups[0].name, "main");
18031×
        assert!(ups[0].force);
18041×
        assert_eq!(ups[0].attestation, up.attestation);
18051×
        let res = vec![RefResult {
18061×
            name: "main".into(),
18071×
            ok: false,
18081×
            reason: "stale".into(),
18091×
        }];
18101×
        assert_eq!(
18111×
            wire::decode_push_response(&wire::encode_push_response(&res)).unwrap(),
1812
            res
1813
        );
18141×
        assert_eq!(
18151×
            wire::decode_capabilities(&wire::encode_capabilities([7; 16])).unwrap(),
1816
            [7; 16]
1817
        );
18181×
    }
1819
}