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