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