OXYGENHUB

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

1100 of 1263 lines run, 179 of 266 functions · run #388 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 {
2501193×
    pub fn open(path: &Path) -> Result<LocalRemote> {
251
        Ok(LocalRemote {
2521193×
            repo: Repo::open(path)?,
2531193×
            claimed_id: None,
254
        })
2551193×
    }
256
}
257
258
impl Remote for LocalRemote {
259936×
    fn repo_id(&self) -> Result<[u8; 16]> {
260936×
        self.repo.id()
261936×
    }
262935×
    fn refs(&self) -> Result<RefsResponse> {
263935×
        self.repo.remote_refs()
264935×
    }
265369×
    fn negotiate(&self, have: &[ChangeHash], want: &[ChangeHash]) -> Result<Vec<ChangeHash>> {
266369×
        self.repo.negotiate(have, want)
267369×
    }
268373×
    fn fetch(&self, changes: &[ChangeHash], max_blob: Option<u64>) -> Result<Bundle> {
269373×
        self.repo.bundle_raw_for(changes, max_blob)
270373×
    }
2715×
    fn objects(&self, refs: &[ObjectRef]) -> Result<Vec<(ObjectType, Vec<u8>)>> {
2725×
        self.repo.objects_for(refs)
2735×
    }
2743×
    fn checkpoint(&self, heads: &[ChangeHash]) -> Result<Bundle> {
2753×
        self.repo.checkpoint_bundle_for(heads)
2763×
    }
2773×
    fn shallow(&self, heads: &[ChangeHash], depth: u32) -> Result<Vec<ChangeHash>> {
2783×
        self.repo.shallow_changes(heads, depth)
2793×
    }
280282×
    fn push(
281282×
        &self,
282282×
        bundle: Bundle,
283282×
        updates: Vec<RefUpdate>,
284282×
        policy: Option<SignedPolicy>,
285282×
        tags: Vec<TagRef>,
286282×
    ) -> Result<Vec<RefResult>> {
287282×
        if self.repo.is_unbound() {
28815×
            match self.claimed_id {
28915×
                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
            }
297267×
        }
298282×
        self.repo.receive_push(bundle, updates, policy, tags)
299282×
    }
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.
3431252×
pub fn open_store(
3441252×
    url: &str,
3451252×
    options: &RemoteOptions,
3461252×
) -> Option<crate::strata::Result<Box<dyn crate::strata::Store>>> {
3471252×
    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
        );
3521193×
    }
3531193×
    let openers = STORE_OPENERS.lock().unwrap_or_else(|p| p.into_inner());
3541193×
    openers.iter().find_map(|open| open(url, options))
3551252×
}
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>`.
379183×
pub fn user_agent() -> String {
380183×
    format!("oxy/{}", env!("CARGO_PKG_VERSION"))
381183×
}
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.
386152×
pub fn declares_feature(header: Option<&str>, feature: &str) -> bool {
387152×
    header.is_some_and(|h| h.split(',').any(|f| f.trim().eq_ignore_ascii_case(feature)))
388152×
}
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.
402186×
pub fn tls_client_config(ca: Option<&Path>) -> Result<Arc<rustls::ClientConfig>> {
403186×
    let mut roots = rustls::RootCertStore::empty();
404186×
    roots.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
405186×
    if let Some(path) = ca {
4065×
        let pem = std::fs::read(path)
4075×
            .map_err(|e| RepoError::Msg(format!("reading CA file {}: {e}", path.display())))?;
4085×
        let certs = rustls_pemfile::certs(&mut pem.as_slice())
4095×
            .collect::<std::result::Result<Vec<_>, _>>()
4105×
            .map_err(|e| RepoError::Msg(format!("parsing CA file {}: {e}", path.display())))?;
4115×
        if certs.is_empty() {
4120×
            return Err(RepoError::Msg(format!(
4130×
                "CA file {} holds no certificates",
4140×
                path.display()
4150×
            )));
4165×
        }
4175×
        for c in certs {
4185×
            roots
4195×
                .add(c)
4205×
                .map_err(|e| RepoError::Msg(format!("CA file {}: {e}", path.display())))?;
421
        }
422181×
    }
423186×
    let cfg = rustls::ClientConfig::builder_with_provider(Arc::new(
424186×
        rustls::crypto::ring::default_provider(),
425
    ))
426186×
    .with_safe_default_protocol_versions()
427186×
    .map_err(|e| RepoError::Msg(e.to_string()))?
428186×
    .with_root_certificates(roots)
429186×
    .with_no_client_auth();
430186×
    Ok(Arc::new(cfg))
431186×
}
432
433
impl HttpRemote {
434180×
    pub fn new(base: &str, options: &RemoteOptions) -> Result<HttpRemote> {
435180×
        refuse_plain_token(base, options)?;
436180×
        let agent = ureq::AgentBuilder::new()
437180×
            .tls_config(tls_client_config(options.ca.as_deref())?)
438180×
            .user_agent(&user_agent())
439180×
            .build();
440180×
        Ok(HttpRemote {
441180×
            base: base.trim_end_matches('/').to_string(),
442180×
            token: Mutex::new(options.token.clone()),
443180×
            fallbacks: Mutex::new(options.fallback_tokens.iter().rev().cloned().collect()),
444180×
            repo_id: options.repo_id,
445180×
            agent,
446180×
        })
447180×
    }
448
449
    /// A request, tried again with the next fallback token while the
450
    /// hub refuses the one in use (oxygen#112).
451453×
    fn call(&self, post: bool, endpoint: &str, body: Option<&[u8]>) -> Result<Vec<u8>> {
452
        loop {
453454×
            let token = self.token.lock().unwrap_or_else(|p| p.into_inner()).clone();
454454×
            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
                }
470451×
                other => return other,
471
            }
472
        }
473453×
    }
474
475454×
    fn call_once(
476454×
        &self,
477454×
        post: bool,
478454×
        endpoint: &str,
479454×
        body: Option<&[u8]>,
480454×
        token: Option<&str>,
481454×
    ) -> Result<Vec<u8>> {
482454×
        let url = format!("{}/oxy/v1/{endpoint}", self.base);
483454×
        let mut req = if post {
484159×
            self.agent.post(&url)
485
        } else {
486295×
            self.agent.get(&url)
487
        };
488454×
        req = req
489454×
            .set("Accept", CONTENT_TYPE)
490454×
            .set(FEATURES_HEADER, &CLIENT_FEATURES.join(","));
491454×
        if let Some(t) = token {
49222×
            req = req.set("Authorization", &format!("Bearer {t}"));
493432×
        }
494454×
        if let Some(id) = &self.repo_id {
495421×
            req = req.set(REPO_ID_HEADER, &hex::encode(id));
496421×
        }
497454×
        let resp = match body {
498159×
            Some(b) => req.set("Content-Type", CONTENT_TYPE).send_bytes(b),
499295×
            None => req.call(),
500
        };
50112×
        match resp {
502442×
            Ok(r) => {
503442×
                let mut out = Vec::new();
504442×
                r.into_reader()
505442×
                    .read_to_end(&mut out)
506442×
                    .map_err(|e| RepoError::Msg(format!("{url}: {e}")))?;
507442×
                Ok(out)
508
            }
5099×
            Err(ureq::Error::Status(code, r)) => {
5109×
                let text = r.into_string().unwrap_or_default();
511
                // The hint comes from the status alone: the server's text
512
                // (a host's reason for refusing a push, several lines
513
                // perhaps) is shown as it is, never read for hints. A
514
                // proxy's HTML error page is shown by its title only
515
                // (oxygen#133).
5169×
                let status = format!("{url}: HTTP {code}");
5179×
                let msg = format!("{status}: {}", plain_error_text(&text));
5189×
                Err(RepoError::Msg(match hint_for(&status) {
5198×
                    Some(h) => format!("{msg}\n  hint: {h}"),
5201×
                    None => msg,
521
                }))
522
            }
523
            // The transport error already names the URL.
5243×
            Err(e) => Err(RepoError::Msg(with_hint(e.to_string()))),
525
        }
526454×
    }
527
}
528
529
/// Whether a failed request's message says the hub refused its token:
530
/// HTTP 401, 403, or 404 (a hub hides a private repository from a token
531
/// that may not read it).
5324×
fn refused(message: &str) -> bool {
5334×
    [": HTTP 401", ": HTTP 403", ": HTTP 404"]
5344×
        .iter()
5356×
        .any(|c| message.contains(c))
5364×
}
537
538
/// Refuse to send a token where anyone on the way could read it: plain
539
/// `http` to another machine (see [`crate::credentials::token_allowed`]).
540182×
fn refuse_plain_token(url: &str, options: &RemoteOptions) -> Result<()> {
541182×
    if options.token.is_some() && !crate::credentials::token_allowed(url) {
5420×
        return Err(RepoError::Msg(format!(
5430×
            "{url}: refusing to send a token over plain http; use https"
5440×
        )));
545182×
    }
546182×
    Ok(())
547182×
}
548
549
/// What to do about a failed request, recognised from its message.
55021×
pub fn hint_for(message: &str) -> Option<&'static str> {
55121×
    let m = message.to_ascii_lowercase();
55221×
    let hint = if m.contains("http 401") {
5536×
        "the hub needs you signed in, or did not accept the token: run `oxy auth login HUB` (pushing needs repo:write)"
55415×
    } else if m.contains("http 403") {
5551×
        "the token or account lacks permission: pushing needs a token with repo:write and write access to the repository"
55614×
    } else if m.contains("http 413") {
5571×
        "the request was larger than the server, or a proxy in front of it, takes at once (Cloudflare's limit is 100 MB): push in smaller parts with `oxy config push.batch-bytes 33554432`, then push again"
55813×
    } else if m.contains("http 404") {
5594×
        "nothing at this URL that you can see: check the owner and repository name; a private repository needs you signed in (`oxy auth login HUB`)"
5609×
    } else if m.contains("unknownissuer")
5617×
        || m.contains("unknown issuer")
5627×
        || m.contains("certificate")
5636×
        || m.contains("invalidcertificate")
564
    {
5653×
        "the server's certificate is not trusted: for a hub with a self-signed certificate, download it from /.well-known/oxyhub-ca.pem on the hub and run `oxy config remote.<remote>.ca FILE`"
5666×
    } else if m.contains("connection refused") {
5673×
        "nothing is listening there: check the URL and port, and that the server is running"
5683×
    } else if m.contains("dns")
5692×
        || m.contains("failed to lookup")
5702×
        || m.contains("name or service not known")
571
    {
5721×
        "the host name does not resolve: check the URL"
5732×
    } else if m.contains("timed out") || m.contains("timeout") {
5740×
        "the server did not answer in time: check the network, or try again"
575
    } else {
5762×
        return None;
577
    };
57819×
    Some(hint)
57921×
}
580
581
/// An error response's text as it is, unless it is an HTML page (a proxy's,
582
/// such as Cloudflare's 413): then its title, or a note that it was one.
58311×
fn plain_error_text(text: &str) -> String {
58411×
    let t = text.trim();
58511×
    let lower = t.to_ascii_lowercase();
58611×
    if !(lower.starts_with("<!doctype html") || lower.starts_with("<html")) {
58710×
        return t.to_string();
5881×
    }
5891×
    let title = lower
5901×
        .find("<title>")
5911×
        .and_then(|i| {
5921×
            lower[i + 7..]
5931×
                .find("</title>")
5941×
                .map(|j| t[i + 7..i + 7 + j].trim())
5951×
        })
5961×
        .filter(|s| !s.is_empty());
5971×
    match title {
5981×
        Some(s) => format!("{s} (an HTML error page, from a proxy in front of the server perhaps)"),
5990×
        None => "an HTML error page (from a proxy in front of the server perhaps)".into(),
600
    }
60111×
}
602
603
/// `message`, followed by what to do about it when that is known.
6043×
pub fn with_hint(message: String) -> String {
6053×
    match hint_for(&message) {
6063×
        Some(h) => format!("{message}\n  hint: {h}"),
6070×
        None => message,
608
    }
6093×
}
610
611
/// A JSON request to a hub API (`GET`, `POST` or `DELETE`), with the same
612
/// TLS trust and token rules as remotes. Returns the status and body, an
613
/// error status included; only transport failures are errors.
6140×
pub fn http_json(
6150×
    method: &str,
6160×
    url: &str,
6170×
    body: Option<&str>,
6180×
    options: &RemoteOptions,
6190×
) -> Result<(u16, String)> {
6200×
    refuse_plain_token(url, options)?;
6210×
    let agent = ureq::AgentBuilder::new()
6220×
        .tls_config(tls_client_config(options.ca.as_deref())?)
6230×
        .timeout(std::time::Duration::from_secs(60))
6240×
        .user_agent(&user_agent())
6250×
        .build();
6260×
    let mut req = agent.request(method, url).set("Accept", "application/json");
6270×
    if let Some(t) = &options.token {
6280×
        req = req.set("Authorization", &format!("Bearer {t}"));
6290×
    }
6300×
    let resp = match body {
6310×
        Some(b) => req.set("Content-Type", "application/json").send_string(b),
6320×
        None => req.call(),
633
    };
6340×
    match resp {
6350×
        Ok(r) => {
6360×
            let code = r.status();
6370×
            Ok((code, r.into_string().unwrap_or_default()))
638
        }
6390×
        Err(ureq::Error::Status(code, r)) => Ok((code, r.into_string().unwrap_or_default())),
6400×
        Err(e) => Err(RepoError::Msg(with_hint(e.to_string()))),
641
    }
6420×
}
643
644
/// An authenticated GET of any URL on a host, with the same TLS trust and
645
/// token as remotes use (for hub APIs: proposals). Returns the body.
6462×
pub fn http_get(url: &str, options: &RemoteOptions) -> Result<Vec<u8>> {
6472×
    refuse_plain_token(url, options)?;
6482×
    let agent = ureq::AgentBuilder::new()
6492×
        .tls_config(tls_client_config(options.ca.as_deref())?)
6502×
        .user_agent(&user_agent())
6512×
        .build();
6522×
    let mut req = agent.get(url).set("Accept", "application/json");
6532×
    if let Some(t) = &options.token {
6540×
        req = req.set("Authorization", &format!("Bearer {t}"));
6552×
    }
6562×
    match req.call() {
6572×
        Ok(r) => {
6582×
            let mut out = Vec::new();
6592×
            r.into_reader()
6602×
                .read_to_end(&mut out)
6612×
                .map_err(|e| RepoError::Msg(format!("{url}: {e}")))?;
6622×
            Ok(out)
663
        }
6640×
        Err(ureq::Error::Status(code, r)) => {
6650×
            let text = r.into_string().unwrap_or_default();
6660×
            Err(RepoError::Msg(with_hint(format!(
6670×
                "{url}: HTTP {code}: {}",
6680×
                text.trim()
6690×
            ))))
670
        }
671
        // The transport error already names the URL.
6720×
        Err(e) => Err(RepoError::Msg(with_hint(e.to_string()))),
673
    }
6742×
}
675
676
impl Remote for HttpRemote {
677151×
    fn repo_id(&self) -> Result<[u8; 16]> {
678151×
        wire::decode_capabilities(&self.call(false, "capabilities", None)?)
679151×
    }
680144×
    fn refs(&self) -> Result<RefsResponse> {
681144×
        Ok(wire::decode_refs(&self.call(false, "refs", None)?)?.1)
682144×
    }
68356×
    fn negotiate(&self, have: &[ChangeHash], want: &[ChangeHash]) -> Result<Vec<ChangeHash>> {
68456×
        wire::decode_hashes(&self.call(
685
            true,
68656×
            "negotiate",
68756×
            Some(&wire::encode_negotiate(have, want)),
6880×
        )?)
68956×
    }
69056×
    fn fetch(&self, changes: &[ChangeHash], max_blob: Option<u64>) -> Result<Bundle> {
69156×
        wire::decode_bundle(&self.call(
692
            true,
69356×
            "fetch",
69456×
            Some(&wire::encode_fetch(changes, max_blob)),
6950×
        )?)
69656×
    }
6971×
    fn objects(&self, refs: &[ObjectRef]) -> Result<Vec<(ObjectType, Vec<u8>)>> {
698
        Ok(
6991×
            wire::decode_bundle(&self.call(true, "objects", Some(&wire::encode_hashes(refs)))?)?
700
                .objects,
701
        )
7021×
    }
7030×
    fn checkpoint(&self, heads: &[ChangeHash]) -> Result<Bundle> {
7040×
        let body = {
7050×
            let _t = crate::timing::phase("remote: checkpoint answer");
7060×
            self.call(true, "checkpoint", Some(&wire::encode_hashes(heads)))?
707
        };
7080×
        let _t = crate::timing::phase("remote: decode the checkpoint");
7090×
        wire::decode_bundle(&body)
7100×
    }
7110×
    fn shallow(&self, heads: &[ChangeHash], depth: u32) -> Result<Vec<ChangeHash>> {
7120×
        wire::decode_hashes(&self.call(
713
            true,
7140×
            "shallow",
7150×
            Some(&wire::encode_shallow(heads, depth)),
7160×
        )?)
7170×
    }
71845×
    fn push(
71945×
        &self,
72045×
        bundle: Bundle,
72145×
        updates: Vec<RefUpdate>,
72245×
        policy: Option<SignedPolicy>,
72345×
        tags: Vec<TagRef>,
72445×
    ) -> Result<Vec<RefResult>> {
72545×
        wire::decode_push_response(&self.call(
726
            true,
72745×
            "push",
72845×
            Some(&wire::encode_push(
72945×
                &bundle,
73045×
                &updates,
73145×
                policy.as_ref(),
73245×
                &tags,
73345×
            )),
7345×
        )?)
73545×
    }
736
}
737
738
/// A remote's URL as it is stored: an `http(s)://` URL as given, a local
739
/// path made absolute (with its `file://` kept), so it still names the same
740
/// repository from inside the clone (oxygen#57).
741292×
pub fn stored_url(url: &str) -> String {
742
    // Only a path is made absolute: a plain one, or one behind file:// or
743
    // dir://. Every other URL (a hub, a bucket) is kept as written.
744292×
    let (prefix, path) = match (url.strip_prefix("file://"), url.strip_prefix("dir://")) {
7451×
        (Some(p), _) => ("file://", p),
74611×
        (_, Some(p)) => ("dir://", p),
747280×
        _ if url.contains("://") => return url.to_string(),
748251×
        _ => ("", url),
749
    };
750263×
    match std::path::absolute(path) {
751263×
        Ok(abs) => format!("{prefix}{}", abs.display()),
7520×
        Err(_) => url.to_string(),
753
    }
754292×
}
755
756
/// Open a remote by URL: a local path (optionally `file://`), `http(s)://`
757
/// (a hub), or a store (`dir://`, and whatever openers are registered).
7581420×
pub fn open_remote(url: &str, options: &RemoteOptions) -> Result<Box<dyn Remote>> {
7591420×
    if url.starts_with("http://") || url.starts_with("https://") {
760180×
        return Ok(Box::new(HttpRemote::new(url, options)?));
7611240×
    }
7621240×
    if let Some(store) = open_store(url, options) {
76348×
        return crate::repo::strata::open_store_remote(store?, options);
7641192×
    }
7651192×
    let path = url.strip_prefix("file://").unwrap_or(url);
7661192×
    if path.contains("://") {
7670×
        return Err(RepoError::Msg(format!("unsupported remote URL {url:?}")));
7681192×
    }
7691192×
    let mut local = LocalRemote::open(Path::new(path))?;
7701192×
    local.claimed_id = options.repo_id;
7711192×
    Ok(Box::new(local))
7721420×
}
773
774
// ---------------------------------------------------------------- wire
775
776
/// CBOR encodings of the protocol messages (spec §16.1).
777
pub mod wire {
778
    use super::*;
779
7800×
    fn schema(msg: &str) -> RepoError {
7810×
        RepoError::Object(ObjectError::Schema(msg.into()))
7820×
    }
783261×
    fn sigs_value(sigs: &[Signature]) -> Value {
784261×
        Value::Array(sigs.iter().map(|s| s.to_value()).collect())
785261×
    }
786257×
    fn sigs_from(v: &Value) -> Result<Vec<Signature>> {
787257×
        Ok(o::array(v, "signatures")?
788257×
            .iter()
789257×
            .map(Signature::from_value)
790257×
            .collect::<std::result::Result<Vec<_>, _>>()?)
791257×
    }
792448×
    fn hashes_value(hs: &[ObjectRef]) -> Value {
793596×
        Value::Array(hs.iter().map(|h| Value::Bytes(h.0.to_vec())).collect())
794448×
    }
795509×
    fn hashes_from(v: &Value) -> Result<Vec<ObjectRef>> {
796509×
        Ok(o::array(v, "hashes")?
797509×
            .iter()
798658×
            .map(|h| o::oref(h, "hash"))
799509×
            .collect::<std::result::Result<Vec<_>, _>>()?)
800509×
    }
80191×
    fn attest_value(sa: &SignedAttest) -> Value {
80291×
        Value::Array(vec![Value::Bytes(sa.attest.encode()), sigs_value(&sa.sigs)])
80391×
    }
804106×
    fn attest_from(v: &Value) -> Result<SignedAttest> {
805106×
        let a = o::array(v, "signed attest")?;
806106×
        if a.len() != 2 {
8070×
            return Err(schema("signed attest: expected [attest, sigs]"));
808106×
        }
809
        Ok(SignedAttest {
810106×
            attest: Attest::decode(o::bytes(&a[0], "attest")?)?,
811106×
            sigs: sigs_from(&a[1])?,
812
        })
813106×
    }
814279×
    fn opt_attest_value(sa: &Option<SignedAttest>) -> Value {
815279×
        sa.as_ref().map(attest_value).unwrap_or(Value::Null)
816279×
    }
817336×
    fn opt_attest_from(v: &Value) -> Result<Option<SignedAttest>> {
818336×
        if v.is_null() {
819246×
            Ok(None)
820
        } else {
82190×
            attest_from(v).map(Some)
822
        }
823336×
    }
824
    /// `[policy bytes, [signature]]`: also the format of a policy proposal
825
    /// file exchanged between root holders (spec §14.5).
82645×
    pub fn policy_value(sp: &SignedPolicy) -> Value {
82745×
        Value::Array(vec![Value::Bytes(sp.policy.encode()), sigs_value(&sp.sigs)])
82845×
    }
82943×
    pub fn policy_from(v: &Value) -> Result<SignedPolicy> {
83043×
        let a = o::array(v, "signed policy")?;
83143×
        if a.len() != 2 {
8320×
            return Err(schema("signed policy: expected [policy, sigs]"));
83343×
        }
834
        Ok(SignedPolicy {
83543×
            policy: Policy::decode(o::bytes(&a[0], "policy")?)?,
83643×
            sigs: sigs_from(&a[1])?,
837
        })
83843×
    }
839223×
    fn opt_policy_value(sp: Option<&SignedPolicy>) -> Value {
840223×
        sp.map(policy_value).unwrap_or(Value::Null)
841223×
    }
842262×
    fn opt_policy_from(v: &Value) -> Result<Option<SignedPolicy>> {
843262×
        if v.is_null() {
844240×
            Ok(None)
845
        } else {
84622×
            policy_from(v).map(Some)
847
        }
848262×
    }
8491120×
    fn map<'a>(v: &'a Value, what: &str) -> Result<&'a o::Map> {
8501120×
        Ok(o::map(v, what)?)
8511120×
    }
8523162×
    fn field<'a>(m: &'a o::Map, k: u64, what: &str) -> Result<&'a Value> {
8533162×
        Ok(o::field(m, k, what)?)
8543162×
    }
855
856
    /// A bundle's value. Each change's text blobs and their chunks (spec
857
    /// §6.1) are added to its objects when they are not already there, so a
858
    /// bundle can always be read on its own.
859139×
    pub fn bundle_value(b: &Bundle) -> Value {
860139×
        let mut changes = Vec::with_capacity(b.raw_changes.len() + b.changes.len());
861
        // Changes as stored are already their encoding, their texts among
862
        // the objects.
863139×
        for (bytes, s) in &b.raw_changes {
8640×
            changes.push(Value::Array(vec![
8650×
                Value::Bytes(bytes.clone()),
8660×
                sigs_value(s),
8670×
            ]));
8680×
        }
869139×
        let mut texts: Vec<(ObjectType, Vec<u8>)> = Vec::new();
870139×
        let mut listed: Option<std::collections::HashSet<ObjectRef>> = None;
871139×
        for (c, s) in &b.changes {
872125×
            let (bytes, stored) = c.encode_parts();
873125×
            for t in stored {
8740×
                let listed = listed.get_or_insert_with(|| {
8750×
                    b.objects
8760×
                        .iter()
8770×
                        .map(|(ty, body)| crate::hash::hash_object(*ty, body))
8780×
                        .collect()
8790×
                });
8800×
                if !listed.insert(t.blob.hash()) {
8810×
                    continue;
8820×
                }
8830×
                for chunk in crate::chunk::chunks(&t.content) {
8840×
                    if listed.insert(crate::hash::hash_object(ObjectType::Chunk, chunk)) {
8850×
                        texts.push((ObjectType::Chunk, chunk.to_vec()));
8860×
                    }
887
                }
8880×
                texts.push((ObjectType::Blob, t.blob.encode()));
889
            }
890125×
            changes.push(Value::Array(vec![Value::Bytes(bytes), sigs_value(s)]));
891
        }
892139×
        let mut v = Value::map([
893139×
            (0, Value::Array(changes)),
894139×
            (
895139×
                1,
896139×
                Value::Array(b.attests.iter().map(attest_value).collect()),
897139×
            ),
898
            (
899
                2,
900
                Value::Array(
901139×
                    b.objects
902139×
                        .iter()
903139×
                        .chain(&texts)
904203×
                        .map(|(t, body)| {
905203×
                            Value::Array(vec![
906203×
                                Value::Text(t.name().into()),
907203×
                                Value::Bytes(body.clone()),
908203×
                            ])
909203×
                        })
910139×
                        .collect(),
911
                ),
912
            ),
913139×
            (
914139×
                3,
915139×
                Value::Array(b.policies.iter().map(policy_value).collect()),
916139×
            ),
917
        ]);
918
        // Only when there are any; older peers ignore the field.
919139×
        if !b.certificates.is_empty() {
9207×
            if let Value::Map(m) = &mut v {
9217×
                m.insert(
922
                    4,
923
                    Value::Array(
9247×
                        b.certificates
9257×
                            .iter()
9267×
                            .map(|c| Value::Bytes(c.encode()))
9277×
                            .collect(),
928
                    ),
929
                );
9300×
            }
931132×
        }
932139×
        v
933139×
    }
934
935129×
    pub fn bundle_from_value(v: &Value) -> Result<Bundle> {
936129×
        let m = map(v, "bundle")?;
937129×
        let mut b = Bundle::default();
938192×
        for ob in o::array(field(m, 2, "objects")?, "objects")? {
939192×
            let pair = o::array(ob, "object")?;
940192×
            if pair.len() != 2 {
9410×
                return Err(schema("object: expected [type, body]"));
942192×
            }
943192×
            let ty = ObjectType::from_name(o::text(&pair[0], "object type")?)
944192×
                .ok_or_else(|| schema("unknown object type"))?;
945192×
            b.objects
946192×
                .push((ty, o::bytes(&pair[1], "object body")?.to_vec()));
947
        }
948
        // Stored inserts are read from the bundle's own objects.
949129×
        let mut by_ref: Option<std::collections::HashMap<ObjectRef, usize>> = None;
950129×
        for c in o::array(field(m, 0, "changes")?, "changes")? {
951108×
            let pair = o::array(c, "change entry")?;
952108×
            if pair.len() != 2 {
9530×
                return Err(schema("change entry: expected [change, sigs]"));
954108×
            }
955108×
            let encoded = o::bytes(&pair[0], "change")?;
956108×
            b.hashes
957108×
                .push(crate::hash::hash_object(ObjectType::Change, encoded));
958108×
            let change = Change::decode_with(encoded, &mut |text, count, form| {
9590×
                let by_ref = by_ref.get_or_insert_with(|| {
9600×
                    b.objects
9610×
                        .iter()
9620×
                        .enumerate()
9630×
                        .map(|(i, (ty, body))| (crate::hash::hash_object(*ty, body), i))
9640×
                        .collect()
9650×
                });
9660×
                let get =
9670×
                    |r: &ObjectRef, want: ObjectType| match by_ref.get(r).map(|i| &b.objects[*i]) {
9680×
                        Some((ty, body)) if *ty == want => Ok(body),
9690×
                        _ => Err(ObjectError::Schema(format!(
9700×
                            "the bundle lacks {} {}",
9710×
                            want.name(),
9720×
                            r.short(12)
9730×
                        ))),
9740×
                    };
9750×
                let blob = crate::objects::Blob::decode(get(text, ObjectType::Blob)?)?;
9760×
                let mut content = Vec::with_capacity(blob.length as usize);
9770×
                for chunk in &blob.chunks {
9780×
                    content.extend_from_slice(get(chunk, ObjectType::Chunk)?);
979
                }
9800×
                crate::objects::text_lines(&content, count, form)
9810×
            })?;
982108×
            b.changes.push((change, sigs_from(&pair[1])?));
983
        }
984129×
        for a in o::array(field(m, 1, "attests")?, "attests")? {
98516×
            b.attests.push(attest_from(a)?);
986
        }
987129×
        if let Some(ps) = m.get(&3) {
988129×
            for p in o::array(ps, "policies")? {
9893×
                b.policies.push(policy_from(p)?);
990
            }
9910×
        }
992129×
        if let Some(cs) = m.get(&4) {
9937×
            for c in o::array(cs, "certificates")? {
9947×
                b.certificates.push(
9957×
                    crate::cert::SignedCertificate::decode(o::bytes(c, "certificate")?)
9967×
                        .map_err(|e| schema(&format!("certificate: {e}")))?,
997
                );
998
            }
999122×
        }
1000129×
        Ok(b)
1001129×
    }
1002
100392×
    pub fn encode_bundle(b: &Bundle) -> Vec<u8> {
100492×
        cbor::encode(&bundle_value(b))
100592×
    }
100686×
    pub fn decode_bundle(bytes: &[u8]) -> Result<Bundle> {
100786×
        bundle_from_value(&cbor::decode(bytes).map_err(ObjectError::from)?)
100886×
    }
1009
1010146×
    pub fn encode_capabilities(id: [u8; 16]) -> Vec<u8> {
1011146×
        cbor::encode(&Value::map([
1012146×
            (0, Value::Array(vec![Value::Uint(PROTOCOL_VERSION)])),
1013146×
            (1, Value::Bytes(id.to_vec())),
1014146×
            (2, Value::Array(vec![Value::Text("seal".into())])),
1015146×
        ]))
1016146×
    }
1017146×
    pub fn decode_capabilities(bytes: &[u8]) -> Result<[u8; 16]> {
1018146×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
1019146×
        let m = map(&v, "capabilities")?;
1020146×
        let versions = o::array(field(m, 0, "versions")?, "versions")?;
1021146×
        if !versions
1022146×
            .iter()
1023146×
            .any(|x| x.as_uint() == Some(PROTOCOL_VERSION))
1024
        {
10250×
            return Err(RepoError::Msg(
10260×
                "remote does not speak protocol version 1".into(),
10270×
            ));
1028146×
        }
1029146×
        o::bytes(field(m, 1, "repo id")?, "repo id")?
1030146×
            .try_into()
1031146×
            .map_err(|_| schema("repo id: expected 16 bytes"))
1032146×
    }
1033
1034223×
    fn tags_value(tags: &[TagRef]) -> Value {
1035
        Value::Array(
1036223×
            tags.iter()
1037223×
                .map(|t| {
103834×
                    let mut v = Value::map([
103934×
                        (0, Value::Text(t.name.clone())),
104034×
                        (1, Value::Bytes(t.state.0.to_vec())),
104134×
                        (2, hashes_value(&t.heads)),
104234×
                        (3, opt_attest_value(&t.attestation)),
104334×
                    ]);
1044
                    // Only when there is one; older peers ignore them
1045
                    // (oxygen#129).
104634×
                    if let Value::Map(m) = &mut v {
104734×
                        if t.accepted.is_some() {
10488×
                            m.insert(4, opt_attest_value(&t.accepted));
104926×
                        }
105034×
                        if let Some(l) = &t.logged {
10512×
                            m.insert(5, logged_value(l));
105232×
                        }
105334×
                        if !t.integration.is_empty() {
10542×
                            m.insert(6, integration_value(&t.integration));
105532×
                        }
10560×
                    }
105734×
                    v
105834×
                })
1059223×
                .collect(),
1060
        )
1061223×
    }
1062262×
    fn tags_from(v: &Value) -> Result<Vec<TagRef>> {
1063262×
        let mut out = Vec::new();
1064262×
        for t in o::array(v, "tags")? {
106550×
            let tm = map(t, "tag")?;
106650×
            out.push(TagRef {
106750×
                name: o::text(field(tm, 0, "name")?, "name")?.to_owned(),
106850×
                state: o::oref(field(tm, 1, "state")?, "state")?,
106950×
                heads: hashes_from(field(tm, 2, "heads")?)?,
107050×
                attestation: opt_attest_from(field(tm, 3, "attestation")?)?,
107150×
                accepted: match tm.get(&4) {
10728×
                    Some(a) => opt_attest_from(a)?,
107342×
                    None => None,
1074
                },
107550×
                logged: tm.get(&5).map(logged_from).transpose()?,
107650×
                integration: match tm.get(&6) {
10772×
                    Some(l) => integration_from(l)?,
107848×
                    None => Vec::new(),
1079
                },
1080
            });
1081
        }
1082262×
        Ok(out)
1083262×
    }
1084
1085
    /// The tags of a refs answer as oxy 0.5.0 read them (and the runners
1086
    /// built with it), keys 0 to 3 only: what an older reader makes of an
1087
    /// answer with keys 4 to 6.
1088
    #[cfg(test)]
10891×
    pub(super) fn tags_as_0_5_read_them(bytes: &[u8]) -> Result<Vec<TagRef>> {
10901×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
10911×
        let m = map(&v, "refs")?;
10921×
        let mut out = Vec::new();
10932×
        for t in o::array(field(m, 3, "tags")?, "tags")? {
10942×
            let tm = map(t, "tag")?;
10952×
            out.push(TagRef::new(
10962×
                o::text(field(tm, 0, "name")?, "name")?.to_owned(),
10972×
                o::oref(field(tm, 1, "state")?, "state")?,
10982×
                hashes_from(field(tm, 2, "heads")?)?,
10992×
                opt_attest_from(field(tm, 3, "attestation")?)?,
1100
            ));
1101
        }
11021×
        Ok(out)
11031×
    }
1104
1105
    /// A log place, `[entry number, entry bytes, [proof hash]]` (spec §14.8).
11064×
    fn logged_value(l: &Logged) -> Value {
11074×
        Value::Array(vec![
11084×
            Value::Uint(l.index),
11094×
            Value::Bytes(l.entry.clone()),
11104×
            proof_value(&l.proof),
11114×
        ])
11124×
    }
11134×
    fn logged_from(v: &Value) -> Result<Logged> {
11144×
        let a = o::array(v, "logged")?;
11154×
        if a.len() != 3 {
11160×
            return Err(schema("logged: expected [index, entry, proof]"));
11174×
        }
1118
        Ok(Logged {
11194×
            index: o::uint(&a[0], "index")?,
11204×
            entry: o::bytes(&a[1], "entry")?.to_vec(),
11214×
            proof: proof_from(&a[2])?,
1122
        })
11234×
    }
1124
1125
    /// Cosigned checkpoints holding an entry, `[[note, [proof hash]]]`.
11264×
    fn integration_value(integration: &[Integration]) -> Value {
1127
        Value::Array(
11284×
            integration
11294×
                .iter()
11304×
                .map(|i| Value::Array(vec![Value::Text(i.note.clone()), proof_value(&i.proof)]))
11314×
                .collect(),
1132
        )
11334×
    }
11344×
    fn integration_from(v: &Value) -> Result<Vec<Integration>> {
11354×
        let mut out = Vec::new();
11364×
        for i in o::array(v, "integration")? {
11374×
            let a = o::array(i, "integration")?;
11384×
            if a.len() != 2 {
11390×
                return Err(schema("integration: expected [note, proof]"));
11404×
            }
11414×
            out.push(Integration {
11424×
                note: o::text(&a[0], "note")?.to_owned(),
11434×
                proof: proof_from(&a[1])?,
1144
            });
1145
        }
11464×
        Ok(out)
11474×
    }
1148
1149176×
    pub fn encode_refs(id: [u8; 16], resp: &RefsResponse) -> Vec<u8> {
1150176×
        let mut v = Value::map([
1151
            (
1152
                0,
1153
                Value::Array(
1154176×
                    resp.refs
1155176×
                        .iter()
1156182×
                        .map(|r| {
1157182×
                            let mut v = Value::map([
1158182×
                                (0, Value::Text(r.name.clone())),
1159182×
                                (1, Value::Bytes(r.state.0.to_vec())),
1160182×
                                (2, hashes_value(&r.heads)),
1161182×
                                (3, opt_attest_value(&r.attestation)),
1162182×
                                (4, r.last_serial.map(Value::Uint).unwrap_or(Value::Null)),
1163182×
                            ]);
1164
                            // Only when there is one; older peers ignore it.
1165182×
                            if let Value::Map(m) = &mut v {
1166182×
                                if r.accepted.is_some() {
11679×
                                    m.insert(5, opt_attest_value(&r.accepted));
1168173×
                                }
1169182×
                                if let Some(l) = &r.logged {
11702×
                                    m.insert(6, logged_value(l));
1171180×
                                }
1172182×
                                if !r.integration.is_empty() {
11732×
                                    m.insert(7, integration_value(&r.integration));
1174180×
                                }
11750×
                            }
1176182×
                            v
1177182×
                        })
1178176×
                        .collect(),
1179
                ),
1180
            ),
1181176×
            (1, Value::Bytes(id.to_vec())),
1182176×
            (2, opt_policy_value(resp.policy.as_ref())),
1183176×
            (3, tags_value(&resp.tags)),
1184176×
            (
1185176×
                4,
1186176×
                Value::Array(resp.history.iter().map(policy_value).collect()),
1187176×
            ),
1188176×
            (
1189176×
                5,
1190176×
                resp.default_bookmark
1191176×
                    .clone()
1192176×
                    .map(Value::Text)
1193176×
                    .unwrap_or(Value::Null),
1194176×
            ),
1195
        ]);
1196176×
        if let Value::Map(m) = &mut v {
1197176×
            if let Some(log) = &resp.log {
11983×
                m.insert(6, Value::Text(log.clone()));
1199173×
            }
1200176×
            if !resp.withdrawn.is_empty() {
12010×
                m.insert(8, tags_value(&resp.withdrawn));
1202176×
            }
1203176×
            if !resp.witnesses.is_empty() {
12042×
                m.insert(
1205
                    7,
1206
                    Value::Array(
12072×
                        resp.witnesses
12082×
                            .iter()
12092×
                            .map(|(name, id)| {
12102×
                                Value::Array(vec![
12112×
                                    Value::Text(name.clone()),
12122×
                                    Value::Bytes(id.clone()),
12132×
                                ])
12142×
                            })
12152×
                            .collect(),
1216
                    ),
1217
                );
1218174×
            }
12190×
        }
1220176×
        cbor::encode(&v)
1221176×
    }
1222219×
    pub fn decode_refs(bytes: &[u8]) -> Result<([u8; 16], RefsResponse)> {
1223219×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
1224219×
        let m = map(&v, "refs")?;
1225219×
        let id: [u8; 16] = o::bytes(field(m, 1, "repo id")?, "repo id")?
1226219×
            .try_into()
1227219×
            .map_err(|_| schema("repo id: expected 16 bytes"))?;
1228219×
        let mut refs = Vec::new();
1229225×
        for r in o::array(field(m, 0, "refs")?, "refs")? {
1230225×
            let rm = map(r, "ref")?;
1231225×
            let ls = field(rm, 4, "last serial")?;
1232225×
            refs.push(RemoteRef {
1233225×
                name: o::text(field(rm, 0, "name")?, "name")?.to_owned(),
1234225×
                state: o::oref(field(rm, 1, "state")?, "state")?,
1235225×
                heads: hashes_from(field(rm, 2, "heads")?)?,
1236225×
                attestation: opt_attest_from(field(rm, 3, "attestation")?)?,
1237225×
                last_serial: if ls.is_null() {
1238192×
                    None
1239
                } else {
124033×
                    Some(o::uint(ls, "last serial")?)
1241
                },
1242225×
                accepted: match rm.get(&5) {
12439×
                    Some(a) => opt_attest_from(a)?,
1244216×
                    None => None,
1245
                },
1246225×
                logged: rm.get(&6).map(logged_from).transpose()?,
1247225×
                integration: match rm.get(&7) {
12482×
                    Some(l) => integration_from(l)?,
1249223×
                    None => Vec::new(),
1250
                },
1251
            });
1252
        }
1253219×
        let policy = match m.get(&2) {
1254219×
            Some(p) => opt_policy_from(p)?,
12550×
            None => None,
1256
        };
1257219×
        let tags = match m.get(&3) {
1258219×
            Some(t) => tags_from(t)?,
12590×
            None => Vec::new(),
1260
        };
1261219×
        let mut history = Vec::new();
1262219×
        if let Some(h) = m.get(&4) {
1263219×
            for p in o::array(h, "history")? {
126417×
                history.push(policy_from(p)?);
1265
            }
12660×
        }
1267219×
        let default_bookmark = match m.get(&5) {
1268150×
            Some(Value::Text(t)) => Some(t.clone()),
126969×
            _ => None,
1270
        };
1271219×
        let log = match m.get(&6) {
12723×
            Some(Value::Text(t)) => Some(t.clone()),
1273216×
            _ => None,
1274
        };
1275219×
        let mut witnesses = Vec::new();
1276219×
        if let Some(w) = m.get(&7) {
12772×
            for x in o::array(w, "witnesses")? {
12782×
                let a = o::array(x, "witness")?;
12792×
                if a.len() != 2 {
12800×
                    return Err(schema("witness: expected [name, identity]"));
12812×
                }
12822×
                witnesses.push((
12832×
                    o::text(&a[0], "witness name")?.to_owned(),
12842×
                    o::bytes(&a[1], "witness identity")?.to_vec(),
1285
                ));
1286
            }
1287217×
        }
1288219×
        let withdrawn = match m.get(&8) {
12890×
            Some(t) => tags_from(t)?,
1290219×
            None => Vec::new(),
1291
        };
1292219×
        Ok((
1293219×
            id,
1294219×
            RefsResponse {
1295219×
                refs,
1296219×
                policy,
1297219×
                tags,
1298219×
                history,
1299219×
                default_bookmark,
1300219×
                log,
1301219×
                witnesses,
1302219×
                withdrawn,
1303219×
            },
1304219×
        ))
1305219×
    }
1306
1307
    /// A proof's hashes, from the leaf upwards (spec §14.8).
13088×
    fn proof_value(proof: &[[u8; 32]]) -> Value {
13098×
        Value::Array(proof.iter().map(|h| Value::Bytes(h.to_vec())).collect())
13108×
    }
1311
13128×
    fn proof_from(v: &Value) -> Result<Vec<[u8; 32]>> {
13138×
        let mut proof = Vec::new();
13148×
        for h in o::array(v, "proof")? {
13158×
            proof.push(
13168×
                o::bytes(h, "proof hash")?
13178×
                    .try_into()
13188×
                    .map_err(|_| schema("proof hash: expected 32 bytes"))?,
1319
            );
1320
        }
13218×
        Ok(proof)
13228×
    }
1323
132457×
    pub fn encode_negotiate(have: &[ChangeHash], want: &[ChangeHash]) -> Vec<u8> {
132557×
        cbor::encode(&Value::map([
132657×
            (0, hashes_value(have)),
132757×
            (1, hashes_value(want)),
132857×
        ]))
132957×
    }
133057×
    pub fn decode_negotiate(bytes: &[u8]) -> Result<(Vec<ChangeHash>, Vec<ChangeHash>)> {
133157×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
133257×
        let m = map(&v, "negotiate")?;
1333
        Ok((
133457×
            hashes_from(field(m, 0, "have")?)?,
133557×
            hashes_from(field(m, 1, "want")?)?,
1336
        ))
133757×
    }
1338
1339
    /// `fetch` request: `{0: [changes], 1: max blob size or null}`.
134058×
    pub fn encode_fetch(hs: &[ChangeHash], max_blob: Option<u64>) -> Vec<u8> {
134158×
        cbor::encode(&Value::map([
134258×
            (0, hashes_value(hs)),
134358×
            (1, max_blob.map(Value::Uint).unwrap_or(Value::Null)),
134458×
        ]))
134558×
    }
134659×
    pub fn decode_fetch(bytes: &[u8]) -> Result<(Vec<ChangeHash>, Option<u64>)> {
134759×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
134859×
        let m = map(&v, "fetch")?;
134959×
        let max = match m.get(&1) {
135058×
            Some(x) if !x.is_null() => Some(o::uint(x, "max blob")?),
135157×
            _ => None,
1352
        };
135359×
        Ok((hashes_from(field(m, 0, "changes")?)?, max))
135459×
    }
1355
1356
    /// `shallow` request: `{0: [heads], 1: depth}`.
13571×
    pub fn encode_shallow(hs: &[ChangeHash], depth: u32) -> Vec<u8> {
13581×
        cbor::encode(&Value::map([
13591×
            (0, hashes_value(hs)),
13601×
            (1, Value::Uint(depth as u64)),
13611×
        ]))
13621×
    }
13631×
    pub fn decode_shallow(bytes: &[u8]) -> Result<(Vec<ChangeHash>, u32)> {
13641×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
13651×
        let m = map(&v, "shallow")?;
1366
        Ok((
13671×
            hashes_from(field(m, 0, "heads")?)?,
13681×
            o::u32_(field(m, 1, "depth")?, "depth")?,
1369
        ))
13701×
    }
1371
137259×
    pub fn encode_hashes(hs: &[ChangeHash]) -> Vec<u8> {
137359×
        cbor::encode(&Value::map([(0, hashes_value(hs))]))
137459×
    }
137558×
    pub fn decode_hashes(bytes: &[u8]) -> Result<Vec<ChangeHash>> {
137658×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
137758×
        hashes_from(field(map(&v, "hashes")?, 0, "hashes")?)
137858×
    }
1379
138047×
    pub fn encode_push(
138147×
        bundle: &Bundle,
138247×
        updates: &[RefUpdate],
138347×
        policy: Option<&SignedPolicy>,
138447×
        tags: &[TagRef],
138547×
    ) -> Vec<u8> {
138647×
        cbor::encode(&Value::map([
138747×
            (0, bundle_value(bundle)),
138847×
            (2, opt_policy_value(policy)),
138947×
            (3, tags_value(tags)),
1390
            (
1391
                1,
1392
                Value::Array(
139347×
                    updates
139447×
                        .iter()
139547×
                        .map(|u| {
139646×
                            Value::map([
139746×
                                (0, Value::Text(u.name.clone())),
139846×
                                (1, Value::Bytes(u.old_state.0.to_vec())),
139946×
                                (2, Value::Bytes(u.new_state.0.to_vec())),
140046×
                                (3, Value::Bool(u.force)),
140146×
                                (4, opt_attest_value(&u.attestation)),
140246×
                            ])
140346×
                        })
140447×
                        .collect(),
1405
                ),
1406
            ),
1407
        ]))
140847×
    }
1409
    /// A decoded push: bundle, bookmark updates, policy, tags.
1410
    pub type PushParts = (Bundle, Vec<RefUpdate>, Option<SignedPolicy>, Vec<TagRef>);
1411
141243×
    pub fn decode_push(bytes: &[u8]) -> Result<PushParts> {
141343×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
141443×
        let m = map(&v, "push")?;
141543×
        let bundle = bundle_from_value(field(m, 0, "bundle")?)?;
141643×
        let mut updates = Vec::new();
141743×
        for u in o::array(field(m, 1, "updates")?, "updates")? {
141842×
            let um = map(u, "update")?;
141942×
            updates.push(RefUpdate {
142042×
                name: o::text(field(um, 0, "name")?, "name")?.to_owned(),
142142×
                old_state: o::oref(field(um, 1, "old_state")?, "old_state")?,
142242×
                new_state: o::oref(field(um, 2, "new_state")?, "new_state")?,
142342×
                force: field(um, 3, "force")?
142442×
                    .as_bool()
142542×
                    .ok_or_else(|| schema("force: expected bool"))?,
142642×
                attestation: opt_attest_from(field(um, 4, "attestation")?)?,
1427
            });
1428
        }
142943×
        let policy = match m.get(&2) {
143043×
            Some(p) => opt_policy_from(p)?,
14310×
            None => None,
1432
        };
143343×
        let tags = match m.get(&3) {
143443×
            Some(t) => tags_from(t)?,
14350×
            None => Vec::new(),
1436
        };
143743×
        Ok((bundle, updates, policy, tags))
143843×
    }
1439
144041×
    pub fn encode_push_response(results: &[RefResult]) -> Vec<u8> {
144141×
        cbor::encode(&Value::map([(
1442
            0,
1443
            Value::Array(
144441×
                results
144541×
                    .iter()
144647×
                    .map(|r| {
144747×
                        Value::map([
144847×
                            (0, Value::Text(r.name.clone())),
144947×
                            (1, Value::Bool(r.ok)),
145047×
                            (2, Value::Text(r.reason.clone())),
145147×
                        ])
145247×
                    })
145341×
                    .collect(),
1454
            ),
1455
        )]))
145641×
    }
145741×
    pub fn decode_push_response(bytes: &[u8]) -> Result<Vec<RefResult>> {
145841×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
145941×
        let m = map(&v, "push response")?;
146041×
        let mut out = Vec::new();
146147×
        for r in o::array(field(m, 0, "results")?, "results")? {
146247×
            let rm = map(r, "result")?;
146347×
            out.push(RefResult {
146447×
                name: o::text(field(rm, 0, "name")?, "name")?.to_owned(),
146547×
                ok: field(rm, 1, "ok")?
146647×
                    .as_bool()
146747×
                    .ok_or_else(|| schema("ok: expected bool"))?,
146847×
                reason: o::text(field(rm, 2, "reason")?, "reason")?.to_owned(),
1469
            });
1470
        }
147141×
        Ok(out)
147241×
    }
1473
}
1474
1475
#[cfg(test)]
1476
mod tests {
1477
    use super::*;
1478
    use crate::attest::AttestBody;
1479
    use crate::objects::Hlc;
1480
1481
    /// oxygen#133: a proxy's HTML error page is shown by its title, and a
1482
    /// server's own text as it is; a 413 says to push in smaller parts.
1483
    #[test]
14841×
    fn html_error_pages_are_shown_by_their_title() {
14851×
        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>";
14861×
        assert_eq!(
14871×
            plain_error_text(cloudflare),
1488
            "413 Request Entity Too Large (an HTML error page, from a proxy in front of the server perhaps)"
1489
        );
14901×
        assert_eq!(
14911×
            plain_error_text("  refused: a secret\nat a.txt:3 "),
1492
            "refused: a secret\nat a.txt:3"
1493
        );
14941×
        assert!(hint_for("https://hub/x: HTTP 413: too large")
14951×
            .unwrap()
14961×
            .contains("push.batch-bytes"));
14971×
    }
1498
1499
    #[test]
15001×
    fn client_features_are_declared_and_read() {
15011×
        assert_eq!(CLIENT_FEATURES.join(","), "certified-tags");
15021×
        assert!(user_agent().starts_with("oxy/"));
15031×
        assert!(declares_feature(
15041×
            Some("certified-tags"),
15051×
            FEATURE_CERTIFIED_TAGS
1506
        ));
15071×
        assert!(declares_feature(
15081×
            Some("later-thing, Certified-Tags ,x"),
15091×
            FEATURE_CERTIFIED_TAGS
1510
        ));
15111×
        assert!(!declares_feature(
15121×
            Some("certified-tags-v2"),
15131×
            FEATURE_CERTIFIED_TAGS
15141×
        ));
15151×
        assert!(!declares_feature(Some(""), FEATURE_CERTIFIED_TAGS));
15161×
        assert!(!declares_feature(None, FEATURE_CERTIFIED_TAGS));
15171×
    }
1518
1519
    #[test]
15201×
    fn wire_round_trips() {
15211×
        let c = crate::objects::tests::sample_change();
15221×
        let sk = crate::identity::SecretKey {
15231×
            ed_seed: [1; 32],
15241×
            ml_seed: [2; 32],
15251×
        };
15261×
        let id = sk.identity("a", "b", 0);
15271×
        let key = id.hash();
15281×
        let sig = sk.sign(crate::identity::Domain::Change, &key, &c.hash());
15291×
        let seal = Attest::seal([3; 16], vec![c.hash()]);
15301×
        let seal_sig = sk.sign(crate::identity::Domain::Attest, &key, &seal.hash());
15311×
        let policy = Policy::single_root([3; 16], id.clone(), 99);
15321×
        let psig = sk.sign(crate::identity::Domain::Policy, &key, &policy.hash());
15331×
        let bundle = Bundle {
15341×
            changes: vec![(c.clone(), vec![sig.clone()])],
15351×
            attests: vec![SignedAttest {
15361×
                attest: seal.clone(),
15371×
                sigs: vec![seal_sig],
15381×
            }],
15391×
            objects: vec![
15401×
                (ObjectType::Identity, id.encode()),
15411×
                (ObjectType::Chunk, b"xyz".to_vec()),
15421×
            ],
15431×
            policies: vec![SignedPolicy {
15441×
                policy: policy.clone(),
15451×
                sigs: vec![psig.clone()],
15461×
            }],
15471×
            hashes: vec![],
15481×
            raw_changes: vec![],
15491×
            certificates: vec![],
15501×
        };
15511×
        let d = wire::decode_bundle(&wire::encode_bundle(&bundle)).unwrap();
15521×
        assert_eq!(
1553
            d.hashes,
15541×
            vec![c.hash()],
1555
            "the receiver hashes what it was sent"
1556
        );
15571×
        assert_eq!(d.changes, bundle.changes);
15581×
        assert_eq!(d.attests, bundle.attests);
15591×
        assert_eq!(d.objects, bundle.objects);
15601×
        assert_eq!(d.policies, bundle.policies);
15611×
        assert!(d.certificates.is_empty());
1562
        // Certificates (keyless, oxygenhub#241) travel as field 4, only
1563
        // when there are any: a bundle without them encodes as before.
15641×
        let plain = wire::encode_bundle(&bundle);
15651×
        let mut with = bundle.clone();
15661×
        let issuer_sk = crate::identity::SecretKey::generate();
15671×
        let issuer = issuer_sk.identity("hub", "h@x", 1);
15681×
        with.certificates.push(crate::cert::SignedCertificate::sign(
15691×
            crate::cert::Certificate {
15701×
                key: id.clone(),
15711×
                issuer: issuer.hash(),
15721×
                subject: "agent:a@b".into(),
15731×
                claims: vec![],
15741×
                scope: crate::identity::Scope::CHANGES,
15751×
                not_before: 1,
15761×
                expires: 2,
15771×
                grant: None,
15781×
            },
15791×
            &issuer,
15801×
            &issuer_sk,
1581
        ));
15821×
        let encoded = wire::encode_bundle(&with);
15831×
        assert_ne!(encoded, plain);
15841×
        assert_eq!(
15851×
            wire::decode_bundle(&encoded).unwrap().certificates,
1586
            with.certificates
1587
        );
15881×
        with.certificates.clear();
15891×
        assert_eq!(wire::encode_bundle(&with), plain);
1590
15911×
        let att = Attest {
15921×
            repo: [3; 16],
15931×
            hlc: Hlc::default(),
15941×
            body: AttestBody::Ref {
15951×
                name: "main".into(),
15961×
                old_state: ObjectRef([1; 32]),
15971×
                new_state: ObjectRef([2; 32]),
15981×
                serial: 4,
15991×
            },
16001×
        };
16011×
        let refs = vec![
16021×
            RemoteRef {
16031×
                name: "main".into(),
16041×
                state: ObjectRef([2; 32]),
16051×
                heads: vec![c.hash()],
16061×
                attestation: Some(SignedAttest {
16071×
                    attest: att.clone(),
16081×
                    sigs: vec![sig.clone()],
16091×
                }),
16101×
                last_serial: Some(4),
16111×
                accepted: None,
16121×
                logged: None,
16131×
                integration: vec![],
16141×
            },
16151×
            RemoteRef {
16161×
                name: "dev".into(),
16171×
                state: ObjectRef([5; 32]),
16181×
                heads: vec![],
16191×
                attestation: None,
16201×
                last_serial: None,
16211×
                accepted: None,
16221×
                logged: None,
16231×
                integration: vec![],
16241×
            },
1625
        ];
16261×
        let tag = TagRef::new("v1".into(), ObjectRef([2; 32]), vec![c.hash()], None);
16271×
        let mut resp = RefsResponse {
16281×
            refs,
16291×
            policy: Some(SignedPolicy {
16301×
                policy: policy.clone(),
16311×
                sigs: vec![psig.clone()],
16321×
            }),
16331×
            tags: vec![tag.clone()],
16341×
            history: vec![SignedPolicy {
16351×
                policy: policy.clone(),
16361×
                sigs: vec![],
16371×
            }],
16381×
            default_bookmark: Some("develop".into()),
16391×
            log: Some("hub.example/log\n2\nroot\n\n- sig\n".into()),
16401×
            witnesses: vec![],
16411×
            withdrawn: vec![],
16421×
        };
1643
        // Without integrated times (spec §14.8) nothing is added: an old
1644
        // peer's answer, and what it reads.
16451×
        let old = wire::encode_refs([3; 16], &resp);
16461×
        let back = wire::decode_refs(&old).unwrap().1;
16472×
        assert!(back.witnesses.is_empty() && back.refs.iter().all(|r| r.integration.is_empty()));
16481×
        resp.refs[1].logged = Some(Logged {
16491×
            index: 41,
16501×
            entry: vec![1, 2, 3],
16511×
            proof: vec![[9; 32], [8; 32]],
16521×
        });
16531×
        resp.refs[1].integration = vec![Integration {
16541×
            note: "hub.example/log\n42\nroot\n\n- sig\n".into(),
16551×
            proof: vec![[7; 32]],
16561×
        }];
16571×
        resp.witnesses = vec![("w.example".into(), vec![4, 5, 6])];
16581×
        let new = wire::encode_refs([3; 16], &resp);
16591×
        let (id_back, back) = wire::decode_refs(&new).unwrap();
16601×
        assert_eq!(back.log, resp.log);
16611×
        assert_eq!(back.refs[1].logged, resp.refs[1].logged);
16621×
        assert_eq!(back.refs[1].integration, resp.refs[1].integration);
16631×
        assert_eq!(back.witnesses, resp.witnesses);
16641×
        assert_eq!(back.refs[0].logged, None);
1665
        // The new keys are 7s an old reader never asks for.
16661×
        let crate::cbor::Value::Map(m) = crate::cbor::decode(&new).unwrap() else {
16670×
            panic!()
1668
        };
16691×
        assert!(m.contains_key(&7));
16701×
        assert_eq!(id_back, [3; 16]);
16711×
        assert_eq!(back.refs.len(), 2);
16721×
        assert_eq!(back.refs[0].attestation.as_ref().unwrap().attest, att);
16731×
        assert_eq!(back.refs[1].last_serial, None);
16741×
        assert_eq!(back.policy.as_ref().unwrap().policy, policy);
16751×
        assert_eq!(back.history, resp.history);
16761×
        assert_eq!(back.tags, vec![tag.clone()]);
1677
1678
        // A tag's acceptance and log place (oxygen#129): keys 4 to 6, only
1679
        // when there are any, so a tag without them encodes as before.
16801×
        let crate::cbor::Value::Map(m) = crate::cbor::decode(&new).unwrap() else {
16810×
            panic!()
1682
        };
16831×
        let crate::cbor::Value::Array(tags) = &m[&3] else {
16840×
            panic!()
1685
        };
16861×
        let crate::cbor::Value::Map(plain) = &tags[0] else {
16870×
            panic!()
1688
        };
16891×
        assert_eq!(plain.keys().copied().collect::<Vec<_>>(), vec![0, 1, 2, 3]);
16901×
        let mut full = tag.clone();
16911×
        full.name = "v2".into();
16921×
        full.attestation = Some(SignedAttest {
16931×
            attest: att.clone(),
16941×
            sigs: vec![sig.clone()],
16951×
        });
16961×
        full.accepted = full.attestation.clone();
16971×
        full.logged = Some(Logged {
16981×
            index: 7,
16991×
            entry: vec![4],
17001×
            proof: vec![[3; 32]],
17011×
        });
17021×
        full.integration = vec![Integration {
17031×
            note: "hub.example/log\n8\nroot\n\n- sig\n".into(),
17041×
            proof: vec![],
17051×
        }];
17061×
        resp.tags = vec![full.clone(), tag.clone()];
17071×
        let bytes = wire::encode_refs([3; 16], &resp);
17081×
        assert_eq!(wire::decode_refs(&bytes).unwrap().1.tags, resp.tags);
1709
        // In a push too.
17101×
        let pushed = wire::encode_push(&Bundle::default(), &[], None, &resp.tags);
17111×
        assert_eq!(wire::decode_push(&pushed).unwrap().3, resp.tags);
1712
        // A reader that knows only keys 0 to 3 (oxy 0.5.0 and older, and
1713
        // the runners built with it) reads the same tags from the new answer.
17141×
        let stripped: Vec<TagRef> = resp
17151×
            .tags
17161×
            .iter()
17172×
            .map(|t| {
17182×
                TagRef::new(
17192×
                    t.name.clone(),
17202×
                    t.state,
17212×
                    t.heads.clone(),
17222×
                    t.attestation.clone(),
1723
                )
17242×
            })
17251×
            .collect();
17261×
        assert_eq!(wire::tags_as_0_5_read_them(&bytes).unwrap(), stripped);
1727
17281×
        let (h, w) = wire::decode_negotiate(&wire::encode_negotiate(
17291×
            &[ObjectRef([1; 32])],
17301×
            &[ObjectRef([2; 32])],
17311×
        ))
17321×
        .unwrap();
17331×
        assert_eq!((h, w), (vec![ObjectRef([1; 32])], vec![ObjectRef([2; 32])]));
17341×
        assert_eq!(
17351×
            wire::decode_hashes(&wire::encode_hashes(&[c.hash()])).unwrap(),
17361×
            vec![c.hash()]
1737
        );
17381×
        assert_eq!(
17391×
            wire::decode_fetch(&wire::encode_fetch(&[c.hash()], Some(4096))).unwrap(),
17401×
            (vec![c.hash()], Some(4096))
1741
        );
17421×
        assert_eq!(
17431×
            wire::decode_fetch(&wire::encode_fetch(&[], None)).unwrap(),
17441×
            (vec![], None)
1745
        );
17461×
        assert_eq!(
17471×
            wire::decode_shallow(&wire::encode_shallow(&[c.hash()], 3)).unwrap(),
17481×
            (vec![c.hash()], 3)
1749
        );
1750
        // An old-style fetch request without the filter field still decodes.
17511×
        assert_eq!(
17521×
            wire::decode_fetch(&wire::encode_hashes(&[c.hash()])).unwrap(),
17531×
            (vec![c.hash()], None)
1754
        );
1755
17561×
        let up = RefUpdate {
17571×
            name: "main".into(),
17581×
            old_state: ObjectRef([1; 32]),
17591×
            new_state: ObjectRef([2; 32]),
17601×
            force: true,
17611×
            attestation: Some(SignedAttest {
17621×
                attest: att,
17631×
                sigs: vec![sig],
17641×
            }),
17651×
        };
17661×
        let sp = SignedPolicy {
17671×
            policy,
17681×
            sigs: vec![psig],
17691×
        };
17701×
        let (b2, ups, pol, tags) = wire::decode_push(&wire::encode_push(
17711×
            &bundle,
17721×
            std::slice::from_ref(&up),
17731×
            Some(&sp),
17741×
            std::slice::from_ref(&tag),
17751×
        ))
17761×
        .unwrap();
17771×
        assert_eq!(pol, Some(sp));
17781×
        assert_eq!(tags, vec![tag]);
17791×
        assert_eq!(b2.changes.len(), 1);
17801×
        assert_eq!(ups[0].name, "main");
17811×
        assert!(ups[0].force);
17821×
        assert_eq!(ups[0].attestation, up.attestation);
17831×
        let res = vec![RefResult {
17841×
            name: "main".into(),
17851×
            ok: false,
17861×
            reason: "stale".into(),
17871×
        }];
17881×
        assert_eq!(
17891×
            wire::decode_push_response(&wire::encode_push_response(&res)).unwrap(),
1790
            res
1791
        );
17921×
        assert_eq!(
17931×
            wire::decode_capabilities(&wire::encode_capabilities([7; 16])).unwrap(),
1794
            [7; 16]
1795
        );
17961×
    }
1797
}