OXYGENHUB
# d82e44097323 oxygen / crates / oxy-core / src / protocol.rs
34.9 KiB · Rust · last changed Proposal clients: oxy seal --proposal, oxy proposal show|land, seal-only pushes, http_get for hub APIs 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!("{url}: HTTP {code}: {}", text.trim())))
323
        }
324
        Err(e) => Err(RepoError::Msg(format!("{url}: {e}"))),
325
    }
326
}
327
328
impl Remote for HttpRemote {
329
    fn repo_id(&self) -> Result<[u8; 16]> {
330
        wire::decode_capabilities(&self.call(false, "capabilities", None)?)
331
    }
332
    fn refs(&self) -> Result<RefsResponse> {
333
        Ok(wire::decode_refs(&self.call(false, "refs", None)?)?.1)
334
    }
335
    fn negotiate(&self, have: &[ChangeHash], want: &[ChangeHash]) -> Result<Vec<ChangeHash>> {
336
        wire::decode_hashes(&self.call(
337
            true,
338
            "negotiate",
339
            Some(&wire::encode_negotiate(have, want)),
340
        )?)
341
    }
342
    fn fetch(&self, changes: &[ChangeHash], max_blob: Option<u64>) -> Result<Bundle> {
343
        wire::decode_bundle(&self.call(
344
            true,
345
            "fetch",
346
            Some(&wire::encode_fetch(changes, max_blob)),
347
        )?)
348
    }
349
    fn objects(&self, refs: &[ObjectRef]) -> Result<Vec<(ObjectType, Vec<u8>)>> {
350
        Ok(
351
            wire::decode_bundle(&self.call(true, "objects", Some(&wire::encode_hashes(refs)))?)?
352
                .objects,
353
        )
354
    }
355
    fn checkpoint(&self, heads: &[ChangeHash]) -> Result<Bundle> {
356
        wire::decode_bundle(&self.call(true, "checkpoint", Some(&wire::encode_hashes(heads)))?)
357
    }
358
    fn shallow(&self, heads: &[ChangeHash], depth: u32) -> Result<Vec<ChangeHash>> {
359
        wire::decode_hashes(&self.call(
360
            true,
361
            "shallow",
362
            Some(&wire::encode_shallow(heads, depth)),
363
        )?)
364
    }
365
    fn push(
366
        &self,
367
        bundle: Bundle,
368
        updates: Vec<RefUpdate>,
369
        policy: Option<SignedPolicy>,
370
        tags: Vec<TagRef>,
371
    ) -> Result<Vec<RefResult>> {
372
        wire::decode_push_response(&self.call(
373
            true,
374
            "push",
375
            Some(&wire::encode_push(
376
                &bundle,
377
                &updates,
378
                policy.as_ref(),
379
                &tags,
380
            )),
381
        )?)
382
    }
383
}
384
385
/// Open a remote by URL: a local path (optionally `file://`), or `http(s)://`.
386
pub fn open_remote(url: &str, options: &RemoteOptions) -> Result<Box<dyn Remote>> {
387
    if url.starts_with("http://") || url.starts_with("https://") {
388
        return Ok(Box::new(HttpRemote::new(url, options)?));
389
    }
390
    let path = url.strip_prefix("file://").unwrap_or(url);
391
    if path.contains("://") {
392
        return Err(RepoError::Msg(format!("unsupported remote URL {url:?}")));
393
    }
394
    Ok(Box::new(LocalRemote::open(Path::new(path))?))
395
}
396
397
// ---------------------------------------------------------------- wire
398
399
/// CBOR encodings of the protocol messages (spec §16.1).
400
pub mod wire {
401
    use super::*;
402
403
    fn schema(msg: &str) -> RepoError {
404
        RepoError::Object(ObjectError::Schema(msg.into()))
405
    }
406
    fn sigs_value(sigs: &[Signature]) -> Value {
407
        Value::Array(sigs.iter().map(|s| s.to_value()).collect())
408
    }
409
    fn sigs_from(v: &Value) -> Result<Vec<Signature>> {
410
        Ok(o::array(v, "signatures")?
411
            .iter()
412
            .map(Signature::from_value)
413
            .collect::<std::result::Result<Vec<_>, _>>()?)
414
    }
415
    fn hashes_value(hs: &[ObjectRef]) -> Value {
416
        Value::Array(hs.iter().map(|h| Value::Bytes(h.0.to_vec())).collect())
417
    }
418
    fn hashes_from(v: &Value) -> Result<Vec<ObjectRef>> {
419
        Ok(o::array(v, "hashes")?
420
            .iter()
421
            .map(|h| o::oref(h, "hash"))
422
            .collect::<std::result::Result<Vec<_>, _>>()?)
423
    }
424
    fn attest_value(sa: &SignedAttest) -> Value {
425
        Value::Array(vec![Value::Bytes(sa.attest.encode()), sigs_value(&sa.sigs)])
426
    }
427
    fn attest_from(v: &Value) -> Result<SignedAttest> {
428
        let a = o::array(v, "signed attest")?;
429
        if a.len() != 2 {
430
            return Err(schema("signed attest: expected [attest, sigs]"));
431
        }
432
        Ok(SignedAttest {
433
            attest: Attest::decode(o::bytes(&a[0], "attest")?)?,
434
            sigs: sigs_from(&a[1])?,
435
        })
436
    }
437
    fn opt_attest_value(sa: &Option<SignedAttest>) -> Value {
438
        sa.as_ref().map(attest_value).unwrap_or(Value::Null)
439
    }
440
    fn opt_attest_from(v: &Value) -> Result<Option<SignedAttest>> {
441
        if v.is_null() {
442
            Ok(None)
443
        } else {
444
            attest_from(v).map(Some)
445
        }
446
    }
447
    /// `[policy bytes, [signature]]`: also the format of a policy proposal
448
    /// file exchanged between root holders (spec §14.5).
449
    pub fn policy_value(sp: &SignedPolicy) -> Value {
450
        Value::Array(vec![Value::Bytes(sp.policy.encode()), sigs_value(&sp.sigs)])
451
    }
452
    pub fn policy_from(v: &Value) -> Result<SignedPolicy> {
453
        let a = o::array(v, "signed policy")?;
454
        if a.len() != 2 {
455
            return Err(schema("signed policy: expected [policy, sigs]"));
456
        }
457
        Ok(SignedPolicy {
458
            policy: Policy::decode(o::bytes(&a[0], "policy")?)?,
459
            sigs: sigs_from(&a[1])?,
460
        })
461
    }
462
    fn opt_policy_value(sp: Option<&SignedPolicy>) -> Value {
463
        sp.map(policy_value).unwrap_or(Value::Null)
464
    }
465
    fn opt_policy_from(v: &Value) -> Result<Option<SignedPolicy>> {
466
        if v.is_null() {
467
            Ok(None)
468
        } else {
469
            policy_from(v).map(Some)
470
        }
471
    }
472
    fn map<'a>(v: &'a Value, what: &str) -> Result<&'a o::Map> {
473
        Ok(o::map(v, what)?)
474
    }
475
    fn field<'a>(m: &'a o::Map, k: u64, what: &str) -> Result<&'a Value> {
476
        Ok(o::field(m, k, what)?)
477
    }
478
479
    pub fn bundle_value(b: &Bundle) -> Value {
480
        Value::map([
481
            (
482
                0,
483
                Value::Array(
484
                    b.changes
485
                        .iter()
486
                        .map(|(c, s)| Value::Array(vec![Value::Bytes(c.encode()), sigs_value(s)]))
487
                        .collect(),
488
                ),
489
            ),
490
            (
491
                1,
492
                Value::Array(b.attests.iter().map(attest_value).collect()),
493
            ),
494
            (
495
                2,
496
                Value::Array(
497
                    b.objects
498
                        .iter()
499
                        .map(|(t, body)| {
500
                            Value::Array(vec![
501
                                Value::Text(t.name().into()),
502
                                Value::Bytes(body.clone()),
503
                            ])
504
                        })
505
                        .collect(),
506
                ),
507
            ),
508
            (
509
                3,
510
                Value::Array(b.policies.iter().map(policy_value).collect()),
511
            ),
512
        ])
513
    }
514
515
    pub fn bundle_from_value(v: &Value) -> Result<Bundle> {
516
        let m = map(v, "bundle")?;
517
        let mut b = Bundle::default();
518
        for c in o::array(field(m, 0, "changes")?, "changes")? {
519
            let pair = o::array(c, "change entry")?;
520
            if pair.len() != 2 {
521
                return Err(schema("change entry: expected [change, sigs]"));
522
            }
523
            b.changes.push((
524
                Change::decode(o::bytes(&pair[0], "change")?)?,
525
                sigs_from(&pair[1])?,
526
            ));
527
        }
528
        for a in o::array(field(m, 1, "attests")?, "attests")? {
529
            b.attests.push(attest_from(a)?);
530
        }
531
        for ob in o::array(field(m, 2, "objects")?, "objects")? {
532
            let pair = o::array(ob, "object")?;
533
            if pair.len() != 2 {
534
                return Err(schema("object: expected [type, body]"));
535
            }
536
            let ty = ObjectType::from_name(o::text(&pair[0], "object type")?)
537
                .ok_or_else(|| schema("unknown object type"))?;
538
            b.objects
539
                .push((ty, o::bytes(&pair[1], "object body")?.to_vec()));
540
        }
541
        if let Some(ps) = m.get(&3) {
542
            for p in o::array(ps, "policies")? {
543
                b.policies.push(policy_from(p)?);
544
            }
545
        }
546
        Ok(b)
547
    }
548
549
    pub fn encode_bundle(b: &Bundle) -> Vec<u8> {
550
        cbor::encode(&bundle_value(b))
551
    }
552
    pub fn decode_bundle(bytes: &[u8]) -> Result<Bundle> {
553
        bundle_from_value(&cbor::decode(bytes).map_err(ObjectError::from)?)
554
    }
555
556
    pub fn encode_capabilities(id: [u8; 16]) -> Vec<u8> {
557
        cbor::encode(&Value::map([
558
            (0, Value::Array(vec![Value::Uint(PROTOCOL_VERSION)])),
559
            (1, Value::Bytes(id.to_vec())),
560
            (2, Value::Array(vec![Value::Text("seal".into())])),
561
        ]))
562
    }
563
    pub fn decode_capabilities(bytes: &[u8]) -> Result<[u8; 16]> {
564
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
565
        let m = map(&v, "capabilities")?;
566
        let versions = o::array(field(m, 0, "versions")?, "versions")?;
567
        if !versions
568
            .iter()
569
            .any(|x| x.as_uint() == Some(PROTOCOL_VERSION))
570
        {
571
            return Err(RepoError::Msg(
572
                "remote does not speak protocol version 1".into(),
573
            ));
574
        }
575
        o::bytes(field(m, 1, "repo id")?, "repo id")?
576
            .try_into()
577
            .map_err(|_| schema("repo id: expected 16 bytes"))
578
    }
579
580
    fn tags_value(tags: &[TagRef]) -> Value {
581
        Value::Array(
582
            tags.iter()
583
                .map(|t| {
584
                    Value::map([
585
                        (0, Value::Text(t.name.clone())),
586
                        (1, Value::Bytes(t.state.0.to_vec())),
587
                        (2, hashes_value(&t.heads)),
588
                        (3, opt_attest_value(&t.attestation)),
589
                    ])
590
                })
591
                .collect(),
592
        )
593
    }
594
    fn tags_from(v: &Value) -> Result<Vec<TagRef>> {
595
        let mut out = Vec::new();
596
        for t in o::array(v, "tags")? {
597
            let tm = map(t, "tag")?;
598
            out.push(TagRef {
599
                name: o::text(field(tm, 0, "name")?, "name")?.to_owned(),
600
                state: o::oref(field(tm, 1, "state")?, "state")?,
601
                heads: hashes_from(field(tm, 2, "heads")?)?,
602
                attestation: opt_attest_from(field(tm, 3, "attestation")?)?,
603
            });
604
        }
605
        Ok(out)
606
    }
607
608
    pub fn encode_refs(id: [u8; 16], resp: &RefsResponse) -> Vec<u8> {
609
        cbor::encode(&Value::map([
610
            (
611
                0,
612
                Value::Array(
613
                    resp.refs
614
                        .iter()
615
                        .map(|r| {
616
                            Value::map([
617
                                (0, Value::Text(r.name.clone())),
618
                                (1, Value::Bytes(r.state.0.to_vec())),
619
                                (2, hashes_value(&r.heads)),
620
                                (3, opt_attest_value(&r.attestation)),
621
                                (4, r.last_serial.map(Value::Uint).unwrap_or(Value::Null)),
622
                            ])
623
                        })
624
                        .collect(),
625
                ),
626
            ),
627
            (1, Value::Bytes(id.to_vec())),
628
            (2, opt_policy_value(resp.policy.as_ref())),
629
            (3, tags_value(&resp.tags)),
630
            (
631
                4,
632
                Value::Array(resp.history.iter().map(policy_value).collect()),
633
            ),
634
        ]))
635
    }
636
    pub fn decode_refs(bytes: &[u8]) -> Result<([u8; 16], RefsResponse)> {
637
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
638
        let m = map(&v, "refs")?;
639
        let id: [u8; 16] = o::bytes(field(m, 1, "repo id")?, "repo id")?
640
            .try_into()
641
            .map_err(|_| schema("repo id: expected 16 bytes"))?;
642
        let mut refs = Vec::new();
643
        for r in o::array(field(m, 0, "refs")?, "refs")? {
644
            let rm = map(r, "ref")?;
645
            let ls = field(rm, 4, "last serial")?;
646
            refs.push(RemoteRef {
647
                name: o::text(field(rm, 0, "name")?, "name")?.to_owned(),
648
                state: o::oref(field(rm, 1, "state")?, "state")?,
649
                heads: hashes_from(field(rm, 2, "heads")?)?,
650
                attestation: opt_attest_from(field(rm, 3, "attestation")?)?,
651
                last_serial: if ls.is_null() {
652
                    None
653
                } else {
654
                    Some(o::uint(ls, "last serial")?)
655
                },
656
            });
657
        }
658
        let policy = match m.get(&2) {
659
            Some(p) => opt_policy_from(p)?,
660
            None => None,
661
        };
662
        let tags = match m.get(&3) {
663
            Some(t) => tags_from(t)?,
664
            None => Vec::new(),
665
        };
666
        let mut history = Vec::new();
667
        if let Some(h) = m.get(&4) {
668
            for p in o::array(h, "history")? {
669
                history.push(policy_from(p)?);
670
            }
671
        }
672
        Ok((
673
            id,
674
            RefsResponse {
675
                refs,
676
                policy,
677
                tags,
678
                history,
679
            },
680
        ))
681
    }
682
683
    pub fn encode_negotiate(have: &[ChangeHash], want: &[ChangeHash]) -> Vec<u8> {
684
        cbor::encode(&Value::map([
685
            (0, hashes_value(have)),
686
            (1, hashes_value(want)),
687
        ]))
688
    }
689
    pub fn decode_negotiate(bytes: &[u8]) -> Result<(Vec<ChangeHash>, Vec<ChangeHash>)> {
690
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
691
        let m = map(&v, "negotiate")?;
692
        Ok((
693
            hashes_from(field(m, 0, "have")?)?,
694
            hashes_from(field(m, 1, "want")?)?,
695
        ))
696
    }
697
698
    /// `fetch` request: `{0: [changes], 1: max blob size or null}`.
699
    pub fn encode_fetch(hs: &[ChangeHash], max_blob: Option<u64>) -> Vec<u8> {
700
        cbor::encode(&Value::map([
701
            (0, hashes_value(hs)),
702
            (1, max_blob.map(Value::Uint).unwrap_or(Value::Null)),
703
        ]))
704
    }
705
    pub fn decode_fetch(bytes: &[u8]) -> Result<(Vec<ChangeHash>, Option<u64>)> {
706
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
707
        let m = map(&v, "fetch")?;
708
        let max = match m.get(&1) {
709
            Some(x) if !x.is_null() => Some(o::uint(x, "max blob")?),
710
            _ => None,
711
        };
712
        Ok((hashes_from(field(m, 0, "changes")?)?, max))
713
    }
714
715
    /// `shallow` request: `{0: [heads], 1: depth}`.
716
    pub fn encode_shallow(hs: &[ChangeHash], depth: u32) -> Vec<u8> {
717
        cbor::encode(&Value::map([
718
            (0, hashes_value(hs)),
719
            (1, Value::Uint(depth as u64)),
720
        ]))
721
    }
722
    pub fn decode_shallow(bytes: &[u8]) -> Result<(Vec<ChangeHash>, u32)> {
723
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
724
        let m = map(&v, "shallow")?;
725
        Ok((
726
            hashes_from(field(m, 0, "heads")?)?,
727
            o::u32_(field(m, 1, "depth")?, "depth")?,
728
        ))
729
    }
730
731
    pub fn encode_hashes(hs: &[ChangeHash]) -> Vec<u8> {
732
        cbor::encode(&Value::map([(0, hashes_value(hs))]))
733
    }
734
    pub fn decode_hashes(bytes: &[u8]) -> Result<Vec<ChangeHash>> {
735
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
736
        hashes_from(field(map(&v, "hashes")?, 0, "hashes")?)
737
    }
738
739
    pub fn encode_push(
740
        bundle: &Bundle,
741
        updates: &[RefUpdate],
742
        policy: Option<&SignedPolicy>,
743
        tags: &[TagRef],
744
    ) -> Vec<u8> {
745
        cbor::encode(&Value::map([
746
            (0, bundle_value(bundle)),
747
            (2, opt_policy_value(policy)),
748
            (3, tags_value(tags)),
749
            (
750
                1,
751
                Value::Array(
752
                    updates
753
                        .iter()
754
                        .map(|u| {
755
                            Value::map([
756
                                (0, Value::Text(u.name.clone())),
757
                                (1, Value::Bytes(u.old_state.0.to_vec())),
758
                                (2, Value::Bytes(u.new_state.0.to_vec())),
759
                                (3, Value::Bool(u.force)),
760
                                (4, opt_attest_value(&u.attestation)),
761
                            ])
762
                        })
763
                        .collect(),
764
                ),
765
            ),
766
        ]))
767
    }
768
    /// A decoded push: bundle, bookmark updates, policy, tags.
769
    pub type PushParts = (Bundle, Vec<RefUpdate>, Option<SignedPolicy>, Vec<TagRef>);
770
771
    pub fn decode_push(bytes: &[u8]) -> Result<PushParts> {
772
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
773
        let m = map(&v, "push")?;
774
        let bundle = bundle_from_value(field(m, 0, "bundle")?)?;
775
        let mut updates = Vec::new();
776
        for u in o::array(field(m, 1, "updates")?, "updates")? {
777
            let um = map(u, "update")?;
778
            updates.push(RefUpdate {
779
                name: o::text(field(um, 0, "name")?, "name")?.to_owned(),
780
                old_state: o::oref(field(um, 1, "old_state")?, "old_state")?,
781
                new_state: o::oref(field(um, 2, "new_state")?, "new_state")?,
782
                force: field(um, 3, "force")?
783
                    .as_bool()
784
                    .ok_or_else(|| schema("force: expected bool"))?,
785
                attestation: opt_attest_from(field(um, 4, "attestation")?)?,
786
            });
787
        }
788
        let policy = match m.get(&2) {
789
            Some(p) => opt_policy_from(p)?,
790
            None => None,
791
        };
792
        let tags = match m.get(&3) {
793
            Some(t) => tags_from(t)?,
794
            None => Vec::new(),
795
        };
796
        Ok((bundle, updates, policy, tags))
797
    }
798
799
    pub fn encode_push_response(results: &[RefResult]) -> Vec<u8> {
800
        cbor::encode(&Value::map([(
801
            0,
802
            Value::Array(
803
                results
804
                    .iter()
805
                    .map(|r| {
806
                        Value::map([
807
                            (0, Value::Text(r.name.clone())),
808
                            (1, Value::Bool(r.ok)),
809
                            (2, Value::Text(r.reason.clone())),
810
                        ])
811
                    })
812
                    .collect(),
813
            ),
814
        )]))
815
    }
816
    pub fn decode_push_response(bytes: &[u8]) -> Result<Vec<RefResult>> {
817
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
818
        let m = map(&v, "push response")?;
819
        let mut out = Vec::new();
820
        for r in o::array(field(m, 0, "results")?, "results")? {
821
            let rm = map(r, "result")?;
822
            out.push(RefResult {
823
                name: o::text(field(rm, 0, "name")?, "name")?.to_owned(),
824
                ok: field(rm, 1, "ok")?
825
                    .as_bool()
826
                    .ok_or_else(|| schema("ok: expected bool"))?,
827
                reason: o::text(field(rm, 2, "reason")?, "reason")?.to_owned(),
828
            });
829
        }
830
        Ok(out)
831
    }
832
}
833
834
#[cfg(test)]
835
mod tests {
836
    use super::*;
837
    use crate::attest::AttestBody;
838
    use crate::objects::Hlc;
839
840
    #[test]
841
    fn wire_round_trips() {
842
        let c = crate::objects::tests::sample_change();
843
        let sk = crate::identity::SecretKey {
844
            ed_seed: [1; 32],
845
            ml_seed: [2; 32],
846
        };
847
        let id = sk.identity("a", "b", 0);
848
        let key = id.hash();
849
        let sig = sk.sign(crate::identity::Domain::Change, &key, &c.hash());
850
        let seal = Attest::seal([3; 16], vec![c.hash()]);
851
        let seal_sig = sk.sign(crate::identity::Domain::Attest, &key, &seal.hash());
852
        let policy = Policy::single_root([3; 16], id.clone(), 99);
853
        let psig = sk.sign(crate::identity::Domain::Policy, &key, &policy.hash());
854
        let bundle = Bundle {
855
            changes: vec![(c.clone(), vec![sig.clone()])],
856
            attests: vec![SignedAttest {
857
                attest: seal.clone(),
858
                sigs: vec![seal_sig],
859
            }],
860
            objects: vec![
861
                (ObjectType::Identity, id.encode()),
862
                (ObjectType::Chunk, b"xyz".to_vec()),
863
            ],
864
            policies: vec![SignedPolicy {
865
                policy: policy.clone(),
866
                sigs: vec![psig.clone()],
867
            }],
868
        };
869
        let d = wire::decode_bundle(&wire::encode_bundle(&bundle)).unwrap();
870
        assert_eq!(d.changes, bundle.changes);
871
        assert_eq!(d.attests, bundle.attests);
872
        assert_eq!(d.objects, bundle.objects);
873
        assert_eq!(d.policies, bundle.policies);
874
875
        let att = Attest {
876
            repo: [3; 16],
877
            hlc: Hlc::default(),
878
            body: AttestBody::Ref {
879
                name: "main".into(),
880
                old_state: ObjectRef([1; 32]),
881
                new_state: ObjectRef([2; 32]),
882
                serial: 4,
883
            },
884
        };
885
        let refs = vec![
886
            RemoteRef {
887
                name: "main".into(),
888
                state: ObjectRef([2; 32]),
889
                heads: vec![c.hash()],
890
                attestation: Some(SignedAttest {
891
                    attest: att.clone(),
892
                    sigs: vec![sig.clone()],
893
                }),
894
                last_serial: Some(4),
895
            },
896
            RemoteRef {
897
                name: "dev".into(),
898
                state: ObjectRef([5; 32]),
899
                heads: vec![],
900
                attestation: None,
901
                last_serial: None,
902
            },
903
        ];
904
        let tag = TagRef {
905
            name: "v1".into(),
906
            state: ObjectRef([2; 32]),
907
            heads: vec![c.hash()],
908
            attestation: None,
909
        };
910
        let resp = RefsResponse {
911
            refs,
912
            policy: Some(SignedPolicy {
913
                policy: policy.clone(),
914
                sigs: vec![psig.clone()],
915
            }),
916
            tags: vec![tag.clone()],
917
            history: vec![SignedPolicy {
918
                policy: policy.clone(),
919
                sigs: vec![],
920
            }],
921
        };
922
        let (id_back, back) = wire::decode_refs(&wire::encode_refs([3; 16], &resp)).unwrap();
923
        assert_eq!(id_back, [3; 16]);
924
        assert_eq!(back.refs.len(), 2);
925
        assert_eq!(back.refs[0].attestation.as_ref().unwrap().attest, att);
926
        assert_eq!(back.refs[1].last_serial, None);
927
        assert_eq!(back.policy.as_ref().unwrap().policy, policy);
928
        assert_eq!(back.history, resp.history);
929
        assert_eq!(back.tags, vec![tag.clone()]);
930
931
        let (h, w) = wire::decode_negotiate(&wire::encode_negotiate(
932
            &[ObjectRef([1; 32])],
933
            &[ObjectRef([2; 32])],
934
        ))
935
        .unwrap();
936
        assert_eq!((h, w), (vec![ObjectRef([1; 32])], vec![ObjectRef([2; 32])]));
937
        assert_eq!(
938
            wire::decode_hashes(&wire::encode_hashes(&[c.hash()])).unwrap(),
939
            vec![c.hash()]
940
        );
941
        assert_eq!(
942
            wire::decode_fetch(&wire::encode_fetch(&[c.hash()], Some(4096))).unwrap(),
943
            (vec![c.hash()], Some(4096))
944
        );
945
        assert_eq!(
946
            wire::decode_fetch(&wire::encode_fetch(&[], None)).unwrap(),
947
            (vec![], None)
948
        );
949
        assert_eq!(
950
            wire::decode_shallow(&wire::encode_shallow(&[c.hash()], 3)).unwrap(),
951
            (vec![c.hash()], 3)
952
        );
953
        // An old-style fetch request without the filter field still decodes.
954
        assert_eq!(
955
            wire::decode_fetch(&wire::encode_hashes(&[c.hash()])).unwrap(),
956
            (vec![c.hash()], None)
957
        );
958
959
        let up = RefUpdate {
960
            name: "main".into(),
961
            old_state: ObjectRef([1; 32]),
962
            new_state: ObjectRef([2; 32]),
963
            force: true,
964
            attestation: Some(SignedAttest {
965
                attest: att,
966
                sigs: vec![sig],
967
            }),
968
        };
969
        let sp = SignedPolicy {
970
            policy,
971
            sigs: vec![psig],
972
        };
973
        let (b2, ups, pol, tags) = wire::decode_push(&wire::encode_push(
974
            &bundle,
975
            std::slice::from_ref(&up),
976
            Some(&sp),
977
            std::slice::from_ref(&tag),
978
        ))
979
        .unwrap();
980
        assert_eq!(pol, Some(sp));
981
        assert_eq!(tags, vec![tag]);
982
        assert_eq!(b2.changes.len(), 1);
983
        assert_eq!(ups[0].name, "main");
984
        assert!(ups[0].force);
985
        assert_eq!(ups[0].attestation, up.attestation);
986
        let res = vec![RefResult {
987
            name: "main".into(),
988
            ok: false,
989
            reason: "stale".into(),
990
        }];
991
        assert_eq!(
992
            wire::decode_push_response(&wire::encode_push_response(&res)).unwrap(),
993
            res
994
        );
995
        assert_eq!(
996
            wire::decode_capabilities(&wire::encode_capabilities([7; 16])).unwrap(),
997
            [7; 16]
998
        );
999
    }
1000
}