OXYGENHUB

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

1105 of 1283 lines run, 179 of 272 functions · run #418 on main · run missed

1
//! Transport-agnostic protocol (spec §16): what a client asks of a remote and
2
//! what a server does with a push. `LocalRemote` serves another repository
3
//! directory in-process, `HttpRemote` speaks to an `oxy-server` over HTTP(S),
4
//! and the server side reuses `Repo::receive_push` and friends unchanged.
5
//!
6
//! Wire messages are deterministic CBOR (`wire` module); over HTTP each is a
7
//! request or response body with content type `application/oxy-cbor`.
8
9
use crate::attest::Attest;
10
use crate::cbor::{self, Value};
11
use crate::hash::{ChangeHash, ObjectRef, ObjectType};
12
use crate::identity::Signature;
13
use crate::objects::{self as o, Change, ObjectError};
14
use crate::policy::Policy;
15
use crate::repo::{Repo, RepoError, Result};
16
use std::path::{Path, PathBuf};
17
use std::sync::{Arc, Mutex};
18
19
pub const CONTENT_TYPE: &str = "application/oxy-cbor";
20
pub const PROTOCOL_VERSION: u64 = 1;
21
22
/// An attestation together with the signatures over its ObjectRef.
23
#[derive(Clone, Debug, PartialEq, Eq)]
24
pub struct SignedAttest {
25
    pub attest: Attest,
26
    pub sigs: Vec<Signature>,
27
}
28
29
/// A policy together with the root signatures over its ObjectRef.
30
#[derive(Clone, Debug, PartialEq, Eq)]
31
pub struct SignedPolicy {
32
    pub policy: Policy,
33
    pub sigs: Vec<Signature>,
34
}
35
36
impl SignedPolicy {
37
    /// The proposal-file encoding (`wire::policy_value`).
381×
    pub fn encode(&self) -> Vec<u8> {
391×
        crate::cbor::encode(&wire::policy_value(self))
401×
    }
411×
    pub fn decode(b: &[u8]) -> Result<SignedPolicy> {
421×
        wire::policy_from(
431×
            &crate::cbor::decode(b).map_err(|e| RepoError::Object(ObjectError::from(e)))?,
44
        )
451×
    }
46
}
47
48
/// What `refs` returns: every bookmark, every tag, and the current policy.
49
#[derive(Clone, Debug, Default)]
50
pub struct RefsResponse {
51
    pub refs: Vec<RemoteRef>,
52
    pub policy: Option<SignedPolicy>,
53
    pub tags: Vec<TagRef>,
54
    /// Earlier policies, ascending by serial, so a client behind by more
55
    /// than one update can verify each step (spec §14.5).
56
    pub history: Vec<SignedPolicy>,
57
    /// The bookmark a clone checks out (spec §16.1), when the remote names one.
58
    pub default_bookmark: Option<String>,
59
    /// The host's latest transparency-log checkpoint, a signed note (spec
60
    /// §14.8), against which `RemoteRef::logged` proofs are made (key 6,
61
    /// only when the host keeps a log).
62
    pub log: Option<String>,
63
    /// The witnesses the host asks to cosign its checkpoints: each one's
64
    /// name in cosignatures and its identity's bytes (key 7, only when it
65
    /// has any), which a client pins (spec §14.8, *Integrated time*).
66
    pub witnesses: Vec<(String, Vec<u8>)>,
67
    /// Tags withdrawn here (spec §10.1; key 8, only when there are any):
68
    /// each with its `untag` attestation as `attestation`, and that
69
    /// attestation's acceptance as `accepted` when a short-lived key
70
    /// signed it. Older clients ignore them and keep the tag they have.
71
    pub withdrawn: Vec<TagRef>,
72
}
73
74
/// Where a reference attestation sits in the host's transparency log
75
/// (spec §14.8): its entry number, the entry, and the inclusion proof
76
/// against the checkpoint served beside it.
77
#[derive(Clone, Debug, PartialEq, Eq)]
78
pub struct Logged {
79
    pub index: u64,
80
    pub entry: Vec<u8>,
81
    pub proof: Vec<[u8; 32]>,
82
}
83
84
/// A checkpoint witnesses cosigned that includes a logged entry (spec
85
/// §14.8, *Integrated time*): the cosigned note, and the entry's inclusion
86
/// proof against it.
87
#[derive(Clone, Debug, PartialEq, Eq)]
88
pub struct Integration {
89
    pub note: String,
90
    pub proof: Vec<[u8; 32]>,
91
}
92
93
/// A tag as a remote reports it (spec §10.1).
94
#[derive(Clone, Debug, PartialEq, Eq)]
95
pub struct TagRef {
96
    pub name: String,
97
    pub state: ObjectRef,
98
    pub heads: Vec<ChangeHash>,
99
    pub attestation: Option<SignedAttest>,
100
    /// The acceptance of `attestation` by its signer's certificate issuer
101
    /// when a short-lived key signed it (spec §14.7; key 4, only when there
102
    /// is one): the time a fetch checks the certificate at.
103
    pub accepted: Option<SignedAttest>,
104
    /// The attestation's place in the host's transparency log (key 5,
105
    /// only when it has one), as a bookmark's.
106
    pub logged: Option<Logged>,
107
    /// The cosigned checkpoints that first included `logged`'s entry (key
108
    /// 6, only when there are any).
109
    pub integration: Vec<Integration>,
110
}
111
112
impl TagRef {
113
    /// Whether this is a tag's withdrawal (its attestation an `untag`), as
114
    /// a push carries one (oxygenhub#301).
11525×
    pub fn is_withdrawal(&self) -> bool {
11625×
        self.attestation
11725×
            .as_ref()
11825×
            .is_some_and(|a| matches!(a.attest.body, crate::attest::AttestBody::Untag { .. }))
11925×
    }
120
121
    /// A tag with no acceptance or log place (yet).
122148×
    pub fn new(
123148×
        name: String,
124148×
        state: ObjectRef,
125148×
        heads: Vec<ChangeHash>,
126148×
        attestation: Option<SignedAttest>,
127148×
    ) -> TagRef {
128148×
        TagRef {
129148×
            name,
130148×
            state,
131148×
            heads,
132148×
            attestation,
133148×
            accepted: None,
134148×
            logged: None,
135148×
            integration: vec![],
136148×
        }
137148×
    }
138
}
139
140
/// One reference as a remote reports it.
141
#[derive(Clone, Debug)]
142
pub struct RemoteRef {
143
    pub name: String,
144
    pub state: ObjectRef,
145
    pub heads: Vec<ChangeHash>,
146
    /// The latest attestation, only when it describes `state`. An unattested
147
    /// push (accepted while no trust policy exists) leaves it `None`.
148
    pub attestation: Option<SignedAttest>,
149
    /// Serial of the latest attestation ever recorded, stale or not, so the
150
    /// next attestation continues the sequence.
151
    pub last_serial: Option<u64>,
152
    /// The host's acceptance of `attestation` when a short-lived key signed
153
    /// it (spec §14.7): the time its certificate is checked at.
154
    pub accepted: Option<SignedAttest>,
155
    /// The attestation's place in the host's transparency log (key 6, only
156
    /// when it has one).
157
    pub logged: Option<Logged>,
158
    /// The cosigned checkpoints that first included `logged`'s entry (key
159
    /// 7, only when there are any): what its integrated time is read from.
160
    pub integration: Vec<Integration>,
161
}
162
163
/// Everything needed to add a set of changes to a repository.
164
#[derive(Clone, Debug, Default)]
165
pub struct Bundle {
166
    /// In dependency order, each with its individual signatures.
167
    pub changes: Vec<(Change, Vec<Signature>)>,
168
    /// Seals covering the changes.
169
    pub attests: Vec<SignedAttest>,
170
    /// Chunks, blobs, identities, and state objects referenced by the changes.
171
    pub objects: Vec<(ObjectType, Vec<u8>)>,
172
    /// Policies between the receiver's and the one sent with the push,
173
    /// ascending by serial (spec §14.5).
174
    pub policies: Vec<SignedPolicy>,
175
    /// Each change's hash, in the order of `changes`, when whoever made
176
    /// the bundle knows it: the store it came from, or the bytes it was
177
    /// decoded from. Never read from the wire. Empty when unknown.
178
    pub hashes: Vec<ChangeHash>,
179
    /// Changes as stored, with their signatures, in dependency order, for a
180
    /// fetch between repositories on one machine: their text blobs and
181
    /// chunks are among `objects`. Never on the wire.
182
    pub raw_changes: Vec<(Vec<u8>, Vec<Signature>)>,
183
    /// Certificates of short-lived keys that signed what the bundle carries
184
    /// (spec §14.7), their issuers' identities among `objects`.
185
    pub certificates: Vec<crate::cert::SignedCertificate>,
186
}
187
188
impl Bundle {
18927×
    pub fn is_empty(&self) -> bool {
19027×
        self.changes.is_empty() && self.attests.is_empty() && self.objects.is_empty()
19127×
    }
192
}
193
194
/// A requested bookmark move (spec §10.2, §16.3).
195
#[derive(Clone, Debug)]
196
pub struct RefUpdate {
197
    pub name: String,
198
    pub old_state: ObjectRef,
199
    pub new_state: ObjectRef,
200
    pub force: bool,
201
    pub attestation: Option<SignedAttest>,
202
}
203
204
#[derive(Clone, Debug, PartialEq, Eq)]
205
pub struct RefResult {
206
    pub name: String,
207
    pub ok: bool,
208
    pub reason: String,
209
}
210
211
pub trait Remote {
212
    fn repo_id(&self) -> Result<[u8; 16]>;
213
    fn refs(&self) -> Result<RefsResponse>;
214
    /// Changes in the closure of `want` but not of `have`, in dependency order.
215
    fn negotiate(&self, have: &[ChangeHash], want: &[ChangeHash]) -> Result<Vec<ChangeHash>>;
216
    /// The changes with their signatures, seals, identities, and blobs; blobs
217
    /// larger than `max_blob` bytes are left out for lazy fetching (spec §13.5).
218
    fn fetch(&self, changes: &[ChangeHash], max_blob: Option<u64>) -> Result<Bundle>;
219
    /// Individual objects by reference (spec §16.1 `objects`); a blob comes
220
    /// with its chunks.
221
    fn objects(&self, refs: &[ObjectRef]) -> Result<Vec<(ObjectType, Vec<u8>)>>;
222
    /// A checkpoint of exactly `heads` (spec §16.1 `checkpoint`): the
223
    /// checkpoint object, its payload blob, and the blob's chunks.
224
    fn checkpoint(&self, heads: &[ChangeHash]) -> Result<Bundle>;
225
    /// A checkpoint of exactly `heads` without its graph blobs (spec §16.1
226
    /// `checkpoint-index`, oxygen#137), which the client then asks for in
227
    /// parts with `objects`. A remote that cannot answer it sends the
228
    /// whole checkpoint, which does as well.
2290×
    fn checkpoint_index(&self, heads: &[ChangeHash]) -> Result<Bundle> {
2300×
        self.checkpoint(heads)
2310×
    }
232
    /// The changes within `depth` dependency steps of `heads` (spec §17).
233
    fn shallow(&self, heads: &[ChangeHash], depth: u32) -> Result<Vec<ChangeHash>>;
234
    /// Push changes, bookmark updates, new tags, and optionally a newer
235
    /// policy. The policy is applied first; a result named `policy` reports
236
    /// it, and each tag reports as `tags/<name>`.
237
    fn push(
238
        &self,
239
        bundle: Bundle,
240
        updates: Vec<RefUpdate>,
241
        policy: Option<SignedPolicy>,
242
        tags: Vec<TagRef>,
243
    ) -> Result<Vec<RefResult>>;
244
}
245
246
// ---------------------------------------------------------------- local
247
248
/// Another repository on this machine, served in-process.
249
pub struct LocalRemote {
250
    pub repo: Repo,
251
    /// The pushing repository's id, which binds an unbound target on the
252
    /// first push, as `Oxy-Repo-Id` does over HTTP.
253
    pub claimed_id: Option<[u8; 16]>,
254
}
255
256
impl LocalRemote {
2571179×
    pub fn open(path: &Path) -> Result<LocalRemote> {
258
        Ok(LocalRemote {
2591179×
            repo: Repo::open(path)?,
2601179×
            claimed_id: None,
261
        })
2621179×
    }
263
}
264
265
impl Remote for LocalRemote {
266923×
    fn repo_id(&self) -> Result<[u8; 16]> {
267923×
        self.repo.id()
268923×
    }
269922×
    fn refs(&self) -> Result<RefsResponse> {
270922×
        self.repo.remote_refs()
271922×
    }
272364×
    fn negotiate(&self, have: &[ChangeHash], want: &[ChangeHash]) -> Result<Vec<ChangeHash>> {
273364×
        self.repo.negotiate(have, want)
274364×
    }
275368×
    fn fetch(&self, changes: &[ChangeHash], max_blob: Option<u64>) -> Result<Bundle> {
276368×
        self.repo.bundle_raw_for(changes, max_blob)
277368×
    }
2785×
    fn objects(&self, refs: &[ObjectRef]) -> Result<Vec<(ObjectType, Vec<u8>)>> {
2795×
        self.repo.objects_for(refs)
2805×
    }
2810×
    fn checkpoint(&self, heads: &[ChangeHash]) -> Result<Bundle> {
2820×
        self.repo.checkpoint_bundle_for(heads)
2830×
    }
2843×
    fn checkpoint_index(&self, heads: &[ChangeHash]) -> Result<Bundle> {
2853×
        self.repo.checkpoint_index_for(heads)
2863×
    }
2873×
    fn shallow(&self, heads: &[ChangeHash], depth: u32) -> Result<Vec<ChangeHash>> {
2883×
        self.repo.shallow_changes(heads, depth)
2893×
    }
290280×
    fn push(
291280×
        &self,
292280×
        bundle: Bundle,
293280×
        updates: Vec<RefUpdate>,
294280×
        policy: Option<SignedPolicy>,
295280×
        tags: Vec<TagRef>,
296280×
    ) -> Result<Vec<RefResult>> {
297280×
        if self.repo.is_unbound() {
29815×
            match self.claimed_id {
29915×
                Some(id) => self.repo.bind_id(id)?,
300
                None => {
3010×
                    return Err(RepoError::Msg(
3020×
                        "the remote is unbound and this client did not say which repository it is"
3030×
                            .into(),
3040×
                    ))
305
                }
306
            }
307265×
        }
308280×
        self.repo.receive_push(bundle, updates, policy, tags)
309280×
    }
310
}
311
312
// ---------------------------------------------------------------- http
313
314
/// How to reach a remote: credentials and trust.
315
#[derive(Clone, Debug, Default)]
316
pub struct RemoteOptions {
317
    /// Bearer token for pushes.
318
    pub token: Option<String>,
319
    /// PEM file with extra root certificates to trust for `https://` remotes
320
    /// (self-hosted servers); the system web roots are always trusted.
321
    pub ca: Option<PathBuf>,
322
    /// The local repository's id, sent as `Oxy-Repo-Id` so an unbound
323
    /// hosted repository can adopt it on the first push (spec §16.1).
324
    pub repo_id: Option<[u8; 16]>,
325
    /// Where a remote kept on a store (`dir://`, `s3://`, …) keeps its
326
    /// mirror and what it has seen: the remote's directory under
327
    /// `.oxy/remotes`. None (a clone, before there is a repository) means
328
    /// a temporary directory.
329
    pub cache_dir: Option<PathBuf>,
330
    /// Other tokens for the same hub, tried in turn when `token` is
331
    /// refused (401, 403 or 404): the credential store's sign-in when
332
    /// `token` is the remote's own (oxygen#155), or those of enclosing
333
    /// checkouts when it came from the credential store (oxygen#112).
334
    pub fallback_tokens: Vec<String>,
335
    /// `token` is the remote's own: fall back only when the hub says it is
336
    /// not a token at all (HTTP 401: expired or unknown), never when it is
337
    /// one that may not do this (403, 404), so a narrowly scoped token is
338
    /// not quietly swapped for a wider sign-in (oxygen#155).
339
    pub fallback_on_401_only: bool,
340
}
341
342
/// Opens a store for a URL it understands, or passes (`None`). Stores that
343
/// need more than the standard library (the cloud ones) are added by the
344
/// program that links them, with [`register_store_opener`].
345
pub type StoreOpener =
346
    fn(&str, &RemoteOptions) -> Option<crate::strata::Result<Box<dyn crate::strata::Store>>>;
347
348
static STORE_OPENERS: Mutex<Vec<StoreOpener>> = Mutex::new(Vec::new());
349
350168×
pub fn register_store_opener(opener: StoreOpener) {
351168×
    STORE_OPENERS
352168×
        .lock()
353168×
        .unwrap_or_else(|p| p.into_inner())
354168×
        .push(opener);
355168×
}
356
357
/// A store for `url`, from `dir://` or any registered opener.
3581238×
pub fn open_store(
3591238×
    url: &str,
3601238×
    options: &RemoteOptions,
3611238×
) -> Option<crate::strata::Result<Box<dyn crate::strata::Store>>> {
3621238×
    if let Some(path) = url.strip_prefix("dir://") {
363
        return Some(
36459×
            crate::strata::LocalStore::open(path)
36559×
                .map(|s| Box::new(s) as Box<dyn crate::strata::Store>),
366
        );
3671179×
    }
3681179×
    let openers = STORE_OPENERS.lock().unwrap_or_else(|p| p.into_inner());
3691179×
    openers.iter().find_map(|open| open(url, options))
3701238×
}
371
372
/// The request header carrying the client's repository id.
373
pub const REPO_ID_HEADER: &str = "Oxy-Repo-Id";
374
375
/// The id of a hosted repository that has not adopted one yet.
376
pub const UNBOUND_ID: [u8; 16] = [0; 16];
377
378
/// The request header in which a client declares the protocol features it
379
/// understands beyond the 0.5.0-era set: a comma-separated list, which a
380
/// server may tailor its answers to (docs/protocol.md, *Client
381
/// capabilities*). A request without it is a client of that era.
382
pub const FEATURES_HEADER: &str = "Oxy-Features";
383
384
/// The feature of a client that authorizes a tag signed by a short-lived,
385
/// certified key by its certificate at the time the host accepted it
386
/// (oxygen#129). A client without it refuses such a tag, and with it the
387
/// whole fetch, so servers leave those tags out of its `refs` (oxygen#131).
388
pub const FEATURE_CERTIFIED_TAGS: &str = "certified-tags";
389
390
/// The features this client declares in [`FEATURES_HEADER`].
391
pub const CLIENT_FEATURES: &[&str] = &[FEATURE_CERTIFIED_TAGS];
392
393
/// The `User-Agent` every request of this client sends: `oxy/<version>`.
394186×
pub fn user_agent() -> String {
395186×
    format!("oxy/{}", env!("CARGO_PKG_VERSION"))
396186×
}
397
398
/// Whether a [`FEATURES_HEADER`] value (absent: `None`) declares `feature`.
399
/// Entries are comma-separated, compared without surrounding blanks and
400
/// regardless of case; unknown ones are ignored.
401155×
pub fn declares_feature(header: Option<&str>, feature: &str) -> bool {
402155×
    header.is_some_and(|h| h.split(',').any(|f| f.trim().eq_ignore_ascii_case(feature)))
403155×
}
404
405
/// A remote served by `oxy-server` at `<base>/oxy/v1/...`.
406
pub struct HttpRemote {
407
    base: String,
408
    /// The token in use, and those still to try when it is refused.
409
    token: Mutex<Option<String>>,
410
    fallbacks: Mutex<Vec<String>>,
411
    fallback_on_401_only: bool,
412
    repo_id: Option<[u8; 16]>,
413
    agent: ureq::Agent,
414
}
415
416
/// A TLS client configuration trusting the web roots plus `ca`, if given:
417
/// the trust every oxy connection uses, shared with tools that call hub APIs.
418189×
pub fn tls_client_config(ca: Option<&Path>) -> Result<Arc<rustls::ClientConfig>> {
419189×
    let mut roots = rustls::RootCertStore::empty();
420189×
    roots.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
421189×
    if let Some(path) = ca {
4225×
        let pem = std::fs::read(path)
4235×
            .map_err(|e| RepoError::Msg(format!("reading CA file {}: {e}", path.display())))?;
4245×
        let certs = rustls_pemfile::certs(&mut pem.as_slice())
4255×
            .collect::<std::result::Result<Vec<_>, _>>()
4265×
            .map_err(|e| RepoError::Msg(format!("parsing CA file {}: {e}", path.display())))?;
4275×
        if certs.is_empty() {
4280×
            return Err(RepoError::Msg(format!(
4290×
                "CA file {} holds no certificates",
4300×
                path.display()
4310×
            )));
4325×
        }
4335×
        for c in certs {
4345×
            roots
4355×
                .add(c)
4365×
                .map_err(|e| RepoError::Msg(format!("CA file {}: {e}", path.display())))?;
437
        }
438184×
    }
439189×
    let cfg = rustls::ClientConfig::builder_with_provider(Arc::new(
440189×
        rustls::crypto::ring::default_provider(),
441
    ))
442189×
    .with_safe_default_protocol_versions()
443189×
    .map_err(|e| RepoError::Msg(e.to_string()))?
444189×
    .with_root_certificates(roots)
445189×
    .with_no_client_auth();
446189×
    Ok(Arc::new(cfg))
447189×
}
448
449
impl HttpRemote {
450183×
    pub fn new(base: &str, options: &RemoteOptions) -> Result<HttpRemote> {
451183×
        refuse_plain_token(base, options)?;
452183×
        let agent = ureq::AgentBuilder::new()
453183×
            .tls_config(tls_client_config(options.ca.as_deref())?)
454183×
            .user_agent(&user_agent())
455183×
            .build();
456183×
        Ok(HttpRemote {
457183×
            base: base.trim_end_matches('/').to_string(),
458183×
            token: Mutex::new(options.token.clone()),
459183×
            fallbacks: Mutex::new(options.fallback_tokens.iter().rev().cloned().collect()),
460183×
            fallback_on_401_only: options.fallback_on_401_only,
461183×
            repo_id: options.repo_id,
462183×
            agent,
463183×
        })
464183×
    }
465
466
    /// A request, tried again with the next fallback token while the
467
    /// hub refuses the one in use (oxygen#112).
468462×
    fn call(&self, post: bool, endpoint: &str, body: Option<&[u8]>) -> Result<Vec<u8>> {
469
        loop {
470465×
            let token = self.token.lock().unwrap_or_else(|p| p.into_inner()).clone();
471465×
            match self.call_once(post, endpoint, body, token.as_deref()) {
4725×
                Err(RepoError::Msg(m))
47314×
                    if token.is_some()
4746×
                        && refused(&m)
4755×
                        && (!self.fallback_on_401_only || m.contains(": HTTP 401")) =>
476
                {
4775×
                    let next = self
4785×
                        .fallbacks
4795×
                        .lock()
4805×
                        .unwrap_or_else(|p| p.into_inner())
4815×
                        .pop();
4825×
                    let Some(next) = next else {
4832×
                        return Err(RepoError::Msg(m));
484
                    };
4853×
                    crate::credentials::warn_once(&format!(
4863×
                        "{}: the token in use was refused; trying another this computer has for the hub \
4873×
                         (a stale remote.NAME.token goes with `oxy config --unset remote.NAME.token`)",
4883×
                        self.base
4893×
                    ));
4903×
                    *self.token.lock().unwrap_or_else(|p| p.into_inner()) = Some(next);
491
                }
492460×
                other => return other,
493
            }
494
        }
495462×
    }
496
497465×
    fn call_once(
498465×
        &self,
499465×
        post: bool,
500465×
        endpoint: &str,
501465×
        body: Option<&[u8]>,
502465×
        token: Option<&str>,
503465×
    ) -> Result<Vec<u8>> {
504465×
        let url = format!("{}/oxy/v1/{endpoint}", self.base);
505465×
        let mut req = if post {
506164×
            self.agent.post(&url)
507
        } else {
508301×
            self.agent.get(&url)
509
        };
510465×
        req = req
511465×
            .set("Accept", CONTENT_TYPE)
512465×
            .set(FEATURES_HEADER, &CLIENT_FEATURES.join(","));
513465×
        if let Some(t) = token {
51427×
            req = req.set("Authorization", &format!("Bearer {t}"));
515438×
        }
516465×
        if let Some(id) = &self.repo_id {
517432×
            req = req.set(REPO_ID_HEADER, &hex::encode(id));
518432×
        }
519465×
        let resp = match body {
520164×
            Some(b) => req.set("Content-Type", CONTENT_TYPE).send_bytes(b),
521301×
            None => req.call(),
522
        };
52314×
        match resp {
524451×
            Ok(r) => {
525451×
                let mut out = Vec::new();
526451×
                r.into_reader()
527451×
                    .read_to_end(&mut out)
528451×
                    .map_err(|e| RepoError::Msg(format!("{url}: {e}")))?;
529451×
                Ok(out)
530
            }
53111×
            Err(ureq::Error::Status(code, r)) => {
53211×
                let text = r.into_string().unwrap_or_default();
533
                // The hint comes from the status alone: the server's text
534
                // (a host's reason for refusing a push, several lines
535
                // perhaps) is shown as it is, never read for hints. A
536
                // proxy's HTML error page is shown by its title only
537
                // (oxygen#133).
53811×
                let status = format!("{url}: HTTP {code}");
53911×
                let msg = format!("{status}: {}", plain_error_text(&text));
54011×
                Err(RepoError::Msg(match hint_for(&status) {
54110×
                    Some(h) => format!("{msg}\n  hint: {h}"),
5421×
                    None => msg,
543
                }))
544
            }
545
            // The transport error already names the URL.
5463×
            Err(e) => Err(RepoError::Msg(with_hint(e.to_string()))),
547
        }
548465×
    }
549
}
550
551
/// Whether a failed request's message says the hub refused its token:
552
/// HTTP 401, 403, or 404 (a hub hides a private repository from a token
553
/// that may not read it).
5546×
fn refused(message: &str) -> bool {
5556×
    [": HTTP 401", ": HTTP 403", ": HTTP 404"]
5566×
        .iter()
5578×
        .any(|c| message.contains(c))
5586×
}
559
560
/// Refuse to send a token where anyone on the way could read it: plain
561
/// `http` to another machine (see [`crate::credentials::token_allowed`]).
562185×
fn refuse_plain_token(url: &str, options: &RemoteOptions) -> Result<()> {
563185×
    if options.token.is_some() && !crate::credentials::token_allowed(url) {
5640×
        return Err(RepoError::Msg(format!(
5650×
            "{url}: refusing to send a token over plain http; use https"
5660×
        )));
567185×
    }
568185×
    Ok(())
569185×
}
570
571
/// What to do about a failed request, recognised from its message.
57223×
pub fn hint_for(message: &str) -> Option<&'static str> {
57323×
    let m = message.to_ascii_lowercase();
57423×
    let hint = if m.contains("http 401") {
5758×
        "the hub needs you signed in, or did not accept the token: run `oxy auth login HUB` (pushing needs repo:write)"
57615×
    } else if m.contains("http 403") {
5771×
        "the token or account lacks permission: pushing needs a token with repo:write and write access to the repository"
57814×
    } else if m.contains("http 413") {
5791×
        "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"
58013×
    } else if m.contains("http 404") {
5814×
        "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`)"
5829×
    } else if m.contains("unknownissuer")
5837×
        || m.contains("unknown issuer")
5847×
        || m.contains("certificate")
5856×
        || m.contains("invalidcertificate")
586
    {
5873×
        "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`"
5886×
    } else if m.contains("connection refused") {
5893×
        "nothing is listening there: check the URL and port, and that the server is running"
5903×
    } else if m.contains("dns")
5912×
        || m.contains("failed to lookup")
5922×
        || m.contains("name or service not known")
593
    {
5941×
        "the host name does not resolve: check the URL"
5952×
    } else if m.contains("timed out") || m.contains("timeout") {
5960×
        "the server did not answer in time: check the network, or try again"
597
    } else {
5982×
        return None;
599
    };
60021×
    Some(hint)
60123×
}
602
603
/// An error response's text as it is, unless it is an HTML page (a proxy's,
604
/// such as Cloudflare's 413): then its title, or a note that it was one.
60513×
fn plain_error_text(text: &str) -> String {
60613×
    let t = text.trim();
60713×
    let lower = t.to_ascii_lowercase();
60813×
    if !(lower.starts_with("<!doctype html") || lower.starts_with("<html")) {
60912×
        return t.to_string();
6101×
    }
6111×
    let title = lower
6121×
        .find("<title>")
6131×
        .and_then(|i| {
6141×
            lower[i + 7..]
6151×
                .find("</title>")
6161×
                .map(|j| t[i + 7..i + 7 + j].trim())
6171×
        })
6181×
        .filter(|s| !s.is_empty());
6191×
    match title {
6201×
        Some(s) => format!("{s} (an HTML error page, from a proxy in front of the server perhaps)"),
6210×
        None => "an HTML error page (from a proxy in front of the server perhaps)".into(),
622
    }
62313×
}
624
625
/// `message`, followed by what to do about it when that is known.
6263×
pub fn with_hint(message: String) -> String {
6273×
    match hint_for(&message) {
6283×
        Some(h) => format!("{message}\n  hint: {h}"),
6290×
        None => message,
630
    }
6313×
}
632
633
/// A JSON request to a hub API (`GET`, `POST` or `DELETE`), with the same
634
/// TLS trust and token rules as remotes. Returns the status and body, an
635
/// error status included; only transport failures are errors.
6360×
pub fn http_json(
6370×
    method: &str,
6380×
    url: &str,
6390×
    body: Option<&str>,
6400×
    options: &RemoteOptions,
6410×
) -> Result<(u16, String)> {
6420×
    refuse_plain_token(url, options)?;
6430×
    let agent = ureq::AgentBuilder::new()
6440×
        .tls_config(tls_client_config(options.ca.as_deref())?)
6450×
        .timeout(std::time::Duration::from_secs(60))
6460×
        .user_agent(&user_agent())
6470×
        .build();
6480×
    let mut req = agent.request(method, url).set("Accept", "application/json");
6490×
    if let Some(t) = &options.token {
6500×
        req = req.set("Authorization", &format!("Bearer {t}"));
6510×
    }
6520×
    let resp = match body {
6530×
        Some(b) => req.set("Content-Type", "application/json").send_string(b),
6540×
        None => req.call(),
655
    };
6560×
    match resp {
6570×
        Ok(r) => {
6580×
            let code = r.status();
6590×
            Ok((code, r.into_string().unwrap_or_default()))
660
        }
6610×
        Err(ureq::Error::Status(code, r)) => Ok((code, r.into_string().unwrap_or_default())),
6620×
        Err(e) => Err(RepoError::Msg(with_hint(e.to_string()))),
663
    }
6640×
}
665
666
/// An authenticated GET of any URL on a host, with the same TLS trust and
667
/// token as remotes use (for hub APIs: proposals). Returns the body.
6682×
pub fn http_get(url: &str, options: &RemoteOptions) -> Result<Vec<u8>> {
6692×
    refuse_plain_token(url, options)?;
6702×
    let agent = ureq::AgentBuilder::new()
6712×
        .tls_config(tls_client_config(options.ca.as_deref())?)
6722×
        .user_agent(&user_agent())
6732×
        .build();
6742×
    let mut req = agent.get(url).set("Accept", "application/json");
6752×
    if let Some(t) = &options.token {
6760×
        req = req.set("Authorization", &format!("Bearer {t}"));
6772×
    }
6782×
    match req.call() {
6792×
        Ok(r) => {
6802×
            let mut out = Vec::new();
6812×
            r.into_reader()
6822×
                .read_to_end(&mut out)
6832×
                .map_err(|e| RepoError::Msg(format!("{url}: {e}")))?;
6842×
            Ok(out)
685
        }
6860×
        Err(ureq::Error::Status(code, r)) => {
6870×
            let text = r.into_string().unwrap_or_default();
6880×
            Err(RepoError::Msg(with_hint(format!(
6890×
                "{url}: HTTP {code}: {}",
6900×
                text.trim()
6910×
            ))))
692
        }
693
        // The transport error already names the URL.
6940×
        Err(e) => Err(RepoError::Msg(with_hint(e.to_string()))),
695
    }
6962×
}
697
698
impl Remote for HttpRemote {
699154×
    fn repo_id(&self) -> Result<[u8; 16]> {
700154×
        wire::decode_capabilities(&self.call(false, "capabilities", None)?)
701154×
    }
702147×
    fn refs(&self) -> Result<RefsResponse> {
703147×
        Ok(wire::decode_refs(&self.call(false, "refs", None)?)?.1)
704147×
    }
70556×
    fn negotiate(&self, have: &[ChangeHash], want: &[ChangeHash]) -> Result<Vec<ChangeHash>> {
70656×
        wire::decode_hashes(&self.call(
707
            true,
70856×
            "negotiate",
70956×
            Some(&wire::encode_negotiate(have, want)),
7100×
        )?)
71156×
    }
71256×
    fn fetch(&self, changes: &[ChangeHash], max_blob: Option<u64>) -> Result<Bundle> {
71356×
        wire::decode_bundle(&self.call(
714
            true,
71556×
            "fetch",
71656×
            Some(&wire::encode_fetch(changes, max_blob)),
7170×
        )?)
71856×
    }
7191×
    fn objects(&self, refs: &[ObjectRef]) -> Result<Vec<(ObjectType, Vec<u8>)>> {
720
        Ok(
7211×
            wire::decode_bundle(&self.call(true, "objects", Some(&wire::encode_hashes(refs)))?)?
722
                .objects,
723
        )
7241×
    }
7250×
    fn checkpoint(&self, heads: &[ChangeHash]) -> Result<Bundle> {
7260×
        let body = {
7270×
            let _t = crate::timing::phase("remote: checkpoint answer");
7280×
            self.call(true, "checkpoint", Some(&wire::encode_hashes(heads)))?
729
        };
7300×
        let _t = crate::timing::phase("remote: decode the checkpoint");
7310×
        wire::decode_bundle(&body)
7320×
    }
7330×
    fn checkpoint_index(&self, heads: &[ChangeHash]) -> Result<Bundle> {
7340×
        let body = {
7350×
            let _t = crate::timing::phase("remote: checkpoint index");
7360×
            match self.call(true, "checkpoint-index", Some(&wire::encode_hashes(heads))) {
7370×
                Ok(b) => b,
738
                // A server from before checkpoint-index: the whole answer.
7390×
                Err(RepoError::Msg(m)) if m.contains("HTTP 404") => return self.checkpoint(heads),
7400×
                Err(e) => return Err(e),
741
            }
742
        };
7430×
        wire::decode_bundle(&body)
7440×
    }
7450×
    fn shallow(&self, heads: &[ChangeHash], depth: u32) -> Result<Vec<ChangeHash>> {
7460×
        wire::decode_hashes(&self.call(
747
            true,
7480×
            "shallow",
7490×
            Some(&wire::encode_shallow(heads, depth)),
7500×
        )?)
7510×
    }
75248×
    fn push(
75348×
        &self,
75448×
        bundle: Bundle,
75548×
        updates: Vec<RefUpdate>,
75648×
        policy: Option<SignedPolicy>,
75748×
        tags: Vec<TagRef>,
75848×
    ) -> Result<Vec<RefResult>> {
75948×
        wire::decode_push_response(&self.call(
760
            true,
76148×
            "push",
76248×
            Some(&wire::encode_push(
76348×
                &bundle,
76448×
                &updates,
76548×
                policy.as_ref(),
76648×
                &tags,
76748×
            )),
7685×
        )?)
76948×
    }
770
}
771
772
/// A remote's URL as it is stored: an `http(s)://` URL as given, a local
773
/// path made absolute (with its `file://` kept), so it still names the same
774
/// repository from inside the clone (oxygen#57).
775291×
pub fn stored_url(url: &str) -> String {
776
    // Only a path is made absolute: a plain one, or one behind file:// or
777
    // dir://. Every other URL (a hub, a bucket) is kept as written.
778291×
    let (prefix, path) = match (url.strip_prefix("file://"), url.strip_prefix("dir://")) {
7791×
        (Some(p), _) => ("file://", p),
78011×
        (_, Some(p)) => ("dir://", p),
781279×
        _ if url.contains("://") => return url.to_string(),
782250×
        _ => ("", url),
783
    };
784262×
    match std::path::absolute(path) {
785262×
        Ok(abs) => format!("{prefix}{}", abs.display()),
7860×
        Err(_) => url.to_string(),
787
    }
788291×
}
789
790
/// Open a remote by URL: a local path (optionally `file://`), `http(s)://`
791
/// (a hub), or a store (`dir://`, and whatever openers are registered).
7921409×
pub fn open_remote(url: &str, options: &RemoteOptions) -> Result<Box<dyn Remote>> {
7931409×
    if url.starts_with("http://") || url.starts_with("https://") {
794183×
        return Ok(Box::new(HttpRemote::new(url, options)?));
7951226×
    }
7961226×
    if let Some(store) = open_store(url, options) {
79748×
        return crate::repo::strata::open_store_remote(store?, options);
7981178×
    }
7991178×
    let path = url.strip_prefix("file://").unwrap_or(url);
8001178×
    if path.contains("://") {
8010×
        return Err(RepoError::Msg(format!("unsupported remote URL {url:?}")));
8021178×
    }
8031178×
    let mut local = LocalRemote::open(Path::new(path))?;
8041178×
    local.claimed_id = options.repo_id;
8051178×
    Ok(Box::new(local))
8061409×
}
807
808
// ---------------------------------------------------------------- wire
809
810
/// CBOR encodings of the protocol messages (spec §16.1).
811
pub mod wire {
812
    use super::*;
813
8140×
    fn schema(msg: &str) -> RepoError {
8150×
        RepoError::Object(ObjectError::Schema(msg.into()))
8160×
    }
817264×
    fn sigs_value(sigs: &[Signature]) -> Value {
818264×
        Value::Array(sigs.iter().map(|s| s.to_value()).collect())
819264×
    }
820260×
    fn sigs_from(v: &Value) -> Result<Vec<Signature>> {
821260×
        Ok(o::array(v, "signatures")?
822260×
            .iter()
823260×
            .map(Signature::from_value)
824260×
            .collect::<std::result::Result<Vec<_>, _>>()?)
825260×
    }
826451×
    fn hashes_value(hs: &[ObjectRef]) -> Value {
827594×
        Value::Array(hs.iter().map(|h| Value::Bytes(h.0.to_vec())).collect())
828451×
    }
829512×
    fn hashes_from(v: &Value) -> Result<Vec<ObjectRef>> {
830512×
        Ok(o::array(v, "hashes")?
831512×
            .iter()
832656×
            .map(|h| o::oref(h, "hash"))
833512×
            .collect::<std::result::Result<Vec<_>, _>>()?)
834512×
    }
83591×
    fn attest_value(sa: &SignedAttest) -> Value {
83691×
        Value::Array(vec![Value::Bytes(sa.attest.encode()), sigs_value(&sa.sigs)])
83791×
    }
838106×
    fn attest_from(v: &Value) -> Result<SignedAttest> {
839106×
        let a = o::array(v, "signed attest")?;
840106×
        if a.len() != 2 {
8410×
            return Err(schema("signed attest: expected [attest, sigs]"));
842106×
        }
843
        Ok(SignedAttest {
844106×
            attest: Attest::decode(o::bytes(&a[0], "attest")?)?,
845106×
            sigs: sigs_from(&a[1])?,
846
        })
847106×
    }
848285×
    fn opt_attest_value(sa: &Option<SignedAttest>) -> Value {
849285×
        sa.as_ref().map(attest_value).unwrap_or(Value::Null)
850285×
    }
851342×
    fn opt_attest_from(v: &Value) -> Result<Option<SignedAttest>> {
852342×
        if v.is_null() {
853252×
            Ok(None)
854
        } else {
85590×
            attest_from(v).map(Some)
856
        }
857342×
    }
858
    /// `[policy bytes, [signature]]`: also the format of a policy proposal
859
    /// file exchanged between root holders (spec §14.5).
86045×
    pub fn policy_value(sp: &SignedPolicy) -> Value {
86145×
        Value::Array(vec![Value::Bytes(sp.policy.encode()), sigs_value(&sp.sigs)])
86245×
    }
86343×
    pub fn policy_from(v: &Value) -> Result<SignedPolicy> {
86443×
        let a = o::array(v, "signed policy")?;
86543×
        if a.len() != 2 {
8660×
            return Err(schema("signed policy: expected [policy, sigs]"));
86743×
        }
868
        Ok(SignedPolicy {
86943×
            policy: Policy::decode(o::bytes(&a[0], "policy")?)?,
87043×
            sigs: sigs_from(&a[1])?,
871
        })
87243×
    }
873229×
    fn opt_policy_value(sp: Option<&SignedPolicy>) -> Value {
874229×
        sp.map(policy_value).unwrap_or(Value::Null)
875229×
    }
876268×
    fn opt_policy_from(v: &Value) -> Result<Option<SignedPolicy>> {
877268×
        if v.is_null() {
878246×
            Ok(None)
879
        } else {
88022×
            policy_from(v).map(Some)
881
        }
882268×
    }
8831144×
    fn map<'a>(v: &'a Value, what: &str) -> Result<&'a o::Map> {
8841144×
        Ok(o::map(v, what)?)
8851144×
    }
8863231×
    fn field<'a>(m: &'a o::Map, k: u64, what: &str) -> Result<&'a Value> {
8873231×
        Ok(o::field(m, k, what)?)
8883231×
    }
889
890
    /// A bundle's value. Each change's text blobs and their chunks (spec
891
    /// §6.1) are added to its objects when they are not already there, so a
892
    /// bundle can always be read on its own.
893142×
    pub fn bundle_value(b: &Bundle) -> Value {
894142×
        let mut changes = Vec::with_capacity(b.raw_changes.len() + b.changes.len());
895
        // Changes as stored are already their encoding, their texts among
896
        // the objects.
897142×
        for (bytes, s) in &b.raw_changes {
8980×
            changes.push(Value::Array(vec![
8990×
                Value::Bytes(bytes.clone()),
9000×
                sigs_value(s),
9010×
            ]));
9020×
        }
903142×
        let mut texts: Vec<(ObjectType, Vec<u8>)> = Vec::new();
904142×
        let mut listed: Option<std::collections::HashSet<ObjectRef>> = None;
905142×
        for (c, s) in &b.changes {
906128×
            let (bytes, stored) = c.encode_parts();
907128×
            for t in stored {
9080×
                let listed = listed.get_or_insert_with(|| {
9090×
                    b.objects
9100×
                        .iter()
9110×
                        .map(|(ty, body)| crate::hash::hash_object(*ty, body))
9120×
                        .collect()
9130×
                });
9140×
                if !listed.insert(t.blob.hash()) {
9150×
                    continue;
9160×
                }
9170×
                for chunk in crate::chunk::chunks(&t.content) {
9180×
                    if listed.insert(crate::hash::hash_object(ObjectType::Chunk, chunk)) {
9190×
                        texts.push((ObjectType::Chunk, chunk.to_vec()));
9200×
                    }
921
                }
9220×
                texts.push((ObjectType::Blob, t.blob.encode()));
923
            }
924128×
            changes.push(Value::Array(vec![Value::Bytes(bytes), sigs_value(s)]));
925
        }
926142×
        let mut v = Value::map([
927142×
            (0, Value::Array(changes)),
928142×
            (
929142×
                1,
930142×
                Value::Array(b.attests.iter().map(attest_value).collect()),
931142×
            ),
932
            (
933
                2,
934
                Value::Array(
935142×
                    b.objects
936142×
                        .iter()
937142×
                        .chain(&texts)
938206×
                        .map(|(t, body)| {
939206×
                            Value::Array(vec![
940206×
                                Value::Text(t.name().into()),
941206×
                                Value::Bytes(body.clone()),
942206×
                            ])
943206×
                        })
944142×
                        .collect(),
945
                ),
946
            ),
947142×
            (
948142×
                3,
949142×
                Value::Array(b.policies.iter().map(policy_value).collect()),
950142×
            ),
951
        ]);
952
        // Only when there are any; older peers ignore the field.
953142×
        if !b.certificates.is_empty() {
9547×
            if let Value::Map(m) = &mut v {
9557×
                m.insert(
956
                    4,
957
                    Value::Array(
9587×
                        b.certificates
9597×
                            .iter()
9607×
                            .map(|c| Value::Bytes(c.encode()))
9617×
                            .collect(),
962
                    ),
963
                );
9640×
            }
965135×
        }
966142×
        v
967142×
    }
968
969132×
    pub fn bundle_from_value(v: &Value) -> Result<Bundle> {
970132×
        let m = map(v, "bundle")?;
971132×
        let mut b = Bundle::default();
972195×
        for ob in o::array(field(m, 2, "objects")?, "objects")? {
973195×
            let pair = o::array(ob, "object")?;
974195×
            if pair.len() != 2 {
9750×
                return Err(schema("object: expected [type, body]"));
976195×
            }
977195×
            let ty = ObjectType::from_name(o::text(&pair[0], "object type")?)
978195×
                .ok_or_else(|| schema("unknown object type"))?;
979195×
            b.objects
980195×
                .push((ty, o::bytes(&pair[1], "object body")?.to_vec()));
981
        }
982
        // Stored inserts are read from the bundle's own objects.
983132×
        let mut by_ref: Option<std::collections::HashMap<ObjectRef, usize>> = None;
984132×
        for c in o::array(field(m, 0, "changes")?, "changes")? {
985111×
            let pair = o::array(c, "change entry")?;
986111×
            if pair.len() != 2 {
9870×
                return Err(schema("change entry: expected [change, sigs]"));
988111×
            }
989111×
            let encoded = o::bytes(&pair[0], "change")?;
990111×
            b.hashes
991111×
                .push(crate::hash::hash_object(ObjectType::Change, encoded));
992111×
            let change = Change::decode_with(encoded, &mut |text, count, form| {
9930×
                let by_ref = by_ref.get_or_insert_with(|| {
9940×
                    b.objects
9950×
                        .iter()
9960×
                        .enumerate()
9970×
                        .map(|(i, (ty, body))| (crate::hash::hash_object(*ty, body), i))
9980×
                        .collect()
9990×
                });
10000×
                let get =
10010×
                    |r: &ObjectRef, want: ObjectType| match by_ref.get(r).map(|i| &b.objects[*i]) {
10020×
                        Some((ty, body)) if *ty == want => Ok(body),
10030×
                        _ => Err(ObjectError::Schema(format!(
10040×
                            "the bundle lacks {} {}",
10050×
                            want.name(),
10060×
                            r.short(12)
10070×
                        ))),
10080×
                    };
10090×
                let blob = crate::objects::Blob::decode(get(text, ObjectType::Blob)?)?;
10100×
                let mut content = Vec::with_capacity(blob.length as usize);
10110×
                for chunk in &blob.chunks {
10120×
                    content.extend_from_slice(get(chunk, ObjectType::Chunk)?);
1013
                }
10140×
                crate::objects::text_lines(&content, count, form)
10150×
            })?;
1016111×
            b.changes.push((change, sigs_from(&pair[1])?));
1017
        }
1018132×
        for a in o::array(field(m, 1, "attests")?, "attests")? {
101916×
            b.attests.push(attest_from(a)?);
1020
        }
1021132×
        if let Some(ps) = m.get(&3) {
1022132×
            for p in o::array(ps, "policies")? {
10233×
                b.policies.push(policy_from(p)?);
1024
            }
10250×
        }
1026132×
        if let Some(cs) = m.get(&4) {
10277×
            for c in o::array(cs, "certificates")? {
10287×
                b.certificates.push(
10297×
                    crate::cert::SignedCertificate::decode(o::bytes(c, "certificate")?)
10307×
                        .map_err(|e| schema(&format!("certificate: {e}")))?,
1031
                );
1032
            }
1033125×
        }
1034132×
        Ok(b)
1035132×
    }
1036
103792×
    pub fn encode_bundle(b: &Bundle) -> Vec<u8> {
103892×
        cbor::encode(&bundle_value(b))
103992×
    }
104086×
    pub fn decode_bundle(bytes: &[u8]) -> Result<Bundle> {
104186×
        bundle_from_value(&cbor::decode(bytes).map_err(ObjectError::from)?)
104286×
    }
1043
1044149×
    pub fn encode_capabilities(id: [u8; 16]) -> Vec<u8> {
1045149×
        cbor::encode(&Value::map([
1046149×
            (0, Value::Array(vec![Value::Uint(PROTOCOL_VERSION)])),
1047149×
            (1, Value::Bytes(id.to_vec())),
1048149×
            (2, Value::Array(vec![Value::Text("seal".into())])),
1049149×
        ]))
1050149×
    }
1051149×
    pub fn decode_capabilities(bytes: &[u8]) -> Result<[u8; 16]> {
1052149×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
1053149×
        let m = map(&v, "capabilities")?;
1054149×
        let versions = o::array(field(m, 0, "versions")?, "versions")?;
1055149×
        if !versions
1056149×
            .iter()
1057149×
            .any(|x| x.as_uint() == Some(PROTOCOL_VERSION))
1058
        {
10590×
            return Err(RepoError::Msg(
10600×
                "remote does not speak protocol version 1".into(),
10610×
            ));
1062149×
        }
1063149×
        o::bytes(field(m, 1, "repo id")?, "repo id")?
1064149×
            .try_into()
1065149×
            .map_err(|_| schema("repo id: expected 16 bytes"))
1066149×
    }
1067
1068229×
    fn tags_value(tags: &[TagRef]) -> Value {
1069
        Value::Array(
1070229×
            tags.iter()
1071229×
                .map(|t| {
107234×
                    let mut v = Value::map([
107334×
                        (0, Value::Text(t.name.clone())),
107434×
                        (1, Value::Bytes(t.state.0.to_vec())),
107534×
                        (2, hashes_value(&t.heads)),
107634×
                        (3, opt_attest_value(&t.attestation)),
107734×
                    ]);
1078
                    // Only when there is one; older peers ignore them
1079
                    // (oxygen#129).
108034×
                    if let Value::Map(m) = &mut v {
108134×
                        if t.accepted.is_some() {
10828×
                            m.insert(4, opt_attest_value(&t.accepted));
108326×
                        }
108434×
                        if let Some(l) = &t.logged {
10852×
                            m.insert(5, logged_value(l));
108632×
                        }
108734×
                        if !t.integration.is_empty() {
10882×
                            m.insert(6, integration_value(&t.integration));
108932×
                        }
10900×
                    }
109134×
                    v
109234×
                })
1093229×
                .collect(),
1094
        )
1095229×
    }
1096268×
    fn tags_from(v: &Value) -> Result<Vec<TagRef>> {
1097268×
        let mut out = Vec::new();
1098268×
        for t in o::array(v, "tags")? {
109950×
            let tm = map(t, "tag")?;
110050×
            out.push(TagRef {
110150×
                name: o::text(field(tm, 0, "name")?, "name")?.to_owned(),
110250×
                state: o::oref(field(tm, 1, "state")?, "state")?,
110350×
                heads: hashes_from(field(tm, 2, "heads")?)?,
110450×
                attestation: opt_attest_from(field(tm, 3, "attestation")?)?,
110550×
                accepted: match tm.get(&4) {
11068×
                    Some(a) => opt_attest_from(a)?,
110742×
                    None => None,
1108
                },
110950×
                logged: tm.get(&5).map(logged_from).transpose()?,
111050×
                integration: match tm.get(&6) {
11112×
                    Some(l) => integration_from(l)?,
111248×
                    None => Vec::new(),
1113
                },
1114
            });
1115
        }
1116268×
        Ok(out)
1117268×
    }
1118
1119
    /// The tags of a refs answer as oxy 0.5.0 read them (and the runners
1120
    /// built with it), keys 0 to 3 only: what an older reader makes of an
1121
    /// answer with keys 4 to 6.
1122
    #[cfg(test)]
11231×
    pub(super) fn tags_as_0_5_read_them(bytes: &[u8]) -> Result<Vec<TagRef>> {
11241×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
11251×
        let m = map(&v, "refs")?;
11261×
        let mut out = Vec::new();
11272×
        for t in o::array(field(m, 3, "tags")?, "tags")? {
11282×
            let tm = map(t, "tag")?;
11292×
            out.push(TagRef::new(
11302×
                o::text(field(tm, 0, "name")?, "name")?.to_owned(),
11312×
                o::oref(field(tm, 1, "state")?, "state")?,
11322×
                hashes_from(field(tm, 2, "heads")?)?,
11332×
                opt_attest_from(field(tm, 3, "attestation")?)?,
1134
            ));
1135
        }
11361×
        Ok(out)
11371×
    }
1138
1139
    /// A log place, `[entry number, entry bytes, [proof hash]]` (spec §14.8).
11404×
    fn logged_value(l: &Logged) -> Value {
11414×
        Value::Array(vec![
11424×
            Value::Uint(l.index),
11434×
            Value::Bytes(l.entry.clone()),
11444×
            proof_value(&l.proof),
11454×
        ])
11464×
    }
11474×
    fn logged_from(v: &Value) -> Result<Logged> {
11484×
        let a = o::array(v, "logged")?;
11494×
        if a.len() != 3 {
11500×
            return Err(schema("logged: expected [index, entry, proof]"));
11514×
        }
1152
        Ok(Logged {
11534×
            index: o::uint(&a[0], "index")?,
11544×
            entry: o::bytes(&a[1], "entry")?.to_vec(),
11554×
            proof: proof_from(&a[2])?,
1156
        })
11574×
    }
1158
1159
    /// Cosigned checkpoints holding an entry, `[[note, [proof hash]]]`.
11604×
    fn integration_value(integration: &[Integration]) -> Value {
1161
        Value::Array(
11624×
            integration
11634×
                .iter()
11644×
                .map(|i| Value::Array(vec![Value::Text(i.note.clone()), proof_value(&i.proof)]))
11654×
                .collect(),
1166
        )
11674×
    }
11684×
    fn integration_from(v: &Value) -> Result<Vec<Integration>> {
11694×
        let mut out = Vec::new();
11704×
        for i in o::array(v, "integration")? {
11714×
            let a = o::array(i, "integration")?;
11724×
            if a.len() != 2 {
11730×
                return Err(schema("integration: expected [note, proof]"));
11744×
            }
11754×
            out.push(Integration {
11764×
                note: o::text(&a[0], "note")?.to_owned(),
11774×
                proof: proof_from(&a[1])?,
1178
            });
1179
        }
11804×
        Ok(out)
11814×
    }
1182
1183179×
    pub fn encode_refs(id: [u8; 16], resp: &RefsResponse) -> Vec<u8> {
1184179×
        let mut v = Value::map([
1185
            (
1186
                0,
1187
                Value::Array(
1188179×
                    resp.refs
1189179×
                        .iter()
1190185×
                        .map(|r| {
1191185×
                            let mut v = Value::map([
1192185×
                                (0, Value::Text(r.name.clone())),
1193185×
                                (1, Value::Bytes(r.state.0.to_vec())),
1194185×
                                (2, hashes_value(&r.heads)),
1195185×
                                (3, opt_attest_value(&r.attestation)),
1196185×
                                (4, r.last_serial.map(Value::Uint).unwrap_or(Value::Null)),
1197185×
                            ]);
1198
                            // Only when there is one; older peers ignore it.
1199185×
                            if let Value::Map(m) = &mut v {
1200185×
                                if r.accepted.is_some() {
12019×
                                    m.insert(5, opt_attest_value(&r.accepted));
1202176×
                                }
1203185×
                                if let Some(l) = &r.logged {
12042×
                                    m.insert(6, logged_value(l));
1205183×
                                }
1206185×
                                if !r.integration.is_empty() {
12072×
                                    m.insert(7, integration_value(&r.integration));
1208183×
                                }
12090×
                            }
1210185×
                            v
1211185×
                        })
1212179×
                        .collect(),
1213
                ),
1214
            ),
1215179×
            (1, Value::Bytes(id.to_vec())),
1216179×
            (2, opt_policy_value(resp.policy.as_ref())),
1217179×
            (3, tags_value(&resp.tags)),
1218179×
            (
1219179×
                4,
1220179×
                Value::Array(resp.history.iter().map(policy_value).collect()),
1221179×
            ),
1222179×
            (
1223179×
                5,
1224179×
                resp.default_bookmark
1225179×
                    .clone()
1226179×
                    .map(Value::Text)
1227179×
                    .unwrap_or(Value::Null),
1228179×
            ),
1229
        ]);
1230179×
        if let Value::Map(m) = &mut v {
1231179×
            if let Some(log) = &resp.log {
12323×
                m.insert(6, Value::Text(log.clone()));
1233176×
            }
1234179×
            if !resp.withdrawn.is_empty() {
12350×
                m.insert(8, tags_value(&resp.withdrawn));
1236179×
            }
1237179×
            if !resp.witnesses.is_empty() {
12382×
                m.insert(
1239
                    7,
1240
                    Value::Array(
12412×
                        resp.witnesses
12422×
                            .iter()
12432×
                            .map(|(name, id)| {
12442×
                                Value::Array(vec![
12452×
                                    Value::Text(name.clone()),
12462×
                                    Value::Bytes(id.clone()),
12472×
                                ])
12482×
                            })
12492×
                            .collect(),
1250
                    ),
1251
                );
1252177×
            }
12530×
        }
1254179×
        cbor::encode(&v)
1255179×
    }
1256222×
    pub fn decode_refs(bytes: &[u8]) -> Result<([u8; 16], RefsResponse)> {
1257222×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
1258222×
        let m = map(&v, "refs")?;
1259222×
        let id: [u8; 16] = o::bytes(field(m, 1, "repo id")?, "repo id")?
1260222×
            .try_into()
1261222×
            .map_err(|_| schema("repo id: expected 16 bytes"))?;
1262222×
        let mut refs = Vec::new();
1263228×
        for r in o::array(field(m, 0, "refs")?, "refs")? {
1264228×
            let rm = map(r, "ref")?;
1265228×
            let ls = field(rm, 4, "last serial")?;
1266228×
            refs.push(RemoteRef {
1267228×
                name: o::text(field(rm, 0, "name")?, "name")?.to_owned(),
1268228×
                state: o::oref(field(rm, 1, "state")?, "state")?,
1269228×
                heads: hashes_from(field(rm, 2, "heads")?)?,
1270228×
                attestation: opt_attest_from(field(rm, 3, "attestation")?)?,
1271228×
                last_serial: if ls.is_null() {
1272195×
                    None
1273
                } else {
127433×
                    Some(o::uint(ls, "last serial")?)
1275
                },
1276228×
                accepted: match rm.get(&5) {
12779×
                    Some(a) => opt_attest_from(a)?,
1278219×
                    None => None,
1279
                },
1280228×
                logged: rm.get(&6).map(logged_from).transpose()?,
1281228×
                integration: match rm.get(&7) {
12822×
                    Some(l) => integration_from(l)?,
1283226×
                    None => Vec::new(),
1284
                },
1285
            });
1286
        }
1287222×
        let policy = match m.get(&2) {
1288222×
            Some(p) => opt_policy_from(p)?,
12890×
            None => None,
1290
        };
1291222×
        let tags = match m.get(&3) {
1292222×
            Some(t) => tags_from(t)?,
12930×
            None => Vec::new(),
1294
        };
1295222×
        let mut history = Vec::new();
1296222×
        if let Some(h) = m.get(&4) {
1297222×
            for p in o::array(h, "history")? {
129817×
                history.push(policy_from(p)?);
1299
            }
13000×
        }
1301222×
        let default_bookmark = match m.get(&5) {
1302153×
            Some(Value::Text(t)) => Some(t.clone()),
130369×
            _ => None,
1304
        };
1305222×
        let log = match m.get(&6) {
13063×
            Some(Value::Text(t)) => Some(t.clone()),
1307219×
            _ => None,
1308
        };
1309222×
        let mut witnesses = Vec::new();
1310222×
        if let Some(w) = m.get(&7) {
13112×
            for x in o::array(w, "witnesses")? {
13122×
                let a = o::array(x, "witness")?;
13132×
                if a.len() != 2 {
13140×
                    return Err(schema("witness: expected [name, identity]"));
13152×
                }
13162×
                witnesses.push((
13172×
                    o::text(&a[0], "witness name")?.to_owned(),
13182×
                    o::bytes(&a[1], "witness identity")?.to_vec(),
1319
                ));
1320
            }
1321220×
        }
1322222×
        let withdrawn = match m.get(&8) {
13230×
            Some(t) => tags_from(t)?,
1324222×
            None => Vec::new(),
1325
        };
1326222×
        Ok((
1327222×
            id,
1328222×
            RefsResponse {
1329222×
                refs,
1330222×
                policy,
1331222×
                tags,
1332222×
                history,
1333222×
                default_bookmark,
1334222×
                log,
1335222×
                witnesses,
1336222×
                withdrawn,
1337222×
            },
1338222×
        ))
1339222×
    }
1340
1341
    /// A proof's hashes, from the leaf upwards (spec §14.8).
13428×
    fn proof_value(proof: &[[u8; 32]]) -> Value {
13438×
        Value::Array(proof.iter().map(|h| Value::Bytes(h.to_vec())).collect())
13448×
    }
1345
13468×
    fn proof_from(v: &Value) -> Result<Vec<[u8; 32]>> {
13478×
        let mut proof = Vec::new();
13488×
        for h in o::array(v, "proof")? {
13498×
            proof.push(
13508×
                o::bytes(h, "proof hash")?
13518×
                    .try_into()
13528×
                    .map_err(|_| schema("proof hash: expected 32 bytes"))?,
1353
            );
1354
        }
13558×
        Ok(proof)
13568×
    }
1357
135857×
    pub fn encode_negotiate(have: &[ChangeHash], want: &[ChangeHash]) -> Vec<u8> {
135957×
        cbor::encode(&Value::map([
136057×
            (0, hashes_value(have)),
136157×
            (1, hashes_value(want)),
136257×
        ]))
136357×
    }
136457×
    pub fn decode_negotiate(bytes: &[u8]) -> Result<(Vec<ChangeHash>, Vec<ChangeHash>)> {
136557×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
136657×
        let m = map(&v, "negotiate")?;
1367
        Ok((
136857×
            hashes_from(field(m, 0, "have")?)?,
136957×
            hashes_from(field(m, 1, "want")?)?,
1370
        ))
137157×
    }
1372
1373
    /// `fetch` request: `{0: [changes], 1: max blob size or null}`.
137458×
    pub fn encode_fetch(hs: &[ChangeHash], max_blob: Option<u64>) -> Vec<u8> {
137558×
        cbor::encode(&Value::map([
137658×
            (0, hashes_value(hs)),
137758×
            (1, max_blob.map(Value::Uint).unwrap_or(Value::Null)),
137858×
        ]))
137958×
    }
138059×
    pub fn decode_fetch(bytes: &[u8]) -> Result<(Vec<ChangeHash>, Option<u64>)> {
138159×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
138259×
        let m = map(&v, "fetch")?;
138359×
        let max = match m.get(&1) {
138458×
            Some(x) if !x.is_null() => Some(o::uint(x, "max blob")?),
138557×
            _ => None,
1386
        };
138759×
        Ok((hashes_from(field(m, 0, "changes")?)?, max))
138859×
    }
1389
1390
    /// `shallow` request: `{0: [heads], 1: depth}`.
13911×
    pub fn encode_shallow(hs: &[ChangeHash], depth: u32) -> Vec<u8> {
13921×
        cbor::encode(&Value::map([
13931×
            (0, hashes_value(hs)),
13941×
            (1, Value::Uint(depth as u64)),
13951×
        ]))
13961×
    }
13971×
    pub fn decode_shallow(bytes: &[u8]) -> Result<(Vec<ChangeHash>, u32)> {
13981×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
13991×
        let m = map(&v, "shallow")?;
1400
        Ok((
14011×
            hashes_from(field(m, 0, "heads")?)?,
14021×
            o::u32_(field(m, 1, "depth")?, "depth")?,
1403
        ))
14041×
    }
1405
140659×
    pub fn encode_hashes(hs: &[ChangeHash]) -> Vec<u8> {
140759×
        cbor::encode(&Value::map([(0, hashes_value(hs))]))
140859×
    }
140958×
    pub fn decode_hashes(bytes: &[u8]) -> Result<Vec<ChangeHash>> {
141058×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
141158×
        hashes_from(field(map(&v, "hashes")?, 0, "hashes")?)
141258×
    }
1413
141450×
    pub fn encode_push(
141550×
        bundle: &Bundle,
141650×
        updates: &[RefUpdate],
141750×
        policy: Option<&SignedPolicy>,
141850×
        tags: &[TagRef],
141950×
    ) -> Vec<u8> {
142050×
        cbor::encode(&Value::map([
142150×
            (0, bundle_value(bundle)),
142250×
            (2, opt_policy_value(policy)),
142350×
            (3, tags_value(tags)),
1424
            (
1425
                1,
1426
                Value::Array(
142750×
                    updates
142850×
                        .iter()
142950×
                        .map(|u| {
143049×
                            Value::map([
143149×
                                (0, Value::Text(u.name.clone())),
143249×
                                (1, Value::Bytes(u.old_state.0.to_vec())),
143349×
                                (2, Value::Bytes(u.new_state.0.to_vec())),
143449×
                                (3, Value::Bool(u.force)),
143549×
                                (4, opt_attest_value(&u.attestation)),
143649×
                            ])
143749×
                        })
143850×
                        .collect(),
1439
                ),
1440
            ),
1441
        ]))
144250×
    }
1443
    /// A decoded push: bundle, bookmark updates, policy, tags.
1444
    pub type PushParts = (Bundle, Vec<RefUpdate>, Option<SignedPolicy>, Vec<TagRef>);
1445
144646×
    pub fn decode_push(bytes: &[u8]) -> Result<PushParts> {
144746×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
144846×
        let m = map(&v, "push")?;
144946×
        let bundle = bundle_from_value(field(m, 0, "bundle")?)?;
145046×
        let mut updates = Vec::new();
145146×
        for u in o::array(field(m, 1, "updates")?, "updates")? {
145245×
            let um = map(u, "update")?;
145345×
            updates.push(RefUpdate {
145445×
                name: o::text(field(um, 0, "name")?, "name")?.to_owned(),
145545×
                old_state: o::oref(field(um, 1, "old_state")?, "old_state")?,
145645×
                new_state: o::oref(field(um, 2, "new_state")?, "new_state")?,
145745×
                force: field(um, 3, "force")?
145845×
                    .as_bool()
145945×
                    .ok_or_else(|| schema("force: expected bool"))?,
146045×
                attestation: opt_attest_from(field(um, 4, "attestation")?)?,
1461
            });
1462
        }
146346×
        let policy = match m.get(&2) {
146446×
            Some(p) => opt_policy_from(p)?,
14650×
            None => None,
1466
        };
146746×
        let tags = match m.get(&3) {
146846×
            Some(t) => tags_from(t)?,
14690×
            None => Vec::new(),
1470
        };
147146×
        Ok((bundle, updates, policy, tags))
147246×
    }
1473
147444×
    pub fn encode_push_response(results: &[RefResult]) -> Vec<u8> {
147544×
        cbor::encode(&Value::map([(
1476
            0,
1477
            Value::Array(
147844×
                results
147944×
                    .iter()
148050×
                    .map(|r| {
148150×
                        Value::map([
148250×
                            (0, Value::Text(r.name.clone())),
148350×
                            (1, Value::Bool(r.ok)),
148450×
                            (2, Value::Text(r.reason.clone())),
148550×
                        ])
148650×
                    })
148744×
                    .collect(),
1488
            ),
1489
        )]))
149044×
    }
149144×
    pub fn decode_push_response(bytes: &[u8]) -> Result<Vec<RefResult>> {
149244×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
149344×
        let m = map(&v, "push response")?;
149444×
        let mut out = Vec::new();
149550×
        for r in o::array(field(m, 0, "results")?, "results")? {
149650×
            let rm = map(r, "result")?;
149750×
            out.push(RefResult {
149850×
                name: o::text(field(rm, 0, "name")?, "name")?.to_owned(),
149950×
                ok: field(rm, 1, "ok")?
150050×
                    .as_bool()
150150×
                    .ok_or_else(|| schema("ok: expected bool"))?,
150250×
                reason: o::text(field(rm, 2, "reason")?, "reason")?.to_owned(),
1503
            });
1504
        }
150544×
        Ok(out)
150644×
    }
1507
}
1508
1509
#[cfg(test)]
1510
mod tests {
1511
    use super::*;
1512
    use crate::attest::AttestBody;
1513
    use crate::objects::Hlc;
1514
1515
    /// oxygen#133: a proxy's HTML error page is shown by its title, and a
1516
    /// server's own text as it is; a 413 says to push in smaller parts.
1517
    #[test]
15181×
    fn html_error_pages_are_shown_by_their_title() {
15191×
        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>";
15201×
        assert_eq!(
15211×
            plain_error_text(cloudflare),
1522
            "413 Request Entity Too Large (an HTML error page, from a proxy in front of the server perhaps)"
1523
        );
15241×
        assert_eq!(
15251×
            plain_error_text("  refused: a secret\nat a.txt:3 "),
1526
            "refused: a secret\nat a.txt:3"
1527
        );
15281×
        assert!(hint_for("https://hub/x: HTTP 413: too large")
15291×
            .unwrap()
15301×
            .contains("push.batch-bytes"));
15311×
    }
1532
1533
    #[test]
15341×
    fn client_features_are_declared_and_read() {
15351×
        assert_eq!(CLIENT_FEATURES.join(","), "certified-tags");
15361×
        assert!(user_agent().starts_with("oxy/"));
15371×
        assert!(declares_feature(
15381×
            Some("certified-tags"),
15391×
            FEATURE_CERTIFIED_TAGS
1540
        ));
15411×
        assert!(declares_feature(
15421×
            Some("later-thing, Certified-Tags ,x"),
15431×
            FEATURE_CERTIFIED_TAGS
1544
        ));
15451×
        assert!(!declares_feature(
15461×
            Some("certified-tags-v2"),
15471×
            FEATURE_CERTIFIED_TAGS
15481×
        ));
15491×
        assert!(!declares_feature(Some(""), FEATURE_CERTIFIED_TAGS));
15501×
        assert!(!declares_feature(None, FEATURE_CERTIFIED_TAGS));
15511×
    }
1552
1553
    #[test]
15541×
    fn wire_round_trips() {
15551×
        let c = crate::objects::tests::sample_change();
15561×
        let sk = crate::identity::SecretKey {
15571×
            ed_seed: [1; 32],
15581×
            ml_seed: [2; 32],
15591×
        };
15601×
        let id = sk.identity("a", "b", 0);
15611×
        let key = id.hash();
15621×
        let sig = sk.sign(crate::identity::Domain::Change, &key, &c.hash());
15631×
        let seal = Attest::seal([3; 16], vec![c.hash()]);
15641×
        let seal_sig = sk.sign(crate::identity::Domain::Attest, &key, &seal.hash());
15651×
        let policy = Policy::single_root([3; 16], id.clone(), 99);
15661×
        let psig = sk.sign(crate::identity::Domain::Policy, &key, &policy.hash());
15671×
        let bundle = Bundle {
15681×
            changes: vec![(c.clone(), vec![sig.clone()])],
15691×
            attests: vec![SignedAttest {
15701×
                attest: seal.clone(),
15711×
                sigs: vec![seal_sig],
15721×
            }],
15731×
            objects: vec![
15741×
                (ObjectType::Identity, id.encode()),
15751×
                (ObjectType::Chunk, b"xyz".to_vec()),
15761×
            ],
15771×
            policies: vec![SignedPolicy {
15781×
                policy: policy.clone(),
15791×
                sigs: vec![psig.clone()],
15801×
            }],
15811×
            hashes: vec![],
15821×
            raw_changes: vec![],
15831×
            certificates: vec![],
15841×
        };
15851×
        let d = wire::decode_bundle(&wire::encode_bundle(&bundle)).unwrap();
15861×
        assert_eq!(
1587
            d.hashes,
15881×
            vec![c.hash()],
1589
            "the receiver hashes what it was sent"
1590
        );
15911×
        assert_eq!(d.changes, bundle.changes);
15921×
        assert_eq!(d.attests, bundle.attests);
15931×
        assert_eq!(d.objects, bundle.objects);
15941×
        assert_eq!(d.policies, bundle.policies);
15951×
        assert!(d.certificates.is_empty());
1596
        // Certificates (keyless, oxygenhub#241) travel as field 4, only
1597
        // when there are any: a bundle without them encodes as before.
15981×
        let plain = wire::encode_bundle(&bundle);
15991×
        let mut with = bundle.clone();
16001×
        let issuer_sk = crate::identity::SecretKey::generate();
16011×
        let issuer = issuer_sk.identity("hub", "h@x", 1);
16021×
        with.certificates.push(crate::cert::SignedCertificate::sign(
16031×
            crate::cert::Certificate {
16041×
                key: id.clone(),
16051×
                issuer: issuer.hash(),
16061×
                subject: "agent:a@b".into(),
16071×
                claims: vec![],
16081×
                scope: crate::identity::Scope::CHANGES,
16091×
                not_before: 1,
16101×
                expires: 2,
16111×
                grant: None,
16121×
            },
16131×
            &issuer,
16141×
            &issuer_sk,
1615
        ));
16161×
        let encoded = wire::encode_bundle(&with);
16171×
        assert_ne!(encoded, plain);
16181×
        assert_eq!(
16191×
            wire::decode_bundle(&encoded).unwrap().certificates,
1620
            with.certificates
1621
        );
16221×
        with.certificates.clear();
16231×
        assert_eq!(wire::encode_bundle(&with), plain);
1624
16251×
        let att = Attest {
16261×
            repo: [3; 16],
16271×
            hlc: Hlc::default(),
16281×
            body: AttestBody::Ref {
16291×
                name: "main".into(),
16301×
                old_state: ObjectRef([1; 32]),
16311×
                new_state: ObjectRef([2; 32]),
16321×
                serial: 4,
16331×
            },
16341×
        };
16351×
        let refs = vec![
16361×
            RemoteRef {
16371×
                name: "main".into(),
16381×
                state: ObjectRef([2; 32]),
16391×
                heads: vec![c.hash()],
16401×
                attestation: Some(SignedAttest {
16411×
                    attest: att.clone(),
16421×
                    sigs: vec![sig.clone()],
16431×
                }),
16441×
                last_serial: Some(4),
16451×
                accepted: None,
16461×
                logged: None,
16471×
                integration: vec![],
16481×
            },
16491×
            RemoteRef {
16501×
                name: "dev".into(),
16511×
                state: ObjectRef([5; 32]),
16521×
                heads: vec![],
16531×
                attestation: None,
16541×
                last_serial: None,
16551×
                accepted: None,
16561×
                logged: None,
16571×
                integration: vec![],
16581×
            },
1659
        ];
16601×
        let tag = TagRef::new("v1".into(), ObjectRef([2; 32]), vec![c.hash()], None);
16611×
        let mut resp = RefsResponse {
16621×
            refs,
16631×
            policy: Some(SignedPolicy {
16641×
                policy: policy.clone(),
16651×
                sigs: vec![psig.clone()],
16661×
            }),
16671×
            tags: vec![tag.clone()],
16681×
            history: vec![SignedPolicy {
16691×
                policy: policy.clone(),
16701×
                sigs: vec![],
16711×
            }],
16721×
            default_bookmark: Some("develop".into()),
16731×
            log: Some("hub.example/log\n2\nroot\n\n- sig\n".into()),
16741×
            witnesses: vec![],
16751×
            withdrawn: vec![],
16761×
        };
1677
        // Without integrated times (spec §14.8) nothing is added: an old
1678
        // peer's answer, and what it reads.
16791×
        let old = wire::encode_refs([3; 16], &resp);
16801×
        let back = wire::decode_refs(&old).unwrap().1;
16812×
        assert!(back.witnesses.is_empty() && back.refs.iter().all(|r| r.integration.is_empty()));
16821×
        resp.refs[1].logged = Some(Logged {
16831×
            index: 41,
16841×
            entry: vec![1, 2, 3],
16851×
            proof: vec![[9; 32], [8; 32]],
16861×
        });
16871×
        resp.refs[1].integration = vec![Integration {
16881×
            note: "hub.example/log\n42\nroot\n\n- sig\n".into(),
16891×
            proof: vec![[7; 32]],
16901×
        }];
16911×
        resp.witnesses = vec![("w.example".into(), vec![4, 5, 6])];
16921×
        let new = wire::encode_refs([3; 16], &resp);
16931×
        let (id_back, back) = wire::decode_refs(&new).unwrap();
16941×
        assert_eq!(back.log, resp.log);
16951×
        assert_eq!(back.refs[1].logged, resp.refs[1].logged);
16961×
        assert_eq!(back.refs[1].integration, resp.refs[1].integration);
16971×
        assert_eq!(back.witnesses, resp.witnesses);
16981×
        assert_eq!(back.refs[0].logged, None);
1699
        // The new keys are 7s an old reader never asks for.
17001×
        let crate::cbor::Value::Map(m) = crate::cbor::decode(&new).unwrap() else {
17010×
            panic!()
1702
        };
17031×
        assert!(m.contains_key(&7));
17041×
        assert_eq!(id_back, [3; 16]);
17051×
        assert_eq!(back.refs.len(), 2);
17061×
        assert_eq!(back.refs[0].attestation.as_ref().unwrap().attest, att);
17071×
        assert_eq!(back.refs[1].last_serial, None);
17081×
        assert_eq!(back.policy.as_ref().unwrap().policy, policy);
17091×
        assert_eq!(back.history, resp.history);
17101×
        assert_eq!(back.tags, vec![tag.clone()]);
1711
1712
        // A tag's acceptance and log place (oxygen#129): keys 4 to 6, only
1713
        // when there are any, so a tag without them encodes as before.
17141×
        let crate::cbor::Value::Map(m) = crate::cbor::decode(&new).unwrap() else {
17150×
            panic!()
1716
        };
17171×
        let crate::cbor::Value::Array(tags) = &m[&3] else {
17180×
            panic!()
1719
        };
17201×
        let crate::cbor::Value::Map(plain) = &tags[0] else {
17210×
            panic!()
1722
        };
17231×
        assert_eq!(plain.keys().copied().collect::<Vec<_>>(), vec![0, 1, 2, 3]);
17241×
        let mut full = tag.clone();
17251×
        full.name = "v2".into();
17261×
        full.attestation = Some(SignedAttest {
17271×
            attest: att.clone(),
17281×
            sigs: vec![sig.clone()],
17291×
        });
17301×
        full.accepted = full.attestation.clone();
17311×
        full.logged = Some(Logged {
17321×
            index: 7,
17331×
            entry: vec![4],
17341×
            proof: vec![[3; 32]],
17351×
        });
17361×
        full.integration = vec![Integration {
17371×
            note: "hub.example/log\n8\nroot\n\n- sig\n".into(),
17381×
            proof: vec![],
17391×
        }];
17401×
        resp.tags = vec![full.clone(), tag.clone()];
17411×
        let bytes = wire::encode_refs([3; 16], &resp);
17421×
        assert_eq!(wire::decode_refs(&bytes).unwrap().1.tags, resp.tags);
1743
        // In a push too.
17441×
        let pushed = wire::encode_push(&Bundle::default(), &[], None, &resp.tags);
17451×
        assert_eq!(wire::decode_push(&pushed).unwrap().3, resp.tags);
1746
        // A reader that knows only keys 0 to 3 (oxy 0.5.0 and older, and
1747
        // the runners built with it) reads the same tags from the new answer.
17481×
        let stripped: Vec<TagRef> = resp
17491×
            .tags
17501×
            .iter()
17512×
            .map(|t| {
17522×
                TagRef::new(
17532×
                    t.name.clone(),
17542×
                    t.state,
17552×
                    t.heads.clone(),
17562×
                    t.attestation.clone(),
1757
                )
17582×
            })
17591×
            .collect();
17601×
        assert_eq!(wire::tags_as_0_5_read_them(&bytes).unwrap(), stripped);
1761
17621×
        let (h, w) = wire::decode_negotiate(&wire::encode_negotiate(
17631×
            &[ObjectRef([1; 32])],
17641×
            &[ObjectRef([2; 32])],
17651×
        ))
17661×
        .unwrap();
17671×
        assert_eq!((h, w), (vec![ObjectRef([1; 32])], vec![ObjectRef([2; 32])]));
17681×
        assert_eq!(
17691×
            wire::decode_hashes(&wire::encode_hashes(&[c.hash()])).unwrap(),
17701×
            vec![c.hash()]
1771
        );
17721×
        assert_eq!(
17731×
            wire::decode_fetch(&wire::encode_fetch(&[c.hash()], Some(4096))).unwrap(),
17741×
            (vec![c.hash()], Some(4096))
1775
        );
17761×
        assert_eq!(
17771×
            wire::decode_fetch(&wire::encode_fetch(&[], None)).unwrap(),
17781×
            (vec![], None)
1779
        );
17801×
        assert_eq!(
17811×
            wire::decode_shallow(&wire::encode_shallow(&[c.hash()], 3)).unwrap(),
17821×
            (vec![c.hash()], 3)
1783
        );
1784
        // An old-style fetch request without the filter field still decodes.
17851×
        assert_eq!(
17861×
            wire::decode_fetch(&wire::encode_hashes(&[c.hash()])).unwrap(),
17871×
            (vec![c.hash()], None)
1788
        );
1789
17901×
        let up = RefUpdate {
17911×
            name: "main".into(),
17921×
            old_state: ObjectRef([1; 32]),
17931×
            new_state: ObjectRef([2; 32]),
17941×
            force: true,
17951×
            attestation: Some(SignedAttest {
17961×
                attest: att,
17971×
                sigs: vec![sig],
17981×
            }),
17991×
        };
18001×
        let sp = SignedPolicy {
18011×
            policy,
18021×
            sigs: vec![psig],
18031×
        };
18041×
        let (b2, ups, pol, tags) = wire::decode_push(&wire::encode_push(
18051×
            &bundle,
18061×
            std::slice::from_ref(&up),
18071×
            Some(&sp),
18081×
            std::slice::from_ref(&tag),
18091×
        ))
18101×
        .unwrap();
18111×
        assert_eq!(pol, Some(sp));
18121×
        assert_eq!(tags, vec![tag]);
18131×
        assert_eq!(b2.changes.len(), 1);
18141×
        assert_eq!(ups[0].name, "main");
18151×
        assert!(ups[0].force);
18161×
        assert_eq!(ups[0].attestation, up.attestation);
18171×
        let res = vec![RefResult {
18181×
            name: "main".into(),
18191×
            ok: false,
18201×
            reason: "stale".into(),
18211×
        }];
18221×
        assert_eq!(
18231×
            wire::decode_push_response(&wire::encode_push_response(&res)).unwrap(),
1824
            res
1825
        );
18261×
        assert_eq!(
18271×
            wire::decode_capabilities(&wire::encode_capabilities([7; 16])).unwrap(),
1828
            [7; 16]
1829
        );
18301×
    }
1831
}