OXYGENHUB
# d3b270909c78 oxygen / crates / oxy-core / src / protocol.rs
66.7 KiB · Rust · last changed A push no longer passes a proxy's request limit (closes #133) 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
        wire::decode_bundle(&self.call(true, "checkpoint", Some(&wire::encode_hashes(heads)))?)
691
    }
692
    fn shallow(&self, heads: &[ChangeHash], depth: u32) -> Result<Vec<ChangeHash>> {
693
        wire::decode_hashes(&self.call(
694
            true,
695
            "shallow",
696
            Some(&wire::encode_shallow(heads, depth)),
697
        )?)
698
    }
699
    fn push(
700
        &self,
701
        bundle: Bundle,
702
        updates: Vec<RefUpdate>,
703
        policy: Option<SignedPolicy>,
704
        tags: Vec<TagRef>,
705
    ) -> Result<Vec<RefResult>> {
706
        wire::decode_push_response(&self.call(
707
            true,
708
            "push",
709
            Some(&wire::encode_push(
710
                &bundle,
711
                &updates,
712
                policy.as_ref(),
713
                &tags,
714
            )),
715
        )?)
716
    }
717
}
718
719
/// A remote's URL as it is stored: an `http(s)://` URL as given, a local
720
/// path made absolute (with its `file://` kept), so it still names the same
721
/// repository from inside the clone (oxygen#57).
722
pub fn stored_url(url: &str) -> String {
723
    // Only a path is made absolute: a plain one, or one behind file:// or
724
    // dir://. Every other URL (a hub, a bucket) is kept as written.
725
    let (prefix, path) = match (url.strip_prefix("file://"), url.strip_prefix("dir://")) {
726
        (Some(p), _) => ("file://", p),
727
        (_, Some(p)) => ("dir://", p),
728
        _ if url.contains("://") => return url.to_string(),
729
        _ => ("", url),
730
    };
731
    match std::path::absolute(path) {
732
        Ok(abs) => format!("{prefix}{}", abs.display()),
733
        Err(_) => url.to_string(),
734
    }
735
}
736
737
/// Open a remote by URL: a local path (optionally `file://`), `http(s)://`
738
/// (a hub), or a store (`dir://`, and whatever openers are registered).
739
pub fn open_remote(url: &str, options: &RemoteOptions) -> Result<Box<dyn Remote>> {
740
    if url.starts_with("http://") || url.starts_with("https://") {
741
        return Ok(Box::new(HttpRemote::new(url, options)?));
742
    }
743
    if let Some(store) = open_store(url, options) {
744
        return crate::repo::strata::open_store_remote(store?, options);
745
    }
746
    let path = url.strip_prefix("file://").unwrap_or(url);
747
    if path.contains("://") {
748
        return Err(RepoError::Msg(format!("unsupported remote URL {url:?}")));
749
    }
750
    let mut local = LocalRemote::open(Path::new(path))?;
751
    local.claimed_id = options.repo_id;
752
    Ok(Box::new(local))
753
}
754
755
// ---------------------------------------------------------------- wire
756
757
/// CBOR encodings of the protocol messages (spec §16.1).
758
pub mod wire {
759
    use super::*;
760
761
    fn schema(msg: &str) -> RepoError {
762
        RepoError::Object(ObjectError::Schema(msg.into()))
763
    }
764
    fn sigs_value(sigs: &[Signature]) -> Value {
765
        Value::Array(sigs.iter().map(|s| s.to_value()).collect())
766
    }
767
    fn sigs_from(v: &Value) -> Result<Vec<Signature>> {
768
        Ok(o::array(v, "signatures")?
769
            .iter()
770
            .map(Signature::from_value)
771
            .collect::<std::result::Result<Vec<_>, _>>()?)
772
    }
773
    fn hashes_value(hs: &[ObjectRef]) -> Value {
774
        Value::Array(hs.iter().map(|h| Value::Bytes(h.0.to_vec())).collect())
775
    }
776
    fn hashes_from(v: &Value) -> Result<Vec<ObjectRef>> {
777
        Ok(o::array(v, "hashes")?
778
            .iter()
779
            .map(|h| o::oref(h, "hash"))
780
            .collect::<std::result::Result<Vec<_>, _>>()?)
781
    }
782
    fn attest_value(sa: &SignedAttest) -> Value {
783
        Value::Array(vec![Value::Bytes(sa.attest.encode()), sigs_value(&sa.sigs)])
784
    }
785
    fn attest_from(v: &Value) -> Result<SignedAttest> {
786
        let a = o::array(v, "signed attest")?;
787
        if a.len() != 2 {
788
            return Err(schema("signed attest: expected [attest, sigs]"));
789
        }
790
        Ok(SignedAttest {
791
            attest: Attest::decode(o::bytes(&a[0], "attest")?)?,
792
            sigs: sigs_from(&a[1])?,
793
        })
794
    }
795
    fn opt_attest_value(sa: &Option<SignedAttest>) -> Value {
796
        sa.as_ref().map(attest_value).unwrap_or(Value::Null)
797
    }
798
    fn opt_attest_from(v: &Value) -> Result<Option<SignedAttest>> {
799
        if v.is_null() {
800
            Ok(None)
801
        } else {
802
            attest_from(v).map(Some)
803
        }
804
    }
805
    /// `[policy bytes, [signature]]`: also the format of a policy proposal
806
    /// file exchanged between root holders (spec §14.5).
807
    pub fn policy_value(sp: &SignedPolicy) -> Value {
808
        Value::Array(vec![Value::Bytes(sp.policy.encode()), sigs_value(&sp.sigs)])
809
    }
810
    pub fn policy_from(v: &Value) -> Result<SignedPolicy> {
811
        let a = o::array(v, "signed policy")?;
812
        if a.len() != 2 {
813
            return Err(schema("signed policy: expected [policy, sigs]"));
814
        }
815
        Ok(SignedPolicy {
816
            policy: Policy::decode(o::bytes(&a[0], "policy")?)?,
817
            sigs: sigs_from(&a[1])?,
818
        })
819
    }
820
    fn opt_policy_value(sp: Option<&SignedPolicy>) -> Value {
821
        sp.map(policy_value).unwrap_or(Value::Null)
822
    }
823
    fn opt_policy_from(v: &Value) -> Result<Option<SignedPolicy>> {
824
        if v.is_null() {
825
            Ok(None)
826
        } else {
827
            policy_from(v).map(Some)
828
        }
829
    }
830
    fn map<'a>(v: &'a Value, what: &str) -> Result<&'a o::Map> {
831
        Ok(o::map(v, what)?)
832
    }
833
    fn field<'a>(m: &'a o::Map, k: u64, what: &str) -> Result<&'a Value> {
834
        Ok(o::field(m, k, what)?)
835
    }
836
837
    /// A bundle's value. Each change's text blobs and their chunks (spec
838
    /// §6.1) are added to its objects when they are not already there, so a
839
    /// bundle can always be read on its own.
840
    pub fn bundle_value(b: &Bundle) -> Value {
841
        let mut changes = Vec::with_capacity(b.raw_changes.len() + b.changes.len());
842
        // Changes as stored are already their encoding, their texts among
843
        // the objects.
844
        for (bytes, s) in &b.raw_changes {
845
            changes.push(Value::Array(vec![
846
                Value::Bytes(bytes.clone()),
847
                sigs_value(s),
848
            ]));
849
        }
850
        let mut texts: Vec<(ObjectType, Vec<u8>)> = Vec::new();
851
        let mut listed: Option<std::collections::HashSet<ObjectRef>> = None;
852
        for (c, s) in &b.changes {
853
            let (bytes, stored) = c.encode_parts();
854
            for t in stored {
855
                let listed = listed.get_or_insert_with(|| {
856
                    b.objects
857
                        .iter()
858
                        .map(|(ty, body)| crate::hash::hash_object(*ty, body))
859
                        .collect()
860
                });
861
                if !listed.insert(t.blob.hash()) {
862
                    continue;
863
                }
864
                for chunk in crate::chunk::chunks(&t.content) {
865
                    if listed.insert(crate::hash::hash_object(ObjectType::Chunk, chunk)) {
866
                        texts.push((ObjectType::Chunk, chunk.to_vec()));
867
                    }
868
                }
869
                texts.push((ObjectType::Blob, t.blob.encode()));
870
            }
871
            changes.push(Value::Array(vec![Value::Bytes(bytes), sigs_value(s)]));
872
        }
873
        let mut v = Value::map([
874
            (0, Value::Array(changes)),
875
            (
876
                1,
877
                Value::Array(b.attests.iter().map(attest_value).collect()),
878
            ),
879
            (
880
                2,
881
                Value::Array(
882
                    b.objects
883
                        .iter()
884
                        .chain(&texts)
885
                        .map(|(t, body)| {
886
                            Value::Array(vec![
887
                                Value::Text(t.name().into()),
888
                                Value::Bytes(body.clone()),
889
                            ])
890
                        })
891
                        .collect(),
892
                ),
893
            ),
894
            (
895
                3,
896
                Value::Array(b.policies.iter().map(policy_value).collect()),
897
            ),
898
        ]);
899
        // Only when there are any; older peers ignore the field.
900
        if !b.certificates.is_empty() {
901
            if let Value::Map(m) = &mut v {
902
                m.insert(
903
                    4,
904
                    Value::Array(
905
                        b.certificates
906
                            .iter()
907
                            .map(|c| Value::Bytes(c.encode()))
908
                            .collect(),
909
                    ),
910
                );
911
            }
912
        }
913
        v
914
    }
915
916
    pub fn bundle_from_value(v: &Value) -> Result<Bundle> {
917
        let m = map(v, "bundle")?;
918
        let mut b = Bundle::default();
919
        for ob in o::array(field(m, 2, "objects")?, "objects")? {
920
            let pair = o::array(ob, "object")?;
921
            if pair.len() != 2 {
922
                return Err(schema("object: expected [type, body]"));
923
            }
924
            let ty = ObjectType::from_name(o::text(&pair[0], "object type")?)
925
                .ok_or_else(|| schema("unknown object type"))?;
926
            b.objects
927
                .push((ty, o::bytes(&pair[1], "object body")?.to_vec()));
928
        }
929
        // Stored inserts are read from the bundle's own objects.
930
        let mut by_ref: Option<std::collections::HashMap<ObjectRef, usize>> = None;
931
        for c in o::array(field(m, 0, "changes")?, "changes")? {
932
            let pair = o::array(c, "change entry")?;
933
            if pair.len() != 2 {
934
                return Err(schema("change entry: expected [change, sigs]"));
935
            }
936
            let encoded = o::bytes(&pair[0], "change")?;
937
            b.hashes
938
                .push(crate::hash::hash_object(ObjectType::Change, encoded));
939
            let change = Change::decode_with(encoded, &mut |text, count, form| {
940
                let by_ref = by_ref.get_or_insert_with(|| {
941
                    b.objects
942
                        .iter()
943
                        .enumerate()
944
                        .map(|(i, (ty, body))| (crate::hash::hash_object(*ty, body), i))
945
                        .collect()
946
                });
947
                let get =
948
                    |r: &ObjectRef, want: ObjectType| match by_ref.get(r).map(|i| &b.objects[*i]) {
949
                        Some((ty, body)) if *ty == want => Ok(body),
950
                        _ => Err(ObjectError::Schema(format!(
951
                            "the bundle lacks {} {}",
952
                            want.name(),
953
                            r.short(12)
954
                        ))),
955
                    };
956
                let blob = crate::objects::Blob::decode(get(text, ObjectType::Blob)?)?;
957
                let mut content = Vec::with_capacity(blob.length as usize);
958
                for chunk in &blob.chunks {
959
                    content.extend_from_slice(get(chunk, ObjectType::Chunk)?);
960
                }
961
                crate::objects::text_lines(&content, count, form)
962
            })?;
963
            b.changes.push((change, sigs_from(&pair[1])?));
964
        }
965
        for a in o::array(field(m, 1, "attests")?, "attests")? {
966
            b.attests.push(attest_from(a)?);
967
        }
968
        if let Some(ps) = m.get(&3) {
969
            for p in o::array(ps, "policies")? {
970
                b.policies.push(policy_from(p)?);
971
            }
972
        }
973
        if let Some(cs) = m.get(&4) {
974
            for c in o::array(cs, "certificates")? {
975
                b.certificates.push(
976
                    crate::cert::SignedCertificate::decode(o::bytes(c, "certificate")?)
977
                        .map_err(|e| schema(&format!("certificate: {e}")))?,
978
                );
979
            }
980
        }
981
        Ok(b)
982
    }
983
984
    pub fn encode_bundle(b: &Bundle) -> Vec<u8> {
985
        cbor::encode(&bundle_value(b))
986
    }
987
    pub fn decode_bundle(bytes: &[u8]) -> Result<Bundle> {
988
        bundle_from_value(&cbor::decode(bytes).map_err(ObjectError::from)?)
989
    }
990
991
    pub fn encode_capabilities(id: [u8; 16]) -> Vec<u8> {
992
        cbor::encode(&Value::map([
993
            (0, Value::Array(vec![Value::Uint(PROTOCOL_VERSION)])),
994
            (1, Value::Bytes(id.to_vec())),
995
            (2, Value::Array(vec![Value::Text("seal".into())])),
996
        ]))
997
    }
998
    pub fn decode_capabilities(bytes: &[u8]) -> Result<[u8; 16]> {
999
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
1000
        let m = map(&v, "capabilities")?;
1001
        let versions = o::array(field(m, 0, "versions")?, "versions")?;
1002
        if !versions
1003
            .iter()
1004
            .any(|x| x.as_uint() == Some(PROTOCOL_VERSION))
1005
        {
1006
            return Err(RepoError::Msg(
1007
                "remote does not speak protocol version 1".into(),
1008
            ));
1009
        }
1010
        o::bytes(field(m, 1, "repo id")?, "repo id")?
1011
            .try_into()
1012
            .map_err(|_| schema("repo id: expected 16 bytes"))
1013
    }
1014
1015
    fn tags_value(tags: &[TagRef]) -> Value {
1016
        Value::Array(
1017
            tags.iter()
1018
                .map(|t| {
1019
                    let mut v = Value::map([
1020
                        (0, Value::Text(t.name.clone())),
1021
                        (1, Value::Bytes(t.state.0.to_vec())),
1022
                        (2, hashes_value(&t.heads)),
1023
                        (3, opt_attest_value(&t.attestation)),
1024
                    ]);
1025
                    // Only when there is one; older peers ignore them
1026
                    // (oxygen#129).
1027
                    if let Value::Map(m) = &mut v {
1028
                        if t.accepted.is_some() {
1029
                            m.insert(4, opt_attest_value(&t.accepted));
1030
                        }
1031
                        if let Some(l) = &t.logged {
1032
                            m.insert(5, logged_value(l));
1033
                        }
1034
                        if !t.integration.is_empty() {
1035
                            m.insert(6, integration_value(&t.integration));
1036
                        }
1037
                    }
1038
                    v
1039
                })
1040
                .collect(),
1041
        )
1042
    }
1043
    fn tags_from(v: &Value) -> Result<Vec<TagRef>> {
1044
        let mut out = Vec::new();
1045
        for t in o::array(v, "tags")? {
1046
            let tm = map(t, "tag")?;
1047
            out.push(TagRef {
1048
                name: o::text(field(tm, 0, "name")?, "name")?.to_owned(),
1049
                state: o::oref(field(tm, 1, "state")?, "state")?,
1050
                heads: hashes_from(field(tm, 2, "heads")?)?,
1051
                attestation: opt_attest_from(field(tm, 3, "attestation")?)?,
1052
                accepted: match tm.get(&4) {
1053
                    Some(a) => opt_attest_from(a)?,
1054
                    None => None,
1055
                },
1056
                logged: tm.get(&5).map(logged_from).transpose()?,
1057
                integration: match tm.get(&6) {
1058
                    Some(l) => integration_from(l)?,
1059
                    None => Vec::new(),
1060
                },
1061
            });
1062
        }
1063
        Ok(out)
1064
    }
1065
1066
    /// The tags of a refs answer as oxy 0.5.0 read them (and the runners
1067
    /// built with it), keys 0 to 3 only: what an older reader makes of an
1068
    /// answer with keys 4 to 6.
1069
    #[cfg(test)]
1070
    pub(super) fn tags_as_0_5_read_them(bytes: &[u8]) -> Result<Vec<TagRef>> {
1071
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
1072
        let m = map(&v, "refs")?;
1073
        let mut out = Vec::new();
1074
        for t in o::array(field(m, 3, "tags")?, "tags")? {
1075
            let tm = map(t, "tag")?;
1076
            out.push(TagRef::new(
1077
                o::text(field(tm, 0, "name")?, "name")?.to_owned(),
1078
                o::oref(field(tm, 1, "state")?, "state")?,
1079
                hashes_from(field(tm, 2, "heads")?)?,
1080
                opt_attest_from(field(tm, 3, "attestation")?)?,
1081
            ));
1082
        }
1083
        Ok(out)
1084
    }
1085
1086
    /// A log place, `[entry number, entry bytes, [proof hash]]` (spec §14.8).
1087
    fn logged_value(l: &Logged) -> Value {
1088
        Value::Array(vec![
1089
            Value::Uint(l.index),
1090
            Value::Bytes(l.entry.clone()),
1091
            proof_value(&l.proof),
1092
        ])
1093
    }
1094
    fn logged_from(v: &Value) -> Result<Logged> {
1095
        let a = o::array(v, "logged")?;
1096
        if a.len() != 3 {
1097
            return Err(schema("logged: expected [index, entry, proof]"));
1098
        }
1099
        Ok(Logged {
1100
            index: o::uint(&a[0], "index")?,
1101
            entry: o::bytes(&a[1], "entry")?.to_vec(),
1102
            proof: proof_from(&a[2])?,
1103
        })
1104
    }
1105
1106
    /// Cosigned checkpoints holding an entry, `[[note, [proof hash]]]`.
1107
    fn integration_value(integration: &[Integration]) -> Value {
1108
        Value::Array(
1109
            integration
1110
                .iter()
1111
                .map(|i| Value::Array(vec![Value::Text(i.note.clone()), proof_value(&i.proof)]))
1112
                .collect(),
1113
        )
1114
    }
1115
    fn integration_from(v: &Value) -> Result<Vec<Integration>> {
1116
        let mut out = Vec::new();
1117
        for i in o::array(v, "integration")? {
1118
            let a = o::array(i, "integration")?;
1119
            if a.len() != 2 {
1120
                return Err(schema("integration: expected [note, proof]"));
1121
            }
1122
            out.push(Integration {
1123
                note: o::text(&a[0], "note")?.to_owned(),
1124
                proof: proof_from(&a[1])?,
1125
            });
1126
        }
1127
        Ok(out)
1128
    }
1129
1130
    pub fn encode_refs(id: [u8; 16], resp: &RefsResponse) -> Vec<u8> {
1131
        let mut v = Value::map([
1132
            (
1133
                0,
1134
                Value::Array(
1135
                    resp.refs
1136
                        .iter()
1137
                        .map(|r| {
1138
                            let mut v = Value::map([
1139
                                (0, Value::Text(r.name.clone())),
1140
                                (1, Value::Bytes(r.state.0.to_vec())),
1141
                                (2, hashes_value(&r.heads)),
1142
                                (3, opt_attest_value(&r.attestation)),
1143
                                (4, r.last_serial.map(Value::Uint).unwrap_or(Value::Null)),
1144
                            ]);
1145
                            // Only when there is one; older peers ignore it.
1146
                            if let Value::Map(m) = &mut v {
1147
                                if r.accepted.is_some() {
1148
                                    m.insert(5, opt_attest_value(&r.accepted));
1149
                                }
1150
                                if let Some(l) = &r.logged {
1151
                                    m.insert(6, logged_value(l));
1152
                                }
1153
                                if !r.integration.is_empty() {
1154
                                    m.insert(7, integration_value(&r.integration));
1155
                                }
1156
                            }
1157
                            v
1158
                        })
1159
                        .collect(),
1160
                ),
1161
            ),
1162
            (1, Value::Bytes(id.to_vec())),
1163
            (2, opt_policy_value(resp.policy.as_ref())),
1164
            (3, tags_value(&resp.tags)),
1165
            (
1166
                4,
1167
                Value::Array(resp.history.iter().map(policy_value).collect()),
1168
            ),
1169
            (
1170
                5,
1171
                resp.default_bookmark
1172
                    .clone()
1173
                    .map(Value::Text)
1174
                    .unwrap_or(Value::Null),
1175
            ),
1176
        ]);
1177
        if let Value::Map(m) = &mut v {
1178
            if let Some(log) = &resp.log {
1179
                m.insert(6, Value::Text(log.clone()));
1180
            }
1181
            if !resp.witnesses.is_empty() {
1182
                m.insert(
1183
                    7,
1184
                    Value::Array(
1185
                        resp.witnesses
1186
                            .iter()
1187
                            .map(|(name, id)| {
1188
                                Value::Array(vec![
1189
                                    Value::Text(name.clone()),
1190
                                    Value::Bytes(id.clone()),
1191
                                ])
1192
                            })
1193
                            .collect(),
1194
                    ),
1195
                );
1196
            }
1197
        }
1198
        cbor::encode(&v)
1199
    }
1200
    pub fn decode_refs(bytes: &[u8]) -> Result<([u8; 16], RefsResponse)> {
1201
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
1202
        let m = map(&v, "refs")?;
1203
        let id: [u8; 16] = o::bytes(field(m, 1, "repo id")?, "repo id")?
1204
            .try_into()
1205
            .map_err(|_| schema("repo id: expected 16 bytes"))?;
1206
        let mut refs = Vec::new();
1207
        for r in o::array(field(m, 0, "refs")?, "refs")? {
1208
            let rm = map(r, "ref")?;
1209
            let ls = field(rm, 4, "last serial")?;
1210
            refs.push(RemoteRef {
1211
                name: o::text(field(rm, 0, "name")?, "name")?.to_owned(),
1212
                state: o::oref(field(rm, 1, "state")?, "state")?,
1213
                heads: hashes_from(field(rm, 2, "heads")?)?,
1214
                attestation: opt_attest_from(field(rm, 3, "attestation")?)?,
1215
                last_serial: if ls.is_null() {
1216
                    None
1217
                } else {
1218
                    Some(o::uint(ls, "last serial")?)
1219
                },
1220
                accepted: match rm.get(&5) {
1221
                    Some(a) => opt_attest_from(a)?,
1222
                    None => None,
1223
                },
1224
                logged: rm.get(&6).map(logged_from).transpose()?,
1225
                integration: match rm.get(&7) {
1226
                    Some(l) => integration_from(l)?,
1227
                    None => Vec::new(),
1228
                },
1229
            });
1230
        }
1231
        let policy = match m.get(&2) {
1232
            Some(p) => opt_policy_from(p)?,
1233
            None => None,
1234
        };
1235
        let tags = match m.get(&3) {
1236
            Some(t) => tags_from(t)?,
1237
            None => Vec::new(),
1238
        };
1239
        let mut history = Vec::new();
1240
        if let Some(h) = m.get(&4) {
1241
            for p in o::array(h, "history")? {
1242
                history.push(policy_from(p)?);
1243
            }
1244
        }
1245
        let default_bookmark = match m.get(&5) {
1246
            Some(Value::Text(t)) => Some(t.clone()),
1247
            _ => None,
1248
        };
1249
        let log = match m.get(&6) {
1250
            Some(Value::Text(t)) => Some(t.clone()),
1251
            _ => None,
1252
        };
1253
        let mut witnesses = Vec::new();
1254
        if let Some(w) = m.get(&7) {
1255
            for x in o::array(w, "witnesses")? {
1256
                let a = o::array(x, "witness")?;
1257
                if a.len() != 2 {
1258
                    return Err(schema("witness: expected [name, identity]"));
1259
                }
1260
                witnesses.push((
1261
                    o::text(&a[0], "witness name")?.to_owned(),
1262
                    o::bytes(&a[1], "witness identity")?.to_vec(),
1263
                ));
1264
            }
1265
        }
1266
        Ok((
1267
            id,
1268
            RefsResponse {
1269
                refs,
1270
                policy,
1271
                tags,
1272
                history,
1273
                default_bookmark,
1274
                log,
1275
                witnesses,
1276
            },
1277
        ))
1278
    }
1279
1280
    /// A proof's hashes, from the leaf upwards (spec §14.8).
1281
    fn proof_value(proof: &[[u8; 32]]) -> Value {
1282
        Value::Array(proof.iter().map(|h| Value::Bytes(h.to_vec())).collect())
1283
    }
1284
1285
    fn proof_from(v: &Value) -> Result<Vec<[u8; 32]>> {
1286
        let mut proof = Vec::new();
1287
        for h in o::array(v, "proof")? {
1288
            proof.push(
1289
                o::bytes(h, "proof hash")?
1290
                    .try_into()
1291
                    .map_err(|_| schema("proof hash: expected 32 bytes"))?,
1292
            );
1293
        }
1294
        Ok(proof)
1295
    }
1296
1297
    pub fn encode_negotiate(have: &[ChangeHash], want: &[ChangeHash]) -> Vec<u8> {
1298
        cbor::encode(&Value::map([
1299
            (0, hashes_value(have)),
1300
            (1, hashes_value(want)),
1301
        ]))
1302
    }
1303
    pub fn decode_negotiate(bytes: &[u8]) -> Result<(Vec<ChangeHash>, Vec<ChangeHash>)> {
1304
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
1305
        let m = map(&v, "negotiate")?;
1306
        Ok((
1307
            hashes_from(field(m, 0, "have")?)?,
1308
            hashes_from(field(m, 1, "want")?)?,
1309
        ))
1310
    }
1311
1312
    /// `fetch` request: `{0: [changes], 1: max blob size or null}`.
1313
    pub fn encode_fetch(hs: &[ChangeHash], max_blob: Option<u64>) -> Vec<u8> {
1314
        cbor::encode(&Value::map([
1315
            (0, hashes_value(hs)),
1316
            (1, max_blob.map(Value::Uint).unwrap_or(Value::Null)),
1317
        ]))
1318
    }
1319
    pub fn decode_fetch(bytes: &[u8]) -> Result<(Vec<ChangeHash>, Option<u64>)> {
1320
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
1321
        let m = map(&v, "fetch")?;
1322
        let max = match m.get(&1) {
1323
            Some(x) if !x.is_null() => Some(o::uint(x, "max blob")?),
1324
            _ => None,
1325
        };
1326
        Ok((hashes_from(field(m, 0, "changes")?)?, max))
1327
    }
1328
1329
    /// `shallow` request: `{0: [heads], 1: depth}`.
1330
    pub fn encode_shallow(hs: &[ChangeHash], depth: u32) -> Vec<u8> {
1331
        cbor::encode(&Value::map([
1332
            (0, hashes_value(hs)),
1333
            (1, Value::Uint(depth as u64)),
1334
        ]))
1335
    }
1336
    pub fn decode_shallow(bytes: &[u8]) -> Result<(Vec<ChangeHash>, u32)> {
1337
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
1338
        let m = map(&v, "shallow")?;
1339
        Ok((
1340
            hashes_from(field(m, 0, "heads")?)?,
1341
            o::u32_(field(m, 1, "depth")?, "depth")?,
1342
        ))
1343
    }
1344
1345
    pub fn encode_hashes(hs: &[ChangeHash]) -> Vec<u8> {
1346
        cbor::encode(&Value::map([(0, hashes_value(hs))]))
1347
    }
1348
    pub fn decode_hashes(bytes: &[u8]) -> Result<Vec<ChangeHash>> {
1349
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
1350
        hashes_from(field(map(&v, "hashes")?, 0, "hashes")?)
1351
    }
1352
1353
    pub fn encode_push(
1354
        bundle: &Bundle,
1355
        updates: &[RefUpdate],
1356
        policy: Option<&SignedPolicy>,
1357
        tags: &[TagRef],
1358
    ) -> Vec<u8> {
1359
        cbor::encode(&Value::map([
1360
            (0, bundle_value(bundle)),
1361
            (2, opt_policy_value(policy)),
1362
            (3, tags_value(tags)),
1363
            (
1364
                1,
1365
                Value::Array(
1366
                    updates
1367
                        .iter()
1368
                        .map(|u| {
1369
                            Value::map([
1370
                                (0, Value::Text(u.name.clone())),
1371
                                (1, Value::Bytes(u.old_state.0.to_vec())),
1372
                                (2, Value::Bytes(u.new_state.0.to_vec())),
1373
                                (3, Value::Bool(u.force)),
1374
                                (4, opt_attest_value(&u.attestation)),
1375
                            ])
1376
                        })
1377
                        .collect(),
1378
                ),
1379
            ),
1380
        ]))
1381
    }
1382
    /// A decoded push: bundle, bookmark updates, policy, tags.
1383
    pub type PushParts = (Bundle, Vec<RefUpdate>, Option<SignedPolicy>, Vec<TagRef>);
1384
1385
    pub fn decode_push(bytes: &[u8]) -> Result<PushParts> {
1386
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
1387
        let m = map(&v, "push")?;
1388
        let bundle = bundle_from_value(field(m, 0, "bundle")?)?;
1389
        let mut updates = Vec::new();
1390
        for u in o::array(field(m, 1, "updates")?, "updates")? {
1391
            let um = map(u, "update")?;
1392
            updates.push(RefUpdate {
1393
                name: o::text(field(um, 0, "name")?, "name")?.to_owned(),
1394
                old_state: o::oref(field(um, 1, "old_state")?, "old_state")?,
1395
                new_state: o::oref(field(um, 2, "new_state")?, "new_state")?,
1396
                force: field(um, 3, "force")?
1397
                    .as_bool()
1398
                    .ok_or_else(|| schema("force: expected bool"))?,
1399
                attestation: opt_attest_from(field(um, 4, "attestation")?)?,
1400
            });
1401
        }
1402
        let policy = match m.get(&2) {
1403
            Some(p) => opt_policy_from(p)?,
1404
            None => None,
1405
        };
1406
        let tags = match m.get(&3) {
1407
            Some(t) => tags_from(t)?,
1408
            None => Vec::new(),
1409
        };
1410
        Ok((bundle, updates, policy, tags))
1411
    }
1412
1413
    pub fn encode_push_response(results: &[RefResult]) -> Vec<u8> {
1414
        cbor::encode(&Value::map([(
1415
            0,
1416
            Value::Array(
1417
                results
1418
                    .iter()
1419
                    .map(|r| {
1420
                        Value::map([
1421
                            (0, Value::Text(r.name.clone())),
1422
                            (1, Value::Bool(r.ok)),
1423
                            (2, Value::Text(r.reason.clone())),
1424
                        ])
1425
                    })
1426
                    .collect(),
1427
            ),
1428
        )]))
1429
    }
1430
    pub fn decode_push_response(bytes: &[u8]) -> Result<Vec<RefResult>> {
1431
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
1432
        let m = map(&v, "push response")?;
1433
        let mut out = Vec::new();
1434
        for r in o::array(field(m, 0, "results")?, "results")? {
1435
            let rm = map(r, "result")?;
1436
            out.push(RefResult {
1437
                name: o::text(field(rm, 0, "name")?, "name")?.to_owned(),
1438
                ok: field(rm, 1, "ok")?
1439
                    .as_bool()
1440
                    .ok_or_else(|| schema("ok: expected bool"))?,
1441
                reason: o::text(field(rm, 2, "reason")?, "reason")?.to_owned(),
1442
            });
1443
        }
1444
        Ok(out)
1445
    }
1446
}
1447
1448
#[cfg(test)]
1449
mod tests {
1450
    use super::*;
1451
    use crate::attest::AttestBody;
1452
    use crate::objects::Hlc;
1453
1454
    /// oxygen#133: a proxy's HTML error page is shown by its title, and a
1455
    /// server's own text as it is; a 413 says to push in smaller parts.
1456
    #[test]
1457
    fn html_error_pages_are_shown_by_their_title() {
1458
        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>";
1459
        assert_eq!(
1460
            plain_error_text(cloudflare),
1461
            "413 Request Entity Too Large (an HTML error page, from a proxy in front of the server perhaps)"
1462
        );
1463
        assert_eq!(
1464
            plain_error_text("  refused: a secret\nat a.txt:3 "),
1465
            "refused: a secret\nat a.txt:3"
1466
        );
1467
        assert!(hint_for("https://hub/x: HTTP 413: too large")
1468
            .unwrap()
1469
            .contains("push.batch-bytes"));
1470
    }
1471
1472
    #[test]
1473
    fn client_features_are_declared_and_read() {
1474
        assert_eq!(CLIENT_FEATURES.join(","), "certified-tags");
1475
        assert!(user_agent().starts_with("oxy/"));
1476
        assert!(declares_feature(
1477
            Some("certified-tags"),
1478
            FEATURE_CERTIFIED_TAGS
1479
        ));
1480
        assert!(declares_feature(
1481
            Some("later-thing, Certified-Tags ,x"),
1482
            FEATURE_CERTIFIED_TAGS
1483
        ));
1484
        assert!(!declares_feature(
1485
            Some("certified-tags-v2"),
1486
            FEATURE_CERTIFIED_TAGS
1487
        ));
1488
        assert!(!declares_feature(Some(""), FEATURE_CERTIFIED_TAGS));
1489
        assert!(!declares_feature(None, FEATURE_CERTIFIED_TAGS));
1490
    }
1491
1492
    #[test]
1493
    fn wire_round_trips() {
1494
        let c = crate::objects::tests::sample_change();
1495
        let sk = crate::identity::SecretKey {
1496
            ed_seed: [1; 32],
1497
            ml_seed: [2; 32],
1498
        };
1499
        let id = sk.identity("a", "b", 0);
1500
        let key = id.hash();
1501
        let sig = sk.sign(crate::identity::Domain::Change, &key, &c.hash());
1502
        let seal = Attest::seal([3; 16], vec![c.hash()]);
1503
        let seal_sig = sk.sign(crate::identity::Domain::Attest, &key, &seal.hash());
1504
        let policy = Policy::single_root([3; 16], id.clone(), 99);
1505
        let psig = sk.sign(crate::identity::Domain::Policy, &key, &policy.hash());
1506
        let bundle = Bundle {
1507
            changes: vec![(c.clone(), vec![sig.clone()])],
1508
            attests: vec![SignedAttest {
1509
                attest: seal.clone(),
1510
                sigs: vec![seal_sig],
1511
            }],
1512
            objects: vec![
1513
                (ObjectType::Identity, id.encode()),
1514
                (ObjectType::Chunk, b"xyz".to_vec()),
1515
            ],
1516
            policies: vec![SignedPolicy {
1517
                policy: policy.clone(),
1518
                sigs: vec![psig.clone()],
1519
            }],
1520
            hashes: vec![],
1521
            raw_changes: vec![],
1522
            certificates: vec![],
1523
        };
1524
        let d = wire::decode_bundle(&wire::encode_bundle(&bundle)).unwrap();
1525
        assert_eq!(
1526
            d.hashes,
1527
            vec![c.hash()],
1528
            "the receiver hashes what it was sent"
1529
        );
1530
        assert_eq!(d.changes, bundle.changes);
1531
        assert_eq!(d.attests, bundle.attests);
1532
        assert_eq!(d.objects, bundle.objects);
1533
        assert_eq!(d.policies, bundle.policies);
1534
        assert!(d.certificates.is_empty());
1535
        // Certificates (keyless, oxygenhub#241) travel as field 4, only
1536
        // when there are any: a bundle without them encodes as before.
1537
        let plain = wire::encode_bundle(&bundle);
1538
        let mut with = bundle.clone();
1539
        let issuer_sk = crate::identity::SecretKey::generate();
1540
        let issuer = issuer_sk.identity("hub", "h@x", 1);
1541
        with.certificates.push(crate::cert::SignedCertificate::sign(
1542
            crate::cert::Certificate {
1543
                key: id.clone(),
1544
                issuer: issuer.hash(),
1545
                subject: "agent:a@b".into(),
1546
                claims: vec![],
1547
                scope: crate::identity::Scope::CHANGES,
1548
                not_before: 1,
1549
                expires: 2,
1550
                grant: None,
1551
            },
1552
            &issuer,
1553
            &issuer_sk,
1554
        ));
1555
        let encoded = wire::encode_bundle(&with);
1556
        assert_ne!(encoded, plain);
1557
        assert_eq!(
1558
            wire::decode_bundle(&encoded).unwrap().certificates,
1559
            with.certificates
1560
        );
1561
        with.certificates.clear();
1562
        assert_eq!(wire::encode_bundle(&with), plain);
1563
1564
        let att = Attest {
1565
            repo: [3; 16],
1566
            hlc: Hlc::default(),
1567
            body: AttestBody::Ref {
1568
                name: "main".into(),
1569
                old_state: ObjectRef([1; 32]),
1570
                new_state: ObjectRef([2; 32]),
1571
                serial: 4,
1572
            },
1573
        };
1574
        let refs = vec![
1575
            RemoteRef {
1576
                name: "main".into(),
1577
                state: ObjectRef([2; 32]),
1578
                heads: vec![c.hash()],
1579
                attestation: Some(SignedAttest {
1580
                    attest: att.clone(),
1581
                    sigs: vec![sig.clone()],
1582
                }),
1583
                last_serial: Some(4),
1584
                accepted: None,
1585
                logged: None,
1586
                integration: vec![],
1587
            },
1588
            RemoteRef {
1589
                name: "dev".into(),
1590
                state: ObjectRef([5; 32]),
1591
                heads: vec![],
1592
                attestation: None,
1593
                last_serial: None,
1594
                accepted: None,
1595
                logged: None,
1596
                integration: vec![],
1597
            },
1598
        ];
1599
        let tag = TagRef::new("v1".into(), ObjectRef([2; 32]), vec![c.hash()], None);
1600
        let mut resp = RefsResponse {
1601
            refs,
1602
            policy: Some(SignedPolicy {
1603
                policy: policy.clone(),
1604
                sigs: vec![psig.clone()],
1605
            }),
1606
            tags: vec![tag.clone()],
1607
            history: vec![SignedPolicy {
1608
                policy: policy.clone(),
1609
                sigs: vec![],
1610
            }],
1611
            default_bookmark: Some("develop".into()),
1612
            log: Some("hub.example/log\n2\nroot\n\n- sig\n".into()),
1613
            witnesses: vec![],
1614
        };
1615
        // Without integrated times (spec §14.8) nothing is added: an old
1616
        // peer's answer, and what it reads.
1617
        let old = wire::encode_refs([3; 16], &resp);
1618
        let back = wire::decode_refs(&old).unwrap().1;
1619
        assert!(back.witnesses.is_empty() && back.refs.iter().all(|r| r.integration.is_empty()));
1620
        resp.refs[1].logged = Some(Logged {
1621
            index: 41,
1622
            entry: vec![1, 2, 3],
1623
            proof: vec![[9; 32], [8; 32]],
1624
        });
1625
        resp.refs[1].integration = vec![Integration {
1626
            note: "hub.example/log\n42\nroot\n\n- sig\n".into(),
1627
            proof: vec![[7; 32]],
1628
        }];
1629
        resp.witnesses = vec![("w.example".into(), vec![4, 5, 6])];
1630
        let new = wire::encode_refs([3; 16], &resp);
1631
        let (id_back, back) = wire::decode_refs(&new).unwrap();
1632
        assert_eq!(back.log, resp.log);
1633
        assert_eq!(back.refs[1].logged, resp.refs[1].logged);
1634
        assert_eq!(back.refs[1].integration, resp.refs[1].integration);
1635
        assert_eq!(back.witnesses, resp.witnesses);
1636
        assert_eq!(back.refs[0].logged, None);
1637
        // The new keys are 7s an old reader never asks for.
1638
        let crate::cbor::Value::Map(m) = crate::cbor::decode(&new).unwrap() else {
1639
            panic!()
1640
        };
1641
        assert!(m.contains_key(&7));
1642
        assert_eq!(id_back, [3; 16]);
1643
        assert_eq!(back.refs.len(), 2);
1644
        assert_eq!(back.refs[0].attestation.as_ref().unwrap().attest, att);
1645
        assert_eq!(back.refs[1].last_serial, None);
1646
        assert_eq!(back.policy.as_ref().unwrap().policy, policy);
1647
        assert_eq!(back.history, resp.history);
1648
        assert_eq!(back.tags, vec![tag.clone()]);
1649
1650
        // A tag's acceptance and log place (oxygen#129): keys 4 to 6, only
1651
        // when there are any, so a tag without them encodes as before.
1652
        let crate::cbor::Value::Map(m) = crate::cbor::decode(&new).unwrap() else {
1653
            panic!()
1654
        };
1655
        let crate::cbor::Value::Array(tags) = &m[&3] else {
1656
            panic!()
1657
        };
1658
        let crate::cbor::Value::Map(plain) = &tags[0] else {
1659
            panic!()
1660
        };
1661
        assert_eq!(plain.keys().copied().collect::<Vec<_>>(), vec![0, 1, 2, 3]);
1662
        let mut full = tag.clone();
1663
        full.name = "v2".into();
1664
        full.attestation = Some(SignedAttest {
1665
            attest: att.clone(),
1666
            sigs: vec![sig.clone()],
1667
        });
1668
        full.accepted = full.attestation.clone();
1669
        full.logged = Some(Logged {
1670
            index: 7,
1671
            entry: vec![4],
1672
            proof: vec![[3; 32]],
1673
        });
1674
        full.integration = vec![Integration {
1675
            note: "hub.example/log\n8\nroot\n\n- sig\n".into(),
1676
            proof: vec![],
1677
        }];
1678
        resp.tags = vec![full.clone(), tag.clone()];
1679
        let bytes = wire::encode_refs([3; 16], &resp);
1680
        assert_eq!(wire::decode_refs(&bytes).unwrap().1.tags, resp.tags);
1681
        // In a push too.
1682
        let pushed = wire::encode_push(&Bundle::default(), &[], None, &resp.tags);
1683
        assert_eq!(wire::decode_push(&pushed).unwrap().3, resp.tags);
1684
        // A reader that knows only keys 0 to 3 (oxy 0.5.0 and older, and
1685
        // the runners built with it) reads the same tags from the new answer.
1686
        let stripped: Vec<TagRef> = resp
1687
            .tags
1688
            .iter()
1689
            .map(|t| {
1690
                TagRef::new(
1691
                    t.name.clone(),
1692
                    t.state,
1693
                    t.heads.clone(),
1694
                    t.attestation.clone(),
1695
                )
1696
            })
1697
            .collect();
1698
        assert_eq!(wire::tags_as_0_5_read_them(&bytes).unwrap(), stripped);
1699
1700
        let (h, w) = wire::decode_negotiate(&wire::encode_negotiate(
1701
            &[ObjectRef([1; 32])],
1702
            &[ObjectRef([2; 32])],
1703
        ))
1704
        .unwrap();
1705
        assert_eq!((h, w), (vec![ObjectRef([1; 32])], vec![ObjectRef([2; 32])]));
1706
        assert_eq!(
1707
            wire::decode_hashes(&wire::encode_hashes(&[c.hash()])).unwrap(),
1708
            vec![c.hash()]
1709
        );
1710
        assert_eq!(
1711
            wire::decode_fetch(&wire::encode_fetch(&[c.hash()], Some(4096))).unwrap(),
1712
            (vec![c.hash()], Some(4096))
1713
        );
1714
        assert_eq!(
1715
            wire::decode_fetch(&wire::encode_fetch(&[], None)).unwrap(),
1716
            (vec![], None)
1717
        );
1718
        assert_eq!(
1719
            wire::decode_shallow(&wire::encode_shallow(&[c.hash()], 3)).unwrap(),
1720
            (vec![c.hash()], 3)
1721
        );
1722
        // An old-style fetch request without the filter field still decodes.
1723
        assert_eq!(
1724
            wire::decode_fetch(&wire::encode_hashes(&[c.hash()])).unwrap(),
1725
            (vec![c.hash()], None)
1726
        );
1727
1728
        let up = RefUpdate {
1729
            name: "main".into(),
1730
            old_state: ObjectRef([1; 32]),
1731
            new_state: ObjectRef([2; 32]),
1732
            force: true,
1733
            attestation: Some(SignedAttest {
1734
                attest: att,
1735
                sigs: vec![sig],
1736
            }),
1737
        };
1738
        let sp = SignedPolicy {
1739
            policy,
1740
            sigs: vec![psig],
1741
        };
1742
        let (b2, ups, pol, tags) = wire::decode_push(&wire::encode_push(
1743
            &bundle,
1744
            std::slice::from_ref(&up),
1745
            Some(&sp),
1746
            std::slice::from_ref(&tag),
1747
        ))
1748
        .unwrap();
1749
        assert_eq!(pol, Some(sp));
1750
        assert_eq!(tags, vec![tag]);
1751
        assert_eq!(b2.changes.len(), 1);
1752
        assert_eq!(ups[0].name, "main");
1753
        assert!(ups[0].force);
1754
        assert_eq!(ups[0].attestation, up.attestation);
1755
        let res = vec![RefResult {
1756
            name: "main".into(),
1757
            ok: false,
1758
            reason: "stale".into(),
1759
        }];
1760
        assert_eq!(
1761
            wire::decode_push_response(&wire::encode_push_response(&res)).unwrap(),
1762
            res
1763
        );
1764
        assert_eq!(
1765
            wire::decode_capabilities(&wire::encode_capabilities([7; 16])).unwrap(),
1766
            [7; 16]
1767
        );
1768
    }
1769
}