OXYGENHUB

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

1068 of 1226 lines run, 173 of 257 functions · run #367 on main · run missed

1
//! Transport-agnostic protocol (spec §16): what a client asks of a remote and
2
//! what a server does with a push. `LocalRemote` serves another repository
3
//! directory in-process, `HttpRemote` speaks to an `oxy-server` over HTTP(S),
4
//! and the server side reuses `Repo::receive_push` and friends unchanged.
5
//!
6
//! Wire messages are deterministic CBOR (`wire` module); over HTTP each is a
7
//! request or response body with content type `application/oxy-cbor`.
8
9
use crate::attest::Attest;
10
use crate::cbor::{self, Value};
11
use crate::hash::{ChangeHash, ObjectRef, ObjectType};
12
use crate::identity::Signature;
13
use crate::objects::{self as o, Change, ObjectError};
14
use crate::policy::Policy;
15
use crate::repo::{Repo, RepoError, Result};
16
use std::path::{Path, PathBuf};
17
use std::sync::{Arc, Mutex};
18
19
pub const CONTENT_TYPE: &str = "application/oxy-cbor";
20
pub const PROTOCOL_VERSION: u64 = 1;
21
22
/// An attestation together with the signatures over its ObjectRef.
23
#[derive(Clone, Debug, PartialEq, Eq)]
24
pub struct SignedAttest {
25
    pub attest: Attest,
26
    pub sigs: Vec<Signature>,
27
}
28
29
/// A policy together with the root signatures over its ObjectRef.
30
#[derive(Clone, Debug, PartialEq, Eq)]
31
pub struct SignedPolicy {
32
    pub policy: Policy,
33
    pub sigs: Vec<Signature>,
34
}
35
36
impl SignedPolicy {
37
    /// The proposal-file encoding (`wire::policy_value`).
381×
    pub fn encode(&self) -> Vec<u8> {
391×
        crate::cbor::encode(&wire::policy_value(self))
401×
    }
411×
    pub fn decode(b: &[u8]) -> Result<SignedPolicy> {
421×
        wire::policy_from(
431×
            &crate::cbor::decode(b).map_err(|e| RepoError::Object(ObjectError::from(e)))?,
44
        )
451×
    }
46
}
47
48
/// What `refs` returns: every bookmark, every tag, and the current policy.
49
#[derive(Clone, Debug, Default)]
50
pub struct RefsResponse {
51
    pub refs: Vec<RemoteRef>,
52
    pub policy: Option<SignedPolicy>,
53
    pub tags: Vec<TagRef>,
54
    /// Earlier policies, ascending by serial, so a client behind by more
55
    /// than one update can verify each step (spec §14.5).
56
    pub history: Vec<SignedPolicy>,
57
    /// The bookmark a clone checks out (spec §16.1), when the remote names one.
58
    pub default_bookmark: Option<String>,
59
    /// The host's latest transparency-log checkpoint, a signed note (spec
60
    /// §14.8), against which `RemoteRef::logged` proofs are made (key 6,
61
    /// only when the host keeps a log).
62
    pub log: Option<String>,
63
    /// The witnesses the host asks to cosign its checkpoints: each one's
64
    /// name in cosignatures and its identity's bytes (key 7, only when it
65
    /// has any), which a client pins (spec §14.8, *Integrated time*).
66
    pub witnesses: Vec<(String, Vec<u8>)>,
67
    /// Tags withdrawn here (spec §10.1; key 8, only when there are any):
68
    /// each with its `untag` attestation as `attestation`, and that
69
    /// attestation's acceptance as `accepted` when a short-lived key
70
    /// signed it. Older clients ignore them and keep the tag they have.
71
    pub withdrawn: Vec<TagRef>,
72
}
73
74
/// Where a reference attestation sits in the host's transparency log
75
/// (spec §14.8): its entry number, the entry, and the inclusion proof
76
/// against the checkpoint served beside it.
77
#[derive(Clone, Debug, PartialEq, Eq)]
78
pub struct Logged {
79
    pub index: u64,
80
    pub entry: Vec<u8>,
81
    pub proof: Vec<[u8; 32]>,
82
}
83
84
/// A checkpoint witnesses cosigned that includes a logged entry (spec
85
/// §14.8, *Integrated time*): the cosigned note, and the entry's inclusion
86
/// proof against it.
87
#[derive(Clone, Debug, PartialEq, Eq)]
88
pub struct Integration {
89
    pub note: String,
90
    pub proof: Vec<[u8; 32]>,
91
}
92
93
/// A tag as a remote reports it (spec §10.1).
94
#[derive(Clone, Debug, PartialEq, Eq)]
95
pub struct TagRef {
96
    pub name: String,
97
    pub state: ObjectRef,
98
    pub heads: Vec<ChangeHash>,
99
    pub attestation: Option<SignedAttest>,
100
    /// The acceptance of `attestation` by its signer's certificate issuer
101
    /// when a short-lived key signed it (spec §14.7; key 4, only when there
102
    /// is one): the time a fetch checks the certificate at.
103
    pub accepted: Option<SignedAttest>,
104
    /// The attestation's place in the host's transparency log (key 5,
105
    /// only when it has one), as a bookmark's.
106
    pub logged: Option<Logged>,
107
    /// The cosigned checkpoints that first included `logged`'s entry (key
108
    /// 6, only when there are any).
109
    pub integration: Vec<Integration>,
110
}
111
112
impl TagRef {
113
    /// Whether this is a tag's withdrawal (its attestation an `untag`), as
114
    /// a push carries one (oxygenhub#301).
11525×
    pub fn is_withdrawal(&self) -> bool {
11625×
        self.attestation
11725×
            .as_ref()
11825×
            .is_some_and(|a| matches!(a.attest.body, crate::attest::AttestBody::Untag { .. }))
11925×
    }
120
121
    /// A tag with no acceptance or log place (yet).
122148×
    pub fn new(
123148×
        name: String,
124148×
        state: ObjectRef,
125148×
        heads: Vec<ChangeHash>,
126148×
        attestation: Option<SignedAttest>,
127148×
    ) -> TagRef {
128148×
        TagRef {
129148×
            name,
130148×
            state,
131148×
            heads,
132148×
            attestation,
133148×
            accepted: None,
134148×
            logged: None,
135148×
            integration: vec![],
136148×
        }
137148×
    }
138
}
139
140
/// One reference as a remote reports it.
141
#[derive(Clone, Debug)]
142
pub struct RemoteRef {
143
    pub name: String,
144
    pub state: ObjectRef,
145
    pub heads: Vec<ChangeHash>,
146
    /// The latest attestation, only when it describes `state`. An unattested
147
    /// push (accepted while no trust policy exists) leaves it `None`.
148
    pub attestation: Option<SignedAttest>,
149
    /// Serial of the latest attestation ever recorded, stale or not, so the
150
    /// next attestation continues the sequence.
151
    pub last_serial: Option<u64>,
152
    /// The host's acceptance of `attestation` when a short-lived key signed
153
    /// it (spec §14.7): the time its certificate is checked at.
154
    pub accepted: Option<SignedAttest>,
155
    /// The attestation's place in the host's transparency log (key 6, only
156
    /// when it has one).
157
    pub logged: Option<Logged>,
158
    /// The cosigned checkpoints that first included `logged`'s entry (key
159
    /// 7, only when there are any): what its integrated time is read from.
160
    pub integration: Vec<Integration>,
161
}
162
163
/// Everything needed to add a set of changes to a repository.
164
#[derive(Clone, Debug, Default)]
165
pub struct Bundle {
166
    /// In dependency order, each with its individual signatures.
167
    pub changes: Vec<(Change, Vec<Signature>)>,
168
    /// Seals covering the changes.
169
    pub attests: Vec<SignedAttest>,
170
    /// Chunks, blobs, identities, and state objects referenced by the changes.
171
    pub objects: Vec<(ObjectType, Vec<u8>)>,
172
    /// Policies between the receiver's and the one sent with the push,
173
    /// ascending by serial (spec §14.5).
174
    pub policies: Vec<SignedPolicy>,
175
    /// Each change's hash, in the order of `changes`, when whoever made
176
    /// the bundle knows it: the store it came from, or the bytes it was
177
    /// decoded from. Never read from the wire. Empty when unknown.
178
    pub hashes: Vec<ChangeHash>,
179
    /// Changes as stored, with their signatures, in dependency order, for a
180
    /// fetch between repositories on one machine: their text blobs and
181
    /// chunks are among `objects`. Never on the wire.
182
    pub raw_changes: Vec<(Vec<u8>, Vec<Signature>)>,
183
    /// Certificates of short-lived keys that signed what the bundle carries
184
    /// (spec §14.7), their issuers' identities among `objects`.
185
    pub certificates: Vec<crate::cert::SignedCertificate>,
186
}
187
188
impl Bundle {
18927×
    pub fn is_empty(&self) -> bool {
19027×
        self.changes.is_empty() && self.attests.is_empty() && self.objects.is_empty()
19127×
    }
192
}
193
194
/// A requested bookmark move (spec §10.2, §16.3).
195
#[derive(Clone, Debug)]
196
pub struct RefUpdate {
197
    pub name: String,
198
    pub old_state: ObjectRef,
199
    pub new_state: ObjectRef,
200
    pub force: bool,
201
    pub attestation: Option<SignedAttest>,
202
}
203
204
#[derive(Clone, Debug, PartialEq, Eq)]
205
pub struct RefResult {
206
    pub name: String,
207
    pub ok: bool,
208
    pub reason: String,
209
}
210
211
pub trait Remote {
212
    fn repo_id(&self) -> Result<[u8; 16]>;
213
    fn refs(&self) -> Result<RefsResponse>;
214
    /// Changes in the closure of `want` but not of `have`, in dependency order.
215
    fn negotiate(&self, have: &[ChangeHash], want: &[ChangeHash]) -> Result<Vec<ChangeHash>>;
216
    /// The changes with their signatures, seals, identities, and blobs; blobs
217
    /// larger than `max_blob` bytes are left out for lazy fetching (spec §13.5).
218
    fn fetch(&self, changes: &[ChangeHash], max_blob: Option<u64>) -> Result<Bundle>;
219
    /// Individual objects by reference (spec §16.1 `objects`); a blob comes
220
    /// with its chunks.
221
    fn objects(&self, refs: &[ObjectRef]) -> Result<Vec<(ObjectType, Vec<u8>)>>;
222
    /// A checkpoint of exactly `heads` (spec §16.1 `checkpoint`): the
223
    /// checkpoint object, its payload blob, and the blob's chunks.
224
    fn checkpoint(&self, heads: &[ChangeHash]) -> Result<Bundle>;
225
    /// The changes within `depth` dependency steps of `heads` (spec §17).
226
    fn shallow(&self, heads: &[ChangeHash], depth: u32) -> Result<Vec<ChangeHash>>;
227
    /// Push changes, bookmark updates, new tags, and optionally a newer
228
    /// policy. The policy is applied first; a result named `policy` reports
229
    /// it, and each tag reports as `tags/<name>`.
230
    fn push(
231
        &self,
232
        bundle: Bundle,
233
        updates: Vec<RefUpdate>,
234
        policy: Option<SignedPolicy>,
235
        tags: Vec<TagRef>,
236
    ) -> Result<Vec<RefResult>>;
237
}
238
239
// ---------------------------------------------------------------- local
240
241
/// Another repository on this machine, served in-process.
242
pub struct LocalRemote {
243
    pub repo: Repo,
244
    /// The pushing repository's id, which binds an unbound target on the
245
    /// first push, as `Oxy-Repo-Id` does over HTTP.
246
    pub claimed_id: Option<[u8; 16]>,
247
}
248
249
impl LocalRemote {
2501133×
    pub fn open(path: &Path) -> Result<LocalRemote> {
251
        Ok(LocalRemote {
2521133×
            repo: Repo::open(path)?,
2531133×
            claimed_id: None,
254
        })
2551133×
    }
256
}
257
258
impl Remote for LocalRemote {
259890×
    fn repo_id(&self) -> Result<[u8; 16]> {
260890×
        self.repo.id()
261890×
    }
262888×
    fn refs(&self) -> Result<RefsResponse> {
263888×
        self.repo.remote_refs()
264888×
    }
265352×
    fn negotiate(&self, have: &[ChangeHash], want: &[ChangeHash]) -> Result<Vec<ChangeHash>> {
266352×
        self.repo.negotiate(have, want)
267352×
    }
268356×
    fn fetch(&self, changes: &[ChangeHash], max_blob: Option<u64>) -> Result<Bundle> {
269356×
        self.repo.bundle_raw_for(changes, max_blob)
270356×
    }
2713×
    fn objects(&self, refs: &[ObjectRef]) -> Result<Vec<(ObjectType, Vec<u8>)>> {
2723×
        self.repo.objects_for(refs)
2733×
    }
2741×
    fn checkpoint(&self, heads: &[ChangeHash]) -> Result<Bundle> {
2751×
        self.repo.checkpoint_bundle_for(heads)
2761×
    }
2773×
    fn shallow(&self, heads: &[ChangeHash], depth: u32) -> Result<Vec<ChangeHash>> {
2783×
        self.repo.shallow_changes(heads, depth)
2793×
    }
280269×
    fn push(
281269×
        &self,
282269×
        bundle: Bundle,
283269×
        updates: Vec<RefUpdate>,
284269×
        policy: Option<SignedPolicy>,
285269×
        tags: Vec<TagRef>,
286269×
    ) -> Result<Vec<RefResult>> {
287269×
        if self.repo.is_unbound() {
28813×
            match self.claimed_id {
28913×
                Some(id) => self.repo.bind_id(id)?,
290
                None => {
2910×
                    return Err(RepoError::Msg(
2920×
                        "the remote is unbound and this client did not say which repository it is"
2930×
                            .into(),
2940×
                    ))
295
                }
296
            }
297256×
        }
298269×
        self.repo.receive_push(bundle, updates, policy, tags)
299269×
    }
300
}
301
302
// ---------------------------------------------------------------- http
303
304
/// How to reach a remote: credentials and trust.
305
#[derive(Clone, Debug, Default)]
306
pub struct RemoteOptions {
307
    /// Bearer token for pushes.
308
    pub token: Option<String>,
309
    /// PEM file with extra root certificates to trust for `https://` remotes
310
    /// (self-hosted servers); the system web roots are always trusted.
311
    pub ca: Option<PathBuf>,
312
    /// The local repository's id, sent as `Oxy-Repo-Id` so an unbound
313
    /// hosted repository can adopt it on the first push (spec §16.1).
314
    pub repo_id: Option<[u8; 16]>,
315
    /// Where a remote kept on a store (`dir://`, `s3://`, …) keeps its
316
    /// mirror and what it has seen: the remote's directory under
317
    /// `.oxy/remotes`. None (a clone, before there is a repository) means
318
    /// a temporary directory.
319
    pub cache_dir: Option<PathBuf>,
320
    /// Other tokens for the same hub, tried in turn when `token` is
321
    /// refused (401, 403 or 404): those of enclosing checkouts, when
322
    /// `token` came from the credential store rather than from this
323
    /// remote's own configuration (oxygen#112).
324
    pub fallback_tokens: Vec<String>,
325
}
326
327
/// Opens a store for a URL it understands, or passes (`None`). Stores that
328
/// need more than the standard library (the cloud ones) are added by the
329
/// program that links them, with [`register_store_opener`].
330
pub type StoreOpener =
331
    fn(&str, &RemoteOptions) -> Option<crate::strata::Result<Box<dyn crate::strata::Store>>>;
332
333
static STORE_OPENERS: Mutex<Vec<StoreOpener>> = Mutex::new(Vec::new());
334
335155×
pub fn register_store_opener(opener: StoreOpener) {
336155×
    STORE_OPENERS
337155×
        .lock()
338155×
        .unwrap_or_else(|p| p.into_inner())
339155×
        .push(opener);
340155×
}
341
342
/// A store for `url`, from `dir://` or any registered opener.
3431192×
pub fn open_store(
3441192×
    url: &str,
3451192×
    options: &RemoteOptions,
3461192×
) -> Option<crate::strata::Result<Box<dyn crate::strata::Store>>> {
3471192×
    if let Some(path) = url.strip_prefix("dir://") {
348
        return Some(
34959×
            crate::strata::LocalStore::open(path)
35059×
                .map(|s| Box::new(s) as Box<dyn crate::strata::Store>),
351
        );
3521133×
    }
3531133×
    let openers = STORE_OPENERS.lock().unwrap_or_else(|p| p.into_inner());
3541133×
    openers.iter().find_map(|open| open(url, options))
3551192×
}
356
357
/// The request header carrying the client's repository id.
358
pub const REPO_ID_HEADER: &str = "Oxy-Repo-Id";
359
360
/// The id of a hosted repository that has not adopted one yet.
361
pub const UNBOUND_ID: [u8; 16] = [0; 16];
362
363
/// The request header in which a client declares the protocol features it
364
/// understands beyond the 0.5.0-era set: a comma-separated list, which a
365
/// server may tailor its answers to (docs/protocol.md, *Client
366
/// capabilities*). A request without it is a client of that era.
367
pub const FEATURES_HEADER: &str = "Oxy-Features";
368
369
/// The feature of a client that authorizes a tag signed by a short-lived,
370
/// certified key by its certificate at the time the host accepted it
371
/// (oxygen#129). A client without it refuses such a tag, and with it the
372
/// whole fetch, so servers leave those tags out of its `refs` (oxygen#131).
373
pub const FEATURE_CERTIFIED_TAGS: &str = "certified-tags";
374
375
/// The features this client declares in [`FEATURES_HEADER`].
376
pub const CLIENT_FEATURES: &[&str] = &[FEATURE_CERTIFIED_TAGS];
377
378
/// The `User-Agent` every request of this client sends: `oxy/<version>`.
379170×
pub fn user_agent() -> String {
380170×
    format!("oxy/{}", env!("CARGO_PKG_VERSION"))
381170×
}
382
383
/// Whether a [`FEATURES_HEADER`] value (absent: `None`) declares `feature`.
384
/// Entries are comma-separated, compared without surrounding blanks and
385
/// regardless of case; unknown ones are ignored.
386141×
pub fn declares_feature(header: Option<&str>, feature: &str) -> bool {
387141×
    header.is_some_and(|h| h.split(',').any(|f| f.trim().eq_ignore_ascii_case(feature)))
388141×
}
389
390
/// A remote served by `oxy-server` at `<base>/oxy/v1/...`.
391
pub struct HttpRemote {
392
    base: String,
393
    /// The token in use, and those still to try when it is refused.
394
    token: Mutex<Option<String>>,
395
    fallbacks: Mutex<Vec<String>>,
396
    repo_id: Option<[u8; 16]>,
397
    agent: ureq::Agent,
398
}
399
400
/// A TLS client configuration trusting the web roots plus `ca`, if given:
401
/// the trust every oxy connection uses, shared with tools that call hub APIs.
402173×
pub fn tls_client_config(ca: Option<&Path>) -> Result<Arc<rustls::ClientConfig>> {
403173×
    let mut roots = rustls::RootCertStore::empty();
404173×
    roots.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
405173×
    if let Some(path) = ca {
40616×
        let pem = std::fs::read(path)
40716×
            .map_err(|e| RepoError::Msg(format!("reading CA file {}: {e}", path.display())))?;
40816×
        let certs = rustls_pemfile::certs(&mut pem.as_slice())
40916×
            .collect::<std::result::Result<Vec<_>, _>>()
41016×
            .map_err(|e| RepoError::Msg(format!("parsing CA file {}: {e}", path.display())))?;
41116×
        if certs.is_empty() {
4120×
            return Err(RepoError::Msg(format!(
4130×
                "CA file {} holds no certificates",
4140×
                path.display()
4150×
            )));
41616×
        }
41716×
        for c in certs {
41816×
            roots
41916×
                .add(c)
42016×
                .map_err(|e| RepoError::Msg(format!("CA file {}: {e}", path.display())))?;
421
        }
422157×
    }
423173×
    let cfg = rustls::ClientConfig::builder_with_provider(Arc::new(
424173×
        rustls::crypto::ring::default_provider(),
425
    ))
426173×
    .with_safe_default_protocol_versions()
427173×
    .map_err(|e| RepoError::Msg(e.to_string()))?
428173×
    .with_root_certificates(roots)
429173×
    .with_no_client_auth();
430173×
    Ok(Arc::new(cfg))
431173×
}
432
433
impl HttpRemote {
434167×
    pub fn new(base: &str, options: &RemoteOptions) -> Result<HttpRemote> {
435167×
        refuse_plain_token(base, options)?;
436167×
        let agent = ureq::AgentBuilder::new()
437167×
            .tls_config(tls_client_config(options.ca.as_deref())?)
438167×
            .user_agent(&user_agent())
439167×
            .build();
440167×
        Ok(HttpRemote {
441167×
            base: base.trim_end_matches('/').to_string(),
442167×
            token: Mutex::new(options.token.clone()),
443167×
            fallbacks: Mutex::new(options.fallback_tokens.iter().rev().cloned().collect()),
444167×
            repo_id: options.repo_id,
445167×
            agent,
446167×
        })
447167×
    }
448
449
    /// A request, tried again with the next fallback token while the
450
    /// hub refuses the one in use (oxygen#112).
451419×
    fn call(&self, post: bool, endpoint: &str, body: Option<&[u8]>) -> Result<Vec<u8>> {
452
        loop {
453420×
            let token = self.token.lock().unwrap_or_else(|p| p.into_inner()).clone();
454420×
            match self.call_once(post, endpoint, body, token.as_deref()) {
45512×
                Err(RepoError::Msg(m)) if token.is_some() && refused(&m) => {
4563×
                    let next = self
4573×
                        .fallbacks
4583×
                        .lock()
4593×
                        .unwrap_or_else(|p| p.into_inner())
4603×
                        .pop();
4613×
                    let Some(next) = next else {
4622×
                        return Err(RepoError::Msg(m));
463
                    };
4641×
                    crate::credentials::warn_once(&format!(
4651×
                        "{}: the stored token was refused; using the one an enclosing checkout has for this hub",
4661×
                        self.base
4671×
                    ));
4681×
                    *self.token.lock().unwrap_or_else(|p| p.into_inner()) = Some(next);
469
                }
470417×
                other => return other,
471
            }
472
        }
473419×
    }
474
475420×
    fn call_once(
476420×
        &self,
477420×
        post: bool,
478420×
        endpoint: &str,
479420×
        body: Option<&[u8]>,
480420×
        token: Option<&str>,
481420×
    ) -> Result<Vec<u8>> {
482420×
        let url = format!("{}/oxy/v1/{endpoint}", self.base);
483420×
        let mut req = if post {
484147×
            self.agent.post(&url)
485
        } else {
486273×
            self.agent.get(&url)
487
        };
488420×
        req = req
489420×
            .set("Accept", CONTENT_TYPE)
490420×
            .set(FEATURES_HEADER, &CLIENT_FEATURES.join(","));
491420×
        if let Some(t) = token {
49222×
            req = req.set("Authorization", &format!("Bearer {t}"));
493398×
        }
494420×
        if let Some(id) = &self.repo_id {
495389×
            req = req.set(REPO_ID_HEADER, &hex::encode(id));
496389×
        }
497420×
        let resp = match body {
498147×
            Some(b) => req.set("Content-Type", CONTENT_TYPE).send_bytes(b),
499273×
            None => req.call(),
500
        };
50112×
        match resp {
502408×
            Ok(r) => {
503408×
                let mut out = Vec::new();
504408×
                r.into_reader()
505408×
                    .read_to_end(&mut out)
506408×
                    .map_err(|e| RepoError::Msg(format!("{url}: {e}")))?;
507408×
                Ok(out)
508
            }
5099×
            Err(ureq::Error::Status(code, r)) => {
5109×
                let text = r.into_string().unwrap_or_default();
511
                // The hint comes from the status alone: the server's text
512
                // (a host's reason for refusing a push, several lines
513
                // perhaps) is shown as it is, never read for hints.
5149×
                let status = format!("{url}: HTTP {code}");
5159×
                let msg = format!("{status}: {}", text.trim());
5169×
                Err(RepoError::Msg(match hint_for(&status) {
5178×
                    Some(h) => format!("{msg}\n  hint: {h}"),
5181×
                    None => msg,
519
                }))
520
            }
521
            // The transport error already names the URL.
5223×
            Err(e) => Err(RepoError::Msg(with_hint(e.to_string()))),
523
        }
524420×
    }
525
}
526
527
/// Whether a failed request's message says the hub refused its token:
528
/// HTTP 401, 403, or 404 (a hub hides a private repository from a token
529
/// that may not read it).
5304×
fn refused(message: &str) -> bool {
5314×
    [": HTTP 401", ": HTTP 403", ": HTTP 404"]
5324×
        .iter()
5336×
        .any(|c| message.contains(c))
5344×
}
535
536
/// Refuse to send a token where anyone on the way could read it: plain
537
/// `http` to another machine (see [`crate::credentials::token_allowed`]).
538169×
fn refuse_plain_token(url: &str, options: &RemoteOptions) -> Result<()> {
539169×
    if options.token.is_some() && !crate::credentials::token_allowed(url) {
5400×
        return Err(RepoError::Msg(format!(
5410×
            "{url}: refusing to send a token over plain http; use https"
5420×
        )));
543169×
    }
544169×
    Ok(())
545169×
}
546
547
/// What to do about a failed request, recognised from its message.
54820×
pub fn hint_for(message: &str) -> Option<&'static str> {
54920×
    let m = message.to_ascii_lowercase();
55020×
    let hint = if m.contains("http 401") {
5516×
        "the hub needs you signed in, or did not accept the token: run `oxy auth login HUB` (pushing needs repo:write)"
55214×
    } else if m.contains("http 403") {
5531×
        "the token or account lacks permission: pushing needs a token with repo:write and write access to the repository"
55413×
    } else if m.contains("http 404") {
5554×
        "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`)"
5569×
    } else if m.contains("unknownissuer")
5577×
        || m.contains("unknown issuer")
5587×
        || m.contains("certificate")
5596×
        || m.contains("invalidcertificate")
560
    {
5613×
        "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`"
5626×
    } else if m.contains("connection refused") {
5633×
        "nothing is listening there: check the URL and port, and that the server is running"
5643×
    } else if m.contains("dns")
5652×
        || m.contains("failed to lookup")
5662×
        || m.contains("name or service not known")
567
    {
5681×
        "the host name does not resolve: check the URL"
5692×
    } else if m.contains("timed out") || m.contains("timeout") {
5700×
        "the server did not answer in time: check the network, or try again"
571
    } else {
5722×
        return None;
573
    };
57418×
    Some(hint)
57520×
}
576
577
/// `message`, followed by what to do about it when that is known.
5783×
pub fn with_hint(message: String) -> String {
5793×
    match hint_for(&message) {
5803×
        Some(h) => format!("{message}\n  hint: {h}"),
5810×
        None => message,
582
    }
5833×
}
584
585
/// A JSON request to a hub API (`GET`, `POST` or `DELETE`), with the same
586
/// TLS trust and token rules as remotes. Returns the status and body, an
587
/// error status included; only transport failures are errors.
5880×
pub fn http_json(
5890×
    method: &str,
5900×
    url: &str,
5910×
    body: Option<&str>,
5920×
    options: &RemoteOptions,
5930×
) -> Result<(u16, String)> {
5940×
    refuse_plain_token(url, options)?;
5950×
    let agent = ureq::AgentBuilder::new()
5960×
        .tls_config(tls_client_config(options.ca.as_deref())?)
5970×
        .timeout(std::time::Duration::from_secs(60))
5980×
        .user_agent(&user_agent())
5990×
        .build();
6000×
    let mut req = agent.request(method, url).set("Accept", "application/json");
6010×
    if let Some(t) = &options.token {
6020×
        req = req.set("Authorization", &format!("Bearer {t}"));
6030×
    }
6040×
    let resp = match body {
6050×
        Some(b) => req.set("Content-Type", "application/json").send_string(b),
6060×
        None => req.call(),
607
    };
6080×
    match resp {
6090×
        Ok(r) => {
6100×
            let code = r.status();
6110×
            Ok((code, r.into_string().unwrap_or_default()))
612
        }
6130×
        Err(ureq::Error::Status(code, r)) => Ok((code, r.into_string().unwrap_or_default())),
6140×
        Err(e) => Err(RepoError::Msg(with_hint(e.to_string()))),
615
    }
6160×
}
617
618
/// An authenticated GET of any URL on a host, with the same TLS trust and
619
/// token as remotes use (for hub APIs: proposals). Returns the body.
6202×
pub fn http_get(url: &str, options: &RemoteOptions) -> Result<Vec<u8>> {
6212×
    refuse_plain_token(url, options)?;
6222×
    let agent = ureq::AgentBuilder::new()
6232×
        .tls_config(tls_client_config(options.ca.as_deref())?)
6242×
        .user_agent(&user_agent())
6252×
        .build();
6262×
    let mut req = agent.get(url).set("Accept", "application/json");
6272×
    if let Some(t) = &options.token {
6280×
        req = req.set("Authorization", &format!("Bearer {t}"));
6292×
    }
6302×
    match req.call() {
6312×
        Ok(r) => {
6322×
            let mut out = Vec::new();
6332×
            r.into_reader()
6342×
                .read_to_end(&mut out)
6352×
                .map_err(|e| RepoError::Msg(format!("{url}: {e}")))?;
6362×
            Ok(out)
637
        }
6380×
        Err(ureq::Error::Status(code, r)) => {
6390×
            let text = r.into_string().unwrap_or_default();
6400×
            Err(RepoError::Msg(with_hint(format!(
6410×
                "{url}: HTTP {code}: {}",
6420×
                text.trim()
6430×
            ))))
644
        }
645
        // The transport error already names the URL.
6460×
        Err(e) => Err(RepoError::Msg(with_hint(e.to_string()))),
647
    }
6482×
}
649
650
impl Remote for HttpRemote {
651140×
    fn repo_id(&self) -> Result<[u8; 16]> {
652140×
        wire::decode_capabilities(&self.call(false, "capabilities", None)?)
653140×
    }
654133×
    fn refs(&self) -> Result<RefsResponse> {
655133×
        Ok(wire::decode_refs(&self.call(false, "refs", None)?)?.1)
656133×
    }
65751×
    fn negotiate(&self, have: &[ChangeHash], want: &[ChangeHash]) -> Result<Vec<ChangeHash>> {
65851×
        wire::decode_hashes(&self.call(
659
            true,
66051×
            "negotiate",
66151×
            Some(&wire::encode_negotiate(have, want)),
6620×
        )?)
66351×
    }
66451×
    fn fetch(&self, changes: &[ChangeHash], max_blob: Option<u64>) -> Result<Bundle> {
66551×
        wire::decode_bundle(&self.call(
666
            true,
66751×
            "fetch",
66851×
            Some(&wire::encode_fetch(changes, max_blob)),
6690×
        )?)
67051×
    }
6711×
    fn objects(&self, refs: &[ObjectRef]) -> Result<Vec<(ObjectType, Vec<u8>)>> {
672
        Ok(
6731×
            wire::decode_bundle(&self.call(true, "objects", Some(&wire::encode_hashes(refs)))?)?
674
                .objects,
675
        )
6761×
    }
6770×
    fn checkpoint(&self, heads: &[ChangeHash]) -> Result<Bundle> {
6780×
        wire::decode_bundle(&self.call(true, "checkpoint", Some(&wire::encode_hashes(heads)))?)
6790×
    }
6800×
    fn shallow(&self, heads: &[ChangeHash], depth: u32) -> Result<Vec<ChangeHash>> {
6810×
        wire::decode_hashes(&self.call(
682
            true,
6830×
            "shallow",
6840×
            Some(&wire::encode_shallow(heads, depth)),
6850×
        )?)
6860×
    }
68743×
    fn push(
68843×
        &self,
68943×
        bundle: Bundle,
69043×
        updates: Vec<RefUpdate>,
69143×
        policy: Option<SignedPolicy>,
69243×
        tags: Vec<TagRef>,
69343×
    ) -> Result<Vec<RefResult>> {
69443×
        wire::decode_push_response(&self.call(
695
            true,
69643×
            "push",
69743×
            Some(&wire::encode_push(
69843×
                &bundle,
69943×
                &updates,
70043×
                policy.as_ref(),
70143×
                &tags,
70243×
            )),
7035×
        )?)
70443×
    }
705
}
706
707
/// A remote's URL as it is stored: an `http(s)://` URL as given, a local
708
/// path made absolute (with its `file://` kept), so it still names the same
709
/// repository from inside the clone (oxygen#57).
710278×
pub fn stored_url(url: &str) -> String {
711
    // Only a path is made absolute: a plain one, or one behind file:// or
712
    // dir://. Every other URL (a hub, a bucket) is kept as written.
713278×
    let (prefix, path) = match (url.strip_prefix("file://"), url.strip_prefix("dir://")) {
7141×
        (Some(p), _) => ("file://", p),
71511×
        (_, Some(p)) => ("dir://", p),
716266×
        _ if url.contains("://") => return url.to_string(),
717239×
        _ => ("", url),
718
    };
719251×
    match std::path::absolute(path) {
720251×
        Ok(abs) => format!("{prefix}{}", abs.display()),
7210×
        Err(_) => url.to_string(),
722
    }
723278×
}
724
725
/// Open a remote by URL: a local path (optionally `file://`), `http(s)://`
726
/// (a hub), or a store (`dir://`, and whatever openers are registered).
7271347×
pub fn open_remote(url: &str, options: &RemoteOptions) -> Result<Box<dyn Remote>> {
7281347×
    if url.starts_with("http://") || url.starts_with("https://") {
729167×
        return Ok(Box::new(HttpRemote::new(url, options)?));
7301180×
    }
7311180×
    if let Some(store) = open_store(url, options) {
73248×
        return crate::repo::strata::open_store_remote(store?, options);
7331132×
    }
7341132×
    let path = url.strip_prefix("file://").unwrap_or(url);
7351132×
    if path.contains("://") {
7360×
        return Err(RepoError::Msg(format!("unsupported remote URL {url:?}")));
7371132×
    }
7381132×
    let mut local = LocalRemote::open(Path::new(path))?;
7391132×
    local.claimed_id = options.repo_id;
7401132×
    Ok(Box::new(local))
7411347×
}
742
743
// ---------------------------------------------------------------- wire
744
745
/// CBOR encodings of the protocol messages (spec §16.1).
746
pub mod wire {
747
    use super::*;
748
7490×
    fn schema(msg: &str) -> RepoError {
7500×
        RepoError::Object(ObjectError::Schema(msg.into()))
7510×
    }
752259×
    fn sigs_value(sigs: &[Signature]) -> Value {
753259×
        Value::Array(sigs.iter().map(|s| s.to_value()).collect())
754259×
    }
755255×
    fn sigs_from(v: &Value) -> Result<Vec<Signature>> {
756255×
        Ok(o::array(v, "signatures")?
757255×
            .iter()
758255×
            .map(Signature::from_value)
759255×
            .collect::<std::result::Result<Vec<_>, _>>()?)
760255×
    }
761417×
    fn hashes_value(hs: &[ObjectRef]) -> Value {
762542×
        Value::Array(hs.iter().map(|h| Value::Bytes(h.0.to_vec())).collect())
763417×
    }
764478×
    fn hashes_from(v: &Value) -> Result<Vec<ObjectRef>> {
765478×
        Ok(o::array(v, "hashes")?
766478×
            .iter()
767604×
            .map(|h| o::oref(h, "hash"))
768478×
            .collect::<std::result::Result<Vec<_>, _>>()?)
769478×
    }
77091×
    fn attest_value(sa: &SignedAttest) -> Value {
77191×
        Value::Array(vec![Value::Bytes(sa.attest.encode()), sigs_value(&sa.sigs)])
77291×
    }
773106×
    fn attest_from(v: &Value) -> Result<SignedAttest> {
774106×
        let a = o::array(v, "signed attest")?;
775106×
        if a.len() != 2 {
7760×
            return Err(schema("signed attest: expected [attest, sigs]"));
777106×
        }
778
        Ok(SignedAttest {
779106×
            attest: Attest::decode(o::bytes(&a[0], "attest")?)?,
780106×
            sigs: sigs_from(&a[1])?,
781
        })
782106×
    }
783266×
    fn opt_attest_value(sa: &Option<SignedAttest>) -> Value {
784266×
        sa.as_ref().map(attest_value).unwrap_or(Value::Null)
785266×
    }
786323×
    fn opt_attest_from(v: &Value) -> Result<Option<SignedAttest>> {
787323×
        if v.is_null() {
788233×
            Ok(None)
789
        } else {
79090×
            attest_from(v).map(Some)
791
        }
792323×
    }
793
    /// `[policy bytes, [signature]]`: also the format of a policy proposal
794
    /// file exchanged between root holders (spec §14.5).
79545×
    pub fn policy_value(sp: &SignedPolicy) -> Value {
79645×
        Value::Array(vec![Value::Bytes(sp.policy.encode()), sigs_value(&sp.sigs)])
79745×
    }
79843×
    pub fn policy_from(v: &Value) -> Result<SignedPolicy> {
79943×
        let a = o::array(v, "signed policy")?;
80043×
        if a.len() != 2 {
8010×
            return Err(schema("signed policy: expected [policy, sigs]"));
80243×
        }
803
        Ok(SignedPolicy {
80443×
            policy: Policy::decode(o::bytes(&a[0], "policy")?)?,
80543×
            sigs: sigs_from(&a[1])?,
806
        })
80743×
    }
808210×
    fn opt_policy_value(sp: Option<&SignedPolicy>) -> Value {
809210×
        sp.map(policy_value).unwrap_or(Value::Null)
810210×
    }
811249×
    fn opt_policy_from(v: &Value) -> Result<Option<SignedPolicy>> {
812249×
        if v.is_null() {
813227×
            Ok(None)
814
        } else {
81522×
            policy_from(v).map(Some)
816
        }
817249×
    }
8181057×
    fn map<'a>(v: &'a Value, what: &str) -> Result<&'a o::Map> {
8191057×
        Ok(o::map(v, what)?)
8201057×
    }
8213000×
    fn field<'a>(m: &'a o::Map, k: u64, what: &str) -> Result<&'a Value> {
8223000×
        Ok(o::field(m, k, what)?)
8233000×
    }
824
825
    /// A bundle's value. Each change's text blobs and their chunks (spec
826
    /// §6.1) are added to its objects when they are not already there, so a
827
    /// bundle can always be read on its own.
828132×
    pub fn bundle_value(b: &Bundle) -> Value {
829132×
        let mut changes = Vec::with_capacity(b.raw_changes.len() + b.changes.len());
830
        // Changes as stored are already their encoding, their texts among
831
        // the objects.
832132×
        for (bytes, s) in &b.raw_changes {
8330×
            changes.push(Value::Array(vec![
8340×
                Value::Bytes(bytes.clone()),
8350×
                sigs_value(s),
8360×
            ]));
8370×
        }
838132×
        let mut texts: Vec<(ObjectType, Vec<u8>)> = Vec::new();
839132×
        let mut listed: Option<std::collections::HashSet<ObjectRef>> = None;
840132×
        for (c, s) in &b.changes {
841123×
            let (bytes, stored) = c.encode_parts();
842123×
            for t in stored {
8430×
                let listed = listed.get_or_insert_with(|| {
8440×
                    b.objects
8450×
                        .iter()
8460×
                        .map(|(ty, body)| crate::hash::hash_object(*ty, body))
8470×
                        .collect()
8480×
                });
8490×
                if !listed.insert(t.blob.hash()) {
8500×
                    continue;
8510×
                }
8520×
                for chunk in crate::chunk::chunks(&t.content) {
8530×
                    if listed.insert(crate::hash::hash_object(ObjectType::Chunk, chunk)) {
8540×
                        texts.push((ObjectType::Chunk, chunk.to_vec()));
8550×
                    }
856
                }
8570×
                texts.push((ObjectType::Blob, t.blob.encode()));
858
            }
859123×
            changes.push(Value::Array(vec![Value::Bytes(bytes), sigs_value(s)]));
860
        }
861132×
        let mut v = Value::map([
862132×
            (0, Value::Array(changes)),
863132×
            (
864132×
                1,
865132×
                Value::Array(b.attests.iter().map(attest_value).collect()),
866132×
            ),
867
            (
868
                2,
869
                Value::Array(
870132×
                    b.objects
871132×
                        .iter()
872132×
                        .chain(&texts)
873132×
                        .map(|(t, body)| {
874121×
                            Value::Array(vec![
875121×
                                Value::Text(t.name().into()),
876121×
                                Value::Bytes(body.clone()),
877121×
                            ])
878121×
                        })
879132×
                        .collect(),
880
                ),
881
            ),
882132×
            (
883132×
                3,
884132×
                Value::Array(b.policies.iter().map(policy_value).collect()),
885132×
            ),
886
        ]);
887
        // Only when there are any; older peers ignore the field.
888132×
        if !b.certificates.is_empty() {
8897×
            if let Value::Map(m) = &mut v {
8907×
                m.insert(
891
                    4,
892
                    Value::Array(
8937×
                        b.certificates
8947×
                            .iter()
8957×
                            .map(|c| Value::Bytes(c.encode()))
8967×
                            .collect(),
897
                    ),
898
                );
8990×
            }
900125×
        }
901132×
        v
902132×
    }
903
904122×
    pub fn bundle_from_value(v: &Value) -> Result<Bundle> {
905122×
        let m = map(v, "bundle")?;
906122×
        let mut b = Bundle::default();
907122×
        for ob in o::array(field(m, 2, "objects")?, "objects")? {
908110×
            let pair = o::array(ob, "object")?;
909110×
            if pair.len() != 2 {
9100×
                return Err(schema("object: expected [type, body]"));
911110×
            }
912110×
            let ty = ObjectType::from_name(o::text(&pair[0], "object type")?)
913110×
                .ok_or_else(|| schema("unknown object type"))?;
914110×
            b.objects
915110×
                .push((ty, o::bytes(&pair[1], "object body")?.to_vec()));
916
        }
917
        // Stored inserts are read from the bundle's own objects.
918122×
        let mut by_ref: Option<std::collections::HashMap<ObjectRef, usize>> = None;
919122×
        for c in o::array(field(m, 0, "changes")?, "changes")? {
920106×
            let pair = o::array(c, "change entry")?;
921106×
            if pair.len() != 2 {
9220×
                return Err(schema("change entry: expected [change, sigs]"));
923106×
            }
924106×
            let encoded = o::bytes(&pair[0], "change")?;
925106×
            b.hashes
926106×
                .push(crate::hash::hash_object(ObjectType::Change, encoded));
927106×
            let change = Change::decode_with(encoded, &mut |text, count, form| {
9280×
                let by_ref = by_ref.get_or_insert_with(|| {
9290×
                    b.objects
9300×
                        .iter()
9310×
                        .enumerate()
9320×
                        .map(|(i, (ty, body))| (crate::hash::hash_object(*ty, body), i))
9330×
                        .collect()
9340×
                });
9350×
                let get =
9360×
                    |r: &ObjectRef, want: ObjectType| match by_ref.get(r).map(|i| &b.objects[*i]) {
9370×
                        Some((ty, body)) if *ty == want => Ok(body),
9380×
                        _ => Err(ObjectError::Schema(format!(
9390×
                            "the bundle lacks {} {}",
9400×
                            want.name(),
9410×
                            r.short(12)
9420×
                        ))),
9430×
                    };
9440×
                let blob = crate::objects::Blob::decode(get(text, ObjectType::Blob)?)?;
9450×
                let mut content = Vec::with_capacity(blob.length as usize);
9460×
                for chunk in &blob.chunks {
9470×
                    content.extend_from_slice(get(chunk, ObjectType::Chunk)?);
948
                }
9490×
                crate::objects::text_lines(&content, count, form)
9500×
            })?;
951106×
            b.changes.push((change, sigs_from(&pair[1])?));
952
        }
953122×
        for a in o::array(field(m, 1, "attests")?, "attests")? {
95416×
            b.attests.push(attest_from(a)?);
955
        }
956122×
        if let Some(ps) = m.get(&3) {
957122×
            for p in o::array(ps, "policies")? {
9583×
                b.policies.push(policy_from(p)?);
959
            }
9600×
        }
961122×
        if let Some(cs) = m.get(&4) {
9627×
            for c in o::array(cs, "certificates")? {
9637×
                b.certificates.push(
9647×
                    crate::cert::SignedCertificate::decode(o::bytes(c, "certificate")?)
9657×
                        .map_err(|e| schema(&format!("certificate: {e}")))?,
966
                );
967
            }
968115×
        }
969122×
        Ok(b)
970122×
    }
971
97287×
    pub fn encode_bundle(b: &Bundle) -> Vec<u8> {
97387×
        cbor::encode(&bundle_value(b))
97487×
    }
97581×
    pub fn decode_bundle(bytes: &[u8]) -> Result<Bundle> {
97681×
        bundle_from_value(&cbor::decode(bytes).map_err(ObjectError::from)?)
97781×
    }
978
979135×
    pub fn encode_capabilities(id: [u8; 16]) -> Vec<u8> {
980135×
        cbor::encode(&Value::map([
981135×
            (0, Value::Array(vec![Value::Uint(PROTOCOL_VERSION)])),
982135×
            (1, Value::Bytes(id.to_vec())),
983135×
            (2, Value::Array(vec![Value::Text("seal".into())])),
984135×
        ]))
985135×
    }
986135×
    pub fn decode_capabilities(bytes: &[u8]) -> Result<[u8; 16]> {
987135×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
988135×
        let m = map(&v, "capabilities")?;
989135×
        let versions = o::array(field(m, 0, "versions")?, "versions")?;
990135×
        if !versions
991135×
            .iter()
992135×
            .any(|x| x.as_uint() == Some(PROTOCOL_VERSION))
993
        {
9940×
            return Err(RepoError::Msg(
9950×
                "remote does not speak protocol version 1".into(),
9960×
            ));
997135×
        }
998135×
        o::bytes(field(m, 1, "repo id")?, "repo id")?
999135×
            .try_into()
1000135×
            .map_err(|_| schema("repo id: expected 16 bytes"))
1001135×
    }
1002
1003210×
    fn tags_value(tags: &[TagRef]) -> Value {
1004
        Value::Array(
1005210×
            tags.iter()
1006210×
                .map(|t| {
100734×
                    let mut v = Value::map([
100834×
                        (0, Value::Text(t.name.clone())),
100934×
                        (1, Value::Bytes(t.state.0.to_vec())),
101034×
                        (2, hashes_value(&t.heads)),
101134×
                        (3, opt_attest_value(&t.attestation)),
101234×
                    ]);
1013
                    // Only when there is one; older peers ignore them
1014
                    // (oxygen#129).
101534×
                    if let Value::Map(m) = &mut v {
101634×
                        if t.accepted.is_some() {
10178×
                            m.insert(4, opt_attest_value(&t.accepted));
101826×
                        }
101934×
                        if let Some(l) = &t.logged {
10202×
                            m.insert(5, logged_value(l));
102132×
                        }
102234×
                        if !t.integration.is_empty() {
10232×
                            m.insert(6, integration_value(&t.integration));
102432×
                        }
10250×
                    }
102634×
                    v
102734×
                })
1028210×
                .collect(),
1029
        )
1030210×
    }
1031249×
    fn tags_from(v: &Value) -> Result<Vec<TagRef>> {
1032249×
        let mut out = Vec::new();
1033249×
        for t in o::array(v, "tags")? {
103450×
            let tm = map(t, "tag")?;
103550×
            out.push(TagRef {
103650×
                name: o::text(field(tm, 0, "name")?, "name")?.to_owned(),
103750×
                state: o::oref(field(tm, 1, "state")?, "state")?,
103850×
                heads: hashes_from(field(tm, 2, "heads")?)?,
103950×
                attestation: opt_attest_from(field(tm, 3, "attestation")?)?,
104050×
                accepted: match tm.get(&4) {
10418×
                    Some(a) => opt_attest_from(a)?,
104242×
                    None => None,
1043
                },
104450×
                logged: tm.get(&5).map(logged_from).transpose()?,
104550×
                integration: match tm.get(&6) {
10462×
                    Some(l) => integration_from(l)?,
104748×
                    None => Vec::new(),
1048
                },
1049
            });
1050
        }
1051249×
        Ok(out)
1052249×
    }
1053
1054
    /// The tags of a refs answer as oxy 0.5.0 read them (and the runners
1055
    /// built with it), keys 0 to 3 only: what an older reader makes of an
1056
    /// answer with keys 4 to 6.
1057
    #[cfg(test)]
10581×
    pub(super) fn tags_as_0_5_read_them(bytes: &[u8]) -> Result<Vec<TagRef>> {
10591×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
10601×
        let m = map(&v, "refs")?;
10611×
        let mut out = Vec::new();
10622×
        for t in o::array(field(m, 3, "tags")?, "tags")? {
10632×
            let tm = map(t, "tag")?;
10642×
            out.push(TagRef::new(
10652×
                o::text(field(tm, 0, "name")?, "name")?.to_owned(),
10662×
                o::oref(field(tm, 1, "state")?, "state")?,
10672×
                hashes_from(field(tm, 2, "heads")?)?,
10682×
                opt_attest_from(field(tm, 3, "attestation")?)?,
1069
            ));
1070
        }
10711×
        Ok(out)
10721×
    }
1073
1074
    /// A log place, `[entry number, entry bytes, [proof hash]]` (spec §14.8).
10754×
    fn logged_value(l: &Logged) -> Value {
10764×
        Value::Array(vec![
10774×
            Value::Uint(l.index),
10784×
            Value::Bytes(l.entry.clone()),
10794×
            proof_value(&l.proof),
10804×
        ])
10814×
    }
10824×
    fn logged_from(v: &Value) -> Result<Logged> {
10834×
        let a = o::array(v, "logged")?;
10844×
        if a.len() != 3 {
10850×
            return Err(schema("logged: expected [index, entry, proof]"));
10864×
        }
1087
        Ok(Logged {
10884×
            index: o::uint(&a[0], "index")?,
10894×
            entry: o::bytes(&a[1], "entry")?.to_vec(),
10904×
            proof: proof_from(&a[2])?,
1091
        })
10924×
    }
1093
1094
    /// Cosigned checkpoints holding an entry, `[[note, [proof hash]]]`.
10954×
    fn integration_value(integration: &[Integration]) -> Value {
1096
        Value::Array(
10974×
            integration
10984×
                .iter()
10994×
                .map(|i| Value::Array(vec![Value::Text(i.note.clone()), proof_value(&i.proof)]))
11004×
                .collect(),
1101
        )
11024×
    }
11034×
    fn integration_from(v: &Value) -> Result<Vec<Integration>> {
11044×
        let mut out = Vec::new();
11054×
        for i in o::array(v, "integration")? {
11064×
            let a = o::array(i, "integration")?;
11074×
            if a.len() != 2 {
11080×
                return Err(schema("integration: expected [note, proof]"));
11094×
            }
11104×
            out.push(Integration {
11114×
                note: o::text(&a[0], "note")?.to_owned(),
11124×
                proof: proof_from(&a[1])?,
1113
            });
1114
        }
11154×
        Ok(out)
11164×
    }
1117
1118165×
    pub fn encode_refs(id: [u8; 16], resp: &RefsResponse) -> Vec<u8> {
1119165×
        let mut v = Value::map([
1120
            (
1121
                0,
1122
                Value::Array(
1123165×
                    resp.refs
1124165×
                        .iter()
1125171×
                        .map(|r| {
1126171×
                            let mut v = Value::map([
1127171×
                                (0, Value::Text(r.name.clone())),
1128171×
                                (1, Value::Bytes(r.state.0.to_vec())),
1129171×
                                (2, hashes_value(&r.heads)),
1130171×
                                (3, opt_attest_value(&r.attestation)),
1131171×
                                (4, r.last_serial.map(Value::Uint).unwrap_or(Value::Null)),
1132171×
                            ]);
1133
                            // Only when there is one; older peers ignore it.
1134171×
                            if let Value::Map(m) = &mut v {
1135171×
                                if r.accepted.is_some() {
11369×
                                    m.insert(5, opt_attest_value(&r.accepted));
1137162×
                                }
1138171×
                                if let Some(l) = &r.logged {
11392×
                                    m.insert(6, logged_value(l));
1140169×
                                }
1141171×
                                if !r.integration.is_empty() {
11422×
                                    m.insert(7, integration_value(&r.integration));
1143169×
                                }
11440×
                            }
1145171×
                            v
1146171×
                        })
1147165×
                        .collect(),
1148
                ),
1149
            ),
1150165×
            (1, Value::Bytes(id.to_vec())),
1151165×
            (2, opt_policy_value(resp.policy.as_ref())),
1152165×
            (3, tags_value(&resp.tags)),
1153165×
            (
1154165×
                4,
1155165×
                Value::Array(resp.history.iter().map(policy_value).collect()),
1156165×
            ),
1157165×
            (
1158165×
                5,
1159165×
                resp.default_bookmark
1160165×
                    .clone()
1161165×
                    .map(Value::Text)
1162165×
                    .unwrap_or(Value::Null),
1163165×
            ),
1164
        ]);
1165165×
        if let Value::Map(m) = &mut v {
1166165×
            if let Some(log) = &resp.log {
11673×
                m.insert(6, Value::Text(log.clone()));
1168162×
            }
1169165×
            if !resp.withdrawn.is_empty() {
11700×
                m.insert(8, tags_value(&resp.withdrawn));
1171165×
            }
1172165×
            if !resp.witnesses.is_empty() {
11732×
                m.insert(
1174
                    7,
1175
                    Value::Array(
11762×
                        resp.witnesses
11772×
                            .iter()
11782×
                            .map(|(name, id)| {
11792×
                                Value::Array(vec![
11802×
                                    Value::Text(name.clone()),
11812×
                                    Value::Bytes(id.clone()),
11822×
                                ])
11832×
                            })
11842×
                            .collect(),
1185
                    ),
1186
                );
1187163×
            }
11880×
        }
1189165×
        cbor::encode(&v)
1190165×
    }
1191208×
    pub fn decode_refs(bytes: &[u8]) -> Result<([u8; 16], RefsResponse)> {
1192208×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
1193208×
        let m = map(&v, "refs")?;
1194208×
        let id: [u8; 16] = o::bytes(field(m, 1, "repo id")?, "repo id")?
1195208×
            .try_into()
1196208×
            .map_err(|_| schema("repo id: expected 16 bytes"))?;
1197208×
        let mut refs = Vec::new();
1198214×
        for r in o::array(field(m, 0, "refs")?, "refs")? {
1199214×
            let rm = map(r, "ref")?;
1200214×
            let ls = field(rm, 4, "last serial")?;
1201214×
            refs.push(RemoteRef {
1202214×
                name: o::text(field(rm, 0, "name")?, "name")?.to_owned(),
1203214×
                state: o::oref(field(rm, 1, "state")?, "state")?,
1204214×
                heads: hashes_from(field(rm, 2, "heads")?)?,
1205214×
                attestation: opt_attest_from(field(rm, 3, "attestation")?)?,
1206214×
                last_serial: if ls.is_null() {
1207181×
                    None
1208
                } else {
120933×
                    Some(o::uint(ls, "last serial")?)
1210
                },
1211214×
                accepted: match rm.get(&5) {
12129×
                    Some(a) => opt_attest_from(a)?,
1213205×
                    None => None,
1214
                },
1215214×
                logged: rm.get(&6).map(logged_from).transpose()?,
1216214×
                integration: match rm.get(&7) {
12172×
                    Some(l) => integration_from(l)?,
1218212×
                    None => Vec::new(),
1219
                },
1220
            });
1221
        }
1222208×
        let policy = match m.get(&2) {
1223208×
            Some(p) => opt_policy_from(p)?,
12240×
            None => None,
1225
        };
1226208×
        let tags = match m.get(&3) {
1227208×
            Some(t) => tags_from(t)?,
12280×
            None => Vec::new(),
1229
        };
1230208×
        let mut history = Vec::new();
1231208×
        if let Some(h) = m.get(&4) {
1232208×
            for p in o::array(h, "history")? {
123317×
                history.push(policy_from(p)?);
1234
            }
12350×
        }
1236208×
        let default_bookmark = match m.get(&5) {
1237139×
            Some(Value::Text(t)) => Some(t.clone()),
123869×
            _ => None,
1239
        };
1240208×
        let log = match m.get(&6) {
12413×
            Some(Value::Text(t)) => Some(t.clone()),
1242205×
            _ => None,
1243
        };
1244208×
        let mut witnesses = Vec::new();
1245208×
        if let Some(w) = m.get(&7) {
12462×
            for x in o::array(w, "witnesses")? {
12472×
                let a = o::array(x, "witness")?;
12482×
                if a.len() != 2 {
12490×
                    return Err(schema("witness: expected [name, identity]"));
12502×
                }
12512×
                witnesses.push((
12522×
                    o::text(&a[0], "witness name")?.to_owned(),
12532×
                    o::bytes(&a[1], "witness identity")?.to_vec(),
1254
                ));
1255
            }
1256206×
        }
1257208×
        let withdrawn = match m.get(&8) {
12580×
            Some(t) => tags_from(t)?,
1259208×
            None => Vec::new(),
1260
        };
1261208×
        Ok((
1262208×
            id,
1263208×
            RefsResponse {
1264208×
                refs,
1265208×
                policy,
1266208×
                tags,
1267208×
                history,
1268208×
                default_bookmark,
1269208×
                log,
1270208×
                witnesses,
1271208×
                withdrawn,
1272208×
            },
1273208×
        ))
1274208×
    }
1275
1276
    /// A proof's hashes, from the leaf upwards (spec §14.8).
12778×
    fn proof_value(proof: &[[u8; 32]]) -> Value {
12788×
        Value::Array(proof.iter().map(|h| Value::Bytes(h.to_vec())).collect())
12798×
    }
1280
12818×
    fn proof_from(v: &Value) -> Result<Vec<[u8; 32]>> {
12828×
        let mut proof = Vec::new();
12838×
        for h in o::array(v, "proof")? {
12848×
            proof.push(
12858×
                o::bytes(h, "proof hash")?
12868×
                    .try_into()
12878×
                    .map_err(|_| schema("proof hash: expected 32 bytes"))?,
1288
            );
1289
        }
12908×
        Ok(proof)
12918×
    }
1292
129352×
    pub fn encode_negotiate(have: &[ChangeHash], want: &[ChangeHash]) -> Vec<u8> {
129452×
        cbor::encode(&Value::map([
129552×
            (0, hashes_value(have)),
129652×
            (1, hashes_value(want)),
129752×
        ]))
129852×
    }
129952×
    pub fn decode_negotiate(bytes: &[u8]) -> Result<(Vec<ChangeHash>, Vec<ChangeHash>)> {
130052×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
130152×
        let m = map(&v, "negotiate")?;
1302
        Ok((
130352×
            hashes_from(field(m, 0, "have")?)?,
130452×
            hashes_from(field(m, 1, "want")?)?,
1305
        ))
130652×
    }
1307
1308
    /// `fetch` request: `{0: [changes], 1: max blob size or null}`.
130953×
    pub fn encode_fetch(hs: &[ChangeHash], max_blob: Option<u64>) -> Vec<u8> {
131053×
        cbor::encode(&Value::map([
131153×
            (0, hashes_value(hs)),
131253×
            (1, max_blob.map(Value::Uint).unwrap_or(Value::Null)),
131353×
        ]))
131453×
    }
131554×
    pub fn decode_fetch(bytes: &[u8]) -> Result<(Vec<ChangeHash>, Option<u64>)> {
131654×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
131754×
        let m = map(&v, "fetch")?;
131854×
        let max = match m.get(&1) {
131953×
            Some(x) if !x.is_null() => Some(o::uint(x, "max blob")?),
132052×
            _ => None,
1321
        };
132254×
        Ok((hashes_from(field(m, 0, "changes")?)?, max))
132354×
    }
1324
1325
    /// `shallow` request: `{0: [heads], 1: depth}`.
13261×
    pub fn encode_shallow(hs: &[ChangeHash], depth: u32) -> Vec<u8> {
13271×
        cbor::encode(&Value::map([
13281×
            (0, hashes_value(hs)),
13291×
            (1, Value::Uint(depth as u64)),
13301×
        ]))
13311×
    }
13321×
    pub fn decode_shallow(bytes: &[u8]) -> Result<(Vec<ChangeHash>, u32)> {
13331×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
13341×
        let m = map(&v, "shallow")?;
1335
        Ok((
13361×
            hashes_from(field(m, 0, "heads")?)?,
13371×
            o::u32_(field(m, 1, "depth")?, "depth")?,
1338
        ))
13391×
    }
1340
134154×
    pub fn encode_hashes(hs: &[ChangeHash]) -> Vec<u8> {
134254×
        cbor::encode(&Value::map([(0, hashes_value(hs))]))
134354×
    }
134453×
    pub fn decode_hashes(bytes: &[u8]) -> Result<Vec<ChangeHash>> {
134553×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
134653×
        hashes_from(field(map(&v, "hashes")?, 0, "hashes")?)
134753×
    }
1348
134945×
    pub fn encode_push(
135045×
        bundle: &Bundle,
135145×
        updates: &[RefUpdate],
135245×
        policy: Option<&SignedPolicy>,
135345×
        tags: &[TagRef],
135445×
    ) -> Vec<u8> {
135545×
        cbor::encode(&Value::map([
135645×
            (0, bundle_value(bundle)),
135745×
            (2, opt_policy_value(policy)),
135845×
            (3, tags_value(tags)),
1359
            (
1360
                1,
1361
                Value::Array(
136245×
                    updates
136345×
                        .iter()
136445×
                        .map(|u| {
136544×
                            Value::map([
136644×
                                (0, Value::Text(u.name.clone())),
136744×
                                (1, Value::Bytes(u.old_state.0.to_vec())),
136844×
                                (2, Value::Bytes(u.new_state.0.to_vec())),
136944×
                                (3, Value::Bool(u.force)),
137044×
                                (4, opt_attest_value(&u.attestation)),
137144×
                            ])
137244×
                        })
137345×
                        .collect(),
1374
                ),
1375
            ),
1376
        ]))
137745×
    }
1378
    /// A decoded push: bundle, bookmark updates, policy, tags.
1379
    pub type PushParts = (Bundle, Vec<RefUpdate>, Option<SignedPolicy>, Vec<TagRef>);
1380
138141×
    pub fn decode_push(bytes: &[u8]) -> Result<PushParts> {
138241×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
138341×
        let m = map(&v, "push")?;
138441×
        let bundle = bundle_from_value(field(m, 0, "bundle")?)?;
138541×
        let mut updates = Vec::new();
138641×
        for u in o::array(field(m, 1, "updates")?, "updates")? {
138740×
            let um = map(u, "update")?;
138840×
            updates.push(RefUpdate {
138940×
                name: o::text(field(um, 0, "name")?, "name")?.to_owned(),
139040×
                old_state: o::oref(field(um, 1, "old_state")?, "old_state")?,
139140×
                new_state: o::oref(field(um, 2, "new_state")?, "new_state")?,
139240×
                force: field(um, 3, "force")?
139340×
                    .as_bool()
139440×
                    .ok_or_else(|| schema("force: expected bool"))?,
139540×
                attestation: opt_attest_from(field(um, 4, "attestation")?)?,
1396
            });
1397
        }
139841×
        let policy = match m.get(&2) {
139941×
            Some(p) => opt_policy_from(p)?,
14000×
            None => None,
1401
        };
140241×
        let tags = match m.get(&3) {
140341×
            Some(t) => tags_from(t)?,
14040×
            None => Vec::new(),
1405
        };
140641×
        Ok((bundle, updates, policy, tags))
140741×
    }
1408
140939×
    pub fn encode_push_response(results: &[RefResult]) -> Vec<u8> {
141039×
        cbor::encode(&Value::map([(
1411
            0,
1412
            Value::Array(
141339×
                results
141439×
                    .iter()
141545×
                    .map(|r| {
141645×
                        Value::map([
141745×
                            (0, Value::Text(r.name.clone())),
141845×
                            (1, Value::Bool(r.ok)),
141945×
                            (2, Value::Text(r.reason.clone())),
142045×
                        ])
142145×
                    })
142239×
                    .collect(),
1423
            ),
1424
        )]))
142539×
    }
142639×
    pub fn decode_push_response(bytes: &[u8]) -> Result<Vec<RefResult>> {
142739×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
142839×
        let m = map(&v, "push response")?;
142939×
        let mut out = Vec::new();
143045×
        for r in o::array(field(m, 0, "results")?, "results")? {
143145×
            let rm = map(r, "result")?;
143245×
            out.push(RefResult {
143345×
                name: o::text(field(rm, 0, "name")?, "name")?.to_owned(),
143445×
                ok: field(rm, 1, "ok")?
143545×
                    .as_bool()
143645×
                    .ok_or_else(|| schema("ok: expected bool"))?,
143745×
                reason: o::text(field(rm, 2, "reason")?, "reason")?.to_owned(),
1438
            });
1439
        }
144039×
        Ok(out)
144139×
    }
1442
}
1443
1444
#[cfg(test)]
1445
mod tests {
1446
    use super::*;
1447
    use crate::attest::AttestBody;
1448
    use crate::objects::Hlc;
1449
1450
    #[test]
14511×
    fn client_features_are_declared_and_read() {
14521×
        assert_eq!(CLIENT_FEATURES.join(","), "certified-tags");
14531×
        assert!(user_agent().starts_with("oxy/"));
14541×
        assert!(declares_feature(
14551×
            Some("certified-tags"),
14561×
            FEATURE_CERTIFIED_TAGS
1457
        ));
14581×
        assert!(declares_feature(
14591×
            Some("later-thing, Certified-Tags ,x"),
14601×
            FEATURE_CERTIFIED_TAGS
1461
        ));
14621×
        assert!(!declares_feature(
14631×
            Some("certified-tags-v2"),
14641×
            FEATURE_CERTIFIED_TAGS
14651×
        ));
14661×
        assert!(!declares_feature(Some(""), FEATURE_CERTIFIED_TAGS));
14671×
        assert!(!declares_feature(None, FEATURE_CERTIFIED_TAGS));
14681×
    }
1469
1470
    #[test]
14711×
    fn wire_round_trips() {
14721×
        let c = crate::objects::tests::sample_change();
14731×
        let sk = crate::identity::SecretKey {
14741×
            ed_seed: [1; 32],
14751×
            ml_seed: [2; 32],
14761×
        };
14771×
        let id = sk.identity("a", "b", 0);
14781×
        let key = id.hash();
14791×
        let sig = sk.sign(crate::identity::Domain::Change, &key, &c.hash());
14801×
        let seal = Attest::seal([3; 16], vec![c.hash()]);
14811×
        let seal_sig = sk.sign(crate::identity::Domain::Attest, &key, &seal.hash());
14821×
        let policy = Policy::single_root([3; 16], id.clone(), 99);
14831×
        let psig = sk.sign(crate::identity::Domain::Policy, &key, &policy.hash());
14841×
        let bundle = Bundle {
14851×
            changes: vec![(c.clone(), vec![sig.clone()])],
14861×
            attests: vec![SignedAttest {
14871×
                attest: seal.clone(),
14881×
                sigs: vec![seal_sig],
14891×
            }],
14901×
            objects: vec![
14911×
                (ObjectType::Identity, id.encode()),
14921×
                (ObjectType::Chunk, b"xyz".to_vec()),
14931×
            ],
14941×
            policies: vec![SignedPolicy {
14951×
                policy: policy.clone(),
14961×
                sigs: vec![psig.clone()],
14971×
            }],
14981×
            hashes: vec![],
14991×
            raw_changes: vec![],
15001×
            certificates: vec![],
15011×
        };
15021×
        let d = wire::decode_bundle(&wire::encode_bundle(&bundle)).unwrap();
15031×
        assert_eq!(
1504
            d.hashes,
15051×
            vec![c.hash()],
1506
            "the receiver hashes what it was sent"
1507
        );
15081×
        assert_eq!(d.changes, bundle.changes);
15091×
        assert_eq!(d.attests, bundle.attests);
15101×
        assert_eq!(d.objects, bundle.objects);
15111×
        assert_eq!(d.policies, bundle.policies);
15121×
        assert!(d.certificates.is_empty());
1513
        // Certificates (keyless, oxygenhub#241) travel as field 4, only
1514
        // when there are any: a bundle without them encodes as before.
15151×
        let plain = wire::encode_bundle(&bundle);
15161×
        let mut with = bundle.clone();
15171×
        let issuer_sk = crate::identity::SecretKey::generate();
15181×
        let issuer = issuer_sk.identity("hub", "h@x", 1);
15191×
        with.certificates.push(crate::cert::SignedCertificate::sign(
15201×
            crate::cert::Certificate {
15211×
                key: id.clone(),
15221×
                issuer: issuer.hash(),
15231×
                subject: "agent:a@b".into(),
15241×
                claims: vec![],
15251×
                scope: crate::identity::Scope::CHANGES,
15261×
                not_before: 1,
15271×
                expires: 2,
15281×
                grant: None,
15291×
            },
15301×
            &issuer,
15311×
            &issuer_sk,
1532
        ));
15331×
        let encoded = wire::encode_bundle(&with);
15341×
        assert_ne!(encoded, plain);
15351×
        assert_eq!(
15361×
            wire::decode_bundle(&encoded).unwrap().certificates,
1537
            with.certificates
1538
        );
15391×
        with.certificates.clear();
15401×
        assert_eq!(wire::encode_bundle(&with), plain);
1541
15421×
        let att = Attest {
15431×
            repo: [3; 16],
15441×
            hlc: Hlc::default(),
15451×
            body: AttestBody::Ref {
15461×
                name: "main".into(),
15471×
                old_state: ObjectRef([1; 32]),
15481×
                new_state: ObjectRef([2; 32]),
15491×
                serial: 4,
15501×
            },
15511×
        };
15521×
        let refs = vec![
15531×
            RemoteRef {
15541×
                name: "main".into(),
15551×
                state: ObjectRef([2; 32]),
15561×
                heads: vec![c.hash()],
15571×
                attestation: Some(SignedAttest {
15581×
                    attest: att.clone(),
15591×
                    sigs: vec![sig.clone()],
15601×
                }),
15611×
                last_serial: Some(4),
15621×
                accepted: None,
15631×
                logged: None,
15641×
                integration: vec![],
15651×
            },
15661×
            RemoteRef {
15671×
                name: "dev".into(),
15681×
                state: ObjectRef([5; 32]),
15691×
                heads: vec![],
15701×
                attestation: None,
15711×
                last_serial: None,
15721×
                accepted: None,
15731×
                logged: None,
15741×
                integration: vec![],
15751×
            },
1576
        ];
15771×
        let tag = TagRef::new("v1".into(), ObjectRef([2; 32]), vec![c.hash()], None);
15781×
        let mut resp = RefsResponse {
15791×
            refs,
15801×
            policy: Some(SignedPolicy {
15811×
                policy: policy.clone(),
15821×
                sigs: vec![psig.clone()],
15831×
            }),
15841×
            tags: vec![tag.clone()],
15851×
            history: vec![SignedPolicy {
15861×
                policy: policy.clone(),
15871×
                sigs: vec![],
15881×
            }],
15891×
            default_bookmark: Some("develop".into()),
15901×
            log: Some("hub.example/log\n2\nroot\n\n- sig\n".into()),
15911×
            witnesses: vec![],
15921×
            withdrawn: vec![],
15931×
        };
1594
        // Without integrated times (spec §14.8) nothing is added: an old
1595
        // peer's answer, and what it reads.
15961×
        let old = wire::encode_refs([3; 16], &resp);
15971×
        let back = wire::decode_refs(&old).unwrap().1;
15982×
        assert!(back.witnesses.is_empty() && back.refs.iter().all(|r| r.integration.is_empty()));
15991×
        resp.refs[1].logged = Some(Logged {
16001×
            index: 41,
16011×
            entry: vec![1, 2, 3],
16021×
            proof: vec![[9; 32], [8; 32]],
16031×
        });
16041×
        resp.refs[1].integration = vec![Integration {
16051×
            note: "hub.example/log\n42\nroot\n\n- sig\n".into(),
16061×
            proof: vec![[7; 32]],
16071×
        }];
16081×
        resp.witnesses = vec![("w.example".into(), vec![4, 5, 6])];
16091×
        let new = wire::encode_refs([3; 16], &resp);
16101×
        let (id_back, back) = wire::decode_refs(&new).unwrap();
16111×
        assert_eq!(back.log, resp.log);
16121×
        assert_eq!(back.refs[1].logged, resp.refs[1].logged);
16131×
        assert_eq!(back.refs[1].integration, resp.refs[1].integration);
16141×
        assert_eq!(back.witnesses, resp.witnesses);
16151×
        assert_eq!(back.refs[0].logged, None);
1616
        // The new keys are 7s an old reader never asks for.
16171×
        let crate::cbor::Value::Map(m) = crate::cbor::decode(&new).unwrap() else {
16180×
            panic!()
1619
        };
16201×
        assert!(m.contains_key(&7));
16211×
        assert_eq!(id_back, [3; 16]);
16221×
        assert_eq!(back.refs.len(), 2);
16231×
        assert_eq!(back.refs[0].attestation.as_ref().unwrap().attest, att);
16241×
        assert_eq!(back.refs[1].last_serial, None);
16251×
        assert_eq!(back.policy.as_ref().unwrap().policy, policy);
16261×
        assert_eq!(back.history, resp.history);
16271×
        assert_eq!(back.tags, vec![tag.clone()]);
1628
1629
        // A tag's acceptance and log place (oxygen#129): keys 4 to 6, only
1630
        // when there are any, so a tag without them encodes as before.
16311×
        let crate::cbor::Value::Map(m) = crate::cbor::decode(&new).unwrap() else {
16320×
            panic!()
1633
        };
16341×
        let crate::cbor::Value::Array(tags) = &m[&3] else {
16350×
            panic!()
1636
        };
16371×
        let crate::cbor::Value::Map(plain) = &tags[0] else {
16380×
            panic!()
1639
        };
16401×
        assert_eq!(plain.keys().copied().collect::<Vec<_>>(), vec![0, 1, 2, 3]);
16411×
        let mut full = tag.clone();
16421×
        full.name = "v2".into();
16431×
        full.attestation = Some(SignedAttest {
16441×
            attest: att.clone(),
16451×
            sigs: vec![sig.clone()],
16461×
        });
16471×
        full.accepted = full.attestation.clone();
16481×
        full.logged = Some(Logged {
16491×
            index: 7,
16501×
            entry: vec![4],
16511×
            proof: vec![[3; 32]],
16521×
        });
16531×
        full.integration = vec![Integration {
16541×
            note: "hub.example/log\n8\nroot\n\n- sig\n".into(),
16551×
            proof: vec![],
16561×
        }];
16571×
        resp.tags = vec![full.clone(), tag.clone()];
16581×
        let bytes = wire::encode_refs([3; 16], &resp);
16591×
        assert_eq!(wire::decode_refs(&bytes).unwrap().1.tags, resp.tags);
1660
        // In a push too.
16611×
        let pushed = wire::encode_push(&Bundle::default(), &[], None, &resp.tags);
16621×
        assert_eq!(wire::decode_push(&pushed).unwrap().3, resp.tags);
1663
        // A reader that knows only keys 0 to 3 (oxy 0.5.0 and older, and
1664
        // the runners built with it) reads the same tags from the new answer.
16651×
        let stripped: Vec<TagRef> = resp
16661×
            .tags
16671×
            .iter()
16682×
            .map(|t| {
16692×
                TagRef::new(
16702×
                    t.name.clone(),
16712×
                    t.state,
16722×
                    t.heads.clone(),
16732×
                    t.attestation.clone(),
1674
                )
16752×
            })
16761×
            .collect();
16771×
        assert_eq!(wire::tags_as_0_5_read_them(&bytes).unwrap(), stripped);
1678
16791×
        let (h, w) = wire::decode_negotiate(&wire::encode_negotiate(
16801×
            &[ObjectRef([1; 32])],
16811×
            &[ObjectRef([2; 32])],
16821×
        ))
16831×
        .unwrap();
16841×
        assert_eq!((h, w), (vec![ObjectRef([1; 32])], vec![ObjectRef([2; 32])]));
16851×
        assert_eq!(
16861×
            wire::decode_hashes(&wire::encode_hashes(&[c.hash()])).unwrap(),
16871×
            vec![c.hash()]
1688
        );
16891×
        assert_eq!(
16901×
            wire::decode_fetch(&wire::encode_fetch(&[c.hash()], Some(4096))).unwrap(),
16911×
            (vec![c.hash()], Some(4096))
1692
        );
16931×
        assert_eq!(
16941×
            wire::decode_fetch(&wire::encode_fetch(&[], None)).unwrap(),
16951×
            (vec![], None)
1696
        );
16971×
        assert_eq!(
16981×
            wire::decode_shallow(&wire::encode_shallow(&[c.hash()], 3)).unwrap(),
16991×
            (vec![c.hash()], 3)
1700
        );
1701
        // An old-style fetch request without the filter field still decodes.
17021×
        assert_eq!(
17031×
            wire::decode_fetch(&wire::encode_hashes(&[c.hash()])).unwrap(),
17041×
            (vec![c.hash()], None)
1705
        );
1706
17071×
        let up = RefUpdate {
17081×
            name: "main".into(),
17091×
            old_state: ObjectRef([1; 32]),
17101×
            new_state: ObjectRef([2; 32]),
17111×
            force: true,
17121×
            attestation: Some(SignedAttest {
17131×
                attest: att,
17141×
                sigs: vec![sig],
17151×
            }),
17161×
        };
17171×
        let sp = SignedPolicy {
17181×
            policy,
17191×
            sigs: vec![psig],
17201×
        };
17211×
        let (b2, ups, pol, tags) = wire::decode_push(&wire::encode_push(
17221×
            &bundle,
17231×
            std::slice::from_ref(&up),
17241×
            Some(&sp),
17251×
            std::slice::from_ref(&tag),
17261×
        ))
17271×
        .unwrap();
17281×
        assert_eq!(pol, Some(sp));
17291×
        assert_eq!(tags, vec![tag]);
17301×
        assert_eq!(b2.changes.len(), 1);
17311×
        assert_eq!(ups[0].name, "main");
17321×
        assert!(ups[0].force);
17331×
        assert_eq!(ups[0].attestation, up.attestation);
17341×
        let res = vec![RefResult {
17351×
            name: "main".into(),
17361×
            ok: false,
17371×
            reason: "stale".into(),
17381×
        }];
17391×
        assert_eq!(
17401×
            wire::decode_push_response(&wire::encode_push_response(&res)).unwrap(),
1741
            res
1742
        );
17431×
        assert_eq!(
17441×
            wire::decode_capabilities(&wire::encode_capabilities([7; 16])).unwrap(),
1745
            [7; 16]
1746
        );
17471×
    }
1748
}