OXYGENHUB

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

1101 of 1279 lines run, 179 of 272 functions · run #407 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
    /// 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 {
2571203×
    pub fn open(path: &Path) -> Result<LocalRemote> {
258
        Ok(LocalRemote {
2591203×
            repo: Repo::open(path)?,
2601203×
            claimed_id: None,
261
        })
2621203×
    }
263
}
264
265
impl Remote for LocalRemote {
266943×
    fn repo_id(&self) -> Result<[u8; 16]> {
267943×
        self.repo.id()
268943×
    }
269942×
    fn refs(&self) -> Result<RefsResponse> {
270942×
        self.repo.remote_refs()
271942×
    }
272372×
    fn negotiate(&self, have: &[ChangeHash], want: &[ChangeHash]) -> Result<Vec<ChangeHash>> {
273372×
        self.repo.negotiate(have, want)
274372×
    }
275376×
    fn fetch(&self, changes: &[ChangeHash], max_blob: Option<u64>) -> Result<Bundle> {
276376×
        self.repo.bundle_raw_for(changes, max_blob)
277376×
    }
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×
    }
290285×
    fn push(
291285×
        &self,
292285×
        bundle: Bundle,
293285×
        updates: Vec<RefUpdate>,
294285×
        policy: Option<SignedPolicy>,
295285×
        tags: Vec<TagRef>,
296285×
    ) -> Result<Vec<RefResult>> {
297285×
        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
            }
307270×
        }
308285×
        self.repo.receive_push(bundle, updates, policy, tags)
309285×
    }
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): the credential store's sign-in when
332
    /// `token` is the remote's own (oxygen#155), or those of enclosing
333
    /// checkouts when it came from the credential store (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
345168×
pub fn register_store_opener(opener: StoreOpener) {
346168×
    STORE_OPENERS
347168×
        .lock()
348168×
        .unwrap_or_else(|p| p.into_inner())
349168×
        .push(opener);
350168×
}
351
352
/// A store for `url`, from `dir://` or any registered opener.
3531262×
pub fn open_store(
3541262×
    url: &str,
3551262×
    options: &RemoteOptions,
3561262×
) -> Option<crate::strata::Result<Box<dyn crate::strata::Store>>> {
3571262×
    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
        );
3621203×
    }
3631203×
    let openers = STORE_OPENERS.lock().unwrap_or_else(|p| p.into_inner());
3641203×
    openers.iter().find_map(|open| open(url, options))
3651262×
}
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>`.
389182×
pub fn user_agent() -> String {
390182×
    format!("oxy/{}", env!("CARGO_PKG_VERSION"))
391182×
}
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.
396151×
pub fn declares_feature(header: Option<&str>, feature: &str) -> bool {
397151×
    header.is_some_and(|h| h.split(',').any(|f| f.trim().eq_ignore_ascii_case(feature)))
398151×
}
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.
412185×
pub fn tls_client_config(ca: Option<&Path>) -> Result<Arc<rustls::ClientConfig>> {
413185×
    let mut roots = rustls::RootCertStore::empty();
414185×
    roots.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
415185×
    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
        }
432180×
    }
433185×
    let cfg = rustls::ClientConfig::builder_with_provider(Arc::new(
434185×
        rustls::crypto::ring::default_provider(),
435
    ))
436185×
    .with_safe_default_protocol_versions()
437185×
    .map_err(|e| RepoError::Msg(e.to_string()))?
438185×
    .with_root_certificates(roots)
439185×
    .with_no_client_auth();
440185×
    Ok(Arc::new(cfg))
441185×
}
442
443
impl HttpRemote {
444179×
    pub fn new(base: &str, options: &RemoteOptions) -> Result<HttpRemote> {
445179×
        refuse_plain_token(base, options)?;
446179×
        let agent = ureq::AgentBuilder::new()
447179×
            .tls_config(tls_client_config(options.ca.as_deref())?)
448179×
            .user_agent(&user_agent())
449179×
            .build();
450179×
        Ok(HttpRemote {
451179×
            base: base.trim_end_matches('/').to_string(),
452179×
            token: Mutex::new(options.token.clone()),
453179×
            fallbacks: Mutex::new(options.fallback_tokens.iter().rev().cloned().collect()),
454179×
            repo_id: options.repo_id,
455179×
            agent,
456179×
        })
457179×
    }
458
459
    /// A request, tried again with the next fallback token while the
460
    /// hub refuses the one in use (oxygen#112).
461447×
    fn call(&self, post: bool, endpoint: &str, body: Option<&[u8]>) -> Result<Vec<u8>> {
462
        loop {
463450×
            let token = self.token.lock().unwrap_or_else(|p| p.into_inner()).clone();
464450×
            match self.call_once(post, endpoint, body, token.as_deref()) {
46514×
                Err(RepoError::Msg(m)) if token.is_some() && refused(&m) => {
4665×
                    let next = self
4675×
                        .fallbacks
4685×
                        .lock()
4695×
                        .unwrap_or_else(|p| p.into_inner())
4705×
                        .pop();
4715×
                    let Some(next) = next else {
4722×
                        return Err(RepoError::Msg(m));
473
                    };
4743×
                    crate::credentials::warn_once(&format!(
4753×
                        "{}: the token in use was refused; trying another this computer has for the hub \
4763×
                         (a stale remote.NAME.token goes with `oxy config --unset remote.NAME.token`)",
4773×
                        self.base
4783×
                    ));
4793×
                    *self.token.lock().unwrap_or_else(|p| p.into_inner()) = Some(next);
480
                }
481445×
                other => return other,
482
            }
483
        }
484447×
    }
485
486450×
    fn call_once(
487450×
        &self,
488450×
        post: bool,
489450×
        endpoint: &str,
490450×
        body: Option<&[u8]>,
491450×
        token: Option<&str>,
492450×
    ) -> Result<Vec<u8>> {
493450×
        let url = format!("{}/oxy/v1/{endpoint}", self.base);
494450×
        let mut req = if post {
495157×
            self.agent.post(&url)
496
        } else {
497293×
            self.agent.get(&url)
498
        };
499450×
        req = req
500450×
            .set("Accept", CONTENT_TYPE)
501450×
            .set(FEATURES_HEADER, &CLIENT_FEATURES.join(","));
502450×
        if let Some(t) = token {
50327×
            req = req.set("Authorization", &format!("Bearer {t}"));
504423×
        }
505450×
        if let Some(id) = &self.repo_id {
506417×
            req = req.set(REPO_ID_HEADER, &hex::encode(id));
507417×
        }
508450×
        let resp = match body {
509157×
            Some(b) => req.set("Content-Type", CONTENT_TYPE).send_bytes(b),
510293×
            None => req.call(),
511
        };
51214×
        match resp {
513436×
            Ok(r) => {
514436×
                let mut out = Vec::new();
515436×
                r.into_reader()
516436×
                    .read_to_end(&mut out)
517436×
                    .map_err(|e| RepoError::Msg(format!("{url}: {e}")))?;
518436×
                Ok(out)
519
            }
52011×
            Err(ureq::Error::Status(code, r)) => {
52111×
                let text = r.into_string().unwrap_or_default();
522
                // The hint comes from the status alone: the server's text
523
                // (a host's reason for refusing a push, several lines
524
                // perhaps) is shown as it is, never read for hints. A
525
                // proxy's HTML error page is shown by its title only
526
                // (oxygen#133).
52711×
                let status = format!("{url}: HTTP {code}");
52811×
                let msg = format!("{status}: {}", plain_error_text(&text));
52911×
                Err(RepoError::Msg(match hint_for(&status) {
53010×
                    Some(h) => format!("{msg}\n  hint: {h}"),
5311×
                    None => msg,
532
                }))
533
            }
534
            // The transport error already names the URL.
5353×
            Err(e) => Err(RepoError::Msg(with_hint(e.to_string()))),
536
        }
537450×
    }
538
}
539
540
/// Whether a failed request's message says the hub refused its token:
541
/// HTTP 401, 403, or 404 (a hub hides a private repository from a token
542
/// that may not read it).
5436×
fn refused(message: &str) -> bool {
5446×
    [": HTTP 401", ": HTTP 403", ": HTTP 404"]
5456×
        .iter()
5468×
        .any(|c| message.contains(c))
5476×
}
548
549
/// Refuse to send a token where anyone on the way could read it: plain
550
/// `http` to another machine (see [`crate::credentials::token_allowed`]).
551181×
fn refuse_plain_token(url: &str, options: &RemoteOptions) -> Result<()> {
552181×
    if options.token.is_some() && !crate::credentials::token_allowed(url) {
5530×
        return Err(RepoError::Msg(format!(
5540×
            "{url}: refusing to send a token over plain http; use https"
5550×
        )));
556181×
    }
557181×
    Ok(())
558181×
}
559
560
/// What to do about a failed request, recognised from its message.
56123×
pub fn hint_for(message: &str) -> Option<&'static str> {
56223×
    let m = message.to_ascii_lowercase();
56323×
    let hint = if m.contains("http 401") {
5648×
        "the hub needs you signed in, or did not accept the token: run `oxy auth login HUB` (pushing needs repo:write)"
56515×
    } else if m.contains("http 403") {
5661×
        "the token or account lacks permission: pushing needs a token with repo:write and write access to the repository"
56714×
    } else if m.contains("http 413") {
5681×
        "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"
56913×
    } else if m.contains("http 404") {
5704×
        "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`)"
5719×
    } else if m.contains("unknownissuer")
5727×
        || m.contains("unknown issuer")
5737×
        || m.contains("certificate")
5746×
        || m.contains("invalidcertificate")
575
    {
5763×
        "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`"
5776×
    } else if m.contains("connection refused") {
5783×
        "nothing is listening there: check the URL and port, and that the server is running"
5793×
    } else if m.contains("dns")
5802×
        || m.contains("failed to lookup")
5812×
        || m.contains("name or service not known")
582
    {
5831×
        "the host name does not resolve: check the URL"
5842×
    } else if m.contains("timed out") || m.contains("timeout") {
5850×
        "the server did not answer in time: check the network, or try again"
586
    } else {
5872×
        return None;
588
    };
58921×
    Some(hint)
59023×
}
591
592
/// An error response's text as it is, unless it is an HTML page (a proxy's,
593
/// such as Cloudflare's 413): then its title, or a note that it was one.
59413×
fn plain_error_text(text: &str) -> String {
59513×
    let t = text.trim();
59613×
    let lower = t.to_ascii_lowercase();
59713×
    if !(lower.starts_with("<!doctype html") || lower.starts_with("<html")) {
59812×
        return t.to_string();
5991×
    }
6001×
    let title = lower
6011×
        .find("<title>")
6021×
        .and_then(|i| {
6031×
            lower[i + 7..]
6041×
                .find("</title>")
6051×
                .map(|j| t[i + 7..i + 7 + j].trim())
6061×
        })
6071×
        .filter(|s| !s.is_empty());
6081×
    match title {
6091×
        Some(s) => format!("{s} (an HTML error page, from a proxy in front of the server perhaps)"),
6100×
        None => "an HTML error page (from a proxy in front of the server perhaps)".into(),
611
    }
61213×
}
613
614
/// `message`, followed by what to do about it when that is known.
6153×
pub fn with_hint(message: String) -> String {
6163×
    match hint_for(&message) {
6173×
        Some(h) => format!("{message}\n  hint: {h}"),
6180×
        None => message,
619
    }
6203×
}
621
622
/// A JSON request to a hub API (`GET`, `POST` or `DELETE`), with the same
623
/// TLS trust and token rules as remotes. Returns the status and body, an
624
/// error status included; only transport failures are errors.
6250×
pub fn http_json(
6260×
    method: &str,
6270×
    url: &str,
6280×
    body: Option<&str>,
6290×
    options: &RemoteOptions,
6300×
) -> Result<(u16, String)> {
6310×
    refuse_plain_token(url, options)?;
6320×
    let agent = ureq::AgentBuilder::new()
6330×
        .tls_config(tls_client_config(options.ca.as_deref())?)
6340×
        .timeout(std::time::Duration::from_secs(60))
6350×
        .user_agent(&user_agent())
6360×
        .build();
6370×
    let mut req = agent.request(method, url).set("Accept", "application/json");
6380×
    if let Some(t) = &options.token {
6390×
        req = req.set("Authorization", &format!("Bearer {t}"));
6400×
    }
6410×
    let resp = match body {
6420×
        Some(b) => req.set("Content-Type", "application/json").send_string(b),
6430×
        None => req.call(),
644
    };
6450×
    match resp {
6460×
        Ok(r) => {
6470×
            let code = r.status();
6480×
            Ok((code, r.into_string().unwrap_or_default()))
649
        }
6500×
        Err(ureq::Error::Status(code, r)) => Ok((code, r.into_string().unwrap_or_default())),
6510×
        Err(e) => Err(RepoError::Msg(with_hint(e.to_string()))),
652
    }
6530×
}
654
655
/// An authenticated GET of any URL on a host, with the same TLS trust and
656
/// token as remotes use (for hub APIs: proposals). Returns the body.
6572×
pub fn http_get(url: &str, options: &RemoteOptions) -> Result<Vec<u8>> {
6582×
    refuse_plain_token(url, options)?;
6592×
    let agent = ureq::AgentBuilder::new()
6602×
        .tls_config(tls_client_config(options.ca.as_deref())?)
6612×
        .user_agent(&user_agent())
6622×
        .build();
6632×
    let mut req = agent.get(url).set("Accept", "application/json");
6642×
    if let Some(t) = &options.token {
6650×
        req = req.set("Authorization", &format!("Bearer {t}"));
6662×
    }
6672×
    match req.call() {
6682×
        Ok(r) => {
6692×
            let mut out = Vec::new();
6702×
            r.into_reader()
6712×
                .read_to_end(&mut out)
6722×
                .map_err(|e| RepoError::Msg(format!("{url}: {e}")))?;
6732×
            Ok(out)
674
        }
6750×
        Err(ureq::Error::Status(code, r)) => {
6760×
            let text = r.into_string().unwrap_or_default();
6770×
            Err(RepoError::Msg(with_hint(format!(
6780×
                "{url}: HTTP {code}: {}",
6790×
                text.trim()
6800×
            ))))
681
        }
682
        // The transport error already names the URL.
6830×
        Err(e) => Err(RepoError::Msg(with_hint(e.to_string()))),
684
    }
6852×
}
686
687
impl Remote for HttpRemote {
688150×
    fn repo_id(&self) -> Result<[u8; 16]> {
689150×
        wire::decode_capabilities(&self.call(false, "capabilities", None)?)
690150×
    }
691143×
    fn refs(&self) -> Result<RefsResponse> {
692143×
        Ok(wire::decode_refs(&self.call(false, "refs", None)?)?.1)
693143×
    }
69454×
    fn negotiate(&self, have: &[ChangeHash], want: &[ChangeHash]) -> Result<Vec<ChangeHash>> {
69554×
        wire::decode_hashes(&self.call(
696
            true,
69754×
            "negotiate",
69854×
            Some(&wire::encode_negotiate(have, want)),
6990×
        )?)
70054×
    }
70154×
    fn fetch(&self, changes: &[ChangeHash], max_blob: Option<u64>) -> Result<Bundle> {
70254×
        wire::decode_bundle(&self.call(
703
            true,
70454×
            "fetch",
70554×
            Some(&wire::encode_fetch(changes, max_blob)),
7060×
        )?)
70754×
    }
7081×
    fn objects(&self, refs: &[ObjectRef]) -> Result<Vec<(ObjectType, Vec<u8>)>> {
709
        Ok(
7101×
            wire::decode_bundle(&self.call(true, "objects", Some(&wire::encode_hashes(refs)))?)?
711
                .objects,
712
        )
7131×
    }
7140×
    fn checkpoint(&self, heads: &[ChangeHash]) -> Result<Bundle> {
7150×
        let body = {
7160×
            let _t = crate::timing::phase("remote: checkpoint answer");
7170×
            self.call(true, "checkpoint", Some(&wire::encode_hashes(heads)))?
718
        };
7190×
        let _t = crate::timing::phase("remote: decode the checkpoint");
7200×
        wire::decode_bundle(&body)
7210×
    }
7220×
    fn checkpoint_index(&self, heads: &[ChangeHash]) -> Result<Bundle> {
7230×
        let body = {
7240×
            let _t = crate::timing::phase("remote: checkpoint index");
7250×
            match self.call(true, "checkpoint-index", Some(&wire::encode_hashes(heads))) {
7260×
                Ok(b) => b,
727
                // A server from before checkpoint-index: the whole answer.
7280×
                Err(RepoError::Msg(m)) if m.contains("HTTP 404") => return self.checkpoint(heads),
7290×
                Err(e) => return Err(e),
730
            }
731
        };
7320×
        wire::decode_bundle(&body)
7330×
    }
7340×
    fn shallow(&self, heads: &[ChangeHash], depth: u32) -> Result<Vec<ChangeHash>> {
7350×
        wire::decode_hashes(&self.call(
736
            true,
7370×
            "shallow",
7380×
            Some(&wire::encode_shallow(heads, depth)),
7390×
        )?)
7400×
    }
74145×
    fn push(
74245×
        &self,
74345×
        bundle: Bundle,
74445×
        updates: Vec<RefUpdate>,
74545×
        policy: Option<SignedPolicy>,
74645×
        tags: Vec<TagRef>,
74745×
    ) -> Result<Vec<RefResult>> {
74845×
        wire::decode_push_response(&self.call(
749
            true,
75045×
            "push",
75145×
            Some(&wire::encode_push(
75245×
                &bundle,
75345×
                &updates,
75445×
                policy.as_ref(),
75545×
                &tags,
75645×
            )),
7575×
        )?)
75845×
    }
759
}
760
761
/// A remote's URL as it is stored: an `http(s)://` URL as given, a local
762
/// path made absolute (with its `file://` kept), so it still names the same
763
/// repository from inside the clone (oxygen#57).
764295×
pub fn stored_url(url: &str) -> String {
765
    // Only a path is made absolute: a plain one, or one behind file:// or
766
    // dir://. Every other URL (a hub, a bucket) is kept as written.
767295×
    let (prefix, path) = match (url.strip_prefix("file://"), url.strip_prefix("dir://")) {
7681×
        (Some(p), _) => ("file://", p),
76911×
        (_, Some(p)) => ("dir://", p),
770283×
        _ if url.contains("://") => return url.to_string(),
771254×
        _ => ("", url),
772
    };
773266×
    match std::path::absolute(path) {
774266×
        Ok(abs) => format!("{prefix}{}", abs.display()),
7750×
        Err(_) => url.to_string(),
776
    }
777295×
}
778
779
/// Open a remote by URL: a local path (optionally `file://`), `http(s)://`
780
/// (a hub), or a store (`dir://`, and whatever openers are registered).
7811429×
pub fn open_remote(url: &str, options: &RemoteOptions) -> Result<Box<dyn Remote>> {
7821429×
    if url.starts_with("http://") || url.starts_with("https://") {
783179×
        return Ok(Box::new(HttpRemote::new(url, options)?));
7841250×
    }
7851250×
    if let Some(store) = open_store(url, options) {
78648×
        return crate::repo::strata::open_store_remote(store?, options);
7871202×
    }
7881202×
    let path = url.strip_prefix("file://").unwrap_or(url);
7891202×
    if path.contains("://") {
7900×
        return Err(RepoError::Msg(format!("unsupported remote URL {url:?}")));
7911202×
    }
7921202×
    let mut local = LocalRemote::open(Path::new(path))?;
7931202×
    local.claimed_id = options.repo_id;
7941202×
    Ok(Box::new(local))
7951429×
}
796
797
// ---------------------------------------------------------------- wire
798
799
/// CBOR encodings of the protocol messages (spec §16.1).
800
pub mod wire {
801
    use super::*;
802
8030×
    fn schema(msg: &str) -> RepoError {
8040×
        RepoError::Object(ObjectError::Schema(msg.into()))
8050×
    }
806261×
    fn sigs_value(sigs: &[Signature]) -> Value {
807261×
        Value::Array(sigs.iter().map(|s| s.to_value()).collect())
808261×
    }
809257×
    fn sigs_from(v: &Value) -> Result<Vec<Signature>> {
810257×
        Ok(o::array(v, "signatures")?
811257×
            .iter()
812257×
            .map(Signature::from_value)
813257×
            .collect::<std::result::Result<Vec<_>, _>>()?)
814257×
    }
815439×
    fn hashes_value(hs: &[ObjectRef]) -> Value {
816561×
        Value::Array(hs.iter().map(|h| Value::Bytes(h.0.to_vec())).collect())
817439×
    }
818500×
    fn hashes_from(v: &Value) -> Result<Vec<ObjectRef>> {
819500×
        Ok(o::array(v, "hashes")?
820500×
            .iter()
821623×
            .map(|h| o::oref(h, "hash"))
822500×
            .collect::<std::result::Result<Vec<_>, _>>()?)
823500×
    }
82491×
    fn attest_value(sa: &SignedAttest) -> Value {
82591×
        Value::Array(vec![Value::Bytes(sa.attest.encode()), sigs_value(&sa.sigs)])
82691×
    }
827106×
    fn attest_from(v: &Value) -> Result<SignedAttest> {
828106×
        let a = o::array(v, "signed attest")?;
829106×
        if a.len() != 2 {
8300×
            return Err(schema("signed attest: expected [attest, sigs]"));
831106×
        }
832
        Ok(SignedAttest {
833106×
            attest: Attest::decode(o::bytes(&a[0], "attest")?)?,
834106×
            sigs: sigs_from(&a[1])?,
835
        })
836106×
    }
837278×
    fn opt_attest_value(sa: &Option<SignedAttest>) -> Value {
838278×
        sa.as_ref().map(attest_value).unwrap_or(Value::Null)
839278×
    }
840335×
    fn opt_attest_from(v: &Value) -> Result<Option<SignedAttest>> {
841335×
        if v.is_null() {
842245×
            Ok(None)
843
        } else {
84490×
            attest_from(v).map(Some)
845
        }
846335×
    }
847
    /// `[policy bytes, [signature]]`: also the format of a policy proposal
848
    /// file exchanged between root holders (spec §14.5).
84945×
    pub fn policy_value(sp: &SignedPolicy) -> Value {
85045×
        Value::Array(vec![Value::Bytes(sp.policy.encode()), sigs_value(&sp.sigs)])
85145×
    }
85243×
    pub fn policy_from(v: &Value) -> Result<SignedPolicy> {
85343×
        let a = o::array(v, "signed policy")?;
85443×
        if a.len() != 2 {
8550×
            return Err(schema("signed policy: expected [policy, sigs]"));
85643×
        }
857
        Ok(SignedPolicy {
85843×
            policy: Policy::decode(o::bytes(&a[0], "policy")?)?,
85943×
            sigs: sigs_from(&a[1])?,
860
        })
86143×
    }
862222×
    fn opt_policy_value(sp: Option<&SignedPolicy>) -> Value {
863222×
        sp.map(policy_value).unwrap_or(Value::Null)
864222×
    }
865261×
    fn opt_policy_from(v: &Value) -> Result<Option<SignedPolicy>> {
866261×
        if v.is_null() {
867239×
            Ok(None)
868
        } else {
86922×
            policy_from(v).map(Some)
870
        }
871261×
    }
8721109×
    fn map<'a>(v: &'a Value, what: &str) -> Result<&'a o::Map> {
8731109×
        Ok(o::map(v, what)?)
8741109×
    }
8753139×
    fn field<'a>(m: &'a o::Map, k: u64, what: &str) -> Result<&'a Value> {
8763139×
        Ok(o::field(m, k, what)?)
8773139×
    }
878
879
    /// A bundle's value. Each change's text blobs and their chunks (spec
880
    /// §6.1) are added to its objects when they are not already there, so a
881
    /// bundle can always be read on its own.
882137×
    pub fn bundle_value(b: &Bundle) -> Value {
883137×
        let mut changes = Vec::with_capacity(b.raw_changes.len() + b.changes.len());
884
        // Changes as stored are already their encoding, their texts among
885
        // the objects.
886137×
        for (bytes, s) in &b.raw_changes {
8870×
            changes.push(Value::Array(vec![
8880×
                Value::Bytes(bytes.clone()),
8890×
                sigs_value(s),
8900×
            ]));
8910×
        }
892137×
        let mut texts: Vec<(ObjectType, Vec<u8>)> = Vec::new();
893137×
        let mut listed: Option<std::collections::HashSet<ObjectRef>> = None;
894137×
        for (c, s) in &b.changes {
895125×
            let (bytes, stored) = c.encode_parts();
896125×
            for t in stored {
8970×
                let listed = listed.get_or_insert_with(|| {
8980×
                    b.objects
8990×
                        .iter()
9000×
                        .map(|(ty, body)| crate::hash::hash_object(*ty, body))
9010×
                        .collect()
9020×
                });
9030×
                if !listed.insert(t.blob.hash()) {
9040×
                    continue;
9050×
                }
9060×
                for chunk in crate::chunk::chunks(&t.content) {
9070×
                    if listed.insert(crate::hash::hash_object(ObjectType::Chunk, chunk)) {
9080×
                        texts.push((ObjectType::Chunk, chunk.to_vec()));
9090×
                    }
910
                }
9110×
                texts.push((ObjectType::Blob, t.blob.encode()));
912
            }
913125×
            changes.push(Value::Array(vec![Value::Bytes(bytes), sigs_value(s)]));
914
        }
915137×
        let mut v = Value::map([
916137×
            (0, Value::Array(changes)),
917137×
            (
918137×
                1,
919137×
                Value::Array(b.attests.iter().map(attest_value).collect()),
920137×
            ),
921
            (
922
                2,
923
                Value::Array(
924137×
                    b.objects
925137×
                        .iter()
926137×
                        .chain(&texts)
927203×
                        .map(|(t, body)| {
928203×
                            Value::Array(vec![
929203×
                                Value::Text(t.name().into()),
930203×
                                Value::Bytes(body.clone()),
931203×
                            ])
932203×
                        })
933137×
                        .collect(),
934
                ),
935
            ),
936137×
            (
937137×
                3,
938137×
                Value::Array(b.policies.iter().map(policy_value).collect()),
939137×
            ),
940
        ]);
941
        // Only when there are any; older peers ignore the field.
942137×
        if !b.certificates.is_empty() {
9437×
            if let Value::Map(m) = &mut v {
9447×
                m.insert(
945
                    4,
946
                    Value::Array(
9477×
                        b.certificates
9487×
                            .iter()
9497×
                            .map(|c| Value::Bytes(c.encode()))
9507×
                            .collect(),
951
                    ),
952
                );
9530×
            }
954130×
        }
955137×
        v
956137×
    }
957
958127×
    pub fn bundle_from_value(v: &Value) -> Result<Bundle> {
959127×
        let m = map(v, "bundle")?;
960127×
        let mut b = Bundle::default();
961192×
        for ob in o::array(field(m, 2, "objects")?, "objects")? {
962192×
            let pair = o::array(ob, "object")?;
963192×
            if pair.len() != 2 {
9640×
                return Err(schema("object: expected [type, body]"));
965192×
            }
966192×
            let ty = ObjectType::from_name(o::text(&pair[0], "object type")?)
967192×
                .ok_or_else(|| schema("unknown object type"))?;
968192×
            b.objects
969192×
                .push((ty, o::bytes(&pair[1], "object body")?.to_vec()));
970
        }
971
        // Stored inserts are read from the bundle's own objects.
972127×
        let mut by_ref: Option<std::collections::HashMap<ObjectRef, usize>> = None;
973127×
        for c in o::array(field(m, 0, "changes")?, "changes")? {
974108×
            let pair = o::array(c, "change entry")?;
975108×
            if pair.len() != 2 {
9760×
                return Err(schema("change entry: expected [change, sigs]"));
977108×
            }
978108×
            let encoded = o::bytes(&pair[0], "change")?;
979108×
            b.hashes
980108×
                .push(crate::hash::hash_object(ObjectType::Change, encoded));
981108×
            let change = Change::decode_with(encoded, &mut |text, count, form| {
9820×
                let by_ref = by_ref.get_or_insert_with(|| {
9830×
                    b.objects
9840×
                        .iter()
9850×
                        .enumerate()
9860×
                        .map(|(i, (ty, body))| (crate::hash::hash_object(*ty, body), i))
9870×
                        .collect()
9880×
                });
9890×
                let get =
9900×
                    |r: &ObjectRef, want: ObjectType| match by_ref.get(r).map(|i| &b.objects[*i]) {
9910×
                        Some((ty, body)) if *ty == want => Ok(body),
9920×
                        _ => Err(ObjectError::Schema(format!(
9930×
                            "the bundle lacks {} {}",
9940×
                            want.name(),
9950×
                            r.short(12)
9960×
                        ))),
9970×
                    };
9980×
                let blob = crate::objects::Blob::decode(get(text, ObjectType::Blob)?)?;
9990×
                let mut content = Vec::with_capacity(blob.length as usize);
10000×
                for chunk in &blob.chunks {
10010×
                    content.extend_from_slice(get(chunk, ObjectType::Chunk)?);
1002
                }
10030×
                crate::objects::text_lines(&content, count, form)
10040×
            })?;
1005108×
            b.changes.push((change, sigs_from(&pair[1])?));
1006
        }
1007127×
        for a in o::array(field(m, 1, "attests")?, "attests")? {
100816×
            b.attests.push(attest_from(a)?);
1009
        }
1010127×
        if let Some(ps) = m.get(&3) {
1011127×
            for p in o::array(ps, "policies")? {
10123×
                b.policies.push(policy_from(p)?);
1013
            }
10140×
        }
1015127×
        if let Some(cs) = m.get(&4) {
10167×
            for c in o::array(cs, "certificates")? {
10177×
                b.certificates.push(
10187×
                    crate::cert::SignedCertificate::decode(o::bytes(c, "certificate")?)
10197×
                        .map_err(|e| schema(&format!("certificate: {e}")))?,
1020
                );
1021
            }
1022120×
        }
1023127×
        Ok(b)
1024127×
    }
1025
102690×
    pub fn encode_bundle(b: &Bundle) -> Vec<u8> {
102790×
        cbor::encode(&bundle_value(b))
102890×
    }
102984×
    pub fn decode_bundle(bytes: &[u8]) -> Result<Bundle> {
103084×
        bundle_from_value(&cbor::decode(bytes).map_err(ObjectError::from)?)
103184×
    }
1032
1033145×
    pub fn encode_capabilities(id: [u8; 16]) -> Vec<u8> {
1034145×
        cbor::encode(&Value::map([
1035145×
            (0, Value::Array(vec![Value::Uint(PROTOCOL_VERSION)])),
1036145×
            (1, Value::Bytes(id.to_vec())),
1037145×
            (2, Value::Array(vec![Value::Text("seal".into())])),
1038145×
        ]))
1039145×
    }
1040145×
    pub fn decode_capabilities(bytes: &[u8]) -> Result<[u8; 16]> {
1041145×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
1042145×
        let m = map(&v, "capabilities")?;
1043145×
        let versions = o::array(field(m, 0, "versions")?, "versions")?;
1044145×
        if !versions
1045145×
            .iter()
1046145×
            .any(|x| x.as_uint() == Some(PROTOCOL_VERSION))
1047
        {
10480×
            return Err(RepoError::Msg(
10490×
                "remote does not speak protocol version 1".into(),
10500×
            ));
1051145×
        }
1052145×
        o::bytes(field(m, 1, "repo id")?, "repo id")?
1053145×
            .try_into()
1054145×
            .map_err(|_| schema("repo id: expected 16 bytes"))
1055145×
    }
1056
1057222×
    fn tags_value(tags: &[TagRef]) -> Value {
1058
        Value::Array(
1059222×
            tags.iter()
1060222×
                .map(|t| {
106134×
                    let mut v = Value::map([
106234×
                        (0, Value::Text(t.name.clone())),
106334×
                        (1, Value::Bytes(t.state.0.to_vec())),
106434×
                        (2, hashes_value(&t.heads)),
106534×
                        (3, opt_attest_value(&t.attestation)),
106634×
                    ]);
1067
                    // Only when there is one; older peers ignore them
1068
                    // (oxygen#129).
106934×
                    if let Value::Map(m) = &mut v {
107034×
                        if t.accepted.is_some() {
10718×
                            m.insert(4, opt_attest_value(&t.accepted));
107226×
                        }
107334×
                        if let Some(l) = &t.logged {
10742×
                            m.insert(5, logged_value(l));
107532×
                        }
107634×
                        if !t.integration.is_empty() {
10772×
                            m.insert(6, integration_value(&t.integration));
107832×
                        }
10790×
                    }
108034×
                    v
108134×
                })
1082222×
                .collect(),
1083
        )
1084222×
    }
1085261×
    fn tags_from(v: &Value) -> Result<Vec<TagRef>> {
1086261×
        let mut out = Vec::new();
1087261×
        for t in o::array(v, "tags")? {
108850×
            let tm = map(t, "tag")?;
108950×
            out.push(TagRef {
109050×
                name: o::text(field(tm, 0, "name")?, "name")?.to_owned(),
109150×
                state: o::oref(field(tm, 1, "state")?, "state")?,
109250×
                heads: hashes_from(field(tm, 2, "heads")?)?,
109350×
                attestation: opt_attest_from(field(tm, 3, "attestation")?)?,
109450×
                accepted: match tm.get(&4) {
10958×
                    Some(a) => opt_attest_from(a)?,
109642×
                    None => None,
1097
                },
109850×
                logged: tm.get(&5).map(logged_from).transpose()?,
109950×
                integration: match tm.get(&6) {
11002×
                    Some(l) => integration_from(l)?,
110148×
                    None => Vec::new(),
1102
                },
1103
            });
1104
        }
1105261×
        Ok(out)
1106261×
    }
1107
1108
    /// The tags of a refs answer as oxy 0.5.0 read them (and the runners
1109
    /// built with it), keys 0 to 3 only: what an older reader makes of an
1110
    /// answer with keys 4 to 6.
1111
    #[cfg(test)]
11121×
    pub(super) fn tags_as_0_5_read_them(bytes: &[u8]) -> Result<Vec<TagRef>> {
11131×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
11141×
        let m = map(&v, "refs")?;
11151×
        let mut out = Vec::new();
11162×
        for t in o::array(field(m, 3, "tags")?, "tags")? {
11172×
            let tm = map(t, "tag")?;
11182×
            out.push(TagRef::new(
11192×
                o::text(field(tm, 0, "name")?, "name")?.to_owned(),
11202×
                o::oref(field(tm, 1, "state")?, "state")?,
11212×
                hashes_from(field(tm, 2, "heads")?)?,
11222×
                opt_attest_from(field(tm, 3, "attestation")?)?,
1123
            ));
1124
        }
11251×
        Ok(out)
11261×
    }
1127
1128
    /// A log place, `[entry number, entry bytes, [proof hash]]` (spec §14.8).
11294×
    fn logged_value(l: &Logged) -> Value {
11304×
        Value::Array(vec![
11314×
            Value::Uint(l.index),
11324×
            Value::Bytes(l.entry.clone()),
11334×
            proof_value(&l.proof),
11344×
        ])
11354×
    }
11364×
    fn logged_from(v: &Value) -> Result<Logged> {
11374×
        let a = o::array(v, "logged")?;
11384×
        if a.len() != 3 {
11390×
            return Err(schema("logged: expected [index, entry, proof]"));
11404×
        }
1141
        Ok(Logged {
11424×
            index: o::uint(&a[0], "index")?,
11434×
            entry: o::bytes(&a[1], "entry")?.to_vec(),
11444×
            proof: proof_from(&a[2])?,
1145
        })
11464×
    }
1147
1148
    /// Cosigned checkpoints holding an entry, `[[note, [proof hash]]]`.
11494×
    fn integration_value(integration: &[Integration]) -> Value {
1150
        Value::Array(
11514×
            integration
11524×
                .iter()
11534×
                .map(|i| Value::Array(vec![Value::Text(i.note.clone()), proof_value(&i.proof)]))
11544×
                .collect(),
1155
        )
11564×
    }
11574×
    fn integration_from(v: &Value) -> Result<Vec<Integration>> {
11584×
        let mut out = Vec::new();
11594×
        for i in o::array(v, "integration")? {
11604×
            let a = o::array(i, "integration")?;
11614×
            if a.len() != 2 {
11620×
                return Err(schema("integration: expected [note, proof]"));
11634×
            }
11644×
            out.push(Integration {
11654×
                note: o::text(&a[0], "note")?.to_owned(),
11664×
                proof: proof_from(&a[1])?,
1167
            });
1168
        }
11694×
        Ok(out)
11704×
    }
1171
1172175×
    pub fn encode_refs(id: [u8; 16], resp: &RefsResponse) -> Vec<u8> {
1173175×
        let mut v = Value::map([
1174
            (
1175
                0,
1176
                Value::Array(
1177175×
                    resp.refs
1178175×
                        .iter()
1179181×
                        .map(|r| {
1180181×
                            let mut v = Value::map([
1181181×
                                (0, Value::Text(r.name.clone())),
1182181×
                                (1, Value::Bytes(r.state.0.to_vec())),
1183181×
                                (2, hashes_value(&r.heads)),
1184181×
                                (3, opt_attest_value(&r.attestation)),
1185181×
                                (4, r.last_serial.map(Value::Uint).unwrap_or(Value::Null)),
1186181×
                            ]);
1187
                            // Only when there is one; older peers ignore it.
1188181×
                            if let Value::Map(m) = &mut v {
1189181×
                                if r.accepted.is_some() {
11909×
                                    m.insert(5, opt_attest_value(&r.accepted));
1191172×
                                }
1192181×
                                if let Some(l) = &r.logged {
11932×
                                    m.insert(6, logged_value(l));
1194179×
                                }
1195181×
                                if !r.integration.is_empty() {
11962×
                                    m.insert(7, integration_value(&r.integration));
1197179×
                                }
11980×
                            }
1199181×
                            v
1200181×
                        })
1201175×
                        .collect(),
1202
                ),
1203
            ),
1204175×
            (1, Value::Bytes(id.to_vec())),
1205175×
            (2, opt_policy_value(resp.policy.as_ref())),
1206175×
            (3, tags_value(&resp.tags)),
1207175×
            (
1208175×
                4,
1209175×
                Value::Array(resp.history.iter().map(policy_value).collect()),
1210175×
            ),
1211175×
            (
1212175×
                5,
1213175×
                resp.default_bookmark
1214175×
                    .clone()
1215175×
                    .map(Value::Text)
1216175×
                    .unwrap_or(Value::Null),
1217175×
            ),
1218
        ]);
1219175×
        if let Value::Map(m) = &mut v {
1220175×
            if let Some(log) = &resp.log {
12213×
                m.insert(6, Value::Text(log.clone()));
1222172×
            }
1223175×
            if !resp.withdrawn.is_empty() {
12240×
                m.insert(8, tags_value(&resp.withdrawn));
1225175×
            }
1226175×
            if !resp.witnesses.is_empty() {
12272×
                m.insert(
1228
                    7,
1229
                    Value::Array(
12302×
                        resp.witnesses
12312×
                            .iter()
12322×
                            .map(|(name, id)| {
12332×
                                Value::Array(vec![
12342×
                                    Value::Text(name.clone()),
12352×
                                    Value::Bytes(id.clone()),
12362×
                                ])
12372×
                            })
12382×
                            .collect(),
1239
                    ),
1240
                );
1241173×
            }
12420×
        }
1243175×
        cbor::encode(&v)
1244175×
    }
1245218×
    pub fn decode_refs(bytes: &[u8]) -> Result<([u8; 16], RefsResponse)> {
1246218×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
1247218×
        let m = map(&v, "refs")?;
1248218×
        let id: [u8; 16] = o::bytes(field(m, 1, "repo id")?, "repo id")?
1249218×
            .try_into()
1250218×
            .map_err(|_| schema("repo id: expected 16 bytes"))?;
1251218×
        let mut refs = Vec::new();
1252224×
        for r in o::array(field(m, 0, "refs")?, "refs")? {
1253224×
            let rm = map(r, "ref")?;
1254224×
            let ls = field(rm, 4, "last serial")?;
1255224×
            refs.push(RemoteRef {
1256224×
                name: o::text(field(rm, 0, "name")?, "name")?.to_owned(),
1257224×
                state: o::oref(field(rm, 1, "state")?, "state")?,
1258224×
                heads: hashes_from(field(rm, 2, "heads")?)?,
1259224×
                attestation: opt_attest_from(field(rm, 3, "attestation")?)?,
1260224×
                last_serial: if ls.is_null() {
1261191×
                    None
1262
                } else {
126333×
                    Some(o::uint(ls, "last serial")?)
1264
                },
1265224×
                accepted: match rm.get(&5) {
12669×
                    Some(a) => opt_attest_from(a)?,
1267215×
                    None => None,
1268
                },
1269224×
                logged: rm.get(&6).map(logged_from).transpose()?,
1270224×
                integration: match rm.get(&7) {
12712×
                    Some(l) => integration_from(l)?,
1272222×
                    None => Vec::new(),
1273
                },
1274
            });
1275
        }
1276218×
        let policy = match m.get(&2) {
1277218×
            Some(p) => opt_policy_from(p)?,
12780×
            None => None,
1279
        };
1280218×
        let tags = match m.get(&3) {
1281218×
            Some(t) => tags_from(t)?,
12820×
            None => Vec::new(),
1283
        };
1284218×
        let mut history = Vec::new();
1285218×
        if let Some(h) = m.get(&4) {
1286218×
            for p in o::array(h, "history")? {
128717×
                history.push(policy_from(p)?);
1288
            }
12890×
        }
1290218×
        let default_bookmark = match m.get(&5) {
1291149×
            Some(Value::Text(t)) => Some(t.clone()),
129269×
            _ => None,
1293
        };
1294218×
        let log = match m.get(&6) {
12953×
            Some(Value::Text(t)) => Some(t.clone()),
1296215×
            _ => None,
1297
        };
1298218×
        let mut witnesses = Vec::new();
1299218×
        if let Some(w) = m.get(&7) {
13002×
            for x in o::array(w, "witnesses")? {
13012×
                let a = o::array(x, "witness")?;
13022×
                if a.len() != 2 {
13030×
                    return Err(schema("witness: expected [name, identity]"));
13042×
                }
13052×
                witnesses.push((
13062×
                    o::text(&a[0], "witness name")?.to_owned(),
13072×
                    o::bytes(&a[1], "witness identity")?.to_vec(),
1308
                ));
1309
            }
1310216×
        }
1311218×
        let withdrawn = match m.get(&8) {
13120×
            Some(t) => tags_from(t)?,
1313218×
            None => Vec::new(),
1314
        };
1315218×
        Ok((
1316218×
            id,
1317218×
            RefsResponse {
1318218×
                refs,
1319218×
                policy,
1320218×
                tags,
1321218×
                history,
1322218×
                default_bookmark,
1323218×
                log,
1324218×
                witnesses,
1325218×
                withdrawn,
1326218×
            },
1327218×
        ))
1328218×
    }
1329
1330
    /// A proof's hashes, from the leaf upwards (spec §14.8).
13318×
    fn proof_value(proof: &[[u8; 32]]) -> Value {
13328×
        Value::Array(proof.iter().map(|h| Value::Bytes(h.to_vec())).collect())
13338×
    }
1334
13358×
    fn proof_from(v: &Value) -> Result<Vec<[u8; 32]>> {
13368×
        let mut proof = Vec::new();
13378×
        for h in o::array(v, "proof")? {
13388×
            proof.push(
13398×
                o::bytes(h, "proof hash")?
13408×
                    .try_into()
13418×
                    .map_err(|_| schema("proof hash: expected 32 bytes"))?,
1342
            );
1343
        }
13448×
        Ok(proof)
13458×
    }
1346
134755×
    pub fn encode_negotiate(have: &[ChangeHash], want: &[ChangeHash]) -> Vec<u8> {
134855×
        cbor::encode(&Value::map([
134955×
            (0, hashes_value(have)),
135055×
            (1, hashes_value(want)),
135155×
        ]))
135255×
    }
135355×
    pub fn decode_negotiate(bytes: &[u8]) -> Result<(Vec<ChangeHash>, Vec<ChangeHash>)> {
135455×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
135555×
        let m = map(&v, "negotiate")?;
1356
        Ok((
135755×
            hashes_from(field(m, 0, "have")?)?,
135855×
            hashes_from(field(m, 1, "want")?)?,
1359
        ))
136055×
    }
1361
1362
    /// `fetch` request: `{0: [changes], 1: max blob size or null}`.
136356×
    pub fn encode_fetch(hs: &[ChangeHash], max_blob: Option<u64>) -> Vec<u8> {
136456×
        cbor::encode(&Value::map([
136556×
            (0, hashes_value(hs)),
136656×
            (1, max_blob.map(Value::Uint).unwrap_or(Value::Null)),
136756×
        ]))
136856×
    }
136957×
    pub fn decode_fetch(bytes: &[u8]) -> Result<(Vec<ChangeHash>, Option<u64>)> {
137057×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
137157×
        let m = map(&v, "fetch")?;
137257×
        let max = match m.get(&1) {
137356×
            Some(x) if !x.is_null() => Some(o::uint(x, "max blob")?),
137455×
            _ => None,
1375
        };
137657×
        Ok((hashes_from(field(m, 0, "changes")?)?, max))
137757×
    }
1378
1379
    /// `shallow` request: `{0: [heads], 1: depth}`.
13801×
    pub fn encode_shallow(hs: &[ChangeHash], depth: u32) -> Vec<u8> {
13811×
        cbor::encode(&Value::map([
13821×
            (0, hashes_value(hs)),
13831×
            (1, Value::Uint(depth as u64)),
13841×
        ]))
13851×
    }
13861×
    pub fn decode_shallow(bytes: &[u8]) -> Result<(Vec<ChangeHash>, u32)> {
13871×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
13881×
        let m = map(&v, "shallow")?;
1389
        Ok((
13901×
            hashes_from(field(m, 0, "heads")?)?,
13911×
            o::u32_(field(m, 1, "depth")?, "depth")?,
1392
        ))
13931×
    }
1394
139557×
    pub fn encode_hashes(hs: &[ChangeHash]) -> Vec<u8> {
139657×
        cbor::encode(&Value::map([(0, hashes_value(hs))]))
139757×
    }
139856×
    pub fn decode_hashes(bytes: &[u8]) -> Result<Vec<ChangeHash>> {
139956×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
140056×
        hashes_from(field(map(&v, "hashes")?, 0, "hashes")?)
140156×
    }
1402
140347×
    pub fn encode_push(
140447×
        bundle: &Bundle,
140547×
        updates: &[RefUpdate],
140647×
        policy: Option<&SignedPolicy>,
140747×
        tags: &[TagRef],
140847×
    ) -> Vec<u8> {
140947×
        cbor::encode(&Value::map([
141047×
            (0, bundle_value(bundle)),
141147×
            (2, opt_policy_value(policy)),
141247×
            (3, tags_value(tags)),
1413
            (
1414
                1,
1415
                Value::Array(
141647×
                    updates
141747×
                        .iter()
141847×
                        .map(|u| {
141946×
                            Value::map([
142046×
                                (0, Value::Text(u.name.clone())),
142146×
                                (1, Value::Bytes(u.old_state.0.to_vec())),
142246×
                                (2, Value::Bytes(u.new_state.0.to_vec())),
142346×
                                (3, Value::Bool(u.force)),
142446×
                                (4, opt_attest_value(&u.attestation)),
142546×
                            ])
142646×
                        })
142747×
                        .collect(),
1428
                ),
1429
            ),
1430
        ]))
143147×
    }
1432
    /// A decoded push: bundle, bookmark updates, policy, tags.
1433
    pub type PushParts = (Bundle, Vec<RefUpdate>, Option<SignedPolicy>, Vec<TagRef>);
1434
143543×
    pub fn decode_push(bytes: &[u8]) -> Result<PushParts> {
143643×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
143743×
        let m = map(&v, "push")?;
143843×
        let bundle = bundle_from_value(field(m, 0, "bundle")?)?;
143943×
        let mut updates = Vec::new();
144043×
        for u in o::array(field(m, 1, "updates")?, "updates")? {
144142×
            let um = map(u, "update")?;
144242×
            updates.push(RefUpdate {
144342×
                name: o::text(field(um, 0, "name")?, "name")?.to_owned(),
144442×
                old_state: o::oref(field(um, 1, "old_state")?, "old_state")?,
144542×
                new_state: o::oref(field(um, 2, "new_state")?, "new_state")?,
144642×
                force: field(um, 3, "force")?
144742×
                    .as_bool()
144842×
                    .ok_or_else(|| schema("force: expected bool"))?,
144942×
                attestation: opt_attest_from(field(um, 4, "attestation")?)?,
1450
            });
1451
        }
145243×
        let policy = match m.get(&2) {
145343×
            Some(p) => opt_policy_from(p)?,
14540×
            None => None,
1455
        };
145643×
        let tags = match m.get(&3) {
145743×
            Some(t) => tags_from(t)?,
14580×
            None => Vec::new(),
1459
        };
146043×
        Ok((bundle, updates, policy, tags))
146143×
    }
1462
146341×
    pub fn encode_push_response(results: &[RefResult]) -> Vec<u8> {
146441×
        cbor::encode(&Value::map([(
1465
            0,
1466
            Value::Array(
146741×
                results
146841×
                    .iter()
146947×
                    .map(|r| {
147047×
                        Value::map([
147147×
                            (0, Value::Text(r.name.clone())),
147247×
                            (1, Value::Bool(r.ok)),
147347×
                            (2, Value::Text(r.reason.clone())),
147447×
                        ])
147547×
                    })
147641×
                    .collect(),
1477
            ),
1478
        )]))
147941×
    }
148041×
    pub fn decode_push_response(bytes: &[u8]) -> Result<Vec<RefResult>> {
148141×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
148241×
        let m = map(&v, "push response")?;
148341×
        let mut out = Vec::new();
148447×
        for r in o::array(field(m, 0, "results")?, "results")? {
148547×
            let rm = map(r, "result")?;
148647×
            out.push(RefResult {
148747×
                name: o::text(field(rm, 0, "name")?, "name")?.to_owned(),
148847×
                ok: field(rm, 1, "ok")?
148947×
                    .as_bool()
149047×
                    .ok_or_else(|| schema("ok: expected bool"))?,
149147×
                reason: o::text(field(rm, 2, "reason")?, "reason")?.to_owned(),
1492
            });
1493
        }
149441×
        Ok(out)
149541×
    }
1496
}
1497
1498
#[cfg(test)]
1499
mod tests {
1500
    use super::*;
1501
    use crate::attest::AttestBody;
1502
    use crate::objects::Hlc;
1503
1504
    /// oxygen#133: a proxy's HTML error page is shown by its title, and a
1505
    /// server's own text as it is; a 413 says to push in smaller parts.
1506
    #[test]
15071×
    fn html_error_pages_are_shown_by_their_title() {
15081×
        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>";
15091×
        assert_eq!(
15101×
            plain_error_text(cloudflare),
1511
            "413 Request Entity Too Large (an HTML error page, from a proxy in front of the server perhaps)"
1512
        );
15131×
        assert_eq!(
15141×
            plain_error_text("  refused: a secret\nat a.txt:3 "),
1515
            "refused: a secret\nat a.txt:3"
1516
        );
15171×
        assert!(hint_for("https://hub/x: HTTP 413: too large")
15181×
            .unwrap()
15191×
            .contains("push.batch-bytes"));
15201×
    }
1521
1522
    #[test]
15231×
    fn client_features_are_declared_and_read() {
15241×
        assert_eq!(CLIENT_FEATURES.join(","), "certified-tags");
15251×
        assert!(user_agent().starts_with("oxy/"));
15261×
        assert!(declares_feature(
15271×
            Some("certified-tags"),
15281×
            FEATURE_CERTIFIED_TAGS
1529
        ));
15301×
        assert!(declares_feature(
15311×
            Some("later-thing, Certified-Tags ,x"),
15321×
            FEATURE_CERTIFIED_TAGS
1533
        ));
15341×
        assert!(!declares_feature(
15351×
            Some("certified-tags-v2"),
15361×
            FEATURE_CERTIFIED_TAGS
15371×
        ));
15381×
        assert!(!declares_feature(Some(""), FEATURE_CERTIFIED_TAGS));
15391×
        assert!(!declares_feature(None, FEATURE_CERTIFIED_TAGS));
15401×
    }
1541
1542
    #[test]
15431×
    fn wire_round_trips() {
15441×
        let c = crate::objects::tests::sample_change();
15451×
        let sk = crate::identity::SecretKey {
15461×
            ed_seed: [1; 32],
15471×
            ml_seed: [2; 32],
15481×
        };
15491×
        let id = sk.identity("a", "b", 0);
15501×
        let key = id.hash();
15511×
        let sig = sk.sign(crate::identity::Domain::Change, &key, &c.hash());
15521×
        let seal = Attest::seal([3; 16], vec![c.hash()]);
15531×
        let seal_sig = sk.sign(crate::identity::Domain::Attest, &key, &seal.hash());
15541×
        let policy = Policy::single_root([3; 16], id.clone(), 99);
15551×
        let psig = sk.sign(crate::identity::Domain::Policy, &key, &policy.hash());
15561×
        let bundle = Bundle {
15571×
            changes: vec![(c.clone(), vec![sig.clone()])],
15581×
            attests: vec![SignedAttest {
15591×
                attest: seal.clone(),
15601×
                sigs: vec![seal_sig],
15611×
            }],
15621×
            objects: vec![
15631×
                (ObjectType::Identity, id.encode()),
15641×
                (ObjectType::Chunk, b"xyz".to_vec()),
15651×
            ],
15661×
            policies: vec![SignedPolicy {
15671×
                policy: policy.clone(),
15681×
                sigs: vec![psig.clone()],
15691×
            }],
15701×
            hashes: vec![],
15711×
            raw_changes: vec![],
15721×
            certificates: vec![],
15731×
        };
15741×
        let d = wire::decode_bundle(&wire::encode_bundle(&bundle)).unwrap();
15751×
        assert_eq!(
1576
            d.hashes,
15771×
            vec![c.hash()],
1578
            "the receiver hashes what it was sent"
1579
        );
15801×
        assert_eq!(d.changes, bundle.changes);
15811×
        assert_eq!(d.attests, bundle.attests);
15821×
        assert_eq!(d.objects, bundle.objects);
15831×
        assert_eq!(d.policies, bundle.policies);
15841×
        assert!(d.certificates.is_empty());
1585
        // Certificates (keyless, oxygenhub#241) travel as field 4, only
1586
        // when there are any: a bundle without them encodes as before.
15871×
        let plain = wire::encode_bundle(&bundle);
15881×
        let mut with = bundle.clone();
15891×
        let issuer_sk = crate::identity::SecretKey::generate();
15901×
        let issuer = issuer_sk.identity("hub", "h@x", 1);
15911×
        with.certificates.push(crate::cert::SignedCertificate::sign(
15921×
            crate::cert::Certificate {
15931×
                key: id.clone(),
15941×
                issuer: issuer.hash(),
15951×
                subject: "agent:a@b".into(),
15961×
                claims: vec![],
15971×
                scope: crate::identity::Scope::CHANGES,
15981×
                not_before: 1,
15991×
                expires: 2,
16001×
                grant: None,
16011×
            },
16021×
            &issuer,
16031×
            &issuer_sk,
1604
        ));
16051×
        let encoded = wire::encode_bundle(&with);
16061×
        assert_ne!(encoded, plain);
16071×
        assert_eq!(
16081×
            wire::decode_bundle(&encoded).unwrap().certificates,
1609
            with.certificates
1610
        );
16111×
        with.certificates.clear();
16121×
        assert_eq!(wire::encode_bundle(&with), plain);
1613
16141×
        let att = Attest {
16151×
            repo: [3; 16],
16161×
            hlc: Hlc::default(),
16171×
            body: AttestBody::Ref {
16181×
                name: "main".into(),
16191×
                old_state: ObjectRef([1; 32]),
16201×
                new_state: ObjectRef([2; 32]),
16211×
                serial: 4,
16221×
            },
16231×
        };
16241×
        let refs = vec![
16251×
            RemoteRef {
16261×
                name: "main".into(),
16271×
                state: ObjectRef([2; 32]),
16281×
                heads: vec![c.hash()],
16291×
                attestation: Some(SignedAttest {
16301×
                    attest: att.clone(),
16311×
                    sigs: vec![sig.clone()],
16321×
                }),
16331×
                last_serial: Some(4),
16341×
                accepted: None,
16351×
                logged: None,
16361×
                integration: vec![],
16371×
            },
16381×
            RemoteRef {
16391×
                name: "dev".into(),
16401×
                state: ObjectRef([5; 32]),
16411×
                heads: vec![],
16421×
                attestation: None,
16431×
                last_serial: None,
16441×
                accepted: None,
16451×
                logged: None,
16461×
                integration: vec![],
16471×
            },
1648
        ];
16491×
        let tag = TagRef::new("v1".into(), ObjectRef([2; 32]), vec![c.hash()], None);
16501×
        let mut resp = RefsResponse {
16511×
            refs,
16521×
            policy: Some(SignedPolicy {
16531×
                policy: policy.clone(),
16541×
                sigs: vec![psig.clone()],
16551×
            }),
16561×
            tags: vec![tag.clone()],
16571×
            history: vec![SignedPolicy {
16581×
                policy: policy.clone(),
16591×
                sigs: vec![],
16601×
            }],
16611×
            default_bookmark: Some("develop".into()),
16621×
            log: Some("hub.example/log\n2\nroot\n\n- sig\n".into()),
16631×
            witnesses: vec![],
16641×
            withdrawn: vec![],
16651×
        };
1666
        // Without integrated times (spec §14.8) nothing is added: an old
1667
        // peer's answer, and what it reads.
16681×
        let old = wire::encode_refs([3; 16], &resp);
16691×
        let back = wire::decode_refs(&old).unwrap().1;
16702×
        assert!(back.witnesses.is_empty() && back.refs.iter().all(|r| r.integration.is_empty()));
16711×
        resp.refs[1].logged = Some(Logged {
16721×
            index: 41,
16731×
            entry: vec![1, 2, 3],
16741×
            proof: vec![[9; 32], [8; 32]],
16751×
        });
16761×
        resp.refs[1].integration = vec![Integration {
16771×
            note: "hub.example/log\n42\nroot\n\n- sig\n".into(),
16781×
            proof: vec![[7; 32]],
16791×
        }];
16801×
        resp.witnesses = vec![("w.example".into(), vec![4, 5, 6])];
16811×
        let new = wire::encode_refs([3; 16], &resp);
16821×
        let (id_back, back) = wire::decode_refs(&new).unwrap();
16831×
        assert_eq!(back.log, resp.log);
16841×
        assert_eq!(back.refs[1].logged, resp.refs[1].logged);
16851×
        assert_eq!(back.refs[1].integration, resp.refs[1].integration);
16861×
        assert_eq!(back.witnesses, resp.witnesses);
16871×
        assert_eq!(back.refs[0].logged, None);
1688
        // The new keys are 7s an old reader never asks for.
16891×
        let crate::cbor::Value::Map(m) = crate::cbor::decode(&new).unwrap() else {
16900×
            panic!()
1691
        };
16921×
        assert!(m.contains_key(&7));
16931×
        assert_eq!(id_back, [3; 16]);
16941×
        assert_eq!(back.refs.len(), 2);
16951×
        assert_eq!(back.refs[0].attestation.as_ref().unwrap().attest, att);
16961×
        assert_eq!(back.refs[1].last_serial, None);
16971×
        assert_eq!(back.policy.as_ref().unwrap().policy, policy);
16981×
        assert_eq!(back.history, resp.history);
16991×
        assert_eq!(back.tags, vec![tag.clone()]);
1700
1701
        // A tag's acceptance and log place (oxygen#129): keys 4 to 6, only
1702
        // when there are any, so a tag without them encodes as before.
17031×
        let crate::cbor::Value::Map(m) = crate::cbor::decode(&new).unwrap() else {
17040×
            panic!()
1705
        };
17061×
        let crate::cbor::Value::Array(tags) = &m[&3] else {
17070×
            panic!()
1708
        };
17091×
        let crate::cbor::Value::Map(plain) = &tags[0] else {
17100×
            panic!()
1711
        };
17121×
        assert_eq!(plain.keys().copied().collect::<Vec<_>>(), vec![0, 1, 2, 3]);
17131×
        let mut full = tag.clone();
17141×
        full.name = "v2".into();
17151×
        full.attestation = Some(SignedAttest {
17161×
            attest: att.clone(),
17171×
            sigs: vec![sig.clone()],
17181×
        });
17191×
        full.accepted = full.attestation.clone();
17201×
        full.logged = Some(Logged {
17211×
            index: 7,
17221×
            entry: vec![4],
17231×
            proof: vec![[3; 32]],
17241×
        });
17251×
        full.integration = vec![Integration {
17261×
            note: "hub.example/log\n8\nroot\n\n- sig\n".into(),
17271×
            proof: vec![],
17281×
        }];
17291×
        resp.tags = vec![full.clone(), tag.clone()];
17301×
        let bytes = wire::encode_refs([3; 16], &resp);
17311×
        assert_eq!(wire::decode_refs(&bytes).unwrap().1.tags, resp.tags);
1732
        // In a push too.
17331×
        let pushed = wire::encode_push(&Bundle::default(), &[], None, &resp.tags);
17341×
        assert_eq!(wire::decode_push(&pushed).unwrap().3, resp.tags);
1735
        // A reader that knows only keys 0 to 3 (oxy 0.5.0 and older, and
1736
        // the runners built with it) reads the same tags from the new answer.
17371×
        let stripped: Vec<TagRef> = resp
17381×
            .tags
17391×
            .iter()
17402×
            .map(|t| {
17412×
                TagRef::new(
17422×
                    t.name.clone(),
17432×
                    t.state,
17442×
                    t.heads.clone(),
17452×
                    t.attestation.clone(),
1746
                )
17472×
            })
17481×
            .collect();
17491×
        assert_eq!(wire::tags_as_0_5_read_them(&bytes).unwrap(), stripped);
1750
17511×
        let (h, w) = wire::decode_negotiate(&wire::encode_negotiate(
17521×
            &[ObjectRef([1; 32])],
17531×
            &[ObjectRef([2; 32])],
17541×
        ))
17551×
        .unwrap();
17561×
        assert_eq!((h, w), (vec![ObjectRef([1; 32])], vec![ObjectRef([2; 32])]));
17571×
        assert_eq!(
17581×
            wire::decode_hashes(&wire::encode_hashes(&[c.hash()])).unwrap(),
17591×
            vec![c.hash()]
1760
        );
17611×
        assert_eq!(
17621×
            wire::decode_fetch(&wire::encode_fetch(&[c.hash()], Some(4096))).unwrap(),
17631×
            (vec![c.hash()], Some(4096))
1764
        );
17651×
        assert_eq!(
17661×
            wire::decode_fetch(&wire::encode_fetch(&[], None)).unwrap(),
17671×
            (vec![], None)
1768
        );
17691×
        assert_eq!(
17701×
            wire::decode_shallow(&wire::encode_shallow(&[c.hash()], 3)).unwrap(),
17711×
            (vec![c.hash()], 3)
1772
        );
1773
        // An old-style fetch request without the filter field still decodes.
17741×
        assert_eq!(
17751×
            wire::decode_fetch(&wire::encode_hashes(&[c.hash()])).unwrap(),
17761×
            (vec![c.hash()], None)
1777
        );
1778
17791×
        let up = RefUpdate {
17801×
            name: "main".into(),
17811×
            old_state: ObjectRef([1; 32]),
17821×
            new_state: ObjectRef([2; 32]),
17831×
            force: true,
17841×
            attestation: Some(SignedAttest {
17851×
                attest: att,
17861×
                sigs: vec![sig],
17871×
            }),
17881×
        };
17891×
        let sp = SignedPolicy {
17901×
            policy,
17911×
            sigs: vec![psig],
17921×
        };
17931×
        let (b2, ups, pol, tags) = wire::decode_push(&wire::encode_push(
17941×
            &bundle,
17951×
            std::slice::from_ref(&up),
17961×
            Some(&sp),
17971×
            std::slice::from_ref(&tag),
17981×
        ))
17991×
        .unwrap();
18001×
        assert_eq!(pol, Some(sp));
18011×
        assert_eq!(tags, vec![tag]);
18021×
        assert_eq!(b2.changes.len(), 1);
18031×
        assert_eq!(ups[0].name, "main");
18041×
        assert!(ups[0].force);
18051×
        assert_eq!(ups[0].attestation, up.attestation);
18061×
        let res = vec![RefResult {
18071×
            name: "main".into(),
18081×
            ok: false,
18091×
            reason: "stale".into(),
18101×
        }];
18111×
        assert_eq!(
18121×
            wire::decode_push_response(&wire::encode_push_response(&res)).unwrap(),
1813
            res
1814
        );
18151×
        assert_eq!(
18161×
            wire::decode_capabilities(&wire::encode_capabilities([7; 16])).unwrap(),
1817
            [7; 16]
1818
        );
18191×
    }
1820
}