OXYGENHUB

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

1100 of 1259 lines run, 179 of 266 functions · run #371 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
    /// The changes within `depth` dependency steps of `heads` (spec §17).
226
    fn shallow(&self, heads: &[ChangeHash], depth: u32) -> Result<Vec<ChangeHash>>;
227
    /// Push changes, bookmark updates, new tags, and optionally a newer
228
    /// policy. The policy is applied first; a result named `policy` reports
229
    /// it, and each tag reports as `tags/<name>`.
230
    fn push(
231
        &self,
232
        bundle: Bundle,
233
        updates: Vec<RefUpdate>,
234
        policy: Option<SignedPolicy>,
235
        tags: Vec<TagRef>,
236
    ) -> Result<Vec<RefResult>>;
237
}
238
239
// ---------------------------------------------------------------- local
240
241
/// Another repository on this machine, served in-process.
242
pub struct LocalRemote {
243
    pub repo: Repo,
244
    /// The pushing repository's id, which binds an unbound target on the
245
    /// first push, as `Oxy-Repo-Id` does over HTTP.
246
    pub claimed_id: Option<[u8; 16]>,
247
}
248
249
impl LocalRemote {
2501174×
    pub fn open(path: &Path) -> Result<LocalRemote> {
251
        Ok(LocalRemote {
2521174×
            repo: Repo::open(path)?,
2531174×
            claimed_id: None,
254
        })
2551174×
    }
256
}
257
258
impl Remote for LocalRemote {
259922×
    fn repo_id(&self) -> Result<[u8; 16]> {
260922×
        self.repo.id()
261922×
    }
262920×
    fn refs(&self) -> Result<RefsResponse> {
263920×
        self.repo.remote_refs()
264920×
    }
265363×
    fn negotiate(&self, have: &[ChangeHash], want: &[ChangeHash]) -> Result<Vec<ChangeHash>> {
266363×
        self.repo.negotiate(have, want)
267363×
    }
268369×
    fn fetch(&self, changes: &[ChangeHash], max_blob: Option<u64>) -> Result<Bundle> {
269369×
        self.repo.bundle_raw_for(changes, max_blob)
270369×
    }
2715×
    fn objects(&self, refs: &[ObjectRef]) -> Result<Vec<(ObjectType, Vec<u8>)>> {
2725×
        self.repo.objects_for(refs)
2735×
    }
2743×
    fn checkpoint(&self, heads: &[ChangeHash]) -> Result<Bundle> {
2753×
        self.repo.checkpoint_bundle_for(heads)
2763×
    }
2775×
    fn shallow(&self, heads: &[ChangeHash], depth: u32) -> Result<Vec<ChangeHash>> {
2785×
        self.repo.shallow_changes(heads, depth)
2795×
    }
280278×
    fn push(
281278×
        &self,
282278×
        bundle: Bundle,
283278×
        updates: Vec<RefUpdate>,
284278×
        policy: Option<SignedPolicy>,
285278×
        tags: Vec<TagRef>,
286278×
    ) -> Result<Vec<RefResult>> {
287278×
        if self.repo.is_unbound() {
28814×
            match self.claimed_id {
28914×
                Some(id) => self.repo.bind_id(id)?,
290
                None => {
2910×
                    return Err(RepoError::Msg(
2920×
                        "the remote is unbound and this client did not say which repository it is"
2930×
                            .into(),
2940×
                    ))
295
                }
296
            }
297264×
        }
298278×
        self.repo.receive_push(bundle, updates, policy, tags)
299278×
    }
300
}
301
302
// ---------------------------------------------------------------- http
303
304
/// How to reach a remote: credentials and trust.
305
#[derive(Clone, Debug, Default)]
306
pub struct RemoteOptions {
307
    /// Bearer token for pushes.
308
    pub token: Option<String>,
309
    /// PEM file with extra root certificates to trust for `https://` remotes
310
    /// (self-hosted servers); the system web roots are always trusted.
311
    pub ca: Option<PathBuf>,
312
    /// The local repository's id, sent as `Oxy-Repo-Id` so an unbound
313
    /// hosted repository can adopt it on the first push (spec §16.1).
314
    pub repo_id: Option<[u8; 16]>,
315
    /// Where a remote kept on a store (`dir://`, `s3://`, …) keeps its
316
    /// mirror and what it has seen: the remote's directory under
317
    /// `.oxy/remotes`. None (a clone, before there is a repository) means
318
    /// a temporary directory.
319
    pub cache_dir: Option<PathBuf>,
320
    /// Other tokens for the same hub, tried in turn when `token` is
321
    /// refused (401, 403 or 404): those of enclosing checkouts, when
322
    /// `token` came from the credential store rather than from this
323
    /// remote's own configuration (oxygen#112).
324
    pub fallback_tokens: Vec<String>,
325
}
326
327
/// Opens a store for a URL it understands, or passes (`None`). Stores that
328
/// need more than the standard library (the cloud ones) are added by the
329
/// program that links them, with [`register_store_opener`].
330
pub type StoreOpener =
331
    fn(&str, &RemoteOptions) -> Option<crate::strata::Result<Box<dyn crate::strata::Store>>>;
332
333
static STORE_OPENERS: Mutex<Vec<StoreOpener>> = Mutex::new(Vec::new());
334
335155×
pub fn register_store_opener(opener: StoreOpener) {
336155×
    STORE_OPENERS
337155×
        .lock()
338155×
        .unwrap_or_else(|p| p.into_inner())
339155×
        .push(opener);
340155×
}
341
342
/// A store for `url`, from `dir://` or any registered opener.
3431233×
pub fn open_store(
3441233×
    url: &str,
3451233×
    options: &RemoteOptions,
3461233×
) -> Option<crate::strata::Result<Box<dyn crate::strata::Store>>> {
3471233×
    if let Some(path) = url.strip_prefix("dir://") {
348
        return Some(
34959×
            crate::strata::LocalStore::open(path)
35059×
                .map(|s| Box::new(s) as Box<dyn crate::strata::Store>),
351
        );
3521174×
    }
3531174×
    let openers = STORE_OPENERS.lock().unwrap_or_else(|p| p.into_inner());
3541174×
    openers.iter().find_map(|open| open(url, options))
3551233×
}
356
357
/// The request header carrying the client's repository id.
358
pub const REPO_ID_HEADER: &str = "Oxy-Repo-Id";
359
360
/// The id of a hosted repository that has not adopted one yet.
361
pub const UNBOUND_ID: [u8; 16] = [0; 16];
362
363
/// The request header in which a client declares the protocol features it
364
/// understands beyond the 0.5.0-era set: a comma-separated list, which a
365
/// server may tailor its answers to (docs/protocol.md, *Client
366
/// capabilities*). A request without it is a client of that era.
367
pub const FEATURES_HEADER: &str = "Oxy-Features";
368
369
/// The feature of a client that authorizes a tag signed by a short-lived,
370
/// certified key by its certificate at the time the host accepted it
371
/// (oxygen#129). A client without it refuses such a tag, and with it the
372
/// whole fetch, so servers leave those tags out of its `refs` (oxygen#131).
373
pub const FEATURE_CERTIFIED_TAGS: &str = "certified-tags";
374
375
/// The features this client declares in [`FEATURES_HEADER`].
376
pub const CLIENT_FEATURES: &[&str] = &[FEATURE_CERTIFIED_TAGS];
377
378
/// The `User-Agent` every request of this client sends: `oxy/<version>`.
379172×
pub fn user_agent() -> String {
380172×
    format!("oxy/{}", env!("CARGO_PKG_VERSION"))
381172×
}
382
383
/// Whether a [`FEATURES_HEADER`] value (absent: `None`) declares `feature`.
384
/// Entries are comma-separated, compared without surrounding blanks and
385
/// regardless of case; unknown ones are ignored.
386143×
pub fn declares_feature(header: Option<&str>, feature: &str) -> bool {
387143×
    header.is_some_and(|h| h.split(',').any(|f| f.trim().eq_ignore_ascii_case(feature)))
388143×
}
389
390
/// A remote served by `oxy-server` at `<base>/oxy/v1/...`.
391
pub struct HttpRemote {
392
    base: String,
393
    /// The token in use, and those still to try when it is refused.
394
    token: Mutex<Option<String>>,
395
    fallbacks: Mutex<Vec<String>>,
396
    repo_id: Option<[u8; 16]>,
397
    agent: ureq::Agent,
398
}
399
400
/// A TLS client configuration trusting the web roots plus `ca`, if given:
401
/// the trust every oxy connection uses, shared with tools that call hub APIs.
402175×
pub fn tls_client_config(ca: Option<&Path>) -> Result<Arc<rustls::ClientConfig>> {
403175×
    let mut roots = rustls::RootCertStore::empty();
404175×
    roots.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
405175×
    if let Some(path) = ca {
40617×
        let pem = std::fs::read(path)
40717×
            .map_err(|e| RepoError::Msg(format!("reading CA file {}: {e}", path.display())))?;
40817×
        let certs = rustls_pemfile::certs(&mut pem.as_slice())
40917×
            .collect::<std::result::Result<Vec<_>, _>>()
41017×
            .map_err(|e| RepoError::Msg(format!("parsing CA file {}: {e}", path.display())))?;
41117×
        if certs.is_empty() {
4120×
            return Err(RepoError::Msg(format!(
4130×
                "CA file {} holds no certificates",
4140×
                path.display()
4150×
            )));
41617×
        }
41717×
        for c in certs {
41817×
            roots
41917×
                .add(c)
42017×
                .map_err(|e| RepoError::Msg(format!("CA file {}: {e}", path.display())))?;
421
        }
422158×
    }
423175×
    let cfg = rustls::ClientConfig::builder_with_provider(Arc::new(
424175×
        rustls::crypto::ring::default_provider(),
425
    ))
426175×
    .with_safe_default_protocol_versions()
427175×
    .map_err(|e| RepoError::Msg(e.to_string()))?
428175×
    .with_root_certificates(roots)
429175×
    .with_no_client_auth();
430175×
    Ok(Arc::new(cfg))
431175×
}
432
433
impl HttpRemote {
434169×
    pub fn new(base: &str, options: &RemoteOptions) -> Result<HttpRemote> {
435169×
        refuse_plain_token(base, options)?;
436169×
        let agent = ureq::AgentBuilder::new()
437169×
            .tls_config(tls_client_config(options.ca.as_deref())?)
438169×
            .user_agent(&user_agent())
439169×
            .build();
440169×
        Ok(HttpRemote {
441169×
            base: base.trim_end_matches('/').to_string(),
442169×
            token: Mutex::new(options.token.clone()),
443169×
            fallbacks: Mutex::new(options.fallback_tokens.iter().rev().cloned().collect()),
444169×
            repo_id: options.repo_id,
445169×
            agent,
446169×
        })
447169×
    }
448
449
    /// A request, tried again with the next fallback token while the
450
    /// hub refuses the one in use (oxygen#112).
451423×
    fn call(&self, post: bool, endpoint: &str, body: Option<&[u8]>) -> Result<Vec<u8>> {
452
        loop {
453424×
            let token = self.token.lock().unwrap_or_else(|p| p.into_inner()).clone();
454424×
            match self.call_once(post, endpoint, body, token.as_deref()) {
45512×
                Err(RepoError::Msg(m)) if token.is_some() && refused(&m) => {
4563×
                    let next = self
4573×
                        .fallbacks
4583×
                        .lock()
4593×
                        .unwrap_or_else(|p| p.into_inner())
4603×
                        .pop();
4613×
                    let Some(next) = next else {
4622×
                        return Err(RepoError::Msg(m));
463
                    };
4641×
                    crate::credentials::warn_once(&format!(
4651×
                        "{}: the stored token was refused; using the one an enclosing checkout has for this hub",
4661×
                        self.base
4671×
                    ));
4681×
                    *self.token.lock().unwrap_or_else(|p| p.into_inner()) = Some(next);
469
                }
470421×
                other => return other,
471
            }
472
        }
473423×
    }
474
475424×
    fn call_once(
476424×
        &self,
477424×
        post: bool,
478424×
        endpoint: &str,
479424×
        body: Option<&[u8]>,
480424×
        token: Option<&str>,
481424×
    ) -> Result<Vec<u8>> {
482424×
        let url = format!("{}/oxy/v1/{endpoint}", self.base);
483424×
        let mut req = if post {
484147×
            self.agent.post(&url)
485
        } else {
486277×
            self.agent.get(&url)
487
        };
488424×
        req = req
489424×
            .set("Accept", CONTENT_TYPE)
490424×
            .set(FEATURES_HEADER, &CLIENT_FEATURES.join(","));
491424×
        if let Some(t) = token {
49222×
            req = req.set("Authorization", &format!("Bearer {t}"));
493402×
        }
494424×
        if let Some(id) = &self.repo_id {
495393×
            req = req.set(REPO_ID_HEADER, &hex::encode(id));
496393×
        }
497424×
        let resp = match body {
498147×
            Some(b) => req.set("Content-Type", CONTENT_TYPE).send_bytes(b),
499277×
            None => req.call(),
500
        };
50112×
        match resp {
502412×
            Ok(r) => {
503412×
                let mut out = Vec::new();
504412×
                r.into_reader()
505412×
                    .read_to_end(&mut out)
506412×
                    .map_err(|e| RepoError::Msg(format!("{url}: {e}")))?;
507412×
                Ok(out)
508
            }
5099×
            Err(ureq::Error::Status(code, r)) => {
5109×
                let text = r.into_string().unwrap_or_default();
511
                // The hint comes from the status alone: the server's text
512
                // (a host's reason for refusing a push, several lines
513
                // perhaps) is shown as it is, never read for hints. A
514
                // proxy's HTML error page is shown by its title only
515
                // (oxygen#133).
5169×
                let status = format!("{url}: HTTP {code}");
5179×
                let msg = format!("{status}: {}", plain_error_text(&text));
5189×
                Err(RepoError::Msg(match hint_for(&status) {
5198×
                    Some(h) => format!("{msg}\n  hint: {h}"),
5201×
                    None => msg,
521
                }))
522
            }
523
            // The transport error already names the URL.
5243×
            Err(e) => Err(RepoError::Msg(with_hint(e.to_string()))),
525
        }
526424×
    }
527
}
528
529
/// Whether a failed request's message says the hub refused its token:
530
/// HTTP 401, 403, or 404 (a hub hides a private repository from a token
531
/// that may not read it).
5324×
fn refused(message: &str) -> bool {
5334×
    [": HTTP 401", ": HTTP 403", ": HTTP 404"]
5344×
        .iter()
5356×
        .any(|c| message.contains(c))
5364×
}
537
538
/// Refuse to send a token where anyone on the way could read it: plain
539
/// `http` to another machine (see [`crate::credentials::token_allowed`]).
540171×
fn refuse_plain_token(url: &str, options: &RemoteOptions) -> Result<()> {
541171×
    if options.token.is_some() && !crate::credentials::token_allowed(url) {
5420×
        return Err(RepoError::Msg(format!(
5430×
            "{url}: refusing to send a token over plain http; use https"
5440×
        )));
545171×
    }
546171×
    Ok(())
547171×
}
548
549
/// What to do about a failed request, recognised from its message.
55021×
pub fn hint_for(message: &str) -> Option<&'static str> {
55121×
    let m = message.to_ascii_lowercase();
55221×
    let hint = if m.contains("http 401") {
5536×
        "the hub needs you signed in, or did not accept the token: run `oxy auth login HUB` (pushing needs repo:write)"
55415×
    } else if m.contains("http 403") {
5551×
        "the token or account lacks permission: pushing needs a token with repo:write and write access to the repository"
55614×
    } else if m.contains("http 413") {
5571×
        "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"
55813×
    } else if m.contains("http 404") {
5594×
        "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`)"
5609×
    } else if m.contains("unknownissuer")
5617×
        || m.contains("unknown issuer")
5627×
        || m.contains("certificate")
5636×
        || m.contains("invalidcertificate")
564
    {
5653×
        "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`"
5666×
    } else if m.contains("connection refused") {
5673×
        "nothing is listening there: check the URL and port, and that the server is running"
5683×
    } else if m.contains("dns")
5692×
        || m.contains("failed to lookup")
5702×
        || m.contains("name or service not known")
571
    {
5721×
        "the host name does not resolve: check the URL"
5732×
    } else if m.contains("timed out") || m.contains("timeout") {
5740×
        "the server did not answer in time: check the network, or try again"
575
    } else {
5762×
        return None;
577
    };
57819×
    Some(hint)
57921×
}
580
581
/// An error response's text as it is, unless it is an HTML page (a proxy's,
582
/// such as Cloudflare's 413): then its title, or a note that it was one.
58311×
fn plain_error_text(text: &str) -> String {
58411×
    let t = text.trim();
58511×
    let lower = t.to_ascii_lowercase();
58611×
    if !(lower.starts_with("<!doctype html") || lower.starts_with("<html")) {
58710×
        return t.to_string();
5881×
    }
5891×
    let title = lower
5901×
        .find("<title>")
5911×
        .and_then(|i| {
5921×
            lower[i + 7..]
5931×
                .find("</title>")
5941×
                .map(|j| t[i + 7..i + 7 + j].trim())
5951×
        })
5961×
        .filter(|s| !s.is_empty());
5971×
    match title {
5981×
        Some(s) => format!("{s} (an HTML error page, from a proxy in front of the server perhaps)"),
5990×
        None => "an HTML error page (from a proxy in front of the server perhaps)".into(),
600
    }
60111×
}
602
603
/// `message`, followed by what to do about it when that is known.
6043×
pub fn with_hint(message: String) -> String {
6053×
    match hint_for(&message) {
6063×
        Some(h) => format!("{message}\n  hint: {h}"),
6070×
        None => message,
608
    }
6093×
}
610
611
/// A JSON request to a hub API (`GET`, `POST` or `DELETE`), with the same
612
/// TLS trust and token rules as remotes. Returns the status and body, an
613
/// error status included; only transport failures are errors.
6140×
pub fn http_json(
6150×
    method: &str,
6160×
    url: &str,
6170×
    body: Option<&str>,
6180×
    options: &RemoteOptions,
6190×
) -> Result<(u16, String)> {
6200×
    refuse_plain_token(url, options)?;
6210×
    let agent = ureq::AgentBuilder::new()
6220×
        .tls_config(tls_client_config(options.ca.as_deref())?)
6230×
        .timeout(std::time::Duration::from_secs(60))
6240×
        .user_agent(&user_agent())
6250×
        .build();
6260×
    let mut req = agent.request(method, url).set("Accept", "application/json");
6270×
    if let Some(t) = &options.token {
6280×
        req = req.set("Authorization", &format!("Bearer {t}"));
6290×
    }
6300×
    let resp = match body {
6310×
        Some(b) => req.set("Content-Type", "application/json").send_string(b),
6320×
        None => req.call(),
633
    };
6340×
    match resp {
6350×
        Ok(r) => {
6360×
            let code = r.status();
6370×
            Ok((code, r.into_string().unwrap_or_default()))
638
        }
6390×
        Err(ureq::Error::Status(code, r)) => Ok((code, r.into_string().unwrap_or_default())),
6400×
        Err(e) => Err(RepoError::Msg(with_hint(e.to_string()))),
641
    }
6420×
}
643
644
/// An authenticated GET of any URL on a host, with the same TLS trust and
645
/// token as remotes use (for hub APIs: proposals). Returns the body.
6462×
pub fn http_get(url: &str, options: &RemoteOptions) -> Result<Vec<u8>> {
6472×
    refuse_plain_token(url, options)?;
6482×
    let agent = ureq::AgentBuilder::new()
6492×
        .tls_config(tls_client_config(options.ca.as_deref())?)
6502×
        .user_agent(&user_agent())
6512×
        .build();
6522×
    let mut req = agent.get(url).set("Accept", "application/json");
6532×
    if let Some(t) = &options.token {
6540×
        req = req.set("Authorization", &format!("Bearer {t}"));
6552×
    }
6562×
    match req.call() {
6572×
        Ok(r) => {
6582×
            let mut out = Vec::new();
6592×
            r.into_reader()
6602×
                .read_to_end(&mut out)
6612×
                .map_err(|e| RepoError::Msg(format!("{url}: {e}")))?;
6622×
            Ok(out)
663
        }
6640×
        Err(ureq::Error::Status(code, r)) => {
6650×
            let text = r.into_string().unwrap_or_default();
6660×
            Err(RepoError::Msg(with_hint(format!(
6670×
                "{url}: HTTP {code}: {}",
6680×
                text.trim()
6690×
            ))))
670
        }
671
        // The transport error already names the URL.
6720×
        Err(e) => Err(RepoError::Msg(with_hint(e.to_string()))),
673
    }
6742×
}
675
676
impl Remote for HttpRemote {
677142×
    fn repo_id(&self) -> Result<[u8; 16]> {
678142×
        wire::decode_capabilities(&self.call(false, "capabilities", None)?)
679142×
    }
680135×
    fn refs(&self) -> Result<RefsResponse> {
681135×
        Ok(wire::decode_refs(&self.call(false, "refs", None)?)?.1)
682135×
    }
68352×
    fn negotiate(&self, have: &[ChangeHash], want: &[ChangeHash]) -> Result<Vec<ChangeHash>> {
68452×
        wire::decode_hashes(&self.call(
685
            true,
68652×
            "negotiate",
68752×
            Some(&wire::encode_negotiate(have, want)),
6880×
        )?)
68952×
    }
69052×
    fn fetch(&self, changes: &[ChangeHash], max_blob: Option<u64>) -> Result<Bundle> {
69152×
        wire::decode_bundle(&self.call(
692
            true,
69352×
            "fetch",
69452×
            Some(&wire::encode_fetch(changes, max_blob)),
6950×
        )?)
69652×
    }
6971×
    fn objects(&self, refs: &[ObjectRef]) -> Result<Vec<(ObjectType, Vec<u8>)>> {
698
        Ok(
6991×
            wire::decode_bundle(&self.call(true, "objects", Some(&wire::encode_hashes(refs)))?)?
700
                .objects,
701
        )
7021×
    }
7030×
    fn checkpoint(&self, heads: &[ChangeHash]) -> Result<Bundle> {
7040×
        wire::decode_bundle(&self.call(true, "checkpoint", Some(&wire::encode_hashes(heads)))?)
7050×
    }
7060×
    fn shallow(&self, heads: &[ChangeHash], depth: u32) -> Result<Vec<ChangeHash>> {
7070×
        wire::decode_hashes(&self.call(
708
            true,
7090×
            "shallow",
7100×
            Some(&wire::encode_shallow(heads, depth)),
7110×
        )?)
7120×
    }
71341×
    fn push(
71441×
        &self,
71541×
        bundle: Bundle,
71641×
        updates: Vec<RefUpdate>,
71741×
        policy: Option<SignedPolicy>,
71841×
        tags: Vec<TagRef>,
71941×
    ) -> Result<Vec<RefResult>> {
72041×
        wire::decode_push_response(&self.call(
721
            true,
72241×
            "push",
72341×
            Some(&wire::encode_push(
72441×
                &bundle,
72541×
                &updates,
72641×
                policy.as_ref(),
72741×
                &tags,
72841×
            )),
7295×
        )?)
73041×
    }
731
}
732
733
/// A remote's URL as it is stored: an `http(s)://` URL as given, a local
734
/// path made absolute (with its `file://` kept), so it still names the same
735
/// repository from inside the clone (oxygen#57).
736286×
pub fn stored_url(url: &str) -> String {
737
    // Only a path is made absolute: a plain one, or one behind file:// or
738
    // dir://. Every other URL (a hub, a bucket) is kept as written.
739286×
    let (prefix, path) = match (url.strip_prefix("file://"), url.strip_prefix("dir://")) {
7401×
        (Some(p), _) => ("file://", p),
74111×
        (_, Some(p)) => ("dir://", p),
742274×
        _ if url.contains("://") => return url.to_string(),
743247×
        _ => ("", url),
744
    };
745259×
    match std::path::absolute(path) {
746259×
        Ok(abs) => format!("{prefix}{}", abs.display()),
7470×
        Err(_) => url.to_string(),
748
    }
749286×
}
750
751
/// Open a remote by URL: a local path (optionally `file://`), `http(s)://`
752
/// (a hub), or a store (`dir://`, and whatever openers are registered).
7531390×
pub fn open_remote(url: &str, options: &RemoteOptions) -> Result<Box<dyn Remote>> {
7541390×
    if url.starts_with("http://") || url.starts_with("https://") {
755169×
        return Ok(Box::new(HttpRemote::new(url, options)?));
7561221×
    }
7571221×
    if let Some(store) = open_store(url, options) {
75848×
        return crate::repo::strata::open_store_remote(store?, options);
7591173×
    }
7601173×
    let path = url.strip_prefix("file://").unwrap_or(url);
7611173×
    if path.contains("://") {
7620×
        return Err(RepoError::Msg(format!("unsupported remote URL {url:?}")));
7631173×
    }
7641173×
    let mut local = LocalRemote::open(Path::new(path))?;
7651173×
    local.claimed_id = options.repo_id;
7661173×
    Ok(Box::new(local))
7671390×
}
768
769
// ---------------------------------------------------------------- wire
770
771
/// CBOR encodings of the protocol messages (spec §16.1).
772
pub mod wire {
773
    use super::*;
774
7750×
    fn schema(msg: &str) -> RepoError {
7760×
        RepoError::Object(ObjectError::Schema(msg.into()))
7770×
    }
778257×
    fn sigs_value(sigs: &[Signature]) -> Value {
779257×
        Value::Array(sigs.iter().map(|s| s.to_value()).collect())
780257×
    }
781253×
    fn sigs_from(v: &Value) -> Result<Vec<Signature>> {
782253×
        Ok(o::array(v, "signatures")?
783253×
            .iter()
784253×
            .map(Signature::from_value)
785253×
            .collect::<std::result::Result<Vec<_>, _>>()?)
786253×
    }
787423×
    fn hashes_value(hs: &[ObjectRef]) -> Value {
788570×
        Value::Array(hs.iter().map(|h| Value::Bytes(h.0.to_vec())).collect())
789423×
    }
790484×
    fn hashes_from(v: &Value) -> Result<Vec<ObjectRef>> {
791484×
        Ok(o::array(v, "hashes")?
792484×
            .iter()
793632×
            .map(|h| o::oref(h, "hash"))
794484×
            .collect::<std::result::Result<Vec<_>, _>>()?)
795484×
    }
79691×
    fn attest_value(sa: &SignedAttest) -> Value {
79791×
        Value::Array(vec![Value::Bytes(sa.attest.encode()), sigs_value(&sa.sigs)])
79891×
    }
799106×
    fn attest_from(v: &Value) -> Result<SignedAttest> {
800106×
        let a = o::array(v, "signed attest")?;
801106×
        if a.len() != 2 {
8020×
            return Err(schema("signed attest: expected [attest, sigs]"));
803106×
        }
804
        Ok(SignedAttest {
805106×
            attest: Attest::decode(o::bytes(&a[0], "attest")?)?,
806106×
            sigs: sigs_from(&a[1])?,
807
        })
808106×
    }
809266×
    fn opt_attest_value(sa: &Option<SignedAttest>) -> Value {
810266×
        sa.as_ref().map(attest_value).unwrap_or(Value::Null)
811266×
    }
812323×
    fn opt_attest_from(v: &Value) -> Result<Option<SignedAttest>> {
813323×
        if v.is_null() {
814233×
            Ok(None)
815
        } else {
81690×
            attest_from(v).map(Some)
817
        }
818323×
    }
819
    /// `[policy bytes, [signature]]`: also the format of a policy proposal
820
    /// file exchanged between root holders (spec §14.5).
82145×
    pub fn policy_value(sp: &SignedPolicy) -> Value {
82245×
        Value::Array(vec![Value::Bytes(sp.policy.encode()), sigs_value(&sp.sigs)])
82345×
    }
82443×
    pub fn policy_from(v: &Value) -> Result<SignedPolicy> {
82543×
        let a = o::array(v, "signed policy")?;
82643×
        if a.len() != 2 {
8270×
            return Err(schema("signed policy: expected [policy, sigs]"));
82843×
        }
829
        Ok(SignedPolicy {
83043×
            policy: Policy::decode(o::bytes(&a[0], "policy")?)?,
83143×
            sigs: sigs_from(&a[1])?,
832
        })
83343×
    }
834210×
    fn opt_policy_value(sp: Option<&SignedPolicy>) -> Value {
835210×
        sp.map(policy_value).unwrap_or(Value::Null)
836210×
    }
837249×
    fn opt_policy_from(v: &Value) -> Result<Option<SignedPolicy>> {
838249×
        if v.is_null() {
839227×
            Ok(None)
840
        } else {
84122×
            policy_from(v).map(Some)
842
        }
843249×
    }
8441057×
    fn map<'a>(v: &'a Value, what: &str) -> Result<&'a o::Map> {
8451057×
        Ok(o::map(v, what)?)
8461057×
    }
8472997×
    fn field<'a>(m: &'a o::Map, k: u64, what: &str) -> Result<&'a Value> {
8482997×
        Ok(o::field(m, k, what)?)
8492997×
    }
850
851
    /// A bundle's value. Each change's text blobs and their chunks (spec
852
    /// §6.1) are added to its objects when they are not already there, so a
853
    /// bundle can always be read on its own.
854131×
    pub fn bundle_value(b: &Bundle) -> Value {
855131×
        let mut changes = Vec::with_capacity(b.raw_changes.len() + b.changes.len());
856
        // Changes as stored are already their encoding, their texts among
857
        // the objects.
858131×
        for (bytes, s) in &b.raw_changes {
8590×
            changes.push(Value::Array(vec![
8600×
                Value::Bytes(bytes.clone()),
8610×
                sigs_value(s),
8620×
            ]));
8630×
        }
864131×
        let mut texts: Vec<(ObjectType, Vec<u8>)> = Vec::new();
865131×
        let mut listed: Option<std::collections::HashSet<ObjectRef>> = None;
866131×
        for (c, s) in &b.changes {
867121×
            let (bytes, stored) = c.encode_parts();
868121×
            for t in stored {
8690×
                let listed = listed.get_or_insert_with(|| {
8700×
                    b.objects
8710×
                        .iter()
8720×
                        .map(|(ty, body)| crate::hash::hash_object(*ty, body))
8730×
                        .collect()
8740×
                });
8750×
                if !listed.insert(t.blob.hash()) {
8760×
                    continue;
8770×
                }
8780×
                for chunk in crate::chunk::chunks(&t.content) {
8790×
                    if listed.insert(crate::hash::hash_object(ObjectType::Chunk, chunk)) {
8800×
                        texts.push((ObjectType::Chunk, chunk.to_vec()));
8810×
                    }
882
                }
8830×
                texts.push((ObjectType::Blob, t.blob.encode()));
884
            }
885121×
            changes.push(Value::Array(vec![Value::Bytes(bytes), sigs_value(s)]));
886
        }
887131×
        let mut v = Value::map([
888131×
            (0, Value::Array(changes)),
889131×
            (
890131×
                1,
891131×
                Value::Array(b.attests.iter().map(attest_value).collect()),
892131×
            ),
893
            (
894
                2,
895
                Value::Array(
896131×
                    b.objects
897131×
                        .iter()
898131×
                        .chain(&texts)
899131×
                        .map(|(t, body)| {
900119×
                            Value::Array(vec![
901119×
                                Value::Text(t.name().into()),
902119×
                                Value::Bytes(body.clone()),
903119×
                            ])
904119×
                        })
905131×
                        .collect(),
906
                ),
907
            ),
908131×
            (
909131×
                3,
910131×
                Value::Array(b.policies.iter().map(policy_value).collect()),
911131×
            ),
912
        ]);
913
        // Only when there are any; older peers ignore the field.
914131×
        if !b.certificates.is_empty() {
9157×
            if let Value::Map(m) = &mut v {
9167×
                m.insert(
917
                    4,
918
                    Value::Array(
9197×
                        b.certificates
9207×
                            .iter()
9217×
                            .map(|c| Value::Bytes(c.encode()))
9227×
                            .collect(),
923
                    ),
924
                );
9250×
            }
926124×
        }
927131×
        v
928131×
    }
929
930121×
    pub fn bundle_from_value(v: &Value) -> Result<Bundle> {
931121×
        let m = map(v, "bundle")?;
932121×
        let mut b = Bundle::default();
933121×
        for ob in o::array(field(m, 2, "objects")?, "objects")? {
934108×
            let pair = o::array(ob, "object")?;
935108×
            if pair.len() != 2 {
9360×
                return Err(schema("object: expected [type, body]"));
937108×
            }
938108×
            let ty = ObjectType::from_name(o::text(&pair[0], "object type")?)
939108×
                .ok_or_else(|| schema("unknown object type"))?;
940108×
            b.objects
941108×
                .push((ty, o::bytes(&pair[1], "object body")?.to_vec()));
942
        }
943
        // Stored inserts are read from the bundle's own objects.
944121×
        let mut by_ref: Option<std::collections::HashMap<ObjectRef, usize>> = None;
945121×
        for c in o::array(field(m, 0, "changes")?, "changes")? {
946104×
            let pair = o::array(c, "change entry")?;
947104×
            if pair.len() != 2 {
9480×
                return Err(schema("change entry: expected [change, sigs]"));
949104×
            }
950104×
            let encoded = o::bytes(&pair[0], "change")?;
951104×
            b.hashes
952104×
                .push(crate::hash::hash_object(ObjectType::Change, encoded));
953104×
            let change = Change::decode_with(encoded, &mut |text, count, form| {
9540×
                let by_ref = by_ref.get_or_insert_with(|| {
9550×
                    b.objects
9560×
                        .iter()
9570×
                        .enumerate()
9580×
                        .map(|(i, (ty, body))| (crate::hash::hash_object(*ty, body), i))
9590×
                        .collect()
9600×
                });
9610×
                let get =
9620×
                    |r: &ObjectRef, want: ObjectType| match by_ref.get(r).map(|i| &b.objects[*i]) {
9630×
                        Some((ty, body)) if *ty == want => Ok(body),
9640×
                        _ => Err(ObjectError::Schema(format!(
9650×
                            "the bundle lacks {} {}",
9660×
                            want.name(),
9670×
                            r.short(12)
9680×
                        ))),
9690×
                    };
9700×
                let blob = crate::objects::Blob::decode(get(text, ObjectType::Blob)?)?;
9710×
                let mut content = Vec::with_capacity(blob.length as usize);
9720×
                for chunk in &blob.chunks {
9730×
                    content.extend_from_slice(get(chunk, ObjectType::Chunk)?);
974
                }
9750×
                crate::objects::text_lines(&content, count, form)
9760×
            })?;
977104×
            b.changes.push((change, sigs_from(&pair[1])?));
978
        }
979121×
        for a in o::array(field(m, 1, "attests")?, "attests")? {
98016×
            b.attests.push(attest_from(a)?);
981
        }
982121×
        if let Some(ps) = m.get(&3) {
983121×
            for p in o::array(ps, "policies")? {
9843×
                b.policies.push(policy_from(p)?);
985
            }
9860×
        }
987121×
        if let Some(cs) = m.get(&4) {
9887×
            for c in o::array(cs, "certificates")? {
9897×
                b.certificates.push(
9907×
                    crate::cert::SignedCertificate::decode(o::bytes(c, "certificate")?)
9917×
                        .map_err(|e| schema(&format!("certificate: {e}")))?,
992
                );
993
            }
994114×
        }
995121×
        Ok(b)
996121×
    }
997
99888×
    pub fn encode_bundle(b: &Bundle) -> Vec<u8> {
99988×
        cbor::encode(&bundle_value(b))
100088×
    }
100182×
    pub fn decode_bundle(bytes: &[u8]) -> Result<Bundle> {
100282×
        bundle_from_value(&cbor::decode(bytes).map_err(ObjectError::from)?)
100382×
    }
1004
1005137×
    pub fn encode_capabilities(id: [u8; 16]) -> Vec<u8> {
1006137×
        cbor::encode(&Value::map([
1007137×
            (0, Value::Array(vec![Value::Uint(PROTOCOL_VERSION)])),
1008137×
            (1, Value::Bytes(id.to_vec())),
1009137×
            (2, Value::Array(vec![Value::Text("seal".into())])),
1010137×
        ]))
1011137×
    }
1012137×
    pub fn decode_capabilities(bytes: &[u8]) -> Result<[u8; 16]> {
1013137×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
1014137×
        let m = map(&v, "capabilities")?;
1015137×
        let versions = o::array(field(m, 0, "versions")?, "versions")?;
1016137×
        if !versions
1017137×
            .iter()
1018137×
            .any(|x| x.as_uint() == Some(PROTOCOL_VERSION))
1019
        {
10200×
            return Err(RepoError::Msg(
10210×
                "remote does not speak protocol version 1".into(),
10220×
            ));
1023137×
        }
1024137×
        o::bytes(field(m, 1, "repo id")?, "repo id")?
1025137×
            .try_into()
1026137×
            .map_err(|_| schema("repo id: expected 16 bytes"))
1027137×
    }
1028
1029210×
    fn tags_value(tags: &[TagRef]) -> Value {
1030
        Value::Array(
1031210×
            tags.iter()
1032210×
                .map(|t| {
103334×
                    let mut v = Value::map([
103434×
                        (0, Value::Text(t.name.clone())),
103534×
                        (1, Value::Bytes(t.state.0.to_vec())),
103634×
                        (2, hashes_value(&t.heads)),
103734×
                        (3, opt_attest_value(&t.attestation)),
103834×
                    ]);
1039
                    // Only when there is one; older peers ignore them
1040
                    // (oxygen#129).
104134×
                    if let Value::Map(m) = &mut v {
104234×
                        if t.accepted.is_some() {
10438×
                            m.insert(4, opt_attest_value(&t.accepted));
104426×
                        }
104534×
                        if let Some(l) = &t.logged {
10462×
                            m.insert(5, logged_value(l));
104732×
                        }
104834×
                        if !t.integration.is_empty() {
10492×
                            m.insert(6, integration_value(&t.integration));
105032×
                        }
10510×
                    }
105234×
                    v
105334×
                })
1054210×
                .collect(),
1055
        )
1056210×
    }
1057249×
    fn tags_from(v: &Value) -> Result<Vec<TagRef>> {
1058249×
        let mut out = Vec::new();
1059249×
        for t in o::array(v, "tags")? {
106050×
            let tm = map(t, "tag")?;
106150×
            out.push(TagRef {
106250×
                name: o::text(field(tm, 0, "name")?, "name")?.to_owned(),
106350×
                state: o::oref(field(tm, 1, "state")?, "state")?,
106450×
                heads: hashes_from(field(tm, 2, "heads")?)?,
106550×
                attestation: opt_attest_from(field(tm, 3, "attestation")?)?,
106650×
                accepted: match tm.get(&4) {
10678×
                    Some(a) => opt_attest_from(a)?,
106842×
                    None => None,
1069
                },
107050×
                logged: tm.get(&5).map(logged_from).transpose()?,
107150×
                integration: match tm.get(&6) {
10722×
                    Some(l) => integration_from(l)?,
107348×
                    None => Vec::new(),
1074
                },
1075
            });
1076
        }
1077249×
        Ok(out)
1078249×
    }
1079
1080
    /// The tags of a refs answer as oxy 0.5.0 read them (and the runners
1081
    /// built with it), keys 0 to 3 only: what an older reader makes of an
1082
    /// answer with keys 4 to 6.
1083
    #[cfg(test)]
10841×
    pub(super) fn tags_as_0_5_read_them(bytes: &[u8]) -> Result<Vec<TagRef>> {
10851×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
10861×
        let m = map(&v, "refs")?;
10871×
        let mut out = Vec::new();
10882×
        for t in o::array(field(m, 3, "tags")?, "tags")? {
10892×
            let tm = map(t, "tag")?;
10902×
            out.push(TagRef::new(
10912×
                o::text(field(tm, 0, "name")?, "name")?.to_owned(),
10922×
                o::oref(field(tm, 1, "state")?, "state")?,
10932×
                hashes_from(field(tm, 2, "heads")?)?,
10942×
                opt_attest_from(field(tm, 3, "attestation")?)?,
1095
            ));
1096
        }
10971×
        Ok(out)
10981×
    }
1099
1100
    /// A log place, `[entry number, entry bytes, [proof hash]]` (spec §14.8).
11014×
    fn logged_value(l: &Logged) -> Value {
11024×
        Value::Array(vec![
11034×
            Value::Uint(l.index),
11044×
            Value::Bytes(l.entry.clone()),
11054×
            proof_value(&l.proof),
11064×
        ])
11074×
    }
11084×
    fn logged_from(v: &Value) -> Result<Logged> {
11094×
        let a = o::array(v, "logged")?;
11104×
        if a.len() != 3 {
11110×
            return Err(schema("logged: expected [index, entry, proof]"));
11124×
        }
1113
        Ok(Logged {
11144×
            index: o::uint(&a[0], "index")?,
11154×
            entry: o::bytes(&a[1], "entry")?.to_vec(),
11164×
            proof: proof_from(&a[2])?,
1117
        })
11184×
    }
1119
1120
    /// Cosigned checkpoints holding an entry, `[[note, [proof hash]]]`.
11214×
    fn integration_value(integration: &[Integration]) -> Value {
1122
        Value::Array(
11234×
            integration
11244×
                .iter()
11254×
                .map(|i| Value::Array(vec![Value::Text(i.note.clone()), proof_value(&i.proof)]))
11264×
                .collect(),
1127
        )
11284×
    }
11294×
    fn integration_from(v: &Value) -> Result<Vec<Integration>> {
11304×
        let mut out = Vec::new();
11314×
        for i in o::array(v, "integration")? {
11324×
            let a = o::array(i, "integration")?;
11334×
            if a.len() != 2 {
11340×
                return Err(schema("integration: expected [note, proof]"));
11354×
            }
11364×
            out.push(Integration {
11374×
                note: o::text(&a[0], "note")?.to_owned(),
11384×
                proof: proof_from(&a[1])?,
1139
            });
1140
        }
11414×
        Ok(out)
11424×
    }
1143
1144167×
    pub fn encode_refs(id: [u8; 16], resp: &RefsResponse) -> Vec<u8> {
1145167×
        let mut v = Value::map([
1146
            (
1147
                0,
1148
                Value::Array(
1149167×
                    resp.refs
1150167×
                        .iter()
1151173×
                        .map(|r| {
1152173×
                            let mut v = Value::map([
1153173×
                                (0, Value::Text(r.name.clone())),
1154173×
                                (1, Value::Bytes(r.state.0.to_vec())),
1155173×
                                (2, hashes_value(&r.heads)),
1156173×
                                (3, opt_attest_value(&r.attestation)),
1157173×
                                (4, r.last_serial.map(Value::Uint).unwrap_or(Value::Null)),
1158173×
                            ]);
1159
                            // Only when there is one; older peers ignore it.
1160173×
                            if let Value::Map(m) = &mut v {
1161173×
                                if r.accepted.is_some() {
11629×
                                    m.insert(5, opt_attest_value(&r.accepted));
1163164×
                                }
1164173×
                                if let Some(l) = &r.logged {
11652×
                                    m.insert(6, logged_value(l));
1166171×
                                }
1167173×
                                if !r.integration.is_empty() {
11682×
                                    m.insert(7, integration_value(&r.integration));
1169171×
                                }
11700×
                            }
1171173×
                            v
1172173×
                        })
1173167×
                        .collect(),
1174
                ),
1175
            ),
1176167×
            (1, Value::Bytes(id.to_vec())),
1177167×
            (2, opt_policy_value(resp.policy.as_ref())),
1178167×
            (3, tags_value(&resp.tags)),
1179167×
            (
1180167×
                4,
1181167×
                Value::Array(resp.history.iter().map(policy_value).collect()),
1182167×
            ),
1183167×
            (
1184167×
                5,
1185167×
                resp.default_bookmark
1186167×
                    .clone()
1187167×
                    .map(Value::Text)
1188167×
                    .unwrap_or(Value::Null),
1189167×
            ),
1190
        ]);
1191167×
        if let Value::Map(m) = &mut v {
1192167×
            if let Some(log) = &resp.log {
11933×
                m.insert(6, Value::Text(log.clone()));
1194164×
            }
1195167×
            if !resp.withdrawn.is_empty() {
11960×
                m.insert(8, tags_value(&resp.withdrawn));
1197167×
            }
1198167×
            if !resp.witnesses.is_empty() {
11992×
                m.insert(
1200
                    7,
1201
                    Value::Array(
12022×
                        resp.witnesses
12032×
                            .iter()
12042×
                            .map(|(name, id)| {
12052×
                                Value::Array(vec![
12062×
                                    Value::Text(name.clone()),
12072×
                                    Value::Bytes(id.clone()),
12082×
                                ])
12092×
                            })
12102×
                            .collect(),
1211
                    ),
1212
                );
1213165×
            }
12140×
        }
1215167×
        cbor::encode(&v)
1216167×
    }
1217210×
    pub fn decode_refs(bytes: &[u8]) -> Result<([u8; 16], RefsResponse)> {
1218210×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
1219210×
        let m = map(&v, "refs")?;
1220210×
        let id: [u8; 16] = o::bytes(field(m, 1, "repo id")?, "repo id")?
1221210×
            .try_into()
1222210×
            .map_err(|_| schema("repo id: expected 16 bytes"))?;
1223210×
        let mut refs = Vec::new();
1224216×
        for r in o::array(field(m, 0, "refs")?, "refs")? {
1225216×
            let rm = map(r, "ref")?;
1226216×
            let ls = field(rm, 4, "last serial")?;
1227216×
            refs.push(RemoteRef {
1228216×
                name: o::text(field(rm, 0, "name")?, "name")?.to_owned(),
1229216×
                state: o::oref(field(rm, 1, "state")?, "state")?,
1230216×
                heads: hashes_from(field(rm, 2, "heads")?)?,
1231216×
                attestation: opt_attest_from(field(rm, 3, "attestation")?)?,
1232216×
                last_serial: if ls.is_null() {
1233183×
                    None
1234
                } else {
123533×
                    Some(o::uint(ls, "last serial")?)
1236
                },
1237216×
                accepted: match rm.get(&5) {
12389×
                    Some(a) => opt_attest_from(a)?,
1239207×
                    None => None,
1240
                },
1241216×
                logged: rm.get(&6).map(logged_from).transpose()?,
1242216×
                integration: match rm.get(&7) {
12432×
                    Some(l) => integration_from(l)?,
1244214×
                    None => Vec::new(),
1245
                },
1246
            });
1247
        }
1248210×
        let policy = match m.get(&2) {
1249210×
            Some(p) => opt_policy_from(p)?,
12500×
            None => None,
1251
        };
1252210×
        let tags = match m.get(&3) {
1253210×
            Some(t) => tags_from(t)?,
12540×
            None => Vec::new(),
1255
        };
1256210×
        let mut history = Vec::new();
1257210×
        if let Some(h) = m.get(&4) {
1258210×
            for p in o::array(h, "history")? {
125917×
                history.push(policy_from(p)?);
1260
            }
12610×
        }
1262210×
        let default_bookmark = match m.get(&5) {
1263141×
            Some(Value::Text(t)) => Some(t.clone()),
126469×
            _ => None,
1265
        };
1266210×
        let log = match m.get(&6) {
12673×
            Some(Value::Text(t)) => Some(t.clone()),
1268207×
            _ => None,
1269
        };
1270210×
        let mut witnesses = Vec::new();
1271210×
        if let Some(w) = m.get(&7) {
12722×
            for x in o::array(w, "witnesses")? {
12732×
                let a = o::array(x, "witness")?;
12742×
                if a.len() != 2 {
12750×
                    return Err(schema("witness: expected [name, identity]"));
12762×
                }
12772×
                witnesses.push((
12782×
                    o::text(&a[0], "witness name")?.to_owned(),
12792×
                    o::bytes(&a[1], "witness identity")?.to_vec(),
1280
                ));
1281
            }
1282208×
        }
1283210×
        let withdrawn = match m.get(&8) {
12840×
            Some(t) => tags_from(t)?,
1285210×
            None => Vec::new(),
1286
        };
1287210×
        Ok((
1288210×
            id,
1289210×
            RefsResponse {
1290210×
                refs,
1291210×
                policy,
1292210×
                tags,
1293210×
                history,
1294210×
                default_bookmark,
1295210×
                log,
1296210×
                witnesses,
1297210×
                withdrawn,
1298210×
            },
1299210×
        ))
1300210×
    }
1301
1302
    /// A proof's hashes, from the leaf upwards (spec §14.8).
13038×
    fn proof_value(proof: &[[u8; 32]]) -> Value {
13048×
        Value::Array(proof.iter().map(|h| Value::Bytes(h.to_vec())).collect())
13058×
    }
1306
13078×
    fn proof_from(v: &Value) -> Result<Vec<[u8; 32]>> {
13088×
        let mut proof = Vec::new();
13098×
        for h in o::array(v, "proof")? {
13108×
            proof.push(
13118×
                o::bytes(h, "proof hash")?
13128×
                    .try_into()
13138×
                    .map_err(|_| schema("proof hash: expected 32 bytes"))?,
1314
            );
1315
        }
13168×
        Ok(proof)
13178×
    }
1318
131953×
    pub fn encode_negotiate(have: &[ChangeHash], want: &[ChangeHash]) -> Vec<u8> {
132053×
        cbor::encode(&Value::map([
132153×
            (0, hashes_value(have)),
132253×
            (1, hashes_value(want)),
132353×
        ]))
132453×
    }
132553×
    pub fn decode_negotiate(bytes: &[u8]) -> Result<(Vec<ChangeHash>, Vec<ChangeHash>)> {
132653×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
132753×
        let m = map(&v, "negotiate")?;
1328
        Ok((
132953×
            hashes_from(field(m, 0, "have")?)?,
133053×
            hashes_from(field(m, 1, "want")?)?,
1331
        ))
133253×
    }
1333
1334
    /// `fetch` request: `{0: [changes], 1: max blob size or null}`.
133554×
    pub fn encode_fetch(hs: &[ChangeHash], max_blob: Option<u64>) -> Vec<u8> {
133654×
        cbor::encode(&Value::map([
133754×
            (0, hashes_value(hs)),
133854×
            (1, max_blob.map(Value::Uint).unwrap_or(Value::Null)),
133954×
        ]))
134054×
    }
134155×
    pub fn decode_fetch(bytes: &[u8]) -> Result<(Vec<ChangeHash>, Option<u64>)> {
134255×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
134355×
        let m = map(&v, "fetch")?;
134455×
        let max = match m.get(&1) {
134554×
            Some(x) if !x.is_null() => Some(o::uint(x, "max blob")?),
134653×
            _ => None,
1347
        };
134855×
        Ok((hashes_from(field(m, 0, "changes")?)?, max))
134955×
    }
1350
1351
    /// `shallow` request: `{0: [heads], 1: depth}`.
13521×
    pub fn encode_shallow(hs: &[ChangeHash], depth: u32) -> Vec<u8> {
13531×
        cbor::encode(&Value::map([
13541×
            (0, hashes_value(hs)),
13551×
            (1, Value::Uint(depth as u64)),
13561×
        ]))
13571×
    }
13581×
    pub fn decode_shallow(bytes: &[u8]) -> Result<(Vec<ChangeHash>, u32)> {
13591×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
13601×
        let m = map(&v, "shallow")?;
1361
        Ok((
13621×
            hashes_from(field(m, 0, "heads")?)?,
13631×
            o::u32_(field(m, 1, "depth")?, "depth")?,
1364
        ))
13651×
    }
1366
136755×
    pub fn encode_hashes(hs: &[ChangeHash]) -> Vec<u8> {
136855×
        cbor::encode(&Value::map([(0, hashes_value(hs))]))
136955×
    }
137054×
    pub fn decode_hashes(bytes: &[u8]) -> Result<Vec<ChangeHash>> {
137154×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
137254×
        hashes_from(field(map(&v, "hashes")?, 0, "hashes")?)
137354×
    }
1374
137543×
    pub fn encode_push(
137643×
        bundle: &Bundle,
137743×
        updates: &[RefUpdate],
137843×
        policy: Option<&SignedPolicy>,
137943×
        tags: &[TagRef],
138043×
    ) -> Vec<u8> {
138143×
        cbor::encode(&Value::map([
138243×
            (0, bundle_value(bundle)),
138343×
            (2, opt_policy_value(policy)),
138443×
            (3, tags_value(tags)),
1385
            (
1386
                1,
1387
                Value::Array(
138843×
                    updates
138943×
                        .iter()
139043×
                        .map(|u| {
139142×
                            Value::map([
139242×
                                (0, Value::Text(u.name.clone())),
139342×
                                (1, Value::Bytes(u.old_state.0.to_vec())),
139442×
                                (2, Value::Bytes(u.new_state.0.to_vec())),
139542×
                                (3, Value::Bool(u.force)),
139642×
                                (4, opt_attest_value(&u.attestation)),
139742×
                            ])
139842×
                        })
139943×
                        .collect(),
1400
                ),
1401
            ),
1402
        ]))
140343×
    }
1404
    /// A decoded push: bundle, bookmark updates, policy, tags.
1405
    pub type PushParts = (Bundle, Vec<RefUpdate>, Option<SignedPolicy>, Vec<TagRef>);
1406
140739×
    pub fn decode_push(bytes: &[u8]) -> Result<PushParts> {
140839×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
140939×
        let m = map(&v, "push")?;
141039×
        let bundle = bundle_from_value(field(m, 0, "bundle")?)?;
141139×
        let mut updates = Vec::new();
141239×
        for u in o::array(field(m, 1, "updates")?, "updates")? {
141338×
            let um = map(u, "update")?;
141438×
            updates.push(RefUpdate {
141538×
                name: o::text(field(um, 0, "name")?, "name")?.to_owned(),
141638×
                old_state: o::oref(field(um, 1, "old_state")?, "old_state")?,
141738×
                new_state: o::oref(field(um, 2, "new_state")?, "new_state")?,
141838×
                force: field(um, 3, "force")?
141938×
                    .as_bool()
142038×
                    .ok_or_else(|| schema("force: expected bool"))?,
142138×
                attestation: opt_attest_from(field(um, 4, "attestation")?)?,
1422
            });
1423
        }
142439×
        let policy = match m.get(&2) {
142539×
            Some(p) => opt_policy_from(p)?,
14260×
            None => None,
1427
        };
142839×
        let tags = match m.get(&3) {
142939×
            Some(t) => tags_from(t)?,
14300×
            None => Vec::new(),
1431
        };
143239×
        Ok((bundle, updates, policy, tags))
143339×
    }
1434
143537×
    pub fn encode_push_response(results: &[RefResult]) -> Vec<u8> {
143637×
        cbor::encode(&Value::map([(
1437
            0,
1438
            Value::Array(
143937×
                results
144037×
                    .iter()
144143×
                    .map(|r| {
144243×
                        Value::map([
144343×
                            (0, Value::Text(r.name.clone())),
144443×
                            (1, Value::Bool(r.ok)),
144543×
                            (2, Value::Text(r.reason.clone())),
144643×
                        ])
144743×
                    })
144837×
                    .collect(),
1449
            ),
1450
        )]))
145137×
    }
145237×
    pub fn decode_push_response(bytes: &[u8]) -> Result<Vec<RefResult>> {
145337×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
145437×
        let m = map(&v, "push response")?;
145537×
        let mut out = Vec::new();
145643×
        for r in o::array(field(m, 0, "results")?, "results")? {
145743×
            let rm = map(r, "result")?;
145843×
            out.push(RefResult {
145943×
                name: o::text(field(rm, 0, "name")?, "name")?.to_owned(),
146043×
                ok: field(rm, 1, "ok")?
146143×
                    .as_bool()
146243×
                    .ok_or_else(|| schema("ok: expected bool"))?,
146343×
                reason: o::text(field(rm, 2, "reason")?, "reason")?.to_owned(),
1464
            });
1465
        }
146637×
        Ok(out)
146737×
    }
1468
}
1469
1470
#[cfg(test)]
1471
mod tests {
1472
    use super::*;
1473
    use crate::attest::AttestBody;
1474
    use crate::objects::Hlc;
1475
1476
    /// oxygen#133: a proxy's HTML error page is shown by its title, and a
1477
    /// server's own text as it is; a 413 says to push in smaller parts.
1478
    #[test]
14791×
    fn html_error_pages_are_shown_by_their_title() {
14801×
        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>";
14811×
        assert_eq!(
14821×
            plain_error_text(cloudflare),
1483
            "413 Request Entity Too Large (an HTML error page, from a proxy in front of the server perhaps)"
1484
        );
14851×
        assert_eq!(
14861×
            plain_error_text("  refused: a secret\nat a.txt:3 "),
1487
            "refused: a secret\nat a.txt:3"
1488
        );
14891×
        assert!(hint_for("https://hub/x: HTTP 413: too large")
14901×
            .unwrap()
14911×
            .contains("push.batch-bytes"));
14921×
    }
1493
1494
    #[test]
14951×
    fn client_features_are_declared_and_read() {
14961×
        assert_eq!(CLIENT_FEATURES.join(","), "certified-tags");
14971×
        assert!(user_agent().starts_with("oxy/"));
14981×
        assert!(declares_feature(
14991×
            Some("certified-tags"),
15001×
            FEATURE_CERTIFIED_TAGS
1501
        ));
15021×
        assert!(declares_feature(
15031×
            Some("later-thing, Certified-Tags ,x"),
15041×
            FEATURE_CERTIFIED_TAGS
1505
        ));
15061×
        assert!(!declares_feature(
15071×
            Some("certified-tags-v2"),
15081×
            FEATURE_CERTIFIED_TAGS
15091×
        ));
15101×
        assert!(!declares_feature(Some(""), FEATURE_CERTIFIED_TAGS));
15111×
        assert!(!declares_feature(None, FEATURE_CERTIFIED_TAGS));
15121×
    }
1513
1514
    #[test]
15151×
    fn wire_round_trips() {
15161×
        let c = crate::objects::tests::sample_change();
15171×
        let sk = crate::identity::SecretKey {
15181×
            ed_seed: [1; 32],
15191×
            ml_seed: [2; 32],
15201×
        };
15211×
        let id = sk.identity("a", "b", 0);
15221×
        let key = id.hash();
15231×
        let sig = sk.sign(crate::identity::Domain::Change, &key, &c.hash());
15241×
        let seal = Attest::seal([3; 16], vec![c.hash()]);
15251×
        let seal_sig = sk.sign(crate::identity::Domain::Attest, &key, &seal.hash());
15261×
        let policy = Policy::single_root([3; 16], id.clone(), 99);
15271×
        let psig = sk.sign(crate::identity::Domain::Policy, &key, &policy.hash());
15281×
        let bundle = Bundle {
15291×
            changes: vec![(c.clone(), vec![sig.clone()])],
15301×
            attests: vec![SignedAttest {
15311×
                attest: seal.clone(),
15321×
                sigs: vec![seal_sig],
15331×
            }],
15341×
            objects: vec![
15351×
                (ObjectType::Identity, id.encode()),
15361×
                (ObjectType::Chunk, b"xyz".to_vec()),
15371×
            ],
15381×
            policies: vec![SignedPolicy {
15391×
                policy: policy.clone(),
15401×
                sigs: vec![psig.clone()],
15411×
            }],
15421×
            hashes: vec![],
15431×
            raw_changes: vec![],
15441×
            certificates: vec![],
15451×
        };
15461×
        let d = wire::decode_bundle(&wire::encode_bundle(&bundle)).unwrap();
15471×
        assert_eq!(
1548
            d.hashes,
15491×
            vec![c.hash()],
1550
            "the receiver hashes what it was sent"
1551
        );
15521×
        assert_eq!(d.changes, bundle.changes);
15531×
        assert_eq!(d.attests, bundle.attests);
15541×
        assert_eq!(d.objects, bundle.objects);
15551×
        assert_eq!(d.policies, bundle.policies);
15561×
        assert!(d.certificates.is_empty());
1557
        // Certificates (keyless, oxygenhub#241) travel as field 4, only
1558
        // when there are any: a bundle without them encodes as before.
15591×
        let plain = wire::encode_bundle(&bundle);
15601×
        let mut with = bundle.clone();
15611×
        let issuer_sk = crate::identity::SecretKey::generate();
15621×
        let issuer = issuer_sk.identity("hub", "h@x", 1);
15631×
        with.certificates.push(crate::cert::SignedCertificate::sign(
15641×
            crate::cert::Certificate {
15651×
                key: id.clone(),
15661×
                issuer: issuer.hash(),
15671×
                subject: "agent:a@b".into(),
15681×
                claims: vec![],
15691×
                scope: crate::identity::Scope::CHANGES,
15701×
                not_before: 1,
15711×
                expires: 2,
15721×
                grant: None,
15731×
            },
15741×
            &issuer,
15751×
            &issuer_sk,
1576
        ));
15771×
        let encoded = wire::encode_bundle(&with);
15781×
        assert_ne!(encoded, plain);
15791×
        assert_eq!(
15801×
            wire::decode_bundle(&encoded).unwrap().certificates,
1581
            with.certificates
1582
        );
15831×
        with.certificates.clear();
15841×
        assert_eq!(wire::encode_bundle(&with), plain);
1585
15861×
        let att = Attest {
15871×
            repo: [3; 16],
15881×
            hlc: Hlc::default(),
15891×
            body: AttestBody::Ref {
15901×
                name: "main".into(),
15911×
                old_state: ObjectRef([1; 32]),
15921×
                new_state: ObjectRef([2; 32]),
15931×
                serial: 4,
15941×
            },
15951×
        };
15961×
        let refs = vec![
15971×
            RemoteRef {
15981×
                name: "main".into(),
15991×
                state: ObjectRef([2; 32]),
16001×
                heads: vec![c.hash()],
16011×
                attestation: Some(SignedAttest {
16021×
                    attest: att.clone(),
16031×
                    sigs: vec![sig.clone()],
16041×
                }),
16051×
                last_serial: Some(4),
16061×
                accepted: None,
16071×
                logged: None,
16081×
                integration: vec![],
16091×
            },
16101×
            RemoteRef {
16111×
                name: "dev".into(),
16121×
                state: ObjectRef([5; 32]),
16131×
                heads: vec![],
16141×
                attestation: None,
16151×
                last_serial: None,
16161×
                accepted: None,
16171×
                logged: None,
16181×
                integration: vec![],
16191×
            },
1620
        ];
16211×
        let tag = TagRef::new("v1".into(), ObjectRef([2; 32]), vec![c.hash()], None);
16221×
        let mut resp = RefsResponse {
16231×
            refs,
16241×
            policy: Some(SignedPolicy {
16251×
                policy: policy.clone(),
16261×
                sigs: vec![psig.clone()],
16271×
            }),
16281×
            tags: vec![tag.clone()],
16291×
            history: vec![SignedPolicy {
16301×
                policy: policy.clone(),
16311×
                sigs: vec![],
16321×
            }],
16331×
            default_bookmark: Some("develop".into()),
16341×
            log: Some("hub.example/log\n2\nroot\n\n- sig\n".into()),
16351×
            witnesses: vec![],
16361×
            withdrawn: vec![],
16371×
        };
1638
        // Without integrated times (spec §14.8) nothing is added: an old
1639
        // peer's answer, and what it reads.
16401×
        let old = wire::encode_refs([3; 16], &resp);
16411×
        let back = wire::decode_refs(&old).unwrap().1;
16422×
        assert!(back.witnesses.is_empty() && back.refs.iter().all(|r| r.integration.is_empty()));
16431×
        resp.refs[1].logged = Some(Logged {
16441×
            index: 41,
16451×
            entry: vec![1, 2, 3],
16461×
            proof: vec![[9; 32], [8; 32]],
16471×
        });
16481×
        resp.refs[1].integration = vec![Integration {
16491×
            note: "hub.example/log\n42\nroot\n\n- sig\n".into(),
16501×
            proof: vec![[7; 32]],
16511×
        }];
16521×
        resp.witnesses = vec![("w.example".into(), vec![4, 5, 6])];
16531×
        let new = wire::encode_refs([3; 16], &resp);
16541×
        let (id_back, back) = wire::decode_refs(&new).unwrap();
16551×
        assert_eq!(back.log, resp.log);
16561×
        assert_eq!(back.refs[1].logged, resp.refs[1].logged);
16571×
        assert_eq!(back.refs[1].integration, resp.refs[1].integration);
16581×
        assert_eq!(back.witnesses, resp.witnesses);
16591×
        assert_eq!(back.refs[0].logged, None);
1660
        // The new keys are 7s an old reader never asks for.
16611×
        let crate::cbor::Value::Map(m) = crate::cbor::decode(&new).unwrap() else {
16620×
            panic!()
1663
        };
16641×
        assert!(m.contains_key(&7));
16651×
        assert_eq!(id_back, [3; 16]);
16661×
        assert_eq!(back.refs.len(), 2);
16671×
        assert_eq!(back.refs[0].attestation.as_ref().unwrap().attest, att);
16681×
        assert_eq!(back.refs[1].last_serial, None);
16691×
        assert_eq!(back.policy.as_ref().unwrap().policy, policy);
16701×
        assert_eq!(back.history, resp.history);
16711×
        assert_eq!(back.tags, vec![tag.clone()]);
1672
1673
        // A tag's acceptance and log place (oxygen#129): keys 4 to 6, only
1674
        // when there are any, so a tag without them encodes as before.
16751×
        let crate::cbor::Value::Map(m) = crate::cbor::decode(&new).unwrap() else {
16760×
            panic!()
1677
        };
16781×
        let crate::cbor::Value::Array(tags) = &m[&3] else {
16790×
            panic!()
1680
        };
16811×
        let crate::cbor::Value::Map(plain) = &tags[0] else {
16820×
            panic!()
1683
        };
16841×
        assert_eq!(plain.keys().copied().collect::<Vec<_>>(), vec![0, 1, 2, 3]);
16851×
        let mut full = tag.clone();
16861×
        full.name = "v2".into();
16871×
        full.attestation = Some(SignedAttest {
16881×
            attest: att.clone(),
16891×
            sigs: vec![sig.clone()],
16901×
        });
16911×
        full.accepted = full.attestation.clone();
16921×
        full.logged = Some(Logged {
16931×
            index: 7,
16941×
            entry: vec![4],
16951×
            proof: vec![[3; 32]],
16961×
        });
16971×
        full.integration = vec![Integration {
16981×
            note: "hub.example/log\n8\nroot\n\n- sig\n".into(),
16991×
            proof: vec![],
17001×
        }];
17011×
        resp.tags = vec![full.clone(), tag.clone()];
17021×
        let bytes = wire::encode_refs([3; 16], &resp);
17031×
        assert_eq!(wire::decode_refs(&bytes).unwrap().1.tags, resp.tags);
1704
        // In a push too.
17051×
        let pushed = wire::encode_push(&Bundle::default(), &[], None, &resp.tags);
17061×
        assert_eq!(wire::decode_push(&pushed).unwrap().3, resp.tags);
1707
        // A reader that knows only keys 0 to 3 (oxy 0.5.0 and older, and
1708
        // the runners built with it) reads the same tags from the new answer.
17091×
        let stripped: Vec<TagRef> = resp
17101×
            .tags
17111×
            .iter()
17122×
            .map(|t| {
17132×
                TagRef::new(
17142×
                    t.name.clone(),
17152×
                    t.state,
17162×
                    t.heads.clone(),
17172×
                    t.attestation.clone(),
1718
                )
17192×
            })
17201×
            .collect();
17211×
        assert_eq!(wire::tags_as_0_5_read_them(&bytes).unwrap(), stripped);
1722
17231×
        let (h, w) = wire::decode_negotiate(&wire::encode_negotiate(
17241×
            &[ObjectRef([1; 32])],
17251×
            &[ObjectRef([2; 32])],
17261×
        ))
17271×
        .unwrap();
17281×
        assert_eq!((h, w), (vec![ObjectRef([1; 32])], vec![ObjectRef([2; 32])]));
17291×
        assert_eq!(
17301×
            wire::decode_hashes(&wire::encode_hashes(&[c.hash()])).unwrap(),
17311×
            vec![c.hash()]
1732
        );
17331×
        assert_eq!(
17341×
            wire::decode_fetch(&wire::encode_fetch(&[c.hash()], Some(4096))).unwrap(),
17351×
            (vec![c.hash()], Some(4096))
1736
        );
17371×
        assert_eq!(
17381×
            wire::decode_fetch(&wire::encode_fetch(&[], None)).unwrap(),
17391×
            (vec![], None)
1740
        );
17411×
        assert_eq!(
17421×
            wire::decode_shallow(&wire::encode_shallow(&[c.hash()], 3)).unwrap(),
17431×
            (vec![c.hash()], 3)
1744
        );
1745
        // An old-style fetch request without the filter field still decodes.
17461×
        assert_eq!(
17471×
            wire::decode_fetch(&wire::encode_hashes(&[c.hash()])).unwrap(),
17481×
            (vec![c.hash()], None)
1749
        );
1750
17511×
        let up = RefUpdate {
17521×
            name: "main".into(),
17531×
            old_state: ObjectRef([1; 32]),
17541×
            new_state: ObjectRef([2; 32]),
17551×
            force: true,
17561×
            attestation: Some(SignedAttest {
17571×
                attest: att,
17581×
                sigs: vec![sig],
17591×
            }),
17601×
        };
17611×
        let sp = SignedPolicy {
17621×
            policy,
17631×
            sigs: vec![psig],
17641×
        };
17651×
        let (b2, ups, pol, tags) = wire::decode_push(&wire::encode_push(
17661×
            &bundle,
17671×
            std::slice::from_ref(&up),
17681×
            Some(&sp),
17691×
            std::slice::from_ref(&tag),
17701×
        ))
17711×
        .unwrap();
17721×
        assert_eq!(pol, Some(sp));
17731×
        assert_eq!(tags, vec![tag]);
17741×
        assert_eq!(b2.changes.len(), 1);
17751×
        assert_eq!(ups[0].name, "main");
17761×
        assert!(ups[0].force);
17771×
        assert_eq!(ups[0].attestation, up.attestation);
17781×
        let res = vec![RefResult {
17791×
            name: "main".into(),
17801×
            ok: false,
17811×
            reason: "stale".into(),
17821×
        }];
17831×
        assert_eq!(
17841×
            wire::decode_push_response(&wire::encode_push_response(&res)).unwrap(),
1785
            res
1786
        );
17871×
        assert_eq!(
17881×
            wire::decode_capabilities(&wire::encode_capabilities([7; 16])).unwrap(),
1789
            [7; 16]
1790
        );
17911×
    }
1792
}