OXYGENHUB
# f3811eb20bea oxygen / crates / oxy-core / src / protocol.rs
66.9 KiB · Rust · last changed Depth 0 takes no change, and a checkpoint is gathered in parallel (refs #137) 11 days ago source blame history raw
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`).
38
    pub fn encode(&self) -> Vec<u8> {
39
        crate::cbor::encode(&wire::policy_value(self))
40
    }
41
    pub fn decode(b: &[u8]) -> Result<SignedPolicy> {
42
        wire::policy_from(
43
            &crate::cbor::decode(b).map_err(|e| RepoError::Object(ObjectError::from(e)))?,
44
        )
45
    }
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
}
68
69
/// Where a reference attestation sits in the host's transparency log
70
/// (spec §14.8): its entry number, the entry, and the inclusion proof
71
/// against the checkpoint served beside it.
72
#[derive(Clone, Debug, PartialEq, Eq)]
73
pub struct Logged {
74
    pub index: u64,
75
    pub entry: Vec<u8>,
76
    pub proof: Vec<[u8; 32]>,
77
}
78
79
/// A checkpoint witnesses cosigned that includes a logged entry (spec
80
/// §14.8, *Integrated time*): the cosigned note, and the entry's inclusion
81
/// proof against it.
82
#[derive(Clone, Debug, PartialEq, Eq)]
83
pub struct Integration {
84
    pub note: String,
85
    pub proof: Vec<[u8; 32]>,
86
}
87
88
/// A tag as a remote reports it (spec §10.1).
89
#[derive(Clone, Debug, PartialEq, Eq)]
90
pub struct TagRef {
91
    pub name: String,
92
    pub state: ObjectRef,
93
    pub heads: Vec<ChangeHash>,
94
    pub attestation: Option<SignedAttest>,
95
    /// The acceptance of `attestation` by its signer's certificate issuer
96
    /// when a short-lived key signed it (spec §14.7; key 4, only when there
97
    /// is one): the time a fetch checks the certificate at.
98
    pub accepted: Option<SignedAttest>,
99
    /// The attestation's place in the host's transparency log (key 5,
100
    /// only when it has one), as a bookmark's.
101
    pub logged: Option<Logged>,
102
    /// The cosigned checkpoints that first included `logged`'s entry (key
103
    /// 6, only when there are any).
104
    pub integration: Vec<Integration>,
105
}
106
107
impl TagRef {
108
    /// A tag with no acceptance or log place (yet).
109
    pub fn new(
110
        name: String,
111
        state: ObjectRef,
112
        heads: Vec<ChangeHash>,
113
        attestation: Option<SignedAttest>,
114
    ) -> TagRef {
115
        TagRef {
116
            name,
117
            state,
118
            heads,
119
            attestation,
120
            accepted: None,
121
            logged: None,
122
            integration: vec![],
123
        }
124
    }
125
}
126
127
/// One reference as a remote reports it.
128
#[derive(Clone, Debug)]
129
pub struct RemoteRef {
130
    pub name: String,
131
    pub state: ObjectRef,
132
    pub heads: Vec<ChangeHash>,
133
    /// The latest attestation, only when it describes `state`. An unattested
134
    /// push (accepted while no trust policy exists) leaves it `None`.
135
    pub attestation: Option<SignedAttest>,
136
    /// Serial of the latest attestation ever recorded, stale or not, so the
137
    /// next attestation continues the sequence.
138
    pub last_serial: Option<u64>,
139
    /// The host's acceptance of `attestation` when a short-lived key signed
140
    /// it (spec §14.7): the time its certificate is checked at.
141
    pub accepted: Option<SignedAttest>,
142
    /// The attestation's place in the host's transparency log (key 6, only
143
    /// when it has one).
144
    pub logged: Option<Logged>,
145
    /// The cosigned checkpoints that first included `logged`'s entry (key
146
    /// 7, only when there are any): what its integrated time is read from.
147
    pub integration: Vec<Integration>,
148
}
149
150
/// Everything needed to add a set of changes to a repository.
151
#[derive(Clone, Debug, Default)]
152
pub struct Bundle {
153
    /// In dependency order, each with its individual signatures.
154
    pub changes: Vec<(Change, Vec<Signature>)>,
155
    /// Seals covering the changes.
156
    pub attests: Vec<SignedAttest>,
157
    /// Chunks, blobs, identities, and state objects referenced by the changes.
158
    pub objects: Vec<(ObjectType, Vec<u8>)>,
159
    /// Policies between the receiver's and the one sent with the push,
160
    /// ascending by serial (spec §14.5).
161
    pub policies: Vec<SignedPolicy>,
162
    /// Each change's hash, in the order of `changes`, when whoever made
163
    /// the bundle knows it: the store it came from, or the bytes it was
164
    /// decoded from. Never read from the wire. Empty when unknown.
165
    pub hashes: Vec<ChangeHash>,
166
    /// Changes as stored, with their signatures, in dependency order, for a
167
    /// fetch between repositories on one machine: their text blobs and
168
    /// chunks are among `objects`. Never on the wire.
169
    pub raw_changes: Vec<(Vec<u8>, Vec<Signature>)>,
170
    /// Certificates of short-lived keys that signed what the bundle carries
171
    /// (spec §14.7), their issuers' identities among `objects`.
172
    pub certificates: Vec<crate::cert::SignedCertificate>,
173
}
174
175
impl Bundle {
176
    pub fn is_empty(&self) -> bool {
177
        self.changes.is_empty() && self.attests.is_empty() && self.objects.is_empty()
178
    }
179
}
180
181
/// A requested bookmark move (spec §10.2, §16.3).
182
#[derive(Clone, Debug)]
183
pub struct RefUpdate {
184
    pub name: String,
185
    pub old_state: ObjectRef,
186
    pub new_state: ObjectRef,
187
    pub force: bool,
188
    pub attestation: Option<SignedAttest>,
189
}
190
191
#[derive(Clone, Debug, PartialEq, Eq)]
192
pub struct RefResult {
193
    pub name: String,
194
    pub ok: bool,
195
    pub reason: String,
196
}
197
198
pub trait Remote {
199
    fn repo_id(&self) -> Result<[u8; 16]>;
200
    fn refs(&self) -> Result<RefsResponse>;
201
    /// Changes in the closure of `want` but not of `have`, in dependency order.
202
    fn negotiate(&self, have: &[ChangeHash], want: &[ChangeHash]) -> Result<Vec<ChangeHash>>;
203
    /// The changes with their signatures, seals, identities, and blobs; blobs
204
    /// larger than `max_blob` bytes are left out for lazy fetching (spec §13.5).
205
    fn fetch(&self, changes: &[ChangeHash], max_blob: Option<u64>) -> Result<Bundle>;
206
    /// Individual objects by reference (spec §16.1 `objects`); a blob comes
207
    /// with its chunks.
208
    fn objects(&self, refs: &[ObjectRef]) -> Result<Vec<(ObjectType, Vec<u8>)>>;
209
    /// A checkpoint of exactly `heads` (spec §16.1 `checkpoint`): the
210
    /// checkpoint object, its payload blob, and the blob's chunks.
211
    fn checkpoint(&self, heads: &[ChangeHash]) -> Result<Bundle>;
212
    /// The changes within `depth` dependency steps of `heads` (spec §17).
213
    fn shallow(&self, heads: &[ChangeHash], depth: u32) -> Result<Vec<ChangeHash>>;
214
    /// Push changes, bookmark updates, new tags, and optionally a newer
215
    /// policy. The policy is applied first; a result named `policy` reports
216
    /// it, and each tag reports as `tags/<name>`.
217
    fn push(
218
        &self,
219
        bundle: Bundle,
220
        updates: Vec<RefUpdate>,
221
        policy: Option<SignedPolicy>,
222
        tags: Vec<TagRef>,
223
    ) -> Result<Vec<RefResult>>;
224
}
225
226
// ---------------------------------------------------------------- local
227
228
/// Another repository on this machine, served in-process.
229
pub struct LocalRemote {
230
    pub repo: Repo,
231
    /// The pushing repository's id, which binds an unbound target on the
232
    /// first push, as `Oxy-Repo-Id` does over HTTP.
233
    pub claimed_id: Option<[u8; 16]>,
234
}
235
236
impl LocalRemote {
237
    pub fn open(path: &Path) -> Result<LocalRemote> {
238
        Ok(LocalRemote {
239
            repo: Repo::open(path)?,
240
            claimed_id: None,
241
        })
242
    }
243
}
244
245
impl Remote for LocalRemote {
246
    fn repo_id(&self) -> Result<[u8; 16]> {
247
        self.repo.id()
248
    }
249
    fn refs(&self) -> Result<RefsResponse> {
250
        self.repo.remote_refs()
251
    }
252
    fn negotiate(&self, have: &[ChangeHash], want: &[ChangeHash]) -> Result<Vec<ChangeHash>> {
253
        self.repo.negotiate(have, want)
254
    }
255
    fn fetch(&self, changes: &[ChangeHash], max_blob: Option<u64>) -> Result<Bundle> {
256
        self.repo.bundle_raw_for(changes, max_blob)
257
    }
258
    fn objects(&self, refs: &[ObjectRef]) -> Result<Vec<(ObjectType, Vec<u8>)>> {
259
        self.repo.objects_for(refs)
260
    }
261
    fn checkpoint(&self, heads: &[ChangeHash]) -> Result<Bundle> {
262
        self.repo.checkpoint_bundle_for(heads)
263
    }
264
    fn shallow(&self, heads: &[ChangeHash], depth: u32) -> Result<Vec<ChangeHash>> {
265
        self.repo.shallow_changes(heads, depth)
266
    }
267
    fn push(
268
        &self,
269
        bundle: Bundle,
270
        updates: Vec<RefUpdate>,
271
        policy: Option<SignedPolicy>,
272
        tags: Vec<TagRef>,
273
    ) -> Result<Vec<RefResult>> {
274
        if self.repo.is_unbound() {
275
            match self.claimed_id {
276
                Some(id) => self.repo.bind_id(id)?,
277
                None => {
278
                    return Err(RepoError::Msg(
279
                        "the remote is unbound and this client did not say which repository it is"
280
                            .into(),
281
                    ))
282
                }
283
            }
284
        }
285
        self.repo.receive_push(bundle, updates, policy, tags)
286
    }
287
}
288
289
// ---------------------------------------------------------------- http
290
291
/// How to reach a remote: credentials and trust.
292
#[derive(Clone, Debug, Default)]
293
pub struct RemoteOptions {
294
    /// Bearer token for pushes.
295
    pub token: Option<String>,
296
    /// PEM file with extra root certificates to trust for `https://` remotes
297
    /// (self-hosted servers); the system web roots are always trusted.
298
    pub ca: Option<PathBuf>,
299
    /// The local repository's id, sent as `Oxy-Repo-Id` so an unbound
300
    /// hosted repository can adopt it on the first push (spec §16.1).
301
    pub repo_id: Option<[u8; 16]>,
302
    /// Where a remote kept on a store (`dir://`, `s3://`, …) keeps its
303
    /// mirror and what it has seen: the remote's directory under
304
    /// `.oxy/remotes`. None (a clone, before there is a repository) means
305
    /// a temporary directory.
306
    pub cache_dir: Option<PathBuf>,
307
    /// Other tokens for the same hub, tried in turn when `token` is
308
    /// refused (401, 403 or 404): those of enclosing checkouts, when
309
    /// `token` came from the credential store rather than from this
310
    /// remote's own configuration (oxygen#112).
311
    pub fallback_tokens: Vec<String>,
312
}
313
314
/// Opens a store for a URL it understands, or passes (`None`). Stores that
315
/// need more than the standard library (the cloud ones) are added by the
316
/// program that links them, with [`register_store_opener`].
317
pub type StoreOpener =
318
    fn(&str, &RemoteOptions) -> Option<crate::strata::Result<Box<dyn crate::strata::Store>>>;
319
320
static STORE_OPENERS: Mutex<Vec<StoreOpener>> = Mutex::new(Vec::new());
321
322
pub fn register_store_opener(opener: StoreOpener) {
323
    STORE_OPENERS
324
        .lock()
325
        .unwrap_or_else(|p| p.into_inner())
326
        .push(opener);
327
}
328
329
/// A store for `url`, from `dir://` or any registered opener.
330
pub fn open_store(
331
    url: &str,
332
    options: &RemoteOptions,
333
) -> Option<crate::strata::Result<Box<dyn crate::strata::Store>>> {
334
    if let Some(path) = url.strip_prefix("dir://") {
335
        return Some(
336
            crate::strata::LocalStore::open(path)
337
                .map(|s| Box::new(s) as Box<dyn crate::strata::Store>),
338
        );
339
    }
340
    let openers = STORE_OPENERS.lock().unwrap_or_else(|p| p.into_inner());
341
    openers.iter().find_map(|open| open(url, options))
342
}
343
344
/// The request header carrying the client's repository id.
345
pub const REPO_ID_HEADER: &str = "Oxy-Repo-Id";
346
347
/// The id of a hosted repository that has not adopted one yet.
348
pub const UNBOUND_ID: [u8; 16] = [0; 16];
349
350
/// The request header in which a client declares the protocol features it
351
/// understands beyond the 0.5.0-era set: a comma-separated list, which a
352
/// server may tailor its answers to (docs/protocol.md, *Client
353
/// capabilities*). A request without it is a client of that era.
354
pub const FEATURES_HEADER: &str = "Oxy-Features";
355
356
/// The feature of a client that authorizes a tag signed by a short-lived,
357
/// certified key by its certificate at the time the host accepted it
358
/// (oxygen#129). A client without it refuses such a tag, and with it the
359
/// whole fetch, so servers leave those tags out of its `refs` (oxygen#131).
360
pub const FEATURE_CERTIFIED_TAGS: &str = "certified-tags";
361
362
/// The features this client declares in [`FEATURES_HEADER`].
363
pub const CLIENT_FEATURES: &[&str] = &[FEATURE_CERTIFIED_TAGS];
364
365
/// The `User-Agent` every request of this client sends: `oxy/<version>`.
366
pub fn user_agent() -> String {
367
    format!("oxy/{}", env!("CARGO_PKG_VERSION"))
368
}
369
370
/// Whether a [`FEATURES_HEADER`] value (absent: `None`) declares `feature`.
371
/// Entries are comma-separated, compared without surrounding blanks and
372
/// regardless of case; unknown ones are ignored.
373
pub fn declares_feature(header: Option<&str>, feature: &str) -> bool {
374
    header.is_some_and(|h| h.split(',').any(|f| f.trim().eq_ignore_ascii_case(feature)))
375
}
376
377
/// A remote served by `oxy-server` at `<base>/oxy/v1/...`.
378
pub struct HttpRemote {
379
    base: String,
380
    /// The token in use, and those still to try when it is refused.
381
    token: Mutex<Option<String>>,
382
    fallbacks: Mutex<Vec<String>>,
383
    repo_id: Option<[u8; 16]>,
384
    agent: ureq::Agent,
385
}
386
387
/// A TLS client configuration trusting the web roots plus `ca`, if given.
388
fn tls_client_config(ca: Option<&Path>) -> Result<Arc<rustls::ClientConfig>> {
389
    let mut roots = rustls::RootCertStore::empty();
390
    roots.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
391
    if let Some(path) = ca {
392
        let pem = std::fs::read(path)
393
            .map_err(|e| RepoError::Msg(format!("reading CA file {}: {e}", path.display())))?;
394
        let certs = rustls_pemfile::certs(&mut pem.as_slice())
395
            .collect::<std::result::Result<Vec<_>, _>>()
396
            .map_err(|e| RepoError::Msg(format!("parsing CA file {}: {e}", path.display())))?;
397
        if certs.is_empty() {
398
            return Err(RepoError::Msg(format!(
399
                "CA file {} holds no certificates",
400
                path.display()
401
            )));
402
        }
403
        for c in certs {
404
            roots
405
                .add(c)
406
                .map_err(|e| RepoError::Msg(format!("CA file {}: {e}", path.display())))?;
407
        }
408
    }
409
    let cfg = rustls::ClientConfig::builder_with_provider(Arc::new(
410
        rustls::crypto::ring::default_provider(),
411
    ))
412
    .with_safe_default_protocol_versions()
413
    .map_err(|e| RepoError::Msg(e.to_string()))?
414
    .with_root_certificates(roots)
415
    .with_no_client_auth();
416
    Ok(Arc::new(cfg))
417
}
418
419
impl HttpRemote {
420
    pub fn new(base: &str, options: &RemoteOptions) -> Result<HttpRemote> {
421
        refuse_plain_token(base, options)?;
422
        let agent = ureq::AgentBuilder::new()
423
            .tls_config(tls_client_config(options.ca.as_deref())?)
424
            .user_agent(&user_agent())
425
            .build();
426
        Ok(HttpRemote {
427
            base: base.trim_end_matches('/').to_string(),
428
            token: Mutex::new(options.token.clone()),
429
            fallbacks: Mutex::new(options.fallback_tokens.iter().rev().cloned().collect()),
430
            repo_id: options.repo_id,
431
            agent,
432
        })
433
    }
434
435
    /// A request, tried again with the next fallback token while the
436
    /// hub refuses the one in use (oxygen#112).
437
    fn call(&self, post: bool, endpoint: &str, body: Option<&[u8]>) -> Result<Vec<u8>> {
438
        loop {
439
            let token = self.token.lock().unwrap_or_else(|p| p.into_inner()).clone();
440
            match self.call_once(post, endpoint, body, token.as_deref()) {
441
                Err(RepoError::Msg(m)) if token.is_some() && refused(&m) => {
442
                    let next = self
443
                        .fallbacks
444
                        .lock()
445
                        .unwrap_or_else(|p| p.into_inner())
446
                        .pop();
447
                    let Some(next) = next else {
448
                        return Err(RepoError::Msg(m));
449
                    };
450
                    crate::credentials::warn_once(&format!(
451
                        "{}: the stored token was refused; using the one an enclosing checkout has for this hub",
452
                        self.base
453
                    ));
454
                    *self.token.lock().unwrap_or_else(|p| p.into_inner()) = Some(next);
455
                }
456
                other => return other,
457
            }
458
        }
459
    }
460
461
    fn call_once(
462
        &self,
463
        post: bool,
464
        endpoint: &str,
465
        body: Option<&[u8]>,
466
        token: Option<&str>,
467
    ) -> Result<Vec<u8>> {
468
        let url = format!("{}/oxy/v1/{endpoint}", self.base);
469
        let mut req = if post {
470
            self.agent.post(&url)
471
        } else {
472
            self.agent.get(&url)
473
        };
474
        req = req
475
            .set("Accept", CONTENT_TYPE)
476
            .set(FEATURES_HEADER, &CLIENT_FEATURES.join(","));
477
        if let Some(t) = token {
478
            req = req.set("Authorization", &format!("Bearer {t}"));
479
        }
480
        if let Some(id) = &self.repo_id {
481
            req = req.set(REPO_ID_HEADER, &hex::encode(id));
482
        }
483
        let resp = match body {
484
            Some(b) => req.set("Content-Type", CONTENT_TYPE).send_bytes(b),
485
            None => req.call(),
486
        };
487
        match resp {
488
            Ok(r) => {
489
                let mut out = Vec::new();
490
                r.into_reader()
491
                    .read_to_end(&mut out)
492
                    .map_err(|e| RepoError::Msg(format!("{url}: {e}")))?;
493
                Ok(out)
494
            }
495
            Err(ureq::Error::Status(code, r)) => {
496
                let text = r.into_string().unwrap_or_default();
497
                // The hint comes from the status alone: the server's text
498
                // (a host's reason for refusing a push, several lines
499
                // perhaps) is shown as it is, never read for hints. A
500
                // proxy's HTML error page is shown by its title only
501
                // (oxygen#133).
502
                let status = format!("{url}: HTTP {code}");
503
                let msg = format!("{status}: {}", plain_error_text(&text));
504
                Err(RepoError::Msg(match hint_for(&status) {
505
                    Some(h) => format!("{msg}\n  hint: {h}"),
506
                    None => msg,
507
                }))
508
            }
509
            // The transport error already names the URL.
510
            Err(e) => Err(RepoError::Msg(with_hint(e.to_string()))),
511
        }
512
    }
513
}
514
515
/// Whether a failed request's message says the hub refused its token:
516
/// HTTP 401, 403, or 404 (a hub hides a private repository from a token
517
/// that may not read it).
518
fn refused(message: &str) -> bool {
519
    [": HTTP 401", ": HTTP 403", ": HTTP 404"]
520
        .iter()
521
        .any(|c| message.contains(c))
522
}
523
524
/// Refuse to send a token where anyone on the way could read it: plain
525
/// `http` to another machine (see [`crate::credentials::token_allowed`]).
526
fn refuse_plain_token(url: &str, options: &RemoteOptions) -> Result<()> {
527
    if options.token.is_some() && !crate::credentials::token_allowed(url) {
528
        return Err(RepoError::Msg(format!(
529
            "{url}: refusing to send a token over plain http; use https"
530
        )));
531
    }
532
    Ok(())
533
}
534
535
/// What to do about a failed request, recognised from its message.
536
pub fn hint_for(message: &str) -> Option<&'static str> {
537
    let m = message.to_ascii_lowercase();
538
    let hint = if m.contains("http 401") {
539
        "the hub needs you signed in, or did not accept the token: run `oxy auth login HUB` (pushing needs repo:write)"
540
    } else if m.contains("http 403") {
541
        "the token or account lacks permission: pushing needs a token with repo:write and write access to the repository"
542
    } else if m.contains("http 413") {
543
        "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"
544
    } else if m.contains("http 404") {
545
        "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`)"
546
    } else if m.contains("unknownissuer")
547
        || m.contains("unknown issuer")
548
        || m.contains("certificate")
549
        || m.contains("invalidcertificate")
550
    {
551
        "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`"
552
    } else if m.contains("connection refused") {
553
        "nothing is listening there: check the URL and port, and that the server is running"
554
    } else if m.contains("dns")
555
        || m.contains("failed to lookup")
556
        || m.contains("name or service not known")
557
    {
558
        "the host name does not resolve: check the URL"
559
    } else if m.contains("timed out") || m.contains("timeout") {
560
        "the server did not answer in time: check the network, or try again"
561
    } else {
562
        return None;
563
    };
564
    Some(hint)
565
}
566
567
/// An error response's text as it is, unless it is an HTML page (a proxy's,
568
/// such as Cloudflare's 413): then its title, or a note that it was one.
569
fn plain_error_text(text: &str) -> String {
570
    let t = text.trim();
571
    let lower = t.to_ascii_lowercase();
572
    if !(lower.starts_with("<!doctype html") || lower.starts_with("<html")) {
573
        return t.to_string();
574
    }
575
    let title = lower
576
        .find("<title>")
577
        .and_then(|i| {
578
            lower[i + 7..]
579
                .find("</title>")
580
                .map(|j| t[i + 7..i + 7 + j].trim())
581
        })
582
        .filter(|s| !s.is_empty());
583
    match title {
584
        Some(s) => format!("{s} (an HTML error page, from a proxy in front of the server perhaps)"),
585
        None => "an HTML error page (from a proxy in front of the server perhaps)".into(),
586
    }
587
}
588
589
/// `message`, followed by what to do about it when that is known.
590
pub fn with_hint(message: String) -> String {
591
    match hint_for(&message) {
592
        Some(h) => format!("{message}\n  hint: {h}"),
593
        None => message,
594
    }
595
}
596
597
/// A JSON request to a hub API (`GET`, `POST` or `DELETE`), with the same
598
/// TLS trust and token rules as remotes. Returns the status and body, an
599
/// error status included; only transport failures are errors.
600
pub fn http_json(
601
    method: &str,
602
    url: &str,
603
    body: Option<&str>,
604
    options: &RemoteOptions,
605
) -> Result<(u16, String)> {
606
    refuse_plain_token(url, options)?;
607
    let agent = ureq::AgentBuilder::new()
608
        .tls_config(tls_client_config(options.ca.as_deref())?)
609
        .timeout(std::time::Duration::from_secs(60))
610
        .user_agent(&user_agent())
611
        .build();
612
    let mut req = agent.request(method, url).set("Accept", "application/json");
613
    if let Some(t) = &options.token {
614
        req = req.set("Authorization", &format!("Bearer {t}"));
615
    }
616
    let resp = match body {
617
        Some(b) => req.set("Content-Type", "application/json").send_string(b),
618
        None => req.call(),
619
    };
620
    match resp {
621
        Ok(r) => {
622
            let code = r.status();
623
            Ok((code, r.into_string().unwrap_or_default()))
624
        }
625
        Err(ureq::Error::Status(code, r)) => Ok((code, r.into_string().unwrap_or_default())),
626
        Err(e) => Err(RepoError::Msg(with_hint(e.to_string()))),
627
    }
628
}
629
630
/// An authenticated GET of any URL on a host, with the same TLS trust and
631
/// token as remotes use (for hub APIs: proposals). Returns the body.
632
pub fn http_get(url: &str, options: &RemoteOptions) -> Result<Vec<u8>> {
633
    refuse_plain_token(url, options)?;
634
    let agent = ureq::AgentBuilder::new()
635
        .tls_config(tls_client_config(options.ca.as_deref())?)
636
        .user_agent(&user_agent())
637
        .build();
638
    let mut req = agent.get(url).set("Accept", "application/json");
639
    if let Some(t) = &options.token {
640
        req = req.set("Authorization", &format!("Bearer {t}"));
641
    }
642
    match req.call() {
643
        Ok(r) => {
644
            let mut out = Vec::new();
645
            r.into_reader()
646
                .read_to_end(&mut out)
647
                .map_err(|e| RepoError::Msg(format!("{url}: {e}")))?;
648
            Ok(out)
649
        }
650
        Err(ureq::Error::Status(code, r)) => {
651
            let text = r.into_string().unwrap_or_default();
652
            Err(RepoError::Msg(with_hint(format!(
653
                "{url}: HTTP {code}: {}",
654
                text.trim()
655
            ))))
656
        }
657
        // The transport error already names the URL.
658
        Err(e) => Err(RepoError::Msg(with_hint(e.to_string()))),
659
    }
660
}
661
662
impl Remote for HttpRemote {
663
    fn repo_id(&self) -> Result<[u8; 16]> {
664
        wire::decode_capabilities(&self.call(false, "capabilities", None)?)
665
    }
666
    fn refs(&self) -> Result<RefsResponse> {
667
        Ok(wire::decode_refs(&self.call(false, "refs", None)?)?.1)
668
    }
669
    fn negotiate(&self, have: &[ChangeHash], want: &[ChangeHash]) -> Result<Vec<ChangeHash>> {
670
        wire::decode_hashes(&self.call(
671
            true,
672
            "negotiate",
673
            Some(&wire::encode_negotiate(have, want)),
674
        )?)
675
    }
676
    fn fetch(&self, changes: &[ChangeHash], max_blob: Option<u64>) -> Result<Bundle> {
677
        wire::decode_bundle(&self.call(
678
            true,
679
            "fetch",
680
            Some(&wire::encode_fetch(changes, max_blob)),
681
        )?)
682
    }
683
    fn objects(&self, refs: &[ObjectRef]) -> Result<Vec<(ObjectType, Vec<u8>)>> {
684
        Ok(
685
            wire::decode_bundle(&self.call(true, "objects", Some(&wire::encode_hashes(refs)))?)?
686
                .objects,
687
        )
688
    }
689
    fn checkpoint(&self, heads: &[ChangeHash]) -> Result<Bundle> {
690
        let body = {
691
            let _t = crate::timing::phase("remote: checkpoint answer");
692
            self.call(true, "checkpoint", Some(&wire::encode_hashes(heads)))?
693
        };
694
        let _t = crate::timing::phase("remote: decode the checkpoint");
695
        wire::decode_bundle(&body)
696
    }
697
    fn shallow(&self, heads: &[ChangeHash], depth: u32) -> Result<Vec<ChangeHash>> {
698
        wire::decode_hashes(&self.call(
699
            true,
700
            "shallow",
701
            Some(&wire::encode_shallow(heads, depth)),
702
        )?)
703
    }
704
    fn push(
705
        &self,
706
        bundle: Bundle,
707
        updates: Vec<RefUpdate>,
708
        policy: Option<SignedPolicy>,
709
        tags: Vec<TagRef>,
710
    ) -> Result<Vec<RefResult>> {
711
        wire::decode_push_response(&self.call(
712
            true,
713
            "push",
714
            Some(&wire::encode_push(
715
                &bundle,
716
                &updates,
717
                policy.as_ref(),
718
                &tags,
719
            )),
720
        )?)
721
    }
722
}
723
724
/// A remote's URL as it is stored: an `http(s)://` URL as given, a local
725
/// path made absolute (with its `file://` kept), so it still names the same
726
/// repository from inside the clone (oxygen#57).
727
pub fn stored_url(url: &str) -> String {
728
    // Only a path is made absolute: a plain one, or one behind file:// or
729
    // dir://. Every other URL (a hub, a bucket) is kept as written.
730
    let (prefix, path) = match (url.strip_prefix("file://"), url.strip_prefix("dir://")) {
731
        (Some(p), _) => ("file://", p),
732
        (_, Some(p)) => ("dir://", p),
733
        _ if url.contains("://") => return url.to_string(),
734
        _ => ("", url),
735
    };
736
    match std::path::absolute(path) {
737
        Ok(abs) => format!("{prefix}{}", abs.display()),
738
        Err(_) => url.to_string(),
739
    }
740
}
741
742
/// Open a remote by URL: a local path (optionally `file://`), `http(s)://`
743
/// (a hub), or a store (`dir://`, and whatever openers are registered).
744
pub fn open_remote(url: &str, options: &RemoteOptions) -> Result<Box<dyn Remote>> {
745
    if url.starts_with("http://") || url.starts_with("https://") {
746
        return Ok(Box::new(HttpRemote::new(url, options)?));
747
    }
748
    if let Some(store) = open_store(url, options) {
749
        return crate::repo::strata::open_store_remote(store?, options);
750
    }
751
    let path = url.strip_prefix("file://").unwrap_or(url);
752
    if path.contains("://") {
753
        return Err(RepoError::Msg(format!("unsupported remote URL {url:?}")));
754
    }
755
    let mut local = LocalRemote::open(Path::new(path))?;
756
    local.claimed_id = options.repo_id;
757
    Ok(Box::new(local))
758
}
759
760
// ---------------------------------------------------------------- wire
761
762
/// CBOR encodings of the protocol messages (spec §16.1).
763
pub mod wire {
764
    use super::*;
765
766
    fn schema(msg: &str) -> RepoError {
767
        RepoError::Object(ObjectError::Schema(msg.into()))
768
    }
769
    fn sigs_value(sigs: &[Signature]) -> Value {
770
        Value::Array(sigs.iter().map(|s| s.to_value()).collect())
771
    }
772
    fn sigs_from(v: &Value) -> Result<Vec<Signature>> {
773
        Ok(o::array(v, "signatures")?
774
            .iter()
775
            .map(Signature::from_value)
776
            .collect::<std::result::Result<Vec<_>, _>>()?)
777
    }
778
    fn hashes_value(hs: &[ObjectRef]) -> Value {
779
        Value::Array(hs.iter().map(|h| Value::Bytes(h.0.to_vec())).collect())
780
    }
781
    fn hashes_from(v: &Value) -> Result<Vec<ObjectRef>> {
782
        Ok(o::array(v, "hashes")?
783
            .iter()
784
            .map(|h| o::oref(h, "hash"))
785
            .collect::<std::result::Result<Vec<_>, _>>()?)
786
    }
787
    fn attest_value(sa: &SignedAttest) -> Value {
788
        Value::Array(vec![Value::Bytes(sa.attest.encode()), sigs_value(&sa.sigs)])
789
    }
790
    fn attest_from(v: &Value) -> Result<SignedAttest> {
791
        let a = o::array(v, "signed attest")?;
792
        if a.len() != 2 {
793
            return Err(schema("signed attest: expected [attest, sigs]"));
794
        }
795
        Ok(SignedAttest {
796
            attest: Attest::decode(o::bytes(&a[0], "attest")?)?,
797
            sigs: sigs_from(&a[1])?,
798
        })
799
    }
800
    fn opt_attest_value(sa: &Option<SignedAttest>) -> Value {
801
        sa.as_ref().map(attest_value).unwrap_or(Value::Null)
802
    }
803
    fn opt_attest_from(v: &Value) -> Result<Option<SignedAttest>> {
804
        if v.is_null() {
805
            Ok(None)
806
        } else {
807
            attest_from(v).map(Some)
808
        }
809
    }
810
    /// `[policy bytes, [signature]]`: also the format of a policy proposal
811
    /// file exchanged between root holders (spec §14.5).
812
    pub fn policy_value(sp: &SignedPolicy) -> Value {
813
        Value::Array(vec![Value::Bytes(sp.policy.encode()), sigs_value(&sp.sigs)])
814
    }
815
    pub fn policy_from(v: &Value) -> Result<SignedPolicy> {
816
        let a = o::array(v, "signed policy")?;
817
        if a.len() != 2 {
818
            return Err(schema("signed policy: expected [policy, sigs]"));
819
        }
820
        Ok(SignedPolicy {
821
            policy: Policy::decode(o::bytes(&a[0], "policy")?)?,
822
            sigs: sigs_from(&a[1])?,
823
        })
824
    }
825
    fn opt_policy_value(sp: Option<&SignedPolicy>) -> Value {
826
        sp.map(policy_value).unwrap_or(Value::Null)
827
    }
828
    fn opt_policy_from(v: &Value) -> Result<Option<SignedPolicy>> {
829
        if v.is_null() {
830
            Ok(None)
831
        } else {
832
            policy_from(v).map(Some)
833
        }
834
    }
835
    fn map<'a>(v: &'a Value, what: &str) -> Result<&'a o::Map> {
836
        Ok(o::map(v, what)?)
837
    }
838
    fn field<'a>(m: &'a o::Map, k: u64, what: &str) -> Result<&'a Value> {
839
        Ok(o::field(m, k, what)?)
840
    }
841
842
    /// A bundle's value. Each change's text blobs and their chunks (spec
843
    /// §6.1) are added to its objects when they are not already there, so a
844
    /// bundle can always be read on its own.
845
    pub fn bundle_value(b: &Bundle) -> Value {
846
        let mut changes = Vec::with_capacity(b.raw_changes.len() + b.changes.len());
847
        // Changes as stored are already their encoding, their texts among
848
        // the objects.
849
        for (bytes, s) in &b.raw_changes {
850
            changes.push(Value::Array(vec![
851
                Value::Bytes(bytes.clone()),
852
                sigs_value(s),
853
            ]));
854
        }
855
        let mut texts: Vec<(ObjectType, Vec<u8>)> = Vec::new();
856
        let mut listed: Option<std::collections::HashSet<ObjectRef>> = None;
857
        for (c, s) in &b.changes {
858
            let (bytes, stored) = c.encode_parts();
859
            for t in stored {
860
                let listed = listed.get_or_insert_with(|| {
861
                    b.objects
862
                        .iter()
863
                        .map(|(ty, body)| crate::hash::hash_object(*ty, body))
864
                        .collect()
865
                });
866
                if !listed.insert(t.blob.hash()) {
867
                    continue;
868
                }
869
                for chunk in crate::chunk::chunks(&t.content) {
870
                    if listed.insert(crate::hash::hash_object(ObjectType::Chunk, chunk)) {
871
                        texts.push((ObjectType::Chunk, chunk.to_vec()));
872
                    }
873
                }
874
                texts.push((ObjectType::Blob, t.blob.encode()));
875
            }
876
            changes.push(Value::Array(vec![Value::Bytes(bytes), sigs_value(s)]));
877
        }
878
        let mut v = Value::map([
879
            (0, Value::Array(changes)),
880
            (
881
                1,
882
                Value::Array(b.attests.iter().map(attest_value).collect()),
883
            ),
884
            (
885
                2,
886
                Value::Array(
887
                    b.objects
888
                        .iter()
889
                        .chain(&texts)
890
                        .map(|(t, body)| {
891
                            Value::Array(vec![
892
                                Value::Text(t.name().into()),
893
                                Value::Bytes(body.clone()),
894
                            ])
895
                        })
896
                        .collect(),
897
                ),
898
            ),
899
            (
900
                3,
901
                Value::Array(b.policies.iter().map(policy_value).collect()),
902
            ),
903
        ]);
904
        // Only when there are any; older peers ignore the field.
905
        if !b.certificates.is_empty() {
906
            if let Value::Map(m) = &mut v {
907
                m.insert(
908
                    4,
909
                    Value::Array(
910
                        b.certificates
911
                            .iter()
912
                            .map(|c| Value::Bytes(c.encode()))
913
                            .collect(),
914
                    ),
915
                );
916
            }
917
        }
918
        v
919
    }
920
921
    pub fn bundle_from_value(v: &Value) -> Result<Bundle> {
922
        let m = map(v, "bundle")?;
923
        let mut b = Bundle::default();
924
        for ob in o::array(field(m, 2, "objects")?, "objects")? {
925
            let pair = o::array(ob, "object")?;
926
            if pair.len() != 2 {
927
                return Err(schema("object: expected [type, body]"));
928
            }
929
            let ty = ObjectType::from_name(o::text(&pair[0], "object type")?)
930
                .ok_or_else(|| schema("unknown object type"))?;
931
            b.objects
932
                .push((ty, o::bytes(&pair[1], "object body")?.to_vec()));
933
        }
934
        // Stored inserts are read from the bundle's own objects.
935
        let mut by_ref: Option<std::collections::HashMap<ObjectRef, usize>> = None;
936
        for c in o::array(field(m, 0, "changes")?, "changes")? {
937
            let pair = o::array(c, "change entry")?;
938
            if pair.len() != 2 {
939
                return Err(schema("change entry: expected [change, sigs]"));
940
            }
941
            let encoded = o::bytes(&pair[0], "change")?;
942
            b.hashes
943
                .push(crate::hash::hash_object(ObjectType::Change, encoded));
944
            let change = Change::decode_with(encoded, &mut |text, count, form| {
945
                let by_ref = by_ref.get_or_insert_with(|| {
946
                    b.objects
947
                        .iter()
948
                        .enumerate()
949
                        .map(|(i, (ty, body))| (crate::hash::hash_object(*ty, body), i))
950
                        .collect()
951
                });
952
                let get =
953
                    |r: &ObjectRef, want: ObjectType| match by_ref.get(r).map(|i| &b.objects[*i]) {
954
                        Some((ty, body)) if *ty == want => Ok(body),
955
                        _ => Err(ObjectError::Schema(format!(
956
                            "the bundle lacks {} {}",
957
                            want.name(),
958
                            r.short(12)
959
                        ))),
960
                    };
961
                let blob = crate::objects::Blob::decode(get(text, ObjectType::Blob)?)?;
962
                let mut content = Vec::with_capacity(blob.length as usize);
963
                for chunk in &blob.chunks {
964
                    content.extend_from_slice(get(chunk, ObjectType::Chunk)?);
965
                }
966
                crate::objects::text_lines(&content, count, form)
967
            })?;
968
            b.changes.push((change, sigs_from(&pair[1])?));
969
        }
970
        for a in o::array(field(m, 1, "attests")?, "attests")? {
971
            b.attests.push(attest_from(a)?);
972
        }
973
        if let Some(ps) = m.get(&3) {
974
            for p in o::array(ps, "policies")? {
975
                b.policies.push(policy_from(p)?);
976
            }
977
        }
978
        if let Some(cs) = m.get(&4) {
979
            for c in o::array(cs, "certificates")? {
980
                b.certificates.push(
981
                    crate::cert::SignedCertificate::decode(o::bytes(c, "certificate")?)
982
                        .map_err(|e| schema(&format!("certificate: {e}")))?,
983
                );
984
            }
985
        }
986
        Ok(b)
987
    }
988
989
    pub fn encode_bundle(b: &Bundle) -> Vec<u8> {
990
        cbor::encode(&bundle_value(b))
991
    }
992
    pub fn decode_bundle(bytes: &[u8]) -> Result<Bundle> {
993
        bundle_from_value(&cbor::decode(bytes).map_err(ObjectError::from)?)
994
    }
995
996
    pub fn encode_capabilities(id: [u8; 16]) -> Vec<u8> {
997
        cbor::encode(&Value::map([
998
            (0, Value::Array(vec![Value::Uint(PROTOCOL_VERSION)])),
999
            (1, Value::Bytes(id.to_vec())),
1000
            (2, Value::Array(vec![Value::Text("seal".into())])),
1001
        ]))
1002
    }
1003
    pub fn decode_capabilities(bytes: &[u8]) -> Result<[u8; 16]> {
1004
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
1005
        let m = map(&v, "capabilities")?;
1006
        let versions = o::array(field(m, 0, "versions")?, "versions")?;
1007
        if !versions
1008
            .iter()
1009
            .any(|x| x.as_uint() == Some(PROTOCOL_VERSION))
1010
        {
1011
            return Err(RepoError::Msg(
1012
                "remote does not speak protocol version 1".into(),
1013
            ));
1014
        }
1015
        o::bytes(field(m, 1, "repo id")?, "repo id")?
1016
            .try_into()
1017
            .map_err(|_| schema("repo id: expected 16 bytes"))
1018
    }
1019
1020
    fn tags_value(tags: &[TagRef]) -> Value {
1021
        Value::Array(
1022
            tags.iter()
1023
                .map(|t| {
1024
                    let mut v = Value::map([
1025
                        (0, Value::Text(t.name.clone())),
1026
                        (1, Value::Bytes(t.state.0.to_vec())),
1027
                        (2, hashes_value(&t.heads)),
1028
                        (3, opt_attest_value(&t.attestation)),
1029
                    ]);
1030
                    // Only when there is one; older peers ignore them
1031
                    // (oxygen#129).
1032
                    if let Value::Map(m) = &mut v {
1033
                        if t.accepted.is_some() {
1034
                            m.insert(4, opt_attest_value(&t.accepted));
1035
                        }
1036
                        if let Some(l) = &t.logged {
1037
                            m.insert(5, logged_value(l));
1038
                        }
1039
                        if !t.integration.is_empty() {
1040
                            m.insert(6, integration_value(&t.integration));
1041
                        }
1042
                    }
1043
                    v
1044
                })
1045
                .collect(),
1046
        )
1047
    }
1048
    fn tags_from(v: &Value) -> Result<Vec<TagRef>> {
1049
        let mut out = Vec::new();
1050
        for t in o::array(v, "tags")? {
1051
            let tm = map(t, "tag")?;
1052
            out.push(TagRef {
1053
                name: o::text(field(tm, 0, "name")?, "name")?.to_owned(),
1054
                state: o::oref(field(tm, 1, "state")?, "state")?,
1055
                heads: hashes_from(field(tm, 2, "heads")?)?,
1056
                attestation: opt_attest_from(field(tm, 3, "attestation")?)?,
1057
                accepted: match tm.get(&4) {
1058
                    Some(a) => opt_attest_from(a)?,
1059
                    None => None,
1060
                },
1061
                logged: tm.get(&5).map(logged_from).transpose()?,
1062
                integration: match tm.get(&6) {
1063
                    Some(l) => integration_from(l)?,
1064
                    None => Vec::new(),
1065
                },
1066
            });
1067
        }
1068
        Ok(out)
1069
    }
1070
1071
    /// The tags of a refs answer as oxy 0.5.0 read them (and the runners
1072
    /// built with it), keys 0 to 3 only: what an older reader makes of an
1073
    /// answer with keys 4 to 6.
1074
    #[cfg(test)]
1075
    pub(super) fn tags_as_0_5_read_them(bytes: &[u8]) -> Result<Vec<TagRef>> {
1076
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
1077
        let m = map(&v, "refs")?;
1078
        let mut out = Vec::new();
1079
        for t in o::array(field(m, 3, "tags")?, "tags")? {
1080
            let tm = map(t, "tag")?;
1081
            out.push(TagRef::new(
1082
                o::text(field(tm, 0, "name")?, "name")?.to_owned(),
1083
                o::oref(field(tm, 1, "state")?, "state")?,
1084
                hashes_from(field(tm, 2, "heads")?)?,
1085
                opt_attest_from(field(tm, 3, "attestation")?)?,
1086
            ));
1087
        }
1088
        Ok(out)
1089
    }
1090
1091
    /// A log place, `[entry number, entry bytes, [proof hash]]` (spec §14.8).
1092
    fn logged_value(l: &Logged) -> Value {
1093
        Value::Array(vec![
1094
            Value::Uint(l.index),
1095
            Value::Bytes(l.entry.clone()),
1096
            proof_value(&l.proof),
1097
        ])
1098
    }
1099
    fn logged_from(v: &Value) -> Result<Logged> {
1100
        let a = o::array(v, "logged")?;
1101
        if a.len() != 3 {
1102
            return Err(schema("logged: expected [index, entry, proof]"));
1103
        }
1104
        Ok(Logged {
1105
            index: o::uint(&a[0], "index")?,
1106
            entry: o::bytes(&a[1], "entry")?.to_vec(),
1107
            proof: proof_from(&a[2])?,
1108
        })
1109
    }
1110
1111
    /// Cosigned checkpoints holding an entry, `[[note, [proof hash]]]`.
1112
    fn integration_value(integration: &[Integration]) -> Value {
1113
        Value::Array(
1114
            integration
1115
                .iter()
1116
                .map(|i| Value::Array(vec![Value::Text(i.note.clone()), proof_value(&i.proof)]))
1117
                .collect(),
1118
        )
1119
    }
1120
    fn integration_from(v: &Value) -> Result<Vec<Integration>> {
1121
        let mut out = Vec::new();
1122
        for i in o::array(v, "integration")? {
1123
            let a = o::array(i, "integration")?;
1124
            if a.len() != 2 {
1125
                return Err(schema("integration: expected [note, proof]"));
1126
            }
1127
            out.push(Integration {
1128
                note: o::text(&a[0], "note")?.to_owned(),
1129
                proof: proof_from(&a[1])?,
1130
            });
1131
        }
1132
        Ok(out)
1133
    }
1134
1135
    pub fn encode_refs(id: [u8; 16], resp: &RefsResponse) -> Vec<u8> {
1136
        let mut v = Value::map([
1137
            (
1138
                0,
1139
                Value::Array(
1140
                    resp.refs
1141
                        .iter()
1142
                        .map(|r| {
1143
                            let mut v = Value::map([
1144
                                (0, Value::Text(r.name.clone())),
1145
                                (1, Value::Bytes(r.state.0.to_vec())),
1146
                                (2, hashes_value(&r.heads)),
1147
                                (3, opt_attest_value(&r.attestation)),
1148
                                (4, r.last_serial.map(Value::Uint).unwrap_or(Value::Null)),
1149
                            ]);
1150
                            // Only when there is one; older peers ignore it.
1151
                            if let Value::Map(m) = &mut v {
1152
                                if r.accepted.is_some() {
1153
                                    m.insert(5, opt_attest_value(&r.accepted));
1154
                                }
1155
                                if let Some(l) = &r.logged {
1156
                                    m.insert(6, logged_value(l));
1157
                                }
1158
                                if !r.integration.is_empty() {
1159
                                    m.insert(7, integration_value(&r.integration));
1160
                                }
1161
                            }
1162
                            v
1163
                        })
1164
                        .collect(),
1165
                ),
1166
            ),
1167
            (1, Value::Bytes(id.to_vec())),
1168
            (2, opt_policy_value(resp.policy.as_ref())),
1169
            (3, tags_value(&resp.tags)),
1170
            (
1171
                4,
1172
                Value::Array(resp.history.iter().map(policy_value).collect()),
1173
            ),
1174
            (
1175
                5,
1176
                resp.default_bookmark
1177
                    .clone()
1178
                    .map(Value::Text)
1179
                    .unwrap_or(Value::Null),
1180
            ),
1181
        ]);
1182
        if let Value::Map(m) = &mut v {
1183
            if let Some(log) = &resp.log {
1184
                m.insert(6, Value::Text(log.clone()));
1185
            }
1186
            if !resp.witnesses.is_empty() {
1187
                m.insert(
1188
                    7,
1189
                    Value::Array(
1190
                        resp.witnesses
1191
                            .iter()
1192
                            .map(|(name, id)| {
1193
                                Value::Array(vec![
1194
                                    Value::Text(name.clone()),
1195
                                    Value::Bytes(id.clone()),
1196
                                ])
1197
                            })
1198
                            .collect(),
1199
                    ),
1200
                );
1201
            }
1202
        }
1203
        cbor::encode(&v)
1204
    }
1205
    pub fn decode_refs(bytes: &[u8]) -> Result<([u8; 16], RefsResponse)> {
1206
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
1207
        let m = map(&v, "refs")?;
1208
        let id: [u8; 16] = o::bytes(field(m, 1, "repo id")?, "repo id")?
1209
            .try_into()
1210
            .map_err(|_| schema("repo id: expected 16 bytes"))?;
1211
        let mut refs = Vec::new();
1212
        for r in o::array(field(m, 0, "refs")?, "refs")? {
1213
            let rm = map(r, "ref")?;
1214
            let ls = field(rm, 4, "last serial")?;
1215
            refs.push(RemoteRef {
1216
                name: o::text(field(rm, 0, "name")?, "name")?.to_owned(),
1217
                state: o::oref(field(rm, 1, "state")?, "state")?,
1218
                heads: hashes_from(field(rm, 2, "heads")?)?,
1219
                attestation: opt_attest_from(field(rm, 3, "attestation")?)?,
1220
                last_serial: if ls.is_null() {
1221
                    None
1222
                } else {
1223
                    Some(o::uint(ls, "last serial")?)
1224
                },
1225
                accepted: match rm.get(&5) {
1226
                    Some(a) => opt_attest_from(a)?,
1227
                    None => None,
1228
                },
1229
                logged: rm.get(&6).map(logged_from).transpose()?,
1230
                integration: match rm.get(&7) {
1231
                    Some(l) => integration_from(l)?,
1232
                    None => Vec::new(),
1233
                },
1234
            });
1235
        }
1236
        let policy = match m.get(&2) {
1237
            Some(p) => opt_policy_from(p)?,
1238
            None => None,
1239
        };
1240
        let tags = match m.get(&3) {
1241
            Some(t) => tags_from(t)?,
1242
            None => Vec::new(),
1243
        };
1244
        let mut history = Vec::new();
1245
        if let Some(h) = m.get(&4) {
1246
            for p in o::array(h, "history")? {
1247
                history.push(policy_from(p)?);
1248
            }
1249
        }
1250
        let default_bookmark = match m.get(&5) {
1251
            Some(Value::Text(t)) => Some(t.clone()),
1252
            _ => None,
1253
        };
1254
        let log = match m.get(&6) {
1255
            Some(Value::Text(t)) => Some(t.clone()),
1256
            _ => None,
1257
        };
1258
        let mut witnesses = Vec::new();
1259
        if let Some(w) = m.get(&7) {
1260
            for x in o::array(w, "witnesses")? {
1261
                let a = o::array(x, "witness")?;
1262
                if a.len() != 2 {
1263
                    return Err(schema("witness: expected [name, identity]"));
1264
                }
1265
                witnesses.push((
1266
                    o::text(&a[0], "witness name")?.to_owned(),
1267
                    o::bytes(&a[1], "witness identity")?.to_vec(),
1268
                ));
1269
            }
1270
        }
1271
        Ok((
1272
            id,
1273
            RefsResponse {
1274
                refs,
1275
                policy,
1276
                tags,
1277
                history,
1278
                default_bookmark,
1279
                log,
1280
                witnesses,
1281
            },
1282
        ))
1283
    }
1284
1285
    /// A proof's hashes, from the leaf upwards (spec §14.8).
1286
    fn proof_value(proof: &[[u8; 32]]) -> Value {
1287
        Value::Array(proof.iter().map(|h| Value::Bytes(h.to_vec())).collect())
1288
    }
1289
1290
    fn proof_from(v: &Value) -> Result<Vec<[u8; 32]>> {
1291
        let mut proof = Vec::new();
1292
        for h in o::array(v, "proof")? {
1293
            proof.push(
1294
                o::bytes(h, "proof hash")?
1295
                    .try_into()
1296
                    .map_err(|_| schema("proof hash: expected 32 bytes"))?,
1297
            );
1298
        }
1299
        Ok(proof)
1300
    }
1301
1302
    pub fn encode_negotiate(have: &[ChangeHash], want: &[ChangeHash]) -> Vec<u8> {
1303
        cbor::encode(&Value::map([
1304
            (0, hashes_value(have)),
1305
            (1, hashes_value(want)),
1306
        ]))
1307
    }
1308
    pub fn decode_negotiate(bytes: &[u8]) -> Result<(Vec<ChangeHash>, Vec<ChangeHash>)> {
1309
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
1310
        let m = map(&v, "negotiate")?;
1311
        Ok((
1312
            hashes_from(field(m, 0, "have")?)?,
1313
            hashes_from(field(m, 1, "want")?)?,
1314
        ))
1315
    }
1316
1317
    /// `fetch` request: `{0: [changes], 1: max blob size or null}`.
1318
    pub fn encode_fetch(hs: &[ChangeHash], max_blob: Option<u64>) -> Vec<u8> {
1319
        cbor::encode(&Value::map([
1320
            (0, hashes_value(hs)),
1321
            (1, max_blob.map(Value::Uint).unwrap_or(Value::Null)),
1322
        ]))
1323
    }
1324
    pub fn decode_fetch(bytes: &[u8]) -> Result<(Vec<ChangeHash>, Option<u64>)> {
1325
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
1326
        let m = map(&v, "fetch")?;
1327
        let max = match m.get(&1) {
1328
            Some(x) if !x.is_null() => Some(o::uint(x, "max blob")?),
1329
            _ => None,
1330
        };
1331
        Ok((hashes_from(field(m, 0, "changes")?)?, max))
1332
    }
1333
1334
    /// `shallow` request: `{0: [heads], 1: depth}`.
1335
    pub fn encode_shallow(hs: &[ChangeHash], depth: u32) -> Vec<u8> {
1336
        cbor::encode(&Value::map([
1337
            (0, hashes_value(hs)),
1338
            (1, Value::Uint(depth as u64)),
1339
        ]))
1340
    }
1341
    pub fn decode_shallow(bytes: &[u8]) -> Result<(Vec<ChangeHash>, u32)> {
1342
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
1343
        let m = map(&v, "shallow")?;
1344
        Ok((
1345
            hashes_from(field(m, 0, "heads")?)?,
1346
            o::u32_(field(m, 1, "depth")?, "depth")?,
1347
        ))
1348
    }
1349
1350
    pub fn encode_hashes(hs: &[ChangeHash]) -> Vec<u8> {
1351
        cbor::encode(&Value::map([(0, hashes_value(hs))]))
1352
    }
1353
    pub fn decode_hashes(bytes: &[u8]) -> Result<Vec<ChangeHash>> {
1354
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
1355
        hashes_from(field(map(&v, "hashes")?, 0, "hashes")?)
1356
    }
1357
1358
    pub fn encode_push(
1359
        bundle: &Bundle,
1360
        updates: &[RefUpdate],
1361
        policy: Option<&SignedPolicy>,
1362
        tags: &[TagRef],
1363
    ) -> Vec<u8> {
1364
        cbor::encode(&Value::map([
1365
            (0, bundle_value(bundle)),
1366
            (2, opt_policy_value(policy)),
1367
            (3, tags_value(tags)),
1368
            (
1369
                1,
1370
                Value::Array(
1371
                    updates
1372
                        .iter()
1373
                        .map(|u| {
1374
                            Value::map([
1375
                                (0, Value::Text(u.name.clone())),
1376
                                (1, Value::Bytes(u.old_state.0.to_vec())),
1377
                                (2, Value::Bytes(u.new_state.0.to_vec())),
1378
                                (3, Value::Bool(u.force)),
1379
                                (4, opt_attest_value(&u.attestation)),
1380
                            ])
1381
                        })
1382
                        .collect(),
1383
                ),
1384
            ),
1385
        ]))
1386
    }
1387
    /// A decoded push: bundle, bookmark updates, policy, tags.
1388
    pub type PushParts = (Bundle, Vec<RefUpdate>, Option<SignedPolicy>, Vec<TagRef>);
1389
1390
    pub fn decode_push(bytes: &[u8]) -> Result<PushParts> {
1391
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
1392
        let m = map(&v, "push")?;
1393
        let bundle = bundle_from_value(field(m, 0, "bundle")?)?;
1394
        let mut updates = Vec::new();
1395
        for u in o::array(field(m, 1, "updates")?, "updates")? {
1396
            let um = map(u, "update")?;
1397
            updates.push(RefUpdate {
1398
                name: o::text(field(um, 0, "name")?, "name")?.to_owned(),
1399
                old_state: o::oref(field(um, 1, "old_state")?, "old_state")?,
1400
                new_state: o::oref(field(um, 2, "new_state")?, "new_state")?,
1401
                force: field(um, 3, "force")?
1402
                    .as_bool()
1403
                    .ok_or_else(|| schema("force: expected bool"))?,
1404
                attestation: opt_attest_from(field(um, 4, "attestation")?)?,
1405
            });
1406
        }
1407
        let policy = match m.get(&2) {
1408
            Some(p) => opt_policy_from(p)?,
1409
            None => None,
1410
        };
1411
        let tags = match m.get(&3) {
1412
            Some(t) => tags_from(t)?,
1413
            None => Vec::new(),
1414
        };
1415
        Ok((bundle, updates, policy, tags))
1416
    }
1417
1418
    pub fn encode_push_response(results: &[RefResult]) -> Vec<u8> {
1419
        cbor::encode(&Value::map([(
1420
            0,
1421
            Value::Array(
1422
                results
1423
                    .iter()
1424
                    .map(|r| {
1425
                        Value::map([
1426
                            (0, Value::Text(r.name.clone())),
1427
                            (1, Value::Bool(r.ok)),
1428
                            (2, Value::Text(r.reason.clone())),
1429
                        ])
1430
                    })
1431
                    .collect(),
1432
            ),
1433
        )]))
1434
    }
1435
    pub fn decode_push_response(bytes: &[u8]) -> Result<Vec<RefResult>> {
1436
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
1437
        let m = map(&v, "push response")?;
1438
        let mut out = Vec::new();
1439
        for r in o::array(field(m, 0, "results")?, "results")? {
1440
            let rm = map(r, "result")?;
1441
            out.push(RefResult {
1442
                name: o::text(field(rm, 0, "name")?, "name")?.to_owned(),
1443
                ok: field(rm, 1, "ok")?
1444
                    .as_bool()
1445
                    .ok_or_else(|| schema("ok: expected bool"))?,
1446
                reason: o::text(field(rm, 2, "reason")?, "reason")?.to_owned(),
1447
            });
1448
        }
1449
        Ok(out)
1450
    }
1451
}
1452
1453
#[cfg(test)]
1454
mod tests {
1455
    use super::*;
1456
    use crate::attest::AttestBody;
1457
    use crate::objects::Hlc;
1458
1459
    /// oxygen#133: a proxy's HTML error page is shown by its title, and a
1460
    /// server's own text as it is; a 413 says to push in smaller parts.
1461
    #[test]
1462
    fn html_error_pages_are_shown_by_their_title() {
1463
        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>";
1464
        assert_eq!(
1465
            plain_error_text(cloudflare),
1466
            "413 Request Entity Too Large (an HTML error page, from a proxy in front of the server perhaps)"
1467
        );
1468
        assert_eq!(
1469
            plain_error_text("  refused: a secret\nat a.txt:3 "),
1470
            "refused: a secret\nat a.txt:3"
1471
        );
1472
        assert!(hint_for("https://hub/x: HTTP 413: too large")
1473
            .unwrap()
1474
            .contains("push.batch-bytes"));
1475
    }
1476
1477
    #[test]
1478
    fn client_features_are_declared_and_read() {
1479
        assert_eq!(CLIENT_FEATURES.join(","), "certified-tags");
1480
        assert!(user_agent().starts_with("oxy/"));
1481
        assert!(declares_feature(
1482
            Some("certified-tags"),
1483
            FEATURE_CERTIFIED_TAGS
1484
        ));
1485
        assert!(declares_feature(
1486
            Some("later-thing, Certified-Tags ,x"),
1487
            FEATURE_CERTIFIED_TAGS
1488
        ));
1489
        assert!(!declares_feature(
1490
            Some("certified-tags-v2"),
1491
            FEATURE_CERTIFIED_TAGS
1492
        ));
1493
        assert!(!declares_feature(Some(""), FEATURE_CERTIFIED_TAGS));
1494
        assert!(!declares_feature(None, FEATURE_CERTIFIED_TAGS));
1495
    }
1496
1497
    #[test]
1498
    fn wire_round_trips() {
1499
        let c = crate::objects::tests::sample_change();
1500
        let sk = crate::identity::SecretKey {
1501
            ed_seed: [1; 32],
1502
            ml_seed: [2; 32],
1503
        };
1504
        let id = sk.identity("a", "b", 0);
1505
        let key = id.hash();
1506
        let sig = sk.sign(crate::identity::Domain::Change, &key, &c.hash());
1507
        let seal = Attest::seal([3; 16], vec![c.hash()]);
1508
        let seal_sig = sk.sign(crate::identity::Domain::Attest, &key, &seal.hash());
1509
        let policy = Policy::single_root([3; 16], id.clone(), 99);
1510
        let psig = sk.sign(crate::identity::Domain::Policy, &key, &policy.hash());
1511
        let bundle = Bundle {
1512
            changes: vec![(c.clone(), vec![sig.clone()])],
1513
            attests: vec![SignedAttest {
1514
                attest: seal.clone(),
1515
                sigs: vec![seal_sig],
1516
            }],
1517
            objects: vec![
1518
                (ObjectType::Identity, id.encode()),
1519
                (ObjectType::Chunk, b"xyz".to_vec()),
1520
            ],
1521
            policies: vec![SignedPolicy {
1522
                policy: policy.clone(),
1523
                sigs: vec![psig.clone()],
1524
            }],
1525
            hashes: vec![],
1526
            raw_changes: vec![],
1527
            certificates: vec![],
1528
        };
1529
        let d = wire::decode_bundle(&wire::encode_bundle(&bundle)).unwrap();
1530
        assert_eq!(
1531
            d.hashes,
1532
            vec![c.hash()],
1533
            "the receiver hashes what it was sent"
1534
        );
1535
        assert_eq!(d.changes, bundle.changes);
1536
        assert_eq!(d.attests, bundle.attests);
1537
        assert_eq!(d.objects, bundle.objects);
1538
        assert_eq!(d.policies, bundle.policies);
1539
        assert!(d.certificates.is_empty());
1540
        // Certificates (keyless, oxygenhub#241) travel as field 4, only
1541
        // when there are any: a bundle without them encodes as before.
1542
        let plain = wire::encode_bundle(&bundle);
1543
        let mut with = bundle.clone();
1544
        let issuer_sk = crate::identity::SecretKey::generate();
1545
        let issuer = issuer_sk.identity("hub", "h@x", 1);
1546
        with.certificates.push(crate::cert::SignedCertificate::sign(
1547
            crate::cert::Certificate {
1548
                key: id.clone(),
1549
                issuer: issuer.hash(),
1550
                subject: "agent:a@b".into(),
1551
                claims: vec![],
1552
                scope: crate::identity::Scope::CHANGES,
1553
                not_before: 1,
1554
                expires: 2,
1555
                grant: None,
1556
            },
1557
            &issuer,
1558
            &issuer_sk,
1559
        ));
1560
        let encoded = wire::encode_bundle(&with);
1561
        assert_ne!(encoded, plain);
1562
        assert_eq!(
1563
            wire::decode_bundle(&encoded).unwrap().certificates,
1564
            with.certificates
1565
        );
1566
        with.certificates.clear();
1567
        assert_eq!(wire::encode_bundle(&with), plain);
1568
1569
        let att = Attest {
1570
            repo: [3; 16],
1571
            hlc: Hlc::default(),
1572
            body: AttestBody::Ref {
1573
                name: "main".into(),
1574
                old_state: ObjectRef([1; 32]),
1575
                new_state: ObjectRef([2; 32]),
1576
                serial: 4,
1577
            },
1578
        };
1579
        let refs = vec![
1580
            RemoteRef {
1581
                name: "main".into(),
1582
                state: ObjectRef([2; 32]),
1583
                heads: vec![c.hash()],
1584
                attestation: Some(SignedAttest {
1585
                    attest: att.clone(),
1586
                    sigs: vec![sig.clone()],
1587
                }),
1588
                last_serial: Some(4),
1589
                accepted: None,
1590
                logged: None,
1591
                integration: vec![],
1592
            },
1593
            RemoteRef {
1594
                name: "dev".into(),
1595
                state: ObjectRef([5; 32]),
1596
                heads: vec![],
1597
                attestation: None,
1598
                last_serial: None,
1599
                accepted: None,
1600
                logged: None,
1601
                integration: vec![],
1602
            },
1603
        ];
1604
        let tag = TagRef::new("v1".into(), ObjectRef([2; 32]), vec![c.hash()], None);
1605
        let mut resp = RefsResponse {
1606
            refs,
1607
            policy: Some(SignedPolicy {
1608
                policy: policy.clone(),
1609
                sigs: vec![psig.clone()],
1610
            }),
1611
            tags: vec![tag.clone()],
1612
            history: vec![SignedPolicy {
1613
                policy: policy.clone(),
1614
                sigs: vec![],
1615
            }],
1616
            default_bookmark: Some("develop".into()),
1617
            log: Some("hub.example/log\n2\nroot\n\n- sig\n".into()),
1618
            witnesses: vec![],
1619
        };
1620
        // Without integrated times (spec §14.8) nothing is added: an old
1621
        // peer's answer, and what it reads.
1622
        let old = wire::encode_refs([3; 16], &resp);
1623
        let back = wire::decode_refs(&old).unwrap().1;
1624
        assert!(back.witnesses.is_empty() && back.refs.iter().all(|r| r.integration.is_empty()));
1625
        resp.refs[1].logged = Some(Logged {
1626
            index: 41,
1627
            entry: vec![1, 2, 3],
1628
            proof: vec![[9; 32], [8; 32]],
1629
        });
1630
        resp.refs[1].integration = vec![Integration {
1631
            note: "hub.example/log\n42\nroot\n\n- sig\n".into(),
1632
            proof: vec![[7; 32]],
1633
        }];
1634
        resp.witnesses = vec![("w.example".into(), vec![4, 5, 6])];
1635
        let new = wire::encode_refs([3; 16], &resp);
1636
        let (id_back, back) = wire::decode_refs(&new).unwrap();
1637
        assert_eq!(back.log, resp.log);
1638
        assert_eq!(back.refs[1].logged, resp.refs[1].logged);
1639
        assert_eq!(back.refs[1].integration, resp.refs[1].integration);
1640
        assert_eq!(back.witnesses, resp.witnesses);
1641
        assert_eq!(back.refs[0].logged, None);
1642
        // The new keys are 7s an old reader never asks for.
1643
        let crate::cbor::Value::Map(m) = crate::cbor::decode(&new).unwrap() else {
1644
            panic!()
1645
        };
1646
        assert!(m.contains_key(&7));
1647
        assert_eq!(id_back, [3; 16]);
1648
        assert_eq!(back.refs.len(), 2);
1649
        assert_eq!(back.refs[0].attestation.as_ref().unwrap().attest, att);
1650
        assert_eq!(back.refs[1].last_serial, None);
1651
        assert_eq!(back.policy.as_ref().unwrap().policy, policy);
1652
        assert_eq!(back.history, resp.history);
1653
        assert_eq!(back.tags, vec![tag.clone()]);
1654
1655
        // A tag's acceptance and log place (oxygen#129): keys 4 to 6, only
1656
        // when there are any, so a tag without them encodes as before.
1657
        let crate::cbor::Value::Map(m) = crate::cbor::decode(&new).unwrap() else {
1658
            panic!()
1659
        };
1660
        let crate::cbor::Value::Array(tags) = &m[&3] else {
1661
            panic!()
1662
        };
1663
        let crate::cbor::Value::Map(plain) = &tags[0] else {
1664
            panic!()
1665
        };
1666
        assert_eq!(plain.keys().copied().collect::<Vec<_>>(), vec![0, 1, 2, 3]);
1667
        let mut full = tag.clone();
1668
        full.name = "v2".into();
1669
        full.attestation = Some(SignedAttest {
1670
            attest: att.clone(),
1671
            sigs: vec![sig.clone()],
1672
        });
1673
        full.accepted = full.attestation.clone();
1674
        full.logged = Some(Logged {
1675
            index: 7,
1676
            entry: vec![4],
1677
            proof: vec![[3; 32]],
1678
        });
1679
        full.integration = vec![Integration {
1680
            note: "hub.example/log\n8\nroot\n\n- sig\n".into(),
1681
            proof: vec![],
1682
        }];
1683
        resp.tags = vec![full.clone(), tag.clone()];
1684
        let bytes = wire::encode_refs([3; 16], &resp);
1685
        assert_eq!(wire::decode_refs(&bytes).unwrap().1.tags, resp.tags);
1686
        // In a push too.
1687
        let pushed = wire::encode_push(&Bundle::default(), &[], None, &resp.tags);
1688
        assert_eq!(wire::decode_push(&pushed).unwrap().3, resp.tags);
1689
        // A reader that knows only keys 0 to 3 (oxy 0.5.0 and older, and
1690
        // the runners built with it) reads the same tags from the new answer.
1691
        let stripped: Vec<TagRef> = resp
1692
            .tags
1693
            .iter()
1694
            .map(|t| {
1695
                TagRef::new(
1696
                    t.name.clone(),
1697
                    t.state,
1698
                    t.heads.clone(),
1699
                    t.attestation.clone(),
1700
                )
1701
            })
1702
            .collect();
1703
        assert_eq!(wire::tags_as_0_5_read_them(&bytes).unwrap(), stripped);
1704
1705
        let (h, w) = wire::decode_negotiate(&wire::encode_negotiate(
1706
            &[ObjectRef([1; 32])],
1707
            &[ObjectRef([2; 32])],
1708
        ))
1709
        .unwrap();
1710
        assert_eq!((h, w), (vec![ObjectRef([1; 32])], vec![ObjectRef([2; 32])]));
1711
        assert_eq!(
1712
            wire::decode_hashes(&wire::encode_hashes(&[c.hash()])).unwrap(),
1713
            vec![c.hash()]
1714
        );
1715
        assert_eq!(
1716
            wire::decode_fetch(&wire::encode_fetch(&[c.hash()], Some(4096))).unwrap(),
1717
            (vec![c.hash()], Some(4096))
1718
        );
1719
        assert_eq!(
1720
            wire::decode_fetch(&wire::encode_fetch(&[], None)).unwrap(),
1721
            (vec![], None)
1722
        );
1723
        assert_eq!(
1724
            wire::decode_shallow(&wire::encode_shallow(&[c.hash()], 3)).unwrap(),
1725
            (vec![c.hash()], 3)
1726
        );
1727
        // An old-style fetch request without the filter field still decodes.
1728
        assert_eq!(
1729
            wire::decode_fetch(&wire::encode_hashes(&[c.hash()])).unwrap(),
1730
            (vec![c.hash()], None)
1731
        );
1732
1733
        let up = RefUpdate {
1734
            name: "main".into(),
1735
            old_state: ObjectRef([1; 32]),
1736
            new_state: ObjectRef([2; 32]),
1737
            force: true,
1738
            attestation: Some(SignedAttest {
1739
                attest: att,
1740
                sigs: vec![sig],
1741
            }),
1742
        };
1743
        let sp = SignedPolicy {
1744
            policy,
1745
            sigs: vec![psig],
1746
        };
1747
        let (b2, ups, pol, tags) = wire::decode_push(&wire::encode_push(
1748
            &bundle,
1749
            std::slice::from_ref(&up),
1750
            Some(&sp),
1751
            std::slice::from_ref(&tag),
1752
        ))
1753
        .unwrap();
1754
        assert_eq!(pol, Some(sp));
1755
        assert_eq!(tags, vec![tag]);
1756
        assert_eq!(b2.changes.len(), 1);
1757
        assert_eq!(ups[0].name, "main");
1758
        assert!(ups[0].force);
1759
        assert_eq!(ups[0].attestation, up.attestation);
1760
        let res = vec![RefResult {
1761
            name: "main".into(),
1762
            ok: false,
1763
            reason: "stale".into(),
1764
        }];
1765
        assert_eq!(
1766
            wire::decode_push_response(&wire::encode_push_response(&res)).unwrap(),
1767
            res
1768
        );
1769
        assert_eq!(
1770
            wire::decode_capabilities(&wire::encode_capabilities([7; 16])).unwrap(),
1771
            [7; 16]
1772
        );
1773
    }
1774
}