OXYGENHUB

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

1107 of 1285 lines run, 180 of 273 functions · run #427 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).
122150×
    pub fn new(
123150×
        name: String,
124150×
        state: ObjectRef,
125150×
        heads: Vec<ChangeHash>,
126150×
        attestation: Option<SignedAttest>,
127150×
    ) -> TagRef {
128150×
        TagRef {
129150×
            name,
130150×
            state,
131150×
            heads,
132150×
            attestation,
133150×
            accepted: None,
134150×
            logged: None,
135150×
            integration: vec![],
136150×
        }
137150×
    }
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 {
2571223×
    pub fn open(path: &Path) -> Result<LocalRemote> {
258
        Ok(LocalRemote {
2591223×
            repo: Repo::open(path)?,
2601223×
            claimed_id: None,
261
        })
2621223×
    }
263
}
264
265
// Bundles a local remote served on this thread, for tests that count
266
// round trips (oxygen#158).
267
#[cfg(test)]
268
thread_local! {
269
    pub(crate) static LOCAL_FETCHES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
270
}
271
272
impl Remote for LocalRemote {
273959×
    fn repo_id(&self) -> Result<[u8; 16]> {
274959×
        self.repo.id()
275959×
    }
276958×
    fn refs(&self) -> Result<RefsResponse> {
277958×
        self.repo.remote_refs()
278958×
    }
279253×
    fn negotiate(&self, have: &[ChangeHash], want: &[ChangeHash]) -> Result<Vec<ChangeHash>> {
280253×
        self.repo.negotiate(have, want)
281253×
    }
282257×
    fn fetch(&self, changes: &[ChangeHash], max_blob: Option<u64>) -> Result<Bundle> {
283
        #[cfg(test)]
28487×
        LOCAL_FETCHES.with(|n| n.set(n.get() + 1));
285257×
        self.repo.bundle_raw_for(changes, max_blob)
286257×
    }
2875×
    fn objects(&self, refs: &[ObjectRef]) -> Result<Vec<(ObjectType, Vec<u8>)>> {
2885×
        self.repo.objects_for(refs)
2895×
    }
2900×
    fn checkpoint(&self, heads: &[ChangeHash]) -> Result<Bundle> {
2910×
        self.repo.checkpoint_bundle_for(heads)
2920×
    }
2933×
    fn checkpoint_index(&self, heads: &[ChangeHash]) -> Result<Bundle> {
2943×
        self.repo.checkpoint_index_for(heads)
2953×
    }
2963×
    fn shallow(&self, heads: &[ChangeHash], depth: u32) -> Result<Vec<ChangeHash>> {
2973×
        self.repo.shallow_changes(heads, depth)
2983×
    }
299290×
    fn push(
300290×
        &self,
301290×
        bundle: Bundle,
302290×
        updates: Vec<RefUpdate>,
303290×
        policy: Option<SignedPolicy>,
304290×
        tags: Vec<TagRef>,
305290×
    ) -> Result<Vec<RefResult>> {
306290×
        if self.repo.is_unbound() {
30715×
            match self.claimed_id {
30815×
                Some(id) => self.repo.bind_id(id)?,
309
                None => {
3100×
                    return Err(RepoError::Msg(
3110×
                        "the remote is unbound and this client did not say which repository it is"
3120×
                            .into(),
3130×
                    ))
314
                }
315
            }
316275×
        }
317290×
        self.repo.receive_push(bundle, updates, policy, tags)
318290×
    }
319
}
320
321
// ---------------------------------------------------------------- http
322
323
/// How to reach a remote: credentials and trust.
324
#[derive(Clone, Debug, Default)]
325
pub struct RemoteOptions {
326
    /// Bearer token for pushes.
327
    pub token: Option<String>,
328
    /// PEM file with extra root certificates to trust for `https://` remotes
329
    /// (self-hosted servers); the system web roots are always trusted.
330
    pub ca: Option<PathBuf>,
331
    /// The local repository's id, sent as `Oxy-Repo-Id` so an unbound
332
    /// hosted repository can adopt it on the first push (spec §16.1).
333
    pub repo_id: Option<[u8; 16]>,
334
    /// Where a remote kept on a store (`dir://`, `s3://`, …) keeps its
335
    /// mirror and what it has seen: the remote's directory under
336
    /// `.oxy/remotes`. None (a clone, before there is a repository) means
337
    /// a temporary directory.
338
    pub cache_dir: Option<PathBuf>,
339
    /// Other tokens for the same hub, tried in turn when `token` is
340
    /// refused (401, 403 or 404): the credential store's sign-in when
341
    /// `token` is the remote's own (oxygen#155), or those of enclosing
342
    /// checkouts when it came from the credential store (oxygen#112).
343
    pub fallback_tokens: Vec<String>,
344
    /// `token` is the remote's own: fall back only when the hub says it is
345
    /// not a token at all (HTTP 401: expired or unknown), never when it is
346
    /// one that may not do this (403, 404), so a narrowly scoped token is
347
    /// not quietly swapped for a wider sign-in (oxygen#155).
348
    pub fallback_on_401_only: bool,
349
}
350
351
/// Opens a store for a URL it understands, or passes (`None`). Stores that
352
/// need more than the standard library (the cloud ones) are added by the
353
/// program that links them, with [`register_store_opener`].
354
pub type StoreOpener =
355
    fn(&str, &RemoteOptions) -> Option<crate::strata::Result<Box<dyn crate::strata::Store>>>;
356
357
static STORE_OPENERS: Mutex<Vec<StoreOpener>> = Mutex::new(Vec::new());
358
359203×
pub fn register_store_opener(opener: StoreOpener) {
360203×
    STORE_OPENERS
361203×
        .lock()
362203×
        .unwrap_or_else(|p| p.into_inner())
363203×
        .push(opener);
364203×
}
365
366
/// A store for `url`, from `dir://` or any registered opener.
3671282×
pub fn open_store(
3681282×
    url: &str,
3691282×
    options: &RemoteOptions,
3701282×
) -> Option<crate::strata::Result<Box<dyn crate::strata::Store>>> {
3711282×
    if let Some(path) = url.strip_prefix("dir://") {
372
        return Some(
37359×
            crate::strata::LocalStore::open(path)
37459×
                .map(|s| Box::new(s) as Box<dyn crate::strata::Store>),
375
        );
3761223×
    }
3771223×
    let openers = STORE_OPENERS.lock().unwrap_or_else(|p| p.into_inner());
3781223×
    openers.iter().find_map(|open| open(url, options))
3791282×
}
380
381
/// The request header carrying the client's repository id.
382
pub const REPO_ID_HEADER: &str = "Oxy-Repo-Id";
383
384
/// The id of a hosted repository that has not adopted one yet.
385
pub const UNBOUND_ID: [u8; 16] = [0; 16];
386
387
/// The request header in which a client declares the protocol features it
388
/// understands beyond the 0.5.0-era set: a comma-separated list, which a
389
/// server may tailor its answers to (docs/protocol.md, *Client
390
/// capabilities*). A request without it is a client of that era.
391
pub const FEATURES_HEADER: &str = "Oxy-Features";
392
393
/// The feature of a client that authorizes a tag signed by a short-lived,
394
/// certified key by its certificate at the time the host accepted it
395
/// (oxygen#129). A client without it refuses such a tag, and with it the
396
/// whole fetch, so servers leave those tags out of its `refs` (oxygen#131).
397
pub const FEATURE_CERTIFIED_TAGS: &str = "certified-tags";
398
399
/// The features this client declares in [`FEATURES_HEADER`].
400
pub const CLIENT_FEATURES: &[&str] = &[FEATURE_CERTIFIED_TAGS];
401
402
/// The `User-Agent` every request of this client sends: `oxy/<version>`.
403180×
pub fn user_agent() -> String {
404180×
    format!("oxy/{}", env!("CARGO_PKG_VERSION"))
405180×
}
406
407
/// Whether a [`FEATURES_HEADER`] value (absent: `None`) declares `feature`.
408
/// Entries are comma-separated, compared without surrounding blanks and
409
/// regardless of case; unknown ones are ignored.
410149×
pub fn declares_feature(header: Option<&str>, feature: &str) -> bool {
411149×
    header.is_some_and(|h| h.split(',').any(|f| f.trim().eq_ignore_ascii_case(feature)))
412149×
}
413
414
/// A remote served by `oxy-server` at `<base>/oxy/v1/...`.
415
pub struct HttpRemote {
416
    base: String,
417
    /// The token in use, and those still to try when it is refused.
418
    token: Mutex<Option<String>>,
419
    fallbacks: Mutex<Vec<String>>,
420
    fallback_on_401_only: bool,
421
    repo_id: Option<[u8; 16]>,
422
    agent: ureq::Agent,
423
}
424
425
/// A TLS client configuration trusting the web roots plus `ca`, if given:
426
/// the trust every oxy connection uses, shared with tools that call hub APIs.
427183×
pub fn tls_client_config(ca: Option<&Path>) -> Result<Arc<rustls::ClientConfig>> {
428183×
    let mut roots = rustls::RootCertStore::empty();
429183×
    roots.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
430183×
    if let Some(path) = ca {
4315×
        let pem = std::fs::read(path)
4325×
            .map_err(|e| RepoError::Msg(format!("reading CA file {}: {e}", path.display())))?;
4335×
        let certs = rustls_pemfile::certs(&mut pem.as_slice())
4345×
            .collect::<std::result::Result<Vec<_>, _>>()
4355×
            .map_err(|e| RepoError::Msg(format!("parsing CA file {}: {e}", path.display())))?;
4365×
        if certs.is_empty() {
4370×
            return Err(RepoError::Msg(format!(
4380×
                "CA file {} holds no certificates",
4390×
                path.display()
4400×
            )));
4415×
        }
4425×
        for c in certs {
4435×
            roots
4445×
                .add(c)
4455×
                .map_err(|e| RepoError::Msg(format!("CA file {}: {e}", path.display())))?;
446
        }
447178×
    }
448183×
    let cfg = rustls::ClientConfig::builder_with_provider(Arc::new(
449183×
        rustls::crypto::ring::default_provider(),
450
    ))
451183×
    .with_safe_default_protocol_versions()
452183×
    .map_err(|e| RepoError::Msg(e.to_string()))?
453183×
    .with_root_certificates(roots)
454183×
    .with_no_client_auth();
455183×
    Ok(Arc::new(cfg))
456183×
}
457
458
impl HttpRemote {
459177×
    pub fn new(base: &str, options: &RemoteOptions) -> Result<HttpRemote> {
460177×
        refuse_plain_token(base, options)?;
461177×
        let agent = ureq::AgentBuilder::new()
462177×
            .tls_config(tls_client_config(options.ca.as_deref())?)
463177×
            .user_agent(&user_agent())
464177×
            .build();
465177×
        Ok(HttpRemote {
466177×
            base: base.trim_end_matches('/').to_string(),
467177×
            token: Mutex::new(options.token.clone()),
468177×
            fallbacks: Mutex::new(options.fallback_tokens.iter().rev().cloned().collect()),
469177×
            fallback_on_401_only: options.fallback_on_401_only,
470177×
            repo_id: options.repo_id,
471177×
            agent,
472177×
        })
473177×
    }
474
475
    /// A request, tried again with the next fallback token while the
476
    /// hub refuses the one in use (oxygen#112).
477405×
    fn call(&self, post: bool, endpoint: &str, body: Option<&[u8]>) -> Result<Vec<u8>> {
478
        loop {
479408×
            let token = self.token.lock().unwrap_or_else(|p| p.into_inner()).clone();
480408×
            match self.call_once(post, endpoint, body, token.as_deref()) {
4815×
                Err(RepoError::Msg(m))
48214×
                    if token.is_some()
4836×
                        && refused(&m)
4845×
                        && (!self.fallback_on_401_only || m.contains(": HTTP 401")) =>
485
                {
4865×
                    let next = self
4875×
                        .fallbacks
4885×
                        .lock()
4895×
                        .unwrap_or_else(|p| p.into_inner())
4905×
                        .pop();
4915×
                    let Some(next) = next else {
4922×
                        return Err(RepoError::Msg(m));
493
                    };
4943×
                    crate::credentials::warn_once(&format!(
4953×
                        "{}: the token in use was refused; trying another this computer has for the hub \
4963×
                         (a stale remote.NAME.token goes with `oxy config --unset remote.NAME.token`)",
4973×
                        self.base
4983×
                    ));
4993×
                    *self.token.lock().unwrap_or_else(|p| p.into_inner()) = Some(next);
500
                }
501403×
                other => return other,
502
            }
503
        }
504405×
    }
505
506408×
    fn call_once(
507408×
        &self,
508408×
        post: bool,
509408×
        endpoint: &str,
510408×
        body: Option<&[u8]>,
511408×
        token: Option<&str>,
512408×
    ) -> Result<Vec<u8>> {
513408×
        let url = format!("{}/oxy/v1/{endpoint}", self.base);
514408×
        let mut req = if post {
515119×
            self.agent.post(&url)
516
        } else {
517289×
            self.agent.get(&url)
518
        };
519408×
        req = req
520408×
            .set("Accept", CONTENT_TYPE)
521408×
            .set(FEATURES_HEADER, &CLIENT_FEATURES.join(","));
522408×
        if let Some(t) = token {
52325×
            req = req.set("Authorization", &format!("Bearer {t}"));
524383×
        }
525408×
        if let Some(id) = &self.repo_id {
526375×
            req = req.set(REPO_ID_HEADER, &hex::encode(id));
527375×
        }
528408×
        let resp = match body {
529119×
            Some(b) => req.set("Content-Type", CONTENT_TYPE).send_bytes(b),
530289×
            None => req.call(),
531
        };
53214×
        match resp {
533394×
            Ok(r) => {
534394×
                let mut out = Vec::new();
535394×
                r.into_reader()
536394×
                    .read_to_end(&mut out)
537394×
                    .map_err(|e| RepoError::Msg(format!("{url}: {e}")))?;
538394×
                Ok(out)
539
            }
54011×
            Err(ureq::Error::Status(code, r)) => {
54111×
                let text = r.into_string().unwrap_or_default();
542
                // The hint comes from the status alone: the server's text
543
                // (a host's reason for refusing a push, several lines
544
                // perhaps) is shown as it is, never read for hints. A
545
                // proxy's HTML error page is shown by its title only
546
                // (oxygen#133).
54711×
                let status = format!("{url}: HTTP {code}");
54811×
                let msg = format!("{status}: {}", plain_error_text(&text));
54911×
                Err(RepoError::Msg(match hint_for(&status) {
55010×
                    Some(h) => format!("{msg}\n  hint: {h}"),
5511×
                    None => msg,
552
                }))
553
            }
554
            // The transport error already names the URL.
5553×
            Err(e) => Err(RepoError::Msg(with_hint(e.to_string()))),
556
        }
557408×
    }
558
}
559
560
/// Whether a failed request's message says the hub refused its token:
561
/// HTTP 401, 403, or 404 (a hub hides a private repository from a token
562
/// that may not read it).
5636×
fn refused(message: &str) -> bool {
5646×
    [": HTTP 401", ": HTTP 403", ": HTTP 404"]
5656×
        .iter()
5668×
        .any(|c| message.contains(c))
5676×
}
568
569
/// Refuse to send a token where anyone on the way could read it: plain
570
/// `http` to another machine (see [`crate::credentials::token_allowed`]).
571179×
fn refuse_plain_token(url: &str, options: &RemoteOptions) -> Result<()> {
572179×
    if options.token.is_some() && !crate::credentials::token_allowed(url) {
5730×
        return Err(RepoError::Msg(format!(
5740×
            "{url}: refusing to send a token over plain http; use https"
5750×
        )));
576179×
    }
577179×
    Ok(())
578179×
}
579
580
/// What to do about a failed request, recognised from its message.
58123×
pub fn hint_for(message: &str) -> Option<&'static str> {
58223×
    let m = message.to_ascii_lowercase();
58323×
    let hint = if m.contains("http 401") {
5848×
        "the hub needs you signed in, or did not accept the token: run `oxy auth login HUB` (pushing needs repo:write)"
58515×
    } else if m.contains("http 403") {
5861×
        "the token or account lacks permission: pushing needs a token with repo:write and write access to the repository"
58714×
    } else if m.contains("http 413") {
5881×
        "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"
58913×
    } else if m.contains("http 404") {
5904×
        "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`)"
5919×
    } else if m.contains("unknownissuer")
5927×
        || m.contains("unknown issuer")
5937×
        || m.contains("certificate")
5946×
        || m.contains("invalidcertificate")
595
    {
5963×
        "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`"
5976×
    } else if m.contains("connection refused") {
5983×
        "nothing is listening there: check the URL and port, and that the server is running"
5993×
    } else if m.contains("dns")
6002×
        || m.contains("failed to lookup")
6012×
        || m.contains("name or service not known")
602
    {
6031×
        "the host name does not resolve: check the URL"
6042×
    } else if m.contains("timed out") || m.contains("timeout") {
6050×
        "the server did not answer in time: check the network, or try again"
606
    } else {
6072×
        return None;
608
    };
60921×
    Some(hint)
61023×
}
611
612
/// An error response's text as it is, unless it is an HTML page (a proxy's,
613
/// such as Cloudflare's 413): then its title, or a note that it was one.
61413×
fn plain_error_text(text: &str) -> String {
61513×
    let t = text.trim();
61613×
    let lower = t.to_ascii_lowercase();
61713×
    if !(lower.starts_with("<!doctype html") || lower.starts_with("<html")) {
61812×
        return t.to_string();
6191×
    }
6201×
    let title = lower
6211×
        .find("<title>")
6221×
        .and_then(|i| {
6231×
            lower[i + 7..]
6241×
                .find("</title>")
6251×
                .map(|j| t[i + 7..i + 7 + j].trim())
6261×
        })
6271×
        .filter(|s| !s.is_empty());
6281×
    match title {
6291×
        Some(s) => format!("{s} (an HTML error page, from a proxy in front of the server perhaps)"),
6300×
        None => "an HTML error page (from a proxy in front of the server perhaps)".into(),
631
    }
63213×
}
633
634
/// `message`, followed by what to do about it when that is known.
6353×
pub fn with_hint(message: String) -> String {
6363×
    match hint_for(&message) {
6373×
        Some(h) => format!("{message}\n  hint: {h}"),
6380×
        None => message,
639
    }
6403×
}
641
642
/// A JSON request to a hub API (`GET`, `POST` or `DELETE`), with the same
643
/// TLS trust and token rules as remotes. Returns the status and body, an
644
/// error status included; only transport failures are errors.
6450×
pub fn http_json(
6460×
    method: &str,
6470×
    url: &str,
6480×
    body: Option<&str>,
6490×
    options: &RemoteOptions,
6500×
) -> Result<(u16, String)> {
6510×
    refuse_plain_token(url, options)?;
6520×
    let agent = ureq::AgentBuilder::new()
6530×
        .tls_config(tls_client_config(options.ca.as_deref())?)
6540×
        .timeout(std::time::Duration::from_secs(60))
6550×
        .user_agent(&user_agent())
6560×
        .build();
6570×
    let mut req = agent.request(method, url).set("Accept", "application/json");
6580×
    if let Some(t) = &options.token {
6590×
        req = req.set("Authorization", &format!("Bearer {t}"));
6600×
    }
6610×
    let resp = match body {
6620×
        Some(b) => req.set("Content-Type", "application/json").send_string(b),
6630×
        None => req.call(),
664
    };
6650×
    match resp {
6660×
        Ok(r) => {
6670×
            let code = r.status();
6680×
            Ok((code, r.into_string().unwrap_or_default()))
669
        }
6700×
        Err(ureq::Error::Status(code, r)) => Ok((code, r.into_string().unwrap_or_default())),
6710×
        Err(e) => Err(RepoError::Msg(with_hint(e.to_string()))),
672
    }
6730×
}
674
675
/// An authenticated GET of any URL on a host, with the same TLS trust and
676
/// token as remotes use (for hub APIs: proposals). Returns the body.
6772×
pub fn http_get(url: &str, options: &RemoteOptions) -> Result<Vec<u8>> {
6782×
    refuse_plain_token(url, options)?;
6792×
    let agent = ureq::AgentBuilder::new()
6802×
        .tls_config(tls_client_config(options.ca.as_deref())?)
6812×
        .user_agent(&user_agent())
6822×
        .build();
6832×
    let mut req = agent.get(url).set("Accept", "application/json");
6842×
    if let Some(t) = &options.token {
6850×
        req = req.set("Authorization", &format!("Bearer {t}"));
6862×
    }
6872×
    match req.call() {
6882×
        Ok(r) => {
6892×
            let mut out = Vec::new();
6902×
            r.into_reader()
6912×
                .read_to_end(&mut out)
6922×
                .map_err(|e| RepoError::Msg(format!("{url}: {e}")))?;
6932×
            Ok(out)
694
        }
6950×
        Err(ureq::Error::Status(code, r)) => {
6960×
            let text = r.into_string().unwrap_or_default();
6970×
            Err(RepoError::Msg(with_hint(format!(
6980×
                "{url}: HTTP {code}: {}",
6990×
                text.trim()
7000×
            ))))
701
        }
702
        // The transport error already names the URL.
7030×
        Err(e) => Err(RepoError::Msg(with_hint(e.to_string()))),
704
    }
7052×
}
706
707
impl Remote for HttpRemote {
708148×
    fn repo_id(&self) -> Result<[u8; 16]> {
709148×
        wire::decode_capabilities(&self.call(false, "capabilities", None)?)
710148×
    }
711141×
    fn refs(&self) -> Result<RefsResponse> {
712141×
        Ok(wire::decode_refs(&self.call(false, "refs", None)?)?.1)
713141×
    }
71433×
    fn negotiate(&self, have: &[ChangeHash], want: &[ChangeHash]) -> Result<Vec<ChangeHash>> {
71533×
        wire::decode_hashes(&self.call(
716
            true,
71733×
            "negotiate",
71833×
            Some(&wire::encode_negotiate(have, want)),
7190×
        )?)
72033×
    }
72133×
    fn fetch(&self, changes: &[ChangeHash], max_blob: Option<u64>) -> Result<Bundle> {
72233×
        wire::decode_bundle(&self.call(
723
            true,
72433×
            "fetch",
72533×
            Some(&wire::encode_fetch(changes, max_blob)),
7260×
        )?)
72733×
    }
7281×
    fn objects(&self, refs: &[ObjectRef]) -> Result<Vec<(ObjectType, Vec<u8>)>> {
729
        Ok(
7301×
            wire::decode_bundle(&self.call(true, "objects", Some(&wire::encode_hashes(refs)))?)?
731
                .objects,
732
        )
7331×
    }
7340×
    fn checkpoint(&self, heads: &[ChangeHash]) -> Result<Bundle> {
7350×
        let body = {
7360×
            let _t = crate::timing::phase("remote: checkpoint answer");
7370×
            self.call(true, "checkpoint", Some(&wire::encode_hashes(heads)))?
738
        };
7390×
        let _t = crate::timing::phase("remote: decode the checkpoint");
7400×
        wire::decode_bundle(&body)
7410×
    }
7420×
    fn checkpoint_index(&self, heads: &[ChangeHash]) -> Result<Bundle> {
7430×
        let body = {
7440×
            let _t = crate::timing::phase("remote: checkpoint index");
7450×
            match self.call(true, "checkpoint-index", Some(&wire::encode_hashes(heads))) {
7460×
                Ok(b) => b,
747
                // A server from before checkpoint-index: the whole answer.
7480×
                Err(RepoError::Msg(m)) if m.contains("HTTP 404") => return self.checkpoint(heads),
7490×
                Err(e) => return Err(e),
750
            }
751
        };
7520×
        wire::decode_bundle(&body)
7530×
    }
7540×
    fn shallow(&self, heads: &[ChangeHash], depth: u32) -> Result<Vec<ChangeHash>> {
7550×
        wire::decode_hashes(&self.call(
756
            true,
7570×
            "shallow",
7580×
            Some(&wire::encode_shallow(heads, depth)),
7590×
        )?)
7600×
    }
76149×
    fn push(
76249×
        &self,
76349×
        bundle: Bundle,
76449×
        updates: Vec<RefUpdate>,
76549×
        policy: Option<SignedPolicy>,
76649×
        tags: Vec<TagRef>,
76749×
    ) -> Result<Vec<RefResult>> {
76849×
        wire::decode_push_response(&self.call(
769
            true,
77049×
            "push",
77149×
            Some(&wire::encode_push(
77249×
                &bundle,
77349×
                &updates,
77449×
                policy.as_ref(),
77549×
                &tags,
77649×
            )),
7775×
        )?)
77849×
    }
779
}
780
781
/// A remote's URL as it is stored: an `http(s)://` URL as given, a local
782
/// path made absolute (with its `file://` kept), so it still names the same
783
/// repository from inside the clone (oxygen#57).
784299×
pub fn stored_url(url: &str) -> String {
785
    // Only a path is made absolute: a plain one, or one behind file:// or
786
    // dir://. Every other URL (a hub, a bucket) is kept as written.
787299×
    let (prefix, path) = match (url.strip_prefix("file://"), url.strip_prefix("dir://")) {
7881×
        (Some(p), _) => ("file://", p),
78911×
        (_, Some(p)) => ("dir://", p),
790287×
        _ if url.contains("://") => return url.to_string(),
791258×
        _ => ("", url),
792
    };
793270×
    match std::path::absolute(path) {
794270×
        Ok(abs) => format!("{prefix}{}", abs.display()),
7950×
        Err(_) => url.to_string(),
796
    }
797299×
}
798
799
/// Open a remote by URL: a local path (optionally `file://`), `http(s)://`
800
/// (a hub), or a store (`dir://`, and whatever openers are registered).
8011447×
pub fn open_remote(url: &str, options: &RemoteOptions) -> Result<Box<dyn Remote>> {
8021447×
    if url.starts_with("http://") || url.starts_with("https://") {
803177×
        return Ok(Box::new(HttpRemote::new(url, options)?));
8041270×
    }
8051270×
    if let Some(store) = open_store(url, options) {
80648×
        return crate::repo::strata::open_store_remote(store?, options);
8071222×
    }
8081222×
    let path = url.strip_prefix("file://").unwrap_or(url);
8091222×
    if path.contains("://") {
8100×
        return Err(RepoError::Msg(format!("unsupported remote URL {url:?}")));
8111222×
    }
8121222×
    let mut local = LocalRemote::open(Path::new(path))?;
8131222×
    local.claimed_id = options.repo_id;
8141222×
    Ok(Box::new(local))
8151447×
}
816
817
// ---------------------------------------------------------------- wire
818
819
/// CBOR encodings of the protocol messages (spec §16.1).
820
pub mod wire {
821
    use super::*;
822
8230×
    fn schema(msg: &str) -> RepoError {
8240×
        RepoError::Object(ObjectError::Schema(msg.into()))
8250×
    }
826265×
    fn sigs_value(sigs: &[Signature]) -> Value {
827265×
        Value::Array(sigs.iter().map(|s| s.to_value()).collect())
828265×
    }
829261×
    fn sigs_from(v: &Value) -> Result<Vec<Signature>> {
830261×
        Ok(o::array(v, "signatures")?
831261×
            .iter()
832261×
            .map(Signature::from_value)
833261×
            .collect::<std::result::Result<Vec<_>, _>>()?)
834261×
    }
835353×
    fn hashes_value(hs: &[ObjectRef]) -> Value {
836491×
        Value::Array(hs.iter().map(|h| Value::Bytes(h.0.to_vec())).collect())
837353×
    }
838414×
    fn hashes_from(v: &Value) -> Result<Vec<ObjectRef>> {
839414×
        Ok(o::array(v, "hashes")?
840414×
            .iter()
841553×
            .map(|h| o::oref(h, "hash"))
842414×
            .collect::<std::result::Result<Vec<_>, _>>()?)
843414×
    }
84491×
    fn attest_value(sa: &SignedAttest) -> Value {
84591×
        Value::Array(vec![Value::Bytes(sa.attest.encode()), sigs_value(&sa.sigs)])
84691×
    }
847106×
    fn attest_from(v: &Value) -> Result<SignedAttest> {
848106×
        let a = o::array(v, "signed attest")?;
849106×
        if a.len() != 2 {
8500×
            return Err(schema("signed attest: expected [attest, sigs]"));
851106×
        }
852
        Ok(SignedAttest {
853106×
            attest: Attest::decode(o::bytes(&a[0], "attest")?)?,
854106×
            sigs: sigs_from(&a[1])?,
855
        })
856106×
    }
857280×
    fn opt_attest_value(sa: &Option<SignedAttest>) -> Value {
858280×
        sa.as_ref().map(attest_value).unwrap_or(Value::Null)
859280×
    }
860337×
    fn opt_attest_from(v: &Value) -> Result<Option<SignedAttest>> {
861337×
        if v.is_null() {
862247×
            Ok(None)
863
        } else {
86490×
            attest_from(v).map(Some)
865
        }
866337×
    }
867
    /// `[policy bytes, [signature]]`: also the format of a policy proposal
868
    /// file exchanged between root holders (spec §14.5).
86945×
    pub fn policy_value(sp: &SignedPolicy) -> Value {
87045×
        Value::Array(vec![Value::Bytes(sp.policy.encode()), sigs_value(&sp.sigs)])
87145×
    }
87243×
    pub fn policy_from(v: &Value) -> Result<SignedPolicy> {
87343×
        let a = o::array(v, "signed policy")?;
87443×
        if a.len() != 2 {
8750×
            return Err(schema("signed policy: expected [policy, sigs]"));
87643×
        }
877
        Ok(SignedPolicy {
87843×
            policy: Policy::decode(o::bytes(&a[0], "policy")?)?,
87943×
            sigs: sigs_from(&a[1])?,
880
        })
88143×
    }
882224×
    fn opt_policy_value(sp: Option<&SignedPolicy>) -> Value {
883224×
        sp.map(policy_value).unwrap_or(Value::Null)
884224×
    }
885263×
    fn opt_policy_from(v: &Value) -> Result<Option<SignedPolicy>> {
886263×
        if v.is_null() {
887241×
            Ok(None)
888
        } else {
88922×
            policy_from(v).map(Some)
890
        }
891263×
    }
8921039×
    fn map<'a>(v: &'a Value, what: &str) -> Result<&'a o::Map> {
8931039×
        Ok(o::map(v, what)?)
8941039×
    }
8953030×
    fn field<'a>(m: &'a o::Map, k: u64, what: &str) -> Result<&'a Value> {
8963030×
        Ok(o::field(m, k, what)?)
8973030×
    }
898
899
    /// A bundle's value. Each change's text blobs and their chunks (spec
900
    /// §6.1) are added to its objects when they are not already there, so a
901
    /// bundle can always be read on its own.
902120×
    pub fn bundle_value(b: &Bundle) -> Value {
903120×
        let mut changes = Vec::with_capacity(b.raw_changes.len() + b.changes.len());
904
        // Changes as stored are already their encoding, their texts among
905
        // the objects.
906120×
        for (bytes, s) in &b.raw_changes {
9070×
            changes.push(Value::Array(vec![
9080×
                Value::Bytes(bytes.clone()),
9090×
                sigs_value(s),
9100×
            ]));
9110×
        }
912120×
        let mut texts: Vec<(ObjectType, Vec<u8>)> = Vec::new();
913120×
        let mut listed: Option<std::collections::HashSet<ObjectRef>> = None;
914129×
        for (c, s) in &b.changes {
915129×
            let (bytes, stored) = c.encode_parts();
916129×
            for t in stored {
9170×
                let listed = listed.get_or_insert_with(|| {
9180×
                    b.objects
9190×
                        .iter()
9200×
                        .map(|(ty, body)| crate::hash::hash_object(*ty, body))
9210×
                        .collect()
9220×
                });
9230×
                if !listed.insert(t.blob.hash()) {
9240×
                    continue;
9250×
                }
9260×
                for chunk in crate::chunk::chunks(&t.content) {
9270×
                    if listed.insert(crate::hash::hash_object(ObjectType::Chunk, chunk)) {
9280×
                        texts.push((ObjectType::Chunk, chunk.to_vec()));
9290×
                    }
930
                }
9310×
                texts.push((ObjectType::Blob, t.blob.encode()));
932
            }
933129×
            changes.push(Value::Array(vec![Value::Bytes(bytes), sigs_value(s)]));
934
        }
935120×
        let mut v = Value::map([
936120×
            (0, Value::Array(changes)),
937120×
            (
938120×
                1,
939120×
                Value::Array(b.attests.iter().map(attest_value).collect()),
940120×
            ),
941
            (
942
                2,
943
                Value::Array(
944120×
                    b.objects
945120×
                        .iter()
946120×
                        .chain(&texts)
947204×
                        .map(|(t, body)| {
948204×
                            Value::Array(vec![
949204×
                                Value::Text(t.name().into()),
950204×
                                Value::Bytes(body.clone()),
951204×
                            ])
952204×
                        })
953120×
                        .collect(),
954
                ),
955
            ),
956120×
            (
957120×
                3,
958120×
                Value::Array(b.policies.iter().map(policy_value).collect()),
959120×
            ),
960
        ]);
961
        // Only when there are any; older peers ignore the field.
962120×
        if !b.certificates.is_empty() {
9636×
            if let Value::Map(m) = &mut v {
9646×
                m.insert(
965
                    4,
966
                    Value::Array(
9676×
                        b.certificates
9686×
                            .iter()
9696×
                            .map(|c| Value::Bytes(c.encode()))
9706×
                            .collect(),
971
                    ),
972
                );
9730×
            }
974114×
        }
975120×
        v
976120×
    }
977
978110×
    pub fn bundle_from_value(v: &Value) -> Result<Bundle> {
979110×
        let m = map(v, "bundle")?;
980110×
        let mut b = Bundle::default();
981193×
        for ob in o::array(field(m, 2, "objects")?, "objects")? {
982193×
            let pair = o::array(ob, "object")?;
983193×
            if pair.len() != 2 {
9840×
                return Err(schema("object: expected [type, body]"));
985193×
            }
986193×
            let ty = ObjectType::from_name(o::text(&pair[0], "object type")?)
987193×
                .ok_or_else(|| schema("unknown object type"))?;
988193×
            b.objects
989193×
                .push((ty, o::bytes(&pair[1], "object body")?.to_vec()));
990
        }
991
        // Stored inserts are read from the bundle's own objects.
992110×
        let mut by_ref: Option<std::collections::HashMap<ObjectRef, usize>> = None;
993112×
        for c in o::array(field(m, 0, "changes")?, "changes")? {
994112×
            let pair = o::array(c, "change entry")?;
995112×
            if pair.len() != 2 {
9960×
                return Err(schema("change entry: expected [change, sigs]"));
997112×
            }
998112×
            let encoded = o::bytes(&pair[0], "change")?;
999112×
            b.hashes
1000112×
                .push(crate::hash::hash_object(ObjectType::Change, encoded));
1001112×
            let change = Change::decode_with(encoded, &mut |text, count, form| {
10020×
                let by_ref = by_ref.get_or_insert_with(|| {
10030×
                    b.objects
10040×
                        .iter()
10050×
                        .enumerate()
10060×
                        .map(|(i, (ty, body))| (crate::hash::hash_object(*ty, body), i))
10070×
                        .collect()
10080×
                });
10090×
                let get =
10100×
                    |r: &ObjectRef, want: ObjectType| match by_ref.get(r).map(|i| &b.objects[*i]) {
10110×
                        Some((ty, body)) if *ty == want => Ok(body),
10120×
                        _ => Err(ObjectError::Schema(format!(
10130×
                            "the bundle lacks {} {}",
10140×
                            want.name(),
10150×
                            r.short(12)
10160×
                        ))),
10170×
                    };
10180×
                let blob = crate::objects::Blob::decode(get(text, ObjectType::Blob)?)?;
10190×
                let mut content = Vec::with_capacity(blob.length as usize);
10200×
                for chunk in &blob.chunks {
10210×
                    content.extend_from_slice(get(chunk, ObjectType::Chunk)?);
1022
                }
10230×
                crate::objects::text_lines(&content, count, form)
10240×
            })?;
1025112×
            b.changes.push((change, sigs_from(&pair[1])?));
1026
        }
1027110×
        for a in o::array(field(m, 1, "attests")?, "attests")? {
102816×
            b.attests.push(attest_from(a)?);
1029
        }
1030110×
        if let Some(ps) = m.get(&3) {
1031110×
            for p in o::array(ps, "policies")? {
10323×
                b.policies.push(policy_from(p)?);
1033
            }
10340×
        }
1035110×
        if let Some(cs) = m.get(&4) {
10366×
            for c in o::array(cs, "certificates")? {
10376×
                b.certificates.push(
10386×
                    crate::cert::SignedCertificate::decode(o::bytes(c, "certificate")?)
10396×
                        .map_err(|e| schema(&format!("certificate: {e}")))?,
1040
                );
1041
            }
1042104×
        }
1043110×
        Ok(b)
1044110×
    }
1045
104669×
    pub fn encode_bundle(b: &Bundle) -> Vec<u8> {
104769×
        cbor::encode(&bundle_value(b))
104869×
    }
104963×
    pub fn decode_bundle(bytes: &[u8]) -> Result<Bundle> {
105063×
        bundle_from_value(&cbor::decode(bytes).map_err(ObjectError::from)?)
105163×
    }
1052
1053143×
    pub fn encode_capabilities(id: [u8; 16]) -> Vec<u8> {
1054143×
        cbor::encode(&Value::map([
1055143×
            (0, Value::Array(vec![Value::Uint(PROTOCOL_VERSION)])),
1056143×
            (1, Value::Bytes(id.to_vec())),
1057143×
            (2, Value::Array(vec![Value::Text("seal".into())])),
1058143×
        ]))
1059143×
    }
1060143×
    pub fn decode_capabilities(bytes: &[u8]) -> Result<[u8; 16]> {
1061143×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
1062143×
        let m = map(&v, "capabilities")?;
1063143×
        let versions = o::array(field(m, 0, "versions")?, "versions")?;
1064143×
        if !versions
1065143×
            .iter()
1066143×
            .any(|x| x.as_uint() == Some(PROTOCOL_VERSION))
1067
        {
10680×
            return Err(RepoError::Msg(
10690×
                "remote does not speak protocol version 1".into(),
10700×
            ));
1071143×
        }
1072143×
        o::bytes(field(m, 1, "repo id")?, "repo id")?
1073143×
            .try_into()
1074143×
            .map_err(|_| schema("repo id: expected 16 bytes"))
1075143×
    }
1076
1077224×
    fn tags_value(tags: &[TagRef]) -> Value {
1078
        Value::Array(
1079224×
            tags.iter()
1080224×
                .map(|t| {
108134×
                    let mut v = Value::map([
108234×
                        (0, Value::Text(t.name.clone())),
108334×
                        (1, Value::Bytes(t.state.0.to_vec())),
108434×
                        (2, hashes_value(&t.heads)),
108534×
                        (3, opt_attest_value(&t.attestation)),
108634×
                    ]);
1087
                    // Only when there is one; older peers ignore them
1088
                    // (oxygen#129).
108934×
                    if let Value::Map(m) = &mut v {
109034×
                        if t.accepted.is_some() {
10918×
                            m.insert(4, opt_attest_value(&t.accepted));
109226×
                        }
109334×
                        if let Some(l) = &t.logged {
10942×
                            m.insert(5, logged_value(l));
109532×
                        }
109634×
                        if !t.integration.is_empty() {
10972×
                            m.insert(6, integration_value(&t.integration));
109832×
                        }
10990×
                    }
110034×
                    v
110134×
                })
1102224×
                .collect(),
1103
        )
1104224×
    }
1105263×
    fn tags_from(v: &Value) -> Result<Vec<TagRef>> {
1106263×
        let mut out = Vec::new();
1107263×
        for t in o::array(v, "tags")? {
110850×
            let tm = map(t, "tag")?;
110950×
            out.push(TagRef {
111050×
                name: o::text(field(tm, 0, "name")?, "name")?.to_owned(),
111150×
                state: o::oref(field(tm, 1, "state")?, "state")?,
111250×
                heads: hashes_from(field(tm, 2, "heads")?)?,
111350×
                attestation: opt_attest_from(field(tm, 3, "attestation")?)?,
111450×
                accepted: match tm.get(&4) {
11158×
                    Some(a) => opt_attest_from(a)?,
111642×
                    None => None,
1117
                },
111850×
                logged: tm.get(&5).map(logged_from).transpose()?,
111950×
                integration: match tm.get(&6) {
11202×
                    Some(l) => integration_from(l)?,
112148×
                    None => Vec::new(),
1122
                },
1123
            });
1124
        }
1125263×
        Ok(out)
1126263×
    }
1127
1128
    /// The tags of a refs answer as oxy 0.5.0 read them (and the runners
1129
    /// built with it), keys 0 to 3 only: what an older reader makes of an
1130
    /// answer with keys 4 to 6.
1131
    #[cfg(test)]
11321×
    pub(super) fn tags_as_0_5_read_them(bytes: &[u8]) -> Result<Vec<TagRef>> {
11331×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
11341×
        let m = map(&v, "refs")?;
11351×
        let mut out = Vec::new();
11362×
        for t in o::array(field(m, 3, "tags")?, "tags")? {
11372×
            let tm = map(t, "tag")?;
11382×
            out.push(TagRef::new(
11392×
                o::text(field(tm, 0, "name")?, "name")?.to_owned(),
11402×
                o::oref(field(tm, 1, "state")?, "state")?,
11412×
                hashes_from(field(tm, 2, "heads")?)?,
11422×
                opt_attest_from(field(tm, 3, "attestation")?)?,
1143
            ));
1144
        }
11451×
        Ok(out)
11461×
    }
1147
1148
    /// A log place, `[entry number, entry bytes, [proof hash]]` (spec §14.8).
11494×
    fn logged_value(l: &Logged) -> Value {
11504×
        Value::Array(vec![
11514×
            Value::Uint(l.index),
11524×
            Value::Bytes(l.entry.clone()),
11534×
            proof_value(&l.proof),
11544×
        ])
11554×
    }
11564×
    fn logged_from(v: &Value) -> Result<Logged> {
11574×
        let a = o::array(v, "logged")?;
11584×
        if a.len() != 3 {
11590×
            return Err(schema("logged: expected [index, entry, proof]"));
11604×
        }
1161
        Ok(Logged {
11624×
            index: o::uint(&a[0], "index")?,
11634×
            entry: o::bytes(&a[1], "entry")?.to_vec(),
11644×
            proof: proof_from(&a[2])?,
1165
        })
11664×
    }
1167
1168
    /// Cosigned checkpoints holding an entry, `[[note, [proof hash]]]`.
11694×
    fn integration_value(integration: &[Integration]) -> Value {
1170
        Value::Array(
11714×
            integration
11724×
                .iter()
11734×
                .map(|i| Value::Array(vec![Value::Text(i.note.clone()), proof_value(&i.proof)]))
11744×
                .collect(),
1175
        )
11764×
    }
11774×
    fn integration_from(v: &Value) -> Result<Vec<Integration>> {
11784×
        let mut out = Vec::new();
11794×
        for i in o::array(v, "integration")? {
11804×
            let a = o::array(i, "integration")?;
11814×
            if a.len() != 2 {
11820×
                return Err(schema("integration: expected [note, proof]"));
11834×
            }
11844×
            out.push(Integration {
11854×
                note: o::text(&a[0], "note")?.to_owned(),
11864×
                proof: proof_from(&a[1])?,
1187
            });
1188
        }
11894×
        Ok(out)
11904×
    }
1191
1192173×
    pub fn encode_refs(id: [u8; 16], resp: &RefsResponse) -> Vec<u8> {
1193173×
        let mut v = Value::map([
1194
            (
1195
                0,
1196
                Value::Array(
1197173×
                    resp.refs
1198173×
                        .iter()
1199179×
                        .map(|r| {
1200179×
                            let mut v = Value::map([
1201179×
                                (0, Value::Text(r.name.clone())),
1202179×
                                (1, Value::Bytes(r.state.0.to_vec())),
1203179×
                                (2, hashes_value(&r.heads)),
1204179×
                                (3, opt_attest_value(&r.attestation)),
1205179×
                                (4, r.last_serial.map(Value::Uint).unwrap_or(Value::Null)),
1206179×
                            ]);
1207
                            // Only when there is one; older peers ignore it.
1208179×
                            if let Value::Map(m) = &mut v {
1209179×
                                if r.accepted.is_some() {
12109×
                                    m.insert(5, opt_attest_value(&r.accepted));
1211170×
                                }
1212179×
                                if let Some(l) = &r.logged {
12132×
                                    m.insert(6, logged_value(l));
1214177×
                                }
1215179×
                                if !r.integration.is_empty() {
12162×
                                    m.insert(7, integration_value(&r.integration));
1217177×
                                }
12180×
                            }
1219179×
                            v
1220179×
                        })
1221173×
                        .collect(),
1222
                ),
1223
            ),
1224173×
            (1, Value::Bytes(id.to_vec())),
1225173×
            (2, opt_policy_value(resp.policy.as_ref())),
1226173×
            (3, tags_value(&resp.tags)),
1227173×
            (
1228173×
                4,
1229173×
                Value::Array(resp.history.iter().map(policy_value).collect()),
1230173×
            ),
1231173×
            (
1232173×
                5,
1233173×
                resp.default_bookmark
1234173×
                    .clone()
1235173×
                    .map(Value::Text)
1236173×
                    .unwrap_or(Value::Null),
1237173×
            ),
1238
        ]);
1239173×
        if let Value::Map(m) = &mut v {
1240173×
            if let Some(log) = &resp.log {
12413×
                m.insert(6, Value::Text(log.clone()));
1242170×
            }
1243173×
            if !resp.withdrawn.is_empty() {
12440×
                m.insert(8, tags_value(&resp.withdrawn));
1245173×
            }
1246173×
            if !resp.witnesses.is_empty() {
12472×
                m.insert(
1248
                    7,
1249
                    Value::Array(
12502×
                        resp.witnesses
12512×
                            .iter()
12522×
                            .map(|(name, id)| {
12532×
                                Value::Array(vec![
12542×
                                    Value::Text(name.clone()),
12552×
                                    Value::Bytes(id.clone()),
12562×
                                ])
12572×
                            })
12582×
                            .collect(),
1259
                    ),
1260
                );
1261171×
            }
12620×
        }
1263173×
        cbor::encode(&v)
1264173×
    }
1265216×
    pub fn decode_refs(bytes: &[u8]) -> Result<([u8; 16], RefsResponse)> {
1266216×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
1267216×
        let m = map(&v, "refs")?;
1268216×
        let id: [u8; 16] = o::bytes(field(m, 1, "repo id")?, "repo id")?
1269216×
            .try_into()
1270216×
            .map_err(|_| schema("repo id: expected 16 bytes"))?;
1271216×
        let mut refs = Vec::new();
1272222×
        for r in o::array(field(m, 0, "refs")?, "refs")? {
1273222×
            let rm = map(r, "ref")?;
1274222×
            let ls = field(rm, 4, "last serial")?;
1275222×
            refs.push(RemoteRef {
1276222×
                name: o::text(field(rm, 0, "name")?, "name")?.to_owned(),
1277222×
                state: o::oref(field(rm, 1, "state")?, "state")?,
1278222×
                heads: hashes_from(field(rm, 2, "heads")?)?,
1279222×
                attestation: opt_attest_from(field(rm, 3, "attestation")?)?,
1280222×
                last_serial: if ls.is_null() {
1281189×
                    None
1282
                } else {
128333×
                    Some(o::uint(ls, "last serial")?)
1284
                },
1285222×
                accepted: match rm.get(&5) {
12869×
                    Some(a) => opt_attest_from(a)?,
1287213×
                    None => None,
1288
                },
1289222×
                logged: rm.get(&6).map(logged_from).transpose()?,
1290222×
                integration: match rm.get(&7) {
12912×
                    Some(l) => integration_from(l)?,
1292220×
                    None => Vec::new(),
1293
                },
1294
            });
1295
        }
1296216×
        let policy = match m.get(&2) {
1297216×
            Some(p) => opt_policy_from(p)?,
12980×
            None => None,
1299
        };
1300216×
        let tags = match m.get(&3) {
1301216×
            Some(t) => tags_from(t)?,
13020×
            None => Vec::new(),
1303
        };
1304216×
        let mut history = Vec::new();
1305216×
        if let Some(h) = m.get(&4) {
1306216×
            for p in o::array(h, "history")? {
130717×
                history.push(policy_from(p)?);
1308
            }
13090×
        }
1310216×
        let default_bookmark = match m.get(&5) {
1311147×
            Some(Value::Text(t)) => Some(t.clone()),
131269×
            _ => None,
1313
        };
1314216×
        let log = match m.get(&6) {
13153×
            Some(Value::Text(t)) => Some(t.clone()),
1316213×
            _ => None,
1317
        };
1318216×
        let mut witnesses = Vec::new();
1319216×
        if let Some(w) = m.get(&7) {
13202×
            for x in o::array(w, "witnesses")? {
13212×
                let a = o::array(x, "witness")?;
13222×
                if a.len() != 2 {
13230×
                    return Err(schema("witness: expected [name, identity]"));
13242×
                }
13252×
                witnesses.push((
13262×
                    o::text(&a[0], "witness name")?.to_owned(),
13272×
                    o::bytes(&a[1], "witness identity")?.to_vec(),
1328
                ));
1329
            }
1330214×
        }
1331216×
        let withdrawn = match m.get(&8) {
13320×
            Some(t) => tags_from(t)?,
1333216×
            None => Vec::new(),
1334
        };
1335216×
        Ok((
1336216×
            id,
1337216×
            RefsResponse {
1338216×
                refs,
1339216×
                policy,
1340216×
                tags,
1341216×
                history,
1342216×
                default_bookmark,
1343216×
                log,
1344216×
                witnesses,
1345216×
                withdrawn,
1346216×
            },
1347216×
        ))
1348216×
    }
1349
1350
    /// A proof's hashes, from the leaf upwards (spec §14.8).
13518×
    fn proof_value(proof: &[[u8; 32]]) -> Value {
13528×
        Value::Array(proof.iter().map(|h| Value::Bytes(h.to_vec())).collect())
13538×
    }
1354
13558×
    fn proof_from(v: &Value) -> Result<Vec<[u8; 32]>> {
13568×
        let mut proof = Vec::new();
13578×
        for h in o::array(v, "proof")? {
13588×
            proof.push(
13598×
                o::bytes(h, "proof hash")?
13608×
                    .try_into()
13618×
                    .map_err(|_| schema("proof hash: expected 32 bytes"))?,
1362
            );
1363
        }
13648×
        Ok(proof)
13658×
    }
1366
136734×
    pub fn encode_negotiate(have: &[ChangeHash], want: &[ChangeHash]) -> Vec<u8> {
136834×
        cbor::encode(&Value::map([
136934×
            (0, hashes_value(have)),
137034×
            (1, hashes_value(want)),
137134×
        ]))
137234×
    }
137334×
    pub fn decode_negotiate(bytes: &[u8]) -> Result<(Vec<ChangeHash>, Vec<ChangeHash>)> {
137434×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
137534×
        let m = map(&v, "negotiate")?;
1376
        Ok((
137734×
            hashes_from(field(m, 0, "have")?)?,
137834×
            hashes_from(field(m, 1, "want")?)?,
1379
        ))
138034×
    }
1381
1382
    /// `fetch` request: `{0: [changes], 1: max blob size or null}`.
138335×
    pub fn encode_fetch(hs: &[ChangeHash], max_blob: Option<u64>) -> Vec<u8> {
138435×
        cbor::encode(&Value::map([
138535×
            (0, hashes_value(hs)),
138635×
            (1, max_blob.map(Value::Uint).unwrap_or(Value::Null)),
138735×
        ]))
138835×
    }
138936×
    pub fn decode_fetch(bytes: &[u8]) -> Result<(Vec<ChangeHash>, Option<u64>)> {
139036×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
139136×
        let m = map(&v, "fetch")?;
139236×
        let max = match m.get(&1) {
139335×
            Some(x) if !x.is_null() => Some(o::uint(x, "max blob")?),
139434×
            _ => None,
1395
        };
139636×
        Ok((hashes_from(field(m, 0, "changes")?)?, max))
139736×
    }
1398
1399
    /// `shallow` request: `{0: [heads], 1: depth}`.
14001×
    pub fn encode_shallow(hs: &[ChangeHash], depth: u32) -> Vec<u8> {
14011×
        cbor::encode(&Value::map([
14021×
            (0, hashes_value(hs)),
14031×
            (1, Value::Uint(depth as u64)),
14041×
        ]))
14051×
    }
14061×
    pub fn decode_shallow(bytes: &[u8]) -> Result<(Vec<ChangeHash>, u32)> {
14071×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
14081×
        let m = map(&v, "shallow")?;
1409
        Ok((
14101×
            hashes_from(field(m, 0, "heads")?)?,
14111×
            o::u32_(field(m, 1, "depth")?, "depth")?,
1412
        ))
14131×
    }
1414
141536×
    pub fn encode_hashes(hs: &[ChangeHash]) -> Vec<u8> {
141636×
        cbor::encode(&Value::map([(0, hashes_value(hs))]))
141736×
    }
141835×
    pub fn decode_hashes(bytes: &[u8]) -> Result<Vec<ChangeHash>> {
141935×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
142035×
        hashes_from(field(map(&v, "hashes")?, 0, "hashes")?)
142135×
    }
1422
142351×
    pub fn encode_push(
142451×
        bundle: &Bundle,
142551×
        updates: &[RefUpdate],
142651×
        policy: Option<&SignedPolicy>,
142751×
        tags: &[TagRef],
142851×
    ) -> Vec<u8> {
142951×
        cbor::encode(&Value::map([
143051×
            (0, bundle_value(bundle)),
143151×
            (2, opt_policy_value(policy)),
143251×
            (3, tags_value(tags)),
1433
            (
1434
                1,
1435
                Value::Array(
143651×
                    updates
143751×
                        .iter()
143851×
                        .map(|u| {
143950×
                            Value::map([
144050×
                                (0, Value::Text(u.name.clone())),
144150×
                                (1, Value::Bytes(u.old_state.0.to_vec())),
144250×
                                (2, Value::Bytes(u.new_state.0.to_vec())),
144350×
                                (3, Value::Bool(u.force)),
144450×
                                (4, opt_attest_value(&u.attestation)),
144550×
                            ])
144650×
                        })
144751×
                        .collect(),
1448
                ),
1449
            ),
1450
        ]))
145151×
    }
1452
    /// A decoded push: bundle, bookmark updates, policy, tags.
1453
    pub type PushParts = (Bundle, Vec<RefUpdate>, Option<SignedPolicy>, Vec<TagRef>);
1454
145547×
    pub fn decode_push(bytes: &[u8]) -> Result<PushParts> {
145647×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
145747×
        let m = map(&v, "push")?;
145847×
        let bundle = bundle_from_value(field(m, 0, "bundle")?)?;
145947×
        let mut updates = Vec::new();
146047×
        for u in o::array(field(m, 1, "updates")?, "updates")? {
146146×
            let um = map(u, "update")?;
146246×
            updates.push(RefUpdate {
146346×
                name: o::text(field(um, 0, "name")?, "name")?.to_owned(),
146446×
                old_state: o::oref(field(um, 1, "old_state")?, "old_state")?,
146546×
                new_state: o::oref(field(um, 2, "new_state")?, "new_state")?,
146646×
                force: field(um, 3, "force")?
146746×
                    .as_bool()
146846×
                    .ok_or_else(|| schema("force: expected bool"))?,
146946×
                attestation: opt_attest_from(field(um, 4, "attestation")?)?,
1470
            });
1471
        }
147247×
        let policy = match m.get(&2) {
147347×
            Some(p) => opt_policy_from(p)?,
14740×
            None => None,
1475
        };
147647×
        let tags = match m.get(&3) {
147747×
            Some(t) => tags_from(t)?,
14780×
            None => Vec::new(),
1479
        };
148047×
        Ok((bundle, updates, policy, tags))
148147×
    }
1482
148345×
    pub fn encode_push_response(results: &[RefResult]) -> Vec<u8> {
148445×
        cbor::encode(&Value::map([(
1485
            0,
1486
            Value::Array(
148745×
                results
148845×
                    .iter()
148951×
                    .map(|r| {
149051×
                        Value::map([
149151×
                            (0, Value::Text(r.name.clone())),
149251×
                            (1, Value::Bool(r.ok)),
149351×
                            (2, Value::Text(r.reason.clone())),
149451×
                        ])
149551×
                    })
149645×
                    .collect(),
1497
            ),
1498
        )]))
149945×
    }
150045×
    pub fn decode_push_response(bytes: &[u8]) -> Result<Vec<RefResult>> {
150145×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
150245×
        let m = map(&v, "push response")?;
150345×
        let mut out = Vec::new();
150451×
        for r in o::array(field(m, 0, "results")?, "results")? {
150551×
            let rm = map(r, "result")?;
150651×
            out.push(RefResult {
150751×
                name: o::text(field(rm, 0, "name")?, "name")?.to_owned(),
150851×
                ok: field(rm, 1, "ok")?
150951×
                    .as_bool()
151051×
                    .ok_or_else(|| schema("ok: expected bool"))?,
151151×
                reason: o::text(field(rm, 2, "reason")?, "reason")?.to_owned(),
1512
            });
1513
        }
151445×
        Ok(out)
151545×
    }
1516
}
1517
1518
#[cfg(test)]
1519
mod tests {
1520
    use super::*;
1521
    use crate::attest::AttestBody;
1522
    use crate::objects::Hlc;
1523
1524
    /// oxygen#133: a proxy's HTML error page is shown by its title, and a
1525
    /// server's own text as it is; a 413 says to push in smaller parts.
1526
    #[test]
15271×
    fn html_error_pages_are_shown_by_their_title() {
15281×
        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>";
15291×
        assert_eq!(
15301×
            plain_error_text(cloudflare),
1531
            "413 Request Entity Too Large (an HTML error page, from a proxy in front of the server perhaps)"
1532
        );
15331×
        assert_eq!(
15341×
            plain_error_text("  refused: a secret\nat a.txt:3 "),
1535
            "refused: a secret\nat a.txt:3"
1536
        );
15371×
        assert!(hint_for("https://hub/x: HTTP 413: too large")
15381×
            .unwrap()
15391×
            .contains("push.batch-bytes"));
15401×
    }
1541
1542
    #[test]
15431×
    fn client_features_are_declared_and_read() {
15441×
        assert_eq!(CLIENT_FEATURES.join(","), "certified-tags");
15451×
        assert!(user_agent().starts_with("oxy/"));
15461×
        assert!(declares_feature(
15471×
            Some("certified-tags"),
15481×
            FEATURE_CERTIFIED_TAGS
1549
        ));
15501×
        assert!(declares_feature(
15511×
            Some("later-thing, Certified-Tags ,x"),
15521×
            FEATURE_CERTIFIED_TAGS
1553
        ));
15541×
        assert!(!declares_feature(
15551×
            Some("certified-tags-v2"),
15561×
            FEATURE_CERTIFIED_TAGS
15571×
        ));
15581×
        assert!(!declares_feature(Some(""), FEATURE_CERTIFIED_TAGS));
15591×
        assert!(!declares_feature(None, FEATURE_CERTIFIED_TAGS));
15601×
    }
1561
1562
    #[test]
15631×
    fn wire_round_trips() {
15641×
        let c = crate::objects::tests::sample_change();
15651×
        let sk = crate::identity::SecretKey {
15661×
            ed_seed: [1; 32],
15671×
            ml_seed: [2; 32],
15681×
        };
15691×
        let id = sk.identity("a", "b", 0);
15701×
        let key = id.hash();
15711×
        let sig = sk.sign(crate::identity::Domain::Change, &key, &c.hash());
15721×
        let seal = Attest::seal([3; 16], vec![c.hash()]);
15731×
        let seal_sig = sk.sign(crate::identity::Domain::Attest, &key, &seal.hash());
15741×
        let policy = Policy::single_root([3; 16], id.clone(), 99);
15751×
        let psig = sk.sign(crate::identity::Domain::Policy, &key, &policy.hash());
15761×
        let bundle = Bundle {
15771×
            changes: vec![(c.clone(), vec![sig.clone()])],
15781×
            attests: vec![SignedAttest {
15791×
                attest: seal.clone(),
15801×
                sigs: vec![seal_sig],
15811×
            }],
15821×
            objects: vec![
15831×
                (ObjectType::Identity, id.encode()),
15841×
                (ObjectType::Chunk, b"xyz".to_vec()),
15851×
            ],
15861×
            policies: vec![SignedPolicy {
15871×
                policy: policy.clone(),
15881×
                sigs: vec![psig.clone()],
15891×
            }],
15901×
            hashes: vec![],
15911×
            raw_changes: vec![],
15921×
            certificates: vec![],
15931×
        };
15941×
        let d = wire::decode_bundle(&wire::encode_bundle(&bundle)).unwrap();
15951×
        assert_eq!(
1596
            d.hashes,
15971×
            vec![c.hash()],
1598
            "the receiver hashes what it was sent"
1599
        );
16001×
        assert_eq!(d.changes, bundle.changes);
16011×
        assert_eq!(d.attests, bundle.attests);
16021×
        assert_eq!(d.objects, bundle.objects);
16031×
        assert_eq!(d.policies, bundle.policies);
16041×
        assert!(d.certificates.is_empty());
1605
        // Certificates (keyless, oxygenhub#241) travel as field 4, only
1606
        // when there are any: a bundle without them encodes as before.
16071×
        let plain = wire::encode_bundle(&bundle);
16081×
        let mut with = bundle.clone();
16091×
        let issuer_sk = crate::identity::SecretKey::generate();
16101×
        let issuer = issuer_sk.identity("hub", "h@x", 1);
16111×
        with.certificates.push(crate::cert::SignedCertificate::sign(
16121×
            crate::cert::Certificate {
16131×
                key: id.clone(),
16141×
                issuer: issuer.hash(),
16151×
                subject: "agent:a@b".into(),
16161×
                claims: vec![],
16171×
                scope: crate::identity::Scope::CHANGES,
16181×
                not_before: 1,
16191×
                expires: 2,
16201×
                grant: None,
16211×
            },
16221×
            &issuer,
16231×
            &issuer_sk,
1624
        ));
16251×
        let encoded = wire::encode_bundle(&with);
16261×
        assert_ne!(encoded, plain);
16271×
        assert_eq!(
16281×
            wire::decode_bundle(&encoded).unwrap().certificates,
1629
            with.certificates
1630
        );
16311×
        with.certificates.clear();
16321×
        assert_eq!(wire::encode_bundle(&with), plain);
1633
16341×
        let att = Attest {
16351×
            repo: [3; 16],
16361×
            hlc: Hlc::default(),
16371×
            body: AttestBody::Ref {
16381×
                name: "main".into(),
16391×
                old_state: ObjectRef([1; 32]),
16401×
                new_state: ObjectRef([2; 32]),
16411×
                serial: 4,
16421×
            },
16431×
        };
16441×
        let refs = vec![
16451×
            RemoteRef {
16461×
                name: "main".into(),
16471×
                state: ObjectRef([2; 32]),
16481×
                heads: vec![c.hash()],
16491×
                attestation: Some(SignedAttest {
16501×
                    attest: att.clone(),
16511×
                    sigs: vec![sig.clone()],
16521×
                }),
16531×
                last_serial: Some(4),
16541×
                accepted: None,
16551×
                logged: None,
16561×
                integration: vec![],
16571×
            },
16581×
            RemoteRef {
16591×
                name: "dev".into(),
16601×
                state: ObjectRef([5; 32]),
16611×
                heads: vec![],
16621×
                attestation: None,
16631×
                last_serial: None,
16641×
                accepted: None,
16651×
                logged: None,
16661×
                integration: vec![],
16671×
            },
1668
        ];
16691×
        let tag = TagRef::new("v1".into(), ObjectRef([2; 32]), vec![c.hash()], None);
16701×
        let mut resp = RefsResponse {
16711×
            refs,
16721×
            policy: Some(SignedPolicy {
16731×
                policy: policy.clone(),
16741×
                sigs: vec![psig.clone()],
16751×
            }),
16761×
            tags: vec![tag.clone()],
16771×
            history: vec![SignedPolicy {
16781×
                policy: policy.clone(),
16791×
                sigs: vec![],
16801×
            }],
16811×
            default_bookmark: Some("develop".into()),
16821×
            log: Some("hub.example/log\n2\nroot\n\n- sig\n".into()),
16831×
            witnesses: vec![],
16841×
            withdrawn: vec![],
16851×
        };
1686
        // Without integrated times (spec §14.8) nothing is added: an old
1687
        // peer's answer, and what it reads.
16881×
        let old = wire::encode_refs([3; 16], &resp);
16891×
        let back = wire::decode_refs(&old).unwrap().1;
16902×
        assert!(back.witnesses.is_empty() && back.refs.iter().all(|r| r.integration.is_empty()));
16911×
        resp.refs[1].logged = Some(Logged {
16921×
            index: 41,
16931×
            entry: vec![1, 2, 3],
16941×
            proof: vec![[9; 32], [8; 32]],
16951×
        });
16961×
        resp.refs[1].integration = vec![Integration {
16971×
            note: "hub.example/log\n42\nroot\n\n- sig\n".into(),
16981×
            proof: vec![[7; 32]],
16991×
        }];
17001×
        resp.witnesses = vec![("w.example".into(), vec![4, 5, 6])];
17011×
        let new = wire::encode_refs([3; 16], &resp);
17021×
        let (id_back, back) = wire::decode_refs(&new).unwrap();
17031×
        assert_eq!(back.log, resp.log);
17041×
        assert_eq!(back.refs[1].logged, resp.refs[1].logged);
17051×
        assert_eq!(back.refs[1].integration, resp.refs[1].integration);
17061×
        assert_eq!(back.witnesses, resp.witnesses);
17071×
        assert_eq!(back.refs[0].logged, None);
1708
        // The new keys are 7s an old reader never asks for.
17091×
        let crate::cbor::Value::Map(m) = crate::cbor::decode(&new).unwrap() else {
17100×
            panic!()
1711
        };
17121×
        assert!(m.contains_key(&7));
17131×
        assert_eq!(id_back, [3; 16]);
17141×
        assert_eq!(back.refs.len(), 2);
17151×
        assert_eq!(back.refs[0].attestation.as_ref().unwrap().attest, att);
17161×
        assert_eq!(back.refs[1].last_serial, None);
17171×
        assert_eq!(back.policy.as_ref().unwrap().policy, policy);
17181×
        assert_eq!(back.history, resp.history);
17191×
        assert_eq!(back.tags, vec![tag.clone()]);
1720
1721
        // A tag's acceptance and log place (oxygen#129): keys 4 to 6, only
1722
        // when there are any, so a tag without them encodes as before.
17231×
        let crate::cbor::Value::Map(m) = crate::cbor::decode(&new).unwrap() else {
17240×
            panic!()
1725
        };
17261×
        let crate::cbor::Value::Array(tags) = &m[&3] else {
17270×
            panic!()
1728
        };
17291×
        let crate::cbor::Value::Map(plain) = &tags[0] else {
17300×
            panic!()
1731
        };
17321×
        assert_eq!(plain.keys().copied().collect::<Vec<_>>(), vec![0, 1, 2, 3]);
17331×
        let mut full = tag.clone();
17341×
        full.name = "v2".into();
17351×
        full.attestation = Some(SignedAttest {
17361×
            attest: att.clone(),
17371×
            sigs: vec![sig.clone()],
17381×
        });
17391×
        full.accepted = full.attestation.clone();
17401×
        full.logged = Some(Logged {
17411×
            index: 7,
17421×
            entry: vec![4],
17431×
            proof: vec![[3; 32]],
17441×
        });
17451×
        full.integration = vec![Integration {
17461×
            note: "hub.example/log\n8\nroot\n\n- sig\n".into(),
17471×
            proof: vec![],
17481×
        }];
17491×
        resp.tags = vec![full.clone(), tag.clone()];
17501×
        let bytes = wire::encode_refs([3; 16], &resp);
17511×
        assert_eq!(wire::decode_refs(&bytes).unwrap().1.tags, resp.tags);
1752
        // In a push too.
17531×
        let pushed = wire::encode_push(&Bundle::default(), &[], None, &resp.tags);
17541×
        assert_eq!(wire::decode_push(&pushed).unwrap().3, resp.tags);
1755
        // A reader that knows only keys 0 to 3 (oxy 0.5.0 and older, and
1756
        // the runners built with it) reads the same tags from the new answer.
17571×
        let stripped: Vec<TagRef> = resp
17581×
            .tags
17591×
            .iter()
17602×
            .map(|t| {
17612×
                TagRef::new(
17622×
                    t.name.clone(),
17632×
                    t.state,
17642×
                    t.heads.clone(),
17652×
                    t.attestation.clone(),
1766
                )
17672×
            })
17681×
            .collect();
17691×
        assert_eq!(wire::tags_as_0_5_read_them(&bytes).unwrap(), stripped);
1770
17711×
        let (h, w) = wire::decode_negotiate(&wire::encode_negotiate(
17721×
            &[ObjectRef([1; 32])],
17731×
            &[ObjectRef([2; 32])],
17741×
        ))
17751×
        .unwrap();
17761×
        assert_eq!((h, w), (vec![ObjectRef([1; 32])], vec![ObjectRef([2; 32])]));
17771×
        assert_eq!(
17781×
            wire::decode_hashes(&wire::encode_hashes(&[c.hash()])).unwrap(),
17791×
            vec![c.hash()]
1780
        );
17811×
        assert_eq!(
17821×
            wire::decode_fetch(&wire::encode_fetch(&[c.hash()], Some(4096))).unwrap(),
17831×
            (vec![c.hash()], Some(4096))
1784
        );
17851×
        assert_eq!(
17861×
            wire::decode_fetch(&wire::encode_fetch(&[], None)).unwrap(),
17871×
            (vec![], None)
1788
        );
17891×
        assert_eq!(
17901×
            wire::decode_shallow(&wire::encode_shallow(&[c.hash()], 3)).unwrap(),
17911×
            (vec![c.hash()], 3)
1792
        );
1793
        // An old-style fetch request without the filter field still decodes.
17941×
        assert_eq!(
17951×
            wire::decode_fetch(&wire::encode_hashes(&[c.hash()])).unwrap(),
17961×
            (vec![c.hash()], None)
1797
        );
1798
17991×
        let up = RefUpdate {
18001×
            name: "main".into(),
18011×
            old_state: ObjectRef([1; 32]),
18021×
            new_state: ObjectRef([2; 32]),
18031×
            force: true,
18041×
            attestation: Some(SignedAttest {
18051×
                attest: att,
18061×
                sigs: vec![sig],
18071×
            }),
18081×
        };
18091×
        let sp = SignedPolicy {
18101×
            policy,
18111×
            sigs: vec![psig],
18121×
        };
18131×
        let (b2, ups, pol, tags) = wire::decode_push(&wire::encode_push(
18141×
            &bundle,
18151×
            std::slice::from_ref(&up),
18161×
            Some(&sp),
18171×
            std::slice::from_ref(&tag),
18181×
        ))
18191×
        .unwrap();
18201×
        assert_eq!(pol, Some(sp));
18211×
        assert_eq!(tags, vec![tag]);
18221×
        assert_eq!(b2.changes.len(), 1);
18231×
        assert_eq!(ups[0].name, "main");
18241×
        assert!(ups[0].force);
18251×
        assert_eq!(ups[0].attestation, up.attestation);
18261×
        let res = vec![RefResult {
18271×
            name: "main".into(),
18281×
            ok: false,
18291×
            reason: "stale".into(),
18301×
        }];
18311×
        assert_eq!(
18321×
            wire::decode_push_response(&wire::encode_push_response(&res)).unwrap(),
1833
            res
1834
        );
18351×
        assert_eq!(
18361×
            wire::decode_capabilities(&wire::encode_capabilities([7; 16])).unwrap(),
1837
            [7; 16]
1838
        );
18391×
    }
1840
}