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