OXYGENHUB
# 3faccd90ddfa oxygen / crates / oxy-core / src / protocol.rs
34.9 KiB · Rust · last changed Roadmap: phase D done 1 month ago source blame history raw
1
//! Transport-agnostic protocol (spec §16): what a client asks of a remote and
2
//! what a server does with a push. `LocalRemote` serves another repository
3
//! directory in-process, `HttpRemote` speaks to an `oxy-server` over HTTP(S),
4
//! and the server side reuses `Repo::receive_push` and friends unchanged.
5
//!
6
//! Wire messages are deterministic CBOR (`wire` module); over HTTP each is a
7
//! request or response body with content type `application/oxy-cbor`.
8
9
use crate::attest::Attest;
10
use crate::cbor::{self, Value};
11
use crate::hash::{ChangeHash, ObjectRef, ObjectType};
12
use crate::identity::Signature;
13
use crate::objects::{self as o, Change, ObjectError};
14
use crate::policy::Policy;
15
use crate::repo::{Repo, RepoError, Result};
16
use std::path::{Path, PathBuf};
17
use std::sync::Arc;
18
19
pub const CONTENT_TYPE: &str = "application/oxy-cbor";
20
pub const PROTOCOL_VERSION: u64 = 1;
21
22
/// An attestation together with the signatures over its ObjectRef.
23
#[derive(Clone, Debug, PartialEq, Eq)]
24
pub struct SignedAttest {
25
    pub attest: Attest,
26
    pub sigs: Vec<Signature>,
27
}
28
29
/// A policy together with the root signatures over its ObjectRef.
30
#[derive(Clone, Debug, PartialEq, Eq)]
31
pub struct SignedPolicy {
32
    pub policy: Policy,
33
    pub sigs: Vec<Signature>,
34
}
35
36
impl SignedPolicy {
37
    /// The proposal-file encoding (`wire::policy_value`).
38
    pub fn encode(&self) -> Vec<u8> {
39
        crate::cbor::encode(&wire::policy_value(self))
40
    }
41
    pub fn decode(b: &[u8]) -> Result<SignedPolicy> {
42
        wire::policy_from(
43
            &crate::cbor::decode(b).map_err(|e| RepoError::Object(ObjectError::from(e)))?,
44
        )
45
    }
46
}
47
48
/// What `refs` returns: every bookmark, every tag, and the current policy.
49
#[derive(Clone, Debug, Default)]
50
pub struct RefsResponse {
51
    pub refs: Vec<RemoteRef>,
52
    pub policy: Option<SignedPolicy>,
53
    pub tags: Vec<TagRef>,
54
    /// Earlier policies, ascending by serial, so a client behind by more
55
    /// than one update can verify each step (spec §14.5).
56
    pub history: Vec<SignedPolicy>,
57
}
58
59
/// A tag as a remote reports it (spec §10.1).
60
#[derive(Clone, Debug, PartialEq, Eq)]
61
pub struct TagRef {
62
    pub name: String,
63
    pub state: ObjectRef,
64
    pub heads: Vec<ChangeHash>,
65
    pub attestation: Option<SignedAttest>,
66
}
67
68
/// One reference as a remote reports it.
69
#[derive(Clone, Debug)]
70
pub struct RemoteRef {
71
    pub name: String,
72
    pub state: ObjectRef,
73
    pub heads: Vec<ChangeHash>,
74
    pub attestation: Option<SignedAttest>,
75
}
76
77
/// Everything needed to add a set of changes to a repository.
78
#[derive(Clone, Debug, Default)]
79
pub struct Bundle {
80
    /// In dependency order, each with its individual signatures.
81
    pub changes: Vec<(Change, Vec<Signature>)>,
82
    /// Seals covering the changes.
83
    pub attests: Vec<SignedAttest>,
84
    /// Chunks, blobs, identities, and state objects referenced by the changes.
85
    pub objects: Vec<(ObjectType, Vec<u8>)>,
86
    /// Policies between the receiver's and the one sent with the push,
87
    /// ascending by serial (spec §14.5).
88
    pub policies: Vec<SignedPolicy>,
89
}
90
91
impl Bundle {
92
    pub fn is_empty(&self) -> bool {
93
        self.changes.is_empty() && self.attests.is_empty() && self.objects.is_empty()
94
    }
95
}
96
97
/// A requested bookmark move (spec §10.2, §16.3).
98
#[derive(Clone, Debug)]
99
pub struct RefUpdate {
100
    pub name: String,
101
    pub old_state: ObjectRef,
102
    pub new_state: ObjectRef,
103
    pub force: bool,
104
    pub attestation: Option<SignedAttest>,
105
}
106
107
#[derive(Clone, Debug, PartialEq, Eq)]
108
pub struct RefResult {
109
    pub name: String,
110
    pub ok: bool,
111
    pub reason: String,
112
}
113
114
pub trait Remote {
115
    fn repo_id(&self) -> Result<[u8; 16]>;
116
    fn refs(&self) -> Result<RefsResponse>;
117
    /// Changes in the closure of `want` but not of `have`, in dependency order.
118
    fn negotiate(&self, have: &[ChangeHash], want: &[ChangeHash]) -> Result<Vec<ChangeHash>>;
119
    /// The changes with their signatures, seals, identities, and blobs; blobs
120
    /// larger than `max_blob` bytes are left out for lazy fetching (spec §13.5).
121
    fn fetch(&self, changes: &[ChangeHash], max_blob: Option<u64>) -> Result<Bundle>;
122
    /// Individual objects by reference (spec §16.1 `objects`); a blob comes
123
    /// with its chunks.
124
    fn objects(&self, refs: &[ObjectRef]) -> Result<Vec<(ObjectType, Vec<u8>)>>;
125
    /// A checkpoint of exactly `heads` (spec §16.1 `checkpoint`): the
126
    /// checkpoint object, its payload blob, and the blob's chunks.
127
    fn checkpoint(&self, heads: &[ChangeHash]) -> Result<Bundle>;
128
    /// The changes within `depth` dependency steps of `heads` (spec §17).
129
    fn shallow(&self, heads: &[ChangeHash], depth: u32) -> Result<Vec<ChangeHash>>;
130
    /// Push changes, bookmark updates, new tags, and optionally a newer
131
    /// policy. The policy is applied first; a result named `policy` reports
132
    /// it, and each tag reports as `tags/<name>`.
133
    fn push(
134
        &self,
135
        bundle: Bundle,
136
        updates: Vec<RefUpdate>,
137
        policy: Option<SignedPolicy>,
138
        tags: Vec<TagRef>,
139
    ) -> Result<Vec<RefResult>>;
140
}
141
142
// ---------------------------------------------------------------- local
143
144
/// Another repository on this machine, served in-process.
145
pub struct LocalRemote {
146
    pub repo: Repo,
147
}
148
149
impl LocalRemote {
150
    pub fn open(path: &Path) -> Result<LocalRemote> {
151
        Ok(LocalRemote {
152
            repo: Repo::open(path)?,
153
        })
154
    }
155
}
156
157
impl Remote for LocalRemote {
158
    fn repo_id(&self) -> Result<[u8; 16]> {
159
        self.repo.id()
160
    }
161
    fn refs(&self) -> Result<RefsResponse> {
162
        self.repo.remote_refs()
163
    }
164
    fn negotiate(&self, have: &[ChangeHash], want: &[ChangeHash]) -> Result<Vec<ChangeHash>> {
165
        self.repo.negotiate(have, want)
166
    }
167
    fn fetch(&self, changes: &[ChangeHash], max_blob: Option<u64>) -> Result<Bundle> {
168
        self.repo.bundle_for_filtered(changes, max_blob)
169
    }
170
    fn objects(&self, refs: &[ObjectRef]) -> Result<Vec<(ObjectType, Vec<u8>)>> {
171
        self.repo.objects_for(refs)
172
    }
173
    fn checkpoint(&self, heads: &[ChangeHash]) -> Result<Bundle> {
174
        self.repo.checkpoint_bundle_for(heads)
175
    }
176
    fn shallow(&self, heads: &[ChangeHash], depth: u32) -> Result<Vec<ChangeHash>> {
177
        self.repo.shallow_changes(heads, depth)
178
    }
179
    fn push(
180
        &self,
181
        bundle: Bundle,
182
        updates: Vec<RefUpdate>,
183
        policy: Option<SignedPolicy>,
184
        tags: Vec<TagRef>,
185
    ) -> Result<Vec<RefResult>> {
186
        self.repo.receive_push(bundle, updates, policy, tags)
187
    }
188
}
189
190
// ---------------------------------------------------------------- http
191
192
/// How to reach a remote: credentials and trust.
193
#[derive(Clone, Debug, Default)]
194
pub struct RemoteOptions {
195
    /// Bearer token for pushes.
196
    pub token: Option<String>,
197
    /// PEM file with extra root certificates to trust for `https://` remotes
198
    /// (self-hosted servers); the system web roots are always trusted.
199
    pub ca: Option<PathBuf>,
200
    /// The local repository's id, sent as `Oxy-Repo-Id` so an unbound
201
    /// hosted repository can adopt it on the first push (spec §16.1).
202
    pub repo_id: Option<[u8; 16]>,
203
}
204
205
/// The request header carrying the client's repository id.
206
pub const REPO_ID_HEADER: &str = "Oxy-Repo-Id";
207
208
/// The id of a hosted repository that has not adopted one yet.
209
pub const UNBOUND_ID: [u8; 16] = [0; 16];
210
211
/// A remote served by `oxy-server` at `<base>/oxy/v1/...`.
212
pub struct HttpRemote {
213
    base: String,
214
    token: Option<String>,
215
    repo_id: Option<[u8; 16]>,
216
    agent: ureq::Agent,
217
}
218
219
/// A TLS client configuration trusting the web roots plus `ca`, if given.
220
fn tls_client_config(ca: Option<&Path>) -> Result<Arc<rustls::ClientConfig>> {
221
    let mut roots = rustls::RootCertStore::empty();
222
    roots.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
223
    if let Some(path) = ca {
224
        let pem = std::fs::read(path)
225
            .map_err(|e| RepoError::Msg(format!("reading CA file {}: {e}", path.display())))?;
226
        let certs = rustls_pemfile::certs(&mut pem.as_slice())
227
            .collect::<std::result::Result<Vec<_>, _>>()
228
            .map_err(|e| RepoError::Msg(format!("parsing CA file {}: {e}", path.display())))?;
229
        if certs.is_empty() {
230
            return Err(RepoError::Msg(format!(
231
                "CA file {} holds no certificates",
232
                path.display()
233
            )));
234
        }
235
        for c in certs {
236
            roots
237
                .add(c)
238
                .map_err(|e| RepoError::Msg(format!("CA file {}: {e}", path.display())))?;
239
        }
240
    }
241
    let cfg = rustls::ClientConfig::builder_with_provider(Arc::new(
242
        rustls::crypto::ring::default_provider(),
243
    ))
244
    .with_safe_default_protocol_versions()
245
    .map_err(|e| RepoError::Msg(e.to_string()))?
246
    .with_root_certificates(roots)
247
    .with_no_client_auth();
248
    Ok(Arc::new(cfg))
249
}
250
251
impl HttpRemote {
252
    pub fn new(base: &str, options: &RemoteOptions) -> Result<HttpRemote> {
253
        let agent = ureq::AgentBuilder::new()
254
            .tls_config(tls_client_config(options.ca.as_deref())?)
255
            .build();
256
        Ok(HttpRemote {
257
            base: base.trim_end_matches('/').to_string(),
258
            token: options.token.clone(),
259
            repo_id: options.repo_id,
260
            agent,
261
        })
262
    }
263
264
    fn call(&self, post: bool, endpoint: &str, body: Option<&[u8]>) -> Result<Vec<u8>> {
265
        let url = format!("{}/oxy/v1/{endpoint}", self.base);
266
        let mut req = if post {
267
            self.agent.post(&url)
268
        } else {
269
            self.agent.get(&url)
270
        };
271
        req = req.set("Accept", CONTENT_TYPE);
272
        if let Some(t) = &self.token {
273
            req = req.set("Authorization", &format!("Bearer {t}"));
274
        }
275
        if let Some(id) = &self.repo_id {
276
            req = req.set(REPO_ID_HEADER, &hex::encode(id));
277
        }
278
        let resp = match body {
279
            Some(b) => req.set("Content-Type", CONTENT_TYPE).send_bytes(b),
280
            None => req.call(),
281
        };
282
        match resp {
283
            Ok(r) => {
284
                let mut out = Vec::new();
285
                r.into_reader()
286
                    .read_to_end(&mut out)
287
                    .map_err(|e| RepoError::Msg(format!("{url}: {e}")))?;
288
                Ok(out)
289
            }
290
            Err(ureq::Error::Status(code, r)) => {
291
                let text = r.into_string().unwrap_or_default();
292
                Err(RepoError::Msg(format!(
293
                    "{url}: HTTP {code}: {}",
294
                    text.trim()
295
                )))
296
            }
297
            Err(e) => Err(RepoError::Msg(format!("{url}: {e}"))),
298
        }
299
    }
300
}
301
302
/// An authenticated GET of any URL on a host, with the same TLS trust and
303
/// token as remotes use (for hub APIs: proposals). Returns the body.
304
pub fn http_get(url: &str, options: &RemoteOptions) -> Result<Vec<u8>> {
305
    let agent = ureq::AgentBuilder::new()
306
        .tls_config(tls_client_config(options.ca.as_deref())?)
307
        .build();
308
    let mut req = agent.get(url).set("Accept", "application/json");
309
    if let Some(t) = &options.token {
310
        req = req.set("Authorization", &format!("Bearer {t}"));
311
    }
312
    match req.call() {
313
        Ok(r) => {
314
            let mut out = Vec::new();
315
            r.into_reader()
316
                .read_to_end(&mut out)
317
                .map_err(|e| RepoError::Msg(format!("{url}: {e}")))?;
318
            Ok(out)
319
        }
320
        Err(ureq::Error::Status(code, r)) => {
321
            let text = r.into_string().unwrap_or_default();
322
            Err(RepoError::Msg(format!(
323
                "{url}: HTTP {code}: {}",
324
                text.trim()
325
            )))
326
        }
327
        Err(e) => Err(RepoError::Msg(format!("{url}: {e}"))),
328
    }
329
}
330
331
impl Remote for HttpRemote {
332
    fn repo_id(&self) -> Result<[u8; 16]> {
333
        wire::decode_capabilities(&self.call(false, "capabilities", None)?)
334
    }
335
    fn refs(&self) -> Result<RefsResponse> {
336
        Ok(wire::decode_refs(&self.call(false, "refs", None)?)?.1)
337
    }
338
    fn negotiate(&self, have: &[ChangeHash], want: &[ChangeHash]) -> Result<Vec<ChangeHash>> {
339
        wire::decode_hashes(&self.call(
340
            true,
341
            "negotiate",
342
            Some(&wire::encode_negotiate(have, want)),
343
        )?)
344
    }
345
    fn fetch(&self, changes: &[ChangeHash], max_blob: Option<u64>) -> Result<Bundle> {
346
        wire::decode_bundle(&self.call(
347
            true,
348
            "fetch",
349
            Some(&wire::encode_fetch(changes, max_blob)),
350
        )?)
351
    }
352
    fn objects(&self, refs: &[ObjectRef]) -> Result<Vec<(ObjectType, Vec<u8>)>> {
353
        Ok(
354
            wire::decode_bundle(&self.call(true, "objects", Some(&wire::encode_hashes(refs)))?)?
355
                .objects,
356
        )
357
    }
358
    fn checkpoint(&self, heads: &[ChangeHash]) -> Result<Bundle> {
359
        wire::decode_bundle(&self.call(true, "checkpoint", Some(&wire::encode_hashes(heads)))?)
360
    }
361
    fn shallow(&self, heads: &[ChangeHash], depth: u32) -> Result<Vec<ChangeHash>> {
362
        wire::decode_hashes(&self.call(
363
            true,
364
            "shallow",
365
            Some(&wire::encode_shallow(heads, depth)),
366
        )?)
367
    }
368
    fn push(
369
        &self,
370
        bundle: Bundle,
371
        updates: Vec<RefUpdate>,
372
        policy: Option<SignedPolicy>,
373
        tags: Vec<TagRef>,
374
    ) -> Result<Vec<RefResult>> {
375
        wire::decode_push_response(&self.call(
376
            true,
377
            "push",
378
            Some(&wire::encode_push(
379
                &bundle,
380
                &updates,
381
                policy.as_ref(),
382
                &tags,
383
            )),
384
        )?)
385
    }
386
}
387
388
/// Open a remote by URL: a local path (optionally `file://`), or `http(s)://`.
389
pub fn open_remote(url: &str, options: &RemoteOptions) -> Result<Box<dyn Remote>> {
390
    if url.starts_with("http://") || url.starts_with("https://") {
391
        return Ok(Box::new(HttpRemote::new(url, options)?));
392
    }
393
    let path = url.strip_prefix("file://").unwrap_or(url);
394
    if path.contains("://") {
395
        return Err(RepoError::Msg(format!("unsupported remote URL {url:?}")));
396
    }
397
    Ok(Box::new(LocalRemote::open(Path::new(path))?))
398
}
399
400
// ---------------------------------------------------------------- wire
401
402
/// CBOR encodings of the protocol messages (spec §16.1).
403
pub mod wire {
404
    use super::*;
405
406
    fn schema(msg: &str) -> RepoError {
407
        RepoError::Object(ObjectError::Schema(msg.into()))
408
    }
409
    fn sigs_value(sigs: &[Signature]) -> Value {
410
        Value::Array(sigs.iter().map(|s| s.to_value()).collect())
411
    }
412
    fn sigs_from(v: &Value) -> Result<Vec<Signature>> {
413
        Ok(o::array(v, "signatures")?
414
            .iter()
415
            .map(Signature::from_value)
416
            .collect::<std::result::Result<Vec<_>, _>>()?)
417
    }
418
    fn hashes_value(hs: &[ObjectRef]) -> Value {
419
        Value::Array(hs.iter().map(|h| Value::Bytes(h.0.to_vec())).collect())
420
    }
421
    fn hashes_from(v: &Value) -> Result<Vec<ObjectRef>> {
422
        Ok(o::array(v, "hashes")?
423
            .iter()
424
            .map(|h| o::oref(h, "hash"))
425
            .collect::<std::result::Result<Vec<_>, _>>()?)
426
    }
427
    fn attest_value(sa: &SignedAttest) -> Value {
428
        Value::Array(vec![Value::Bytes(sa.attest.encode()), sigs_value(&sa.sigs)])
429
    }
430
    fn attest_from(v: &Value) -> Result<SignedAttest> {
431
        let a = o::array(v, "signed attest")?;
432
        if a.len() != 2 {
433
            return Err(schema("signed attest: expected [attest, sigs]"));
434
        }
435
        Ok(SignedAttest {
436
            attest: Attest::decode(o::bytes(&a[0], "attest")?)?,
437
            sigs: sigs_from(&a[1])?,
438
        })
439
    }
440
    fn opt_attest_value(sa: &Option<SignedAttest>) -> Value {
441
        sa.as_ref().map(attest_value).unwrap_or(Value::Null)
442
    }
443
    fn opt_attest_from(v: &Value) -> Result<Option<SignedAttest>> {
444
        if v.is_null() {
445
            Ok(None)
446
        } else {
447
            attest_from(v).map(Some)
448
        }
449
    }
450
    /// `[policy bytes, [signature]]`: also the format of a policy proposal
451
    /// file exchanged between root holders (spec §14.5).
452
    pub fn policy_value(sp: &SignedPolicy) -> Value {
453
        Value::Array(vec![Value::Bytes(sp.policy.encode()), sigs_value(&sp.sigs)])
454
    }
455
    pub fn policy_from(v: &Value) -> Result<SignedPolicy> {
456
        let a = o::array(v, "signed policy")?;
457
        if a.len() != 2 {
458
            return Err(schema("signed policy: expected [policy, sigs]"));
459
        }
460
        Ok(SignedPolicy {
461
            policy: Policy::decode(o::bytes(&a[0], "policy")?)?,
462
            sigs: sigs_from(&a[1])?,
463
        })
464
    }
465
    fn opt_policy_value(sp: Option<&SignedPolicy>) -> Value {
466
        sp.map(policy_value).unwrap_or(Value::Null)
467
    }
468
    fn opt_policy_from(v: &Value) -> Result<Option<SignedPolicy>> {
469
        if v.is_null() {
470
            Ok(None)
471
        } else {
472
            policy_from(v).map(Some)
473
        }
474
    }
475
    fn map<'a>(v: &'a Value, what: &str) -> Result<&'a o::Map> {
476
        Ok(o::map(v, what)?)
477
    }
478
    fn field<'a>(m: &'a o::Map, k: u64, what: &str) -> Result<&'a Value> {
479
        Ok(o::field(m, k, what)?)
480
    }
481
482
    pub fn bundle_value(b: &Bundle) -> Value {
483
        Value::map([
484
            (
485
                0,
486
                Value::Array(
487
                    b.changes
488
                        .iter()
489
                        .map(|(c, s)| Value::Array(vec![Value::Bytes(c.encode()), sigs_value(s)]))
490
                        .collect(),
491
                ),
492
            ),
493
            (
494
                1,
495
                Value::Array(b.attests.iter().map(attest_value).collect()),
496
            ),
497
            (
498
                2,
499
                Value::Array(
500
                    b.objects
501
                        .iter()
502
                        .map(|(t, body)| {
503
                            Value::Array(vec![
504
                                Value::Text(t.name().into()),
505
                                Value::Bytes(body.clone()),
506
                            ])
507
                        })
508
                        .collect(),
509
                ),
510
            ),
511
            (
512
                3,
513
                Value::Array(b.policies.iter().map(policy_value).collect()),
514
            ),
515
        ])
516
    }
517
518
    pub fn bundle_from_value(v: &Value) -> Result<Bundle> {
519
        let m = map(v, "bundle")?;
520
        let mut b = Bundle::default();
521
        for c in o::array(field(m, 0, "changes")?, "changes")? {
522
            let pair = o::array(c, "change entry")?;
523
            if pair.len() != 2 {
524
                return Err(schema("change entry: expected [change, sigs]"));
525
            }
526
            b.changes.push((
527
                Change::decode(o::bytes(&pair[0], "change")?)?,
528
                sigs_from(&pair[1])?,
529
            ));
530
        }
531
        for a in o::array(field(m, 1, "attests")?, "attests")? {
532
            b.attests.push(attest_from(a)?);
533
        }
534
        for ob in o::array(field(m, 2, "objects")?, "objects")? {
535
            let pair = o::array(ob, "object")?;
536
            if pair.len() != 2 {
537
                return Err(schema("object: expected [type, body]"));
538
            }
539
            let ty = ObjectType::from_name(o::text(&pair[0], "object type")?)
540
                .ok_or_else(|| schema("unknown object type"))?;
541
            b.objects
542
                .push((ty, o::bytes(&pair[1], "object body")?.to_vec()));
543
        }
544
        if let Some(ps) = m.get(&3) {
545
            for p in o::array(ps, "policies")? {
546
                b.policies.push(policy_from(p)?);
547
            }
548
        }
549
        Ok(b)
550
    }
551
552
    pub fn encode_bundle(b: &Bundle) -> Vec<u8> {
553
        cbor::encode(&bundle_value(b))
554
    }
555
    pub fn decode_bundle(bytes: &[u8]) -> Result<Bundle> {
556
        bundle_from_value(&cbor::decode(bytes).map_err(ObjectError::from)?)
557
    }
558
559
    pub fn encode_capabilities(id: [u8; 16]) -> Vec<u8> {
560
        cbor::encode(&Value::map([
561
            (0, Value::Array(vec![Value::Uint(PROTOCOL_VERSION)])),
562
            (1, Value::Bytes(id.to_vec())),
563
            (2, Value::Array(vec![Value::Text("seal".into())])),
564
        ]))
565
    }
566
    pub fn decode_capabilities(bytes: &[u8]) -> Result<[u8; 16]> {
567
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
568
        let m = map(&v, "capabilities")?;
569
        let versions = o::array(field(m, 0, "versions")?, "versions")?;
570
        if !versions
571
            .iter()
572
            .any(|x| x.as_uint() == Some(PROTOCOL_VERSION))
573
        {
574
            return Err(RepoError::Msg(
575
                "remote does not speak protocol version 1".into(),
576
            ));
577
        }
578
        o::bytes(field(m, 1, "repo id")?, "repo id")?
579
            .try_into()
580
            .map_err(|_| schema("repo id: expected 16 bytes"))
581
    }
582
583
    fn tags_value(tags: &[TagRef]) -> Value {
584
        Value::Array(
585
            tags.iter()
586
                .map(|t| {
587
                    Value::map([
588
                        (0, Value::Text(t.name.clone())),
589
                        (1, Value::Bytes(t.state.0.to_vec())),
590
                        (2, hashes_value(&t.heads)),
591
                        (3, opt_attest_value(&t.attestation)),
592
                    ])
593
                })
594
                .collect(),
595
        )
596
    }
597
    fn tags_from(v: &Value) -> Result<Vec<TagRef>> {
598
        let mut out = Vec::new();
599
        for t in o::array(v, "tags")? {
600
            let tm = map(t, "tag")?;
601
            out.push(TagRef {
602
                name: o::text(field(tm, 0, "name")?, "name")?.to_owned(),
603
                state: o::oref(field(tm, 1, "state")?, "state")?,
604
                heads: hashes_from(field(tm, 2, "heads")?)?,
605
                attestation: opt_attest_from(field(tm, 3, "attestation")?)?,
606
            });
607
        }
608
        Ok(out)
609
    }
610
611
    pub fn encode_refs(id: [u8; 16], resp: &RefsResponse) -> Vec<u8> {
612
        cbor::encode(&Value::map([
613
            (
614
                0,
615
                Value::Array(
616
                    resp.refs
617
                        .iter()
618
                        .map(|r| {
619
                            Value::map([
620
                                (0, Value::Text(r.name.clone())),
621
                                (1, Value::Bytes(r.state.0.to_vec())),
622
                                (2, hashes_value(&r.heads)),
623
                                (3, opt_attest_value(&r.attestation)),
624
                                (4, r.last_serial.map(Value::Uint).unwrap_or(Value::Null)),
625
                            ])
626
                        })
627
                        .collect(),
628
                ),
629
            ),
630
            (1, Value::Bytes(id.to_vec())),
631
            (2, opt_policy_value(resp.policy.as_ref())),
632
            (3, tags_value(&resp.tags)),
633
            (
634
                4,
635
                Value::Array(resp.history.iter().map(policy_value).collect()),
636
            ),
637
        ]))
638
    }
639
    pub fn decode_refs(bytes: &[u8]) -> Result<([u8; 16], RefsResponse)> {
640
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
641
        let m = map(&v, "refs")?;
642
        let id: [u8; 16] = o::bytes(field(m, 1, "repo id")?, "repo id")?
643
            .try_into()
644
            .map_err(|_| schema("repo id: expected 16 bytes"))?;
645
        let mut refs = Vec::new();
646
        for r in o::array(field(m, 0, "refs")?, "refs")? {
647
            let rm = map(r, "ref")?;
648
            let ls = field(rm, 4, "last serial")?;
649
            refs.push(RemoteRef {
650
                name: o::text(field(rm, 0, "name")?, "name")?.to_owned(),
651
                state: o::oref(field(rm, 1, "state")?, "state")?,
652
                heads: hashes_from(field(rm, 2, "heads")?)?,
653
                attestation: opt_attest_from(field(rm, 3, "attestation")?)?,
654
                last_serial: if ls.is_null() {
655
                    None
656
                } else {
657
                    Some(o::uint(ls, "last serial")?)
658
                },
659
            });
660
        }
661
        let policy = match m.get(&2) {
662
            Some(p) => opt_policy_from(p)?,
663
            None => None,
664
        };
665
        let tags = match m.get(&3) {
666
            Some(t) => tags_from(t)?,
667
            None => Vec::new(),
668
        };
669
        let mut history = Vec::new();
670
        if let Some(h) = m.get(&4) {
671
            for p in o::array(h, "history")? {
672
                history.push(policy_from(p)?);
673
            }
674
        }
675
        Ok((
676
            id,
677
            RefsResponse {
678
                refs,
679
                policy,
680
                tags,
681
                history,
682
            },
683
        ))
684
    }
685
686
    pub fn encode_negotiate(have: &[ChangeHash], want: &[ChangeHash]) -> Vec<u8> {
687
        cbor::encode(&Value::map([
688
            (0, hashes_value(have)),
689
            (1, hashes_value(want)),
690
        ]))
691
    }
692
    pub fn decode_negotiate(bytes: &[u8]) -> Result<(Vec<ChangeHash>, Vec<ChangeHash>)> {
693
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
694
        let m = map(&v, "negotiate")?;
695
        Ok((
696
            hashes_from(field(m, 0, "have")?)?,
697
            hashes_from(field(m, 1, "want")?)?,
698
        ))
699
    }
700
701
    /// `fetch` request: `{0: [changes], 1: max blob size or null}`.
702
    pub fn encode_fetch(hs: &[ChangeHash], max_blob: Option<u64>) -> Vec<u8> {
703
        cbor::encode(&Value::map([
704
            (0, hashes_value(hs)),
705
            (1, max_blob.map(Value::Uint).unwrap_or(Value::Null)),
706
        ]))
707
    }
708
    pub fn decode_fetch(bytes: &[u8]) -> Result<(Vec<ChangeHash>, Option<u64>)> {
709
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
710
        let m = map(&v, "fetch")?;
711
        let max = match m.get(&1) {
712
            Some(x) if !x.is_null() => Some(o::uint(x, "max blob")?),
713
            _ => None,
714
        };
715
        Ok((hashes_from(field(m, 0, "changes")?)?, max))
716
    }
717
718
    /// `shallow` request: `{0: [heads], 1: depth}`.
719
    pub fn encode_shallow(hs: &[ChangeHash], depth: u32) -> Vec<u8> {
720
        cbor::encode(&Value::map([
721
            (0, hashes_value(hs)),
722
            (1, Value::Uint(depth as u64)),
723
        ]))
724
    }
725
    pub fn decode_shallow(bytes: &[u8]) -> Result<(Vec<ChangeHash>, u32)> {
726
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
727
        let m = map(&v, "shallow")?;
728
        Ok((
729
            hashes_from(field(m, 0, "heads")?)?,
730
            o::u32_(field(m, 1, "depth")?, "depth")?,
731
        ))
732
    }
733
734
    pub fn encode_hashes(hs: &[ChangeHash]) -> Vec<u8> {
735
        cbor::encode(&Value::map([(0, hashes_value(hs))]))
736
    }
737
    pub fn decode_hashes(bytes: &[u8]) -> Result<Vec<ChangeHash>> {
738
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
739
        hashes_from(field(map(&v, "hashes")?, 0, "hashes")?)
740
    }
741
742
    pub fn encode_push(
743
        bundle: &Bundle,
744
        updates: &[RefUpdate],
745
        policy: Option<&SignedPolicy>,
746
        tags: &[TagRef],
747
    ) -> Vec<u8> {
748
        cbor::encode(&Value::map([
749
            (0, bundle_value(bundle)),
750
            (2, opt_policy_value(policy)),
751
            (3, tags_value(tags)),
752
            (
753
                1,
754
                Value::Array(
755
                    updates
756
                        .iter()
757
                        .map(|u| {
758
                            Value::map([
759
                                (0, Value::Text(u.name.clone())),
760
                                (1, Value::Bytes(u.old_state.0.to_vec())),
761
                                (2, Value::Bytes(u.new_state.0.to_vec())),
762
                                (3, Value::Bool(u.force)),
763
                                (4, opt_attest_value(&u.attestation)),
764
                            ])
765
                        })
766
                        .collect(),
767
                ),
768
            ),
769
        ]))
770
    }
771
    /// A decoded push: bundle, bookmark updates, policy, tags.
772
    pub type PushParts = (Bundle, Vec<RefUpdate>, Option<SignedPolicy>, Vec<TagRef>);
773
774
    pub fn decode_push(bytes: &[u8]) -> Result<PushParts> {
775
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
776
        let m = map(&v, "push")?;
777
        let bundle = bundle_from_value(field(m, 0, "bundle")?)?;
778
        let mut updates = Vec::new();
779
        for u in o::array(field(m, 1, "updates")?, "updates")? {
780
            let um = map(u, "update")?;
781
            updates.push(RefUpdate {
782
                name: o::text(field(um, 0, "name")?, "name")?.to_owned(),
783
                old_state: o::oref(field(um, 1, "old_state")?, "old_state")?,
784
                new_state: o::oref(field(um, 2, "new_state")?, "new_state")?,
785
                force: field(um, 3, "force")?
786
                    .as_bool()
787
                    .ok_or_else(|| schema("force: expected bool"))?,
788
                attestation: opt_attest_from(field(um, 4, "attestation")?)?,
789
            });
790
        }
791
        let policy = match m.get(&2) {
792
            Some(p) => opt_policy_from(p)?,
793
            None => None,
794
        };
795
        let tags = match m.get(&3) {
796
            Some(t) => tags_from(t)?,
797
            None => Vec::new(),
798
        };
799
        Ok((bundle, updates, policy, tags))
800
    }
801
802
    pub fn encode_push_response(results: &[RefResult]) -> Vec<u8> {
803
        cbor::encode(&Value::map([(
804
            0,
805
            Value::Array(
806
                results
807
                    .iter()
808
                    .map(|r| {
809
                        Value::map([
810
                            (0, Value::Text(r.name.clone())),
811
                            (1, Value::Bool(r.ok)),
812
                            (2, Value::Text(r.reason.clone())),
813
                        ])
814
                    })
815
                    .collect(),
816
            ),
817
        )]))
818
    }
819
    pub fn decode_push_response(bytes: &[u8]) -> Result<Vec<RefResult>> {
820
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
821
        let m = map(&v, "push response")?;
822
        let mut out = Vec::new();
823
        for r in o::array(field(m, 0, "results")?, "results")? {
824
            let rm = map(r, "result")?;
825
            out.push(RefResult {
826
                name: o::text(field(rm, 0, "name")?, "name")?.to_owned(),
827
                ok: field(rm, 1, "ok")?
828
                    .as_bool()
829
                    .ok_or_else(|| schema("ok: expected bool"))?,
830
                reason: o::text(field(rm, 2, "reason")?, "reason")?.to_owned(),
831
            });
832
        }
833
        Ok(out)
834
    }
835
}
836
837
#[cfg(test)]
838
mod tests {
839
    use super::*;
840
    use crate::attest::AttestBody;
841
    use crate::objects::Hlc;
842
843
    #[test]
844
    fn wire_round_trips() {
845
        let c = crate::objects::tests::sample_change();
846
        let sk = crate::identity::SecretKey {
847
            ed_seed: [1; 32],
848
            ml_seed: [2; 32],
849
        };
850
        let id = sk.identity("a", "b", 0);
851
        let key = id.hash();
852
        let sig = sk.sign(crate::identity::Domain::Change, &key, &c.hash());
853
        let seal = Attest::seal([3; 16], vec![c.hash()]);
854
        let seal_sig = sk.sign(crate::identity::Domain::Attest, &key, &seal.hash());
855
        let policy = Policy::single_root([3; 16], id.clone(), 99);
856
        let psig = sk.sign(crate::identity::Domain::Policy, &key, &policy.hash());
857
        let bundle = Bundle {
858
            changes: vec![(c.clone(), vec![sig.clone()])],
859
            attests: vec![SignedAttest {
860
                attest: seal.clone(),
861
                sigs: vec![seal_sig],
862
            }],
863
            objects: vec![
864
                (ObjectType::Identity, id.encode()),
865
                (ObjectType::Chunk, b"xyz".to_vec()),
866
            ],
867
            policies: vec![SignedPolicy {
868
                policy: policy.clone(),
869
                sigs: vec![psig.clone()],
870
            }],
871
        };
872
        let d = wire::decode_bundle(&wire::encode_bundle(&bundle)).unwrap();
873
        assert_eq!(d.changes, bundle.changes);
874
        assert_eq!(d.attests, bundle.attests);
875
        assert_eq!(d.objects, bundle.objects);
876
        assert_eq!(d.policies, bundle.policies);
877
878
        let att = Attest {
879
            repo: [3; 16],
880
            hlc: Hlc::default(),
881
            body: AttestBody::Ref {
882
                name: "main".into(),
883
                old_state: ObjectRef([1; 32]),
884
                new_state: ObjectRef([2; 32]),
885
                serial: 4,
886
            },
887
        };
888
        let refs = vec![
889
            RemoteRef {
890
                name: "main".into(),
891
                state: ObjectRef([2; 32]),
892
                heads: vec![c.hash()],
893
                attestation: Some(SignedAttest {
894
                    attest: att.clone(),
895
                    sigs: vec![sig.clone()],
896
                }),
897
                last_serial: Some(4),
898
            },
899
            RemoteRef {
900
                name: "dev".into(),
901
                state: ObjectRef([5; 32]),
902
                heads: vec![],
903
                attestation: None,
904
                last_serial: None,
905
            },
906
        ];
907
        let tag = TagRef {
908
            name: "v1".into(),
909
            state: ObjectRef([2; 32]),
910
            heads: vec![c.hash()],
911
            attestation: None,
912
        };
913
        let resp = RefsResponse {
914
            refs,
915
            policy: Some(SignedPolicy {
916
                policy: policy.clone(),
917
                sigs: vec![psig.clone()],
918
            }),
919
            tags: vec![tag.clone()],
920
            history: vec![SignedPolicy {
921
                policy: policy.clone(),
922
                sigs: vec![],
923
            }],
924
        };
925
        let (id_back, back) = wire::decode_refs(&wire::encode_refs([3; 16], &resp)).unwrap();
926
        assert_eq!(id_back, [3; 16]);
927
        assert_eq!(back.refs.len(), 2);
928
        assert_eq!(back.refs[0].attestation.as_ref().unwrap().attest, att);
929
        assert_eq!(back.refs[1].last_serial, None);
930
        assert_eq!(back.policy.as_ref().unwrap().policy, policy);
931
        assert_eq!(back.history, resp.history);
932
        assert_eq!(back.tags, vec![tag.clone()]);
933
934
        let (h, w) = wire::decode_negotiate(&wire::encode_negotiate(
935
            &[ObjectRef([1; 32])],
936
            &[ObjectRef([2; 32])],
937
        ))
938
        .unwrap();
939
        assert_eq!((h, w), (vec![ObjectRef([1; 32])], vec![ObjectRef([2; 32])]));
940
        assert_eq!(
941
            wire::decode_hashes(&wire::encode_hashes(&[c.hash()])).unwrap(),
942
            vec![c.hash()]
943
        );
944
        assert_eq!(
945
            wire::decode_fetch(&wire::encode_fetch(&[c.hash()], Some(4096))).unwrap(),
946
            (vec![c.hash()], Some(4096))
947
        );
948
        assert_eq!(
949
            wire::decode_fetch(&wire::encode_fetch(&[], None)).unwrap(),
950
            (vec![], None)
951
        );
952
        assert_eq!(
953
            wire::decode_shallow(&wire::encode_shallow(&[c.hash()], 3)).unwrap(),
954
            (vec![c.hash()], 3)
955
        );
956
        // An old-style fetch request without the filter field still decodes.
957
        assert_eq!(
958
            wire::decode_fetch(&wire::encode_hashes(&[c.hash()])).unwrap(),
959
            (vec![c.hash()], None)
960
        );
961
962
        let up = RefUpdate {
963
            name: "main".into(),
964
            old_state: ObjectRef([1; 32]),
965
            new_state: ObjectRef([2; 32]),
966
            force: true,
967
            attestation: Some(SignedAttest {
968
                attest: att,
969
                sigs: vec![sig],
970
            }),
971
        };
972
        let sp = SignedPolicy {
973
            policy,
974
            sigs: vec![psig],
975
        };
976
        let (b2, ups, pol, tags) = wire::decode_push(&wire::encode_push(
977
            &bundle,
978
            std::slice::from_ref(&up),
979
            Some(&sp),
980
            std::slice::from_ref(&tag),
981
        ))
982
        .unwrap();
983
        assert_eq!(pol, Some(sp));
984
        assert_eq!(tags, vec![tag]);
985
        assert_eq!(b2.changes.len(), 1);
986
        assert_eq!(ups[0].name, "main");
987
        assert!(ups[0].force);
988
        assert_eq!(ups[0].attestation, up.attestation);
989
        let res = vec![RefResult {
990
            name: "main".into(),
991
            ok: false,
992
            reason: "stale".into(),
993
        }];
994
        assert_eq!(
995
            wire::decode_push_response(&wire::encode_push_response(&res)).unwrap(),
996
            res
997
        );
998
        assert_eq!(
999
            wire::decode_capabilities(&wire::encode_capabilities([7; 16])).unwrap(),
1000
            [7; 16]
1001
        );
1002
    }
1003
}