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