OXYGENHUB
# b2ef93bb2366 oxygen / crates / oxy-core / src / protocol.rs
28.1 KiB · Rust · last changed Lazy blobs: clone --max-blob / filter.max-blob, absent-blob registry fetched on first read, objects endpoint (spec 0.6e) 1 month ago source blame history raw
5b9c6ad4 Andy McCall ↶ 1
//! Transport-agnostic protocol (spec §16): what a client asks of a remote and
2
//! what a server does with a push. `LocalRemote` serves another repository
750251b2 Andy McCall ↶ 3
//! directory in-process, `HttpRemote` speaks to an `oxy-server` over HTTP(S),
4
//! and the server side reuses `Repo::receive_push` and friends unchanged.
5
//!
6
//! Wire messages are deterministic CBOR (`wire` module); over HTTP each is a
7
//! request or response body with content type `application/oxy-cbor`.
5b9c6ad4 Andy McCall ↶ 8
9
use crate::attest::Attest;
750251b2 Andy McCall ↶ 10
use crate::cbor::{self, Value};
5b9c6ad4 Andy McCall ↶ 11
use crate::hash::{ChangeHash, ObjectRef, ObjectType};
12
use crate::identity::Signature;
750251b2 Andy McCall ↶ 13
use crate::objects::{self as o, Change, ObjectError};
83e0677b Andy McCall ↶ 14
use crate::policy::Policy;
5b9c6ad4 Andy McCall ↶ 15
use crate::repo::{Repo, RepoError, Result};
2b5ee371 Andy McCall ↶ 16
use std::path::{Path, PathBuf};
17
use std::sync::Arc;
5b9c6ad4 Andy McCall ↶ 18
750251b2 Andy McCall ↶ 19
pub const CONTENT_TYPE: &str = "application/oxy-cbor";
20
pub const PROTOCOL_VERSION: u64 = 1;
21
5b9c6ad4 Andy McCall ↶ 22
/// An attestation together with the signatures over its ObjectRef.
23
#[derive(Clone, Debug, PartialEq, Eq)]
24
pub struct SignedAttest {
25
    pub attest: Attest,
26
    pub sigs: Vec<Signature>,
27
}
28
83e0677b Andy McCall ↶ 29
/// A policy together with the root signatures over its ObjectRef.
30
#[derive(Clone, Debug, PartialEq, Eq)]
31
pub struct SignedPolicy {
32
    pub policy: Policy,
33
    pub sigs: Vec<Signature>,
34
}
35
132b884b Andy McCall ↶ 36
/// What `refs` returns: every bookmark, every tag, and the current policy.
83e0677b Andy McCall ↶ 37
#[derive(Clone, Debug, Default)]
38
pub struct RefsResponse {
39
    pub refs: Vec<RemoteRef>,
40
    pub policy: Option<SignedPolicy>,
132b884b Andy McCall ↶ 41
    pub tags: Vec<TagRef>,
83e0677b Andy McCall ↶ 42
}
43
132b884b Andy McCall ↶ 44
/// A tag as a remote reports it (spec §10.1).
45
#[derive(Clone, Debug, PartialEq, Eq)]
46
pub struct TagRef {
47
    pub name: String,
48
    pub state: ObjectRef,
49
    pub heads: Vec<ChangeHash>,
50
    pub attestation: Option<SignedAttest>,
51
}
52
5b9c6ad4 Andy McCall ↶ 53
/// One reference as a remote reports it.
54
#[derive(Clone, Debug)]
55
pub struct RemoteRef {
56
    pub name: String,
57
    pub state: ObjectRef,
58
    pub heads: Vec<ChangeHash>,
59
    pub attestation: Option<SignedAttest>,
60
}
61
62
/// Everything needed to add a set of changes to a repository.
63
#[derive(Clone, Debug, Default)]
64
pub struct Bundle {
65
    /// In dependency order, each with its individual signatures.
66
    pub changes: Vec<(Change, Vec<Signature>)>,
67
    /// Seals covering the changes.
68
    pub attests: Vec<SignedAttest>,
69
    /// Chunks, blobs, identities, and state objects referenced by the changes.
70
    pub objects: Vec<(ObjectType, Vec<u8>)>,
71
}
72
73
impl Bundle {
74
    pub fn is_empty(&self) -> bool {
75
        self.changes.is_empty() && self.attests.is_empty() && self.objects.is_empty()
76
    }
77
}
78
79
/// A requested bookmark move (spec §10.2, §16.3).
80
#[derive(Clone, Debug)]
81
pub struct RefUpdate {
82
    pub name: String,
83
    pub old_state: ObjectRef,
84
    pub new_state: ObjectRef,
85
    pub force: bool,
86
    pub attestation: Option<SignedAttest>,
87
}
88
89
#[derive(Clone, Debug, PartialEq, Eq)]
90
pub struct RefResult {
91
    pub name: String,
92
    pub ok: bool,
93
    pub reason: String,
94
}
95
96
pub trait Remote {
97
    fn repo_id(&self) -> Result<[u8; 16]>;
83e0677b Andy McCall ↶ 98
    fn refs(&self) -> Result<RefsResponse>;
5b9c6ad4 Andy McCall ↶ 99
    /// Changes in the closure of `want` but not of `have`, in dependency order.
100
    fn negotiate(&self, have: &[ChangeHash], want: &[ChangeHash]) -> Result<Vec<ChangeHash>>;
b3c5a59a Andy McCall ↶ 101
    /// The changes with their signatures, seals, identities, and blobs; blobs
102
    /// larger than `max_blob` bytes are left out for lazy fetching (spec §13.5).
103
    fn fetch(&self, changes: &[ChangeHash], max_blob: Option<u64>) -> Result<Bundle>;
104
    /// Individual objects by reference (spec §16.1 `objects`); a blob comes
105
    /// with its chunks.
106
    fn objects(&self, refs: &[ObjectRef]) -> Result<Vec<(ObjectType, Vec<u8>)>>;
2863456a Andy McCall ↶ 107
    /// A checkpoint of exactly `heads` (spec §16.1 `checkpoint`): the
108
    /// checkpoint object, its payload blob, and the blob's chunks.
109
    fn checkpoint(&self, heads: &[ChangeHash]) -> Result<Bundle>;
110
    /// The changes within `depth` dependency steps of `heads` (spec §17).
111
    fn shallow(&self, heads: &[ChangeHash], depth: u32) -> Result<Vec<ChangeHash>>;
132b884b Andy McCall ↶ 112
    /// Push changes, bookmark updates, new tags, and optionally a newer
113
    /// policy. The policy is applied first; a result named `policy` reports
114
    /// it, and each tag reports as `tags/<name>`.
115
    fn push(&self, bundle: Bundle, updates: Vec<RefUpdate>, policy: Option<SignedPolicy>, tags: Vec<TagRef>) -> Result<Vec<RefResult>>;
5b9c6ad4 Andy McCall ↶ 116
}
117
750251b2 Andy McCall ↶ 118
// ---------------------------------------------------------------- local
119
5b9c6ad4 Andy McCall ↶ 120
/// Another repository on this machine, served in-process.
121
pub struct LocalRemote {
122
    pub repo: Repo,
123
}
124
125
impl LocalRemote {
126
    pub fn open(path: &Path) -> Result<LocalRemote> {
127
        Ok(LocalRemote { repo: Repo::open(path)? })
128
    }
129
}
130
131
impl Remote for LocalRemote {
132
    fn repo_id(&self) -> Result<[u8; 16]> {
133
        self.repo.id()
134
    }
83e0677b Andy McCall ↶ 135
    fn refs(&self) -> Result<RefsResponse> {
5b9c6ad4 Andy McCall ↶ 136
        self.repo.remote_refs()
137
    }
138
    fn negotiate(&self, have: &[ChangeHash], want: &[ChangeHash]) -> Result<Vec<ChangeHash>> {
139
        self.repo.negotiate(have, want)
140
    }
b3c5a59a Andy McCall ↶ 141
    fn fetch(&self, changes: &[ChangeHash], max_blob: Option<u64>) -> Result<Bundle> {
142
        self.repo.bundle_for_filtered(changes, max_blob)
143
    }
144
    fn objects(&self, refs: &[ObjectRef]) -> Result<Vec<(ObjectType, Vec<u8>)>> {
145
        self.repo.objects_for(refs)
5b9c6ad4 Andy McCall ↶ 146
    }
2863456a Andy McCall ↶ 147
    fn checkpoint(&self, heads: &[ChangeHash]) -> Result<Bundle> {
148
        self.repo.checkpoint_bundle_for(heads)
149
    }
150
    fn shallow(&self, heads: &[ChangeHash], depth: u32) -> Result<Vec<ChangeHash>> {
151
        self.repo.shallow_changes(heads, depth)
152
    }
132b884b Andy McCall ↶ 153
    fn push(&self, bundle: Bundle, updates: Vec<RefUpdate>, policy: Option<SignedPolicy>, tags: Vec<TagRef>) -> Result<Vec<RefResult>> {
154
        self.repo.receive_push(bundle, updates, policy, tags)
5b9c6ad4 Andy McCall ↶ 155
    }
156
}
157
750251b2 Andy McCall ↶ 158
// ---------------------------------------------------------------- http
159
2b5ee371 Andy McCall ↶ 160
/// How to reach a remote: credentials and trust.
161
#[derive(Clone, Debug, Default)]
162
pub struct RemoteOptions {
163
    /// Bearer token for pushes.
164
    pub token: Option<String>,
165
    /// PEM file with extra root certificates to trust for `https://` remotes
166
    /// (self-hosted servers); the system web roots are always trusted.
167
    pub ca: Option<PathBuf>,
168
}
169
750251b2 Andy McCall ↶ 170
/// A remote served by `oxy-server` at `<base>/oxy/v1/...`.
171
pub struct HttpRemote {
172
    base: String,
173
    token: Option<String>,
174
    agent: ureq::Agent,
175
}
176
2b5ee371 Andy McCall ↶ 177
/// A TLS client configuration trusting the web roots plus `ca`, if given.
178
fn tls_client_config(ca: Option<&Path>) -> Result<Arc<rustls::ClientConfig>> {
179
    let mut roots = rustls::RootCertStore::empty();
180
    roots.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
181
    if let Some(path) = ca {
182
        let pem = std::fs::read(path).map_err(|e| RepoError::Msg(format!("reading CA file {}: {e}", path.display())))?;
183
        let certs = rustls_pemfile::certs(&mut pem.as_slice())
184
            .collect::<std::result::Result<Vec<_>, _>>()
185
            .map_err(|e| RepoError::Msg(format!("parsing CA file {}: {e}", path.display())))?;
186
        if certs.is_empty() {
187
            return Err(RepoError::Msg(format!("CA file {} holds no certificates", path.display())));
188
        }
189
        for c in certs {
190
            roots.add(c).map_err(|e| RepoError::Msg(format!("CA file {}: {e}", path.display())))?;
191
        }
192
    }
193
    let cfg = rustls::ClientConfig::builder_with_provider(Arc::new(rustls::crypto::ring::default_provider()))
194
        .with_safe_default_protocol_versions()
195
        .map_err(|e| RepoError::Msg(e.to_string()))?
196
        .with_root_certificates(roots)
197
        .with_no_client_auth();
198
    Ok(Arc::new(cfg))
199
}
200
750251b2 Andy McCall ↶ 201
impl HttpRemote {
2b5ee371 Andy McCall ↶ 202
    pub fn new(base: &str, options: &RemoteOptions) -> Result<HttpRemote> {
203
        let agent = ureq::AgentBuilder::new().tls_config(tls_client_config(options.ca.as_deref())?).build();
204
        Ok(HttpRemote { base: base.trim_end_matches('/').to_string(), token: options.token.clone(), agent })
750251b2 Andy McCall ↶ 205
    }
206
207
    fn call(&self, post: bool, endpoint: &str, body: Option<&[u8]>) -> Result<Vec<u8>> {
208
        let url = format!("{}/oxy/v1/{endpoint}", self.base);
209
        let mut req = if post { self.agent.post(&url) } else { self.agent.get(&url) };
210
        req = req.set("Accept", CONTENT_TYPE);
211
        if let Some(t) = &self.token {
212
            req = req.set("Authorization", &format!("Bearer {t}"));
213
        }
214
        let resp = match body {
215
            Some(b) => req.set("Content-Type", CONTENT_TYPE).send_bytes(b),
216
            None => req.call(),
217
        };
218
        match resp {
219
            Ok(r) => {
220
                let mut out = Vec::new();
221
                r.into_reader().read_to_end(&mut out).map_err(|e| RepoError::Msg(format!("{url}: {e}")))?;
222
                Ok(out)
223
            }
224
            Err(ureq::Error::Status(code, r)) => {
225
                let text = r.into_string().unwrap_or_default();
226
                Err(RepoError::Msg(format!("{url}: HTTP {code}: {}", text.trim())))
227
            }
228
            Err(e) => Err(RepoError::Msg(format!("{url}: {e}"))),
229
        }
230
    }
231
}
232
233
impl Remote for HttpRemote {
234
    fn repo_id(&self) -> Result<[u8; 16]> {
235
        wire::decode_capabilities(&self.call(false, "capabilities", None)?)
236
    }
83e0677b Andy McCall ↶ 237
    fn refs(&self) -> Result<RefsResponse> {
750251b2 Andy McCall ↶ 238
        Ok(wire::decode_refs(&self.call(false, "refs", None)?)?.1)
239
    }
240
    fn negotiate(&self, have: &[ChangeHash], want: &[ChangeHash]) -> Result<Vec<ChangeHash>> {
241
        wire::decode_hashes(&self.call(true, "negotiate", Some(&wire::encode_negotiate(have, want)))?)
242
    }
b3c5a59a Andy McCall ↶ 243
    fn fetch(&self, changes: &[ChangeHash], max_blob: Option<u64>) -> Result<Bundle> {
244
        wire::decode_bundle(&self.call(true, "fetch", Some(&wire::encode_fetch(changes, max_blob)))?)
750251b2 Andy McCall ↶ 245
    }
b3c5a59a Andy McCall ↶ 246
    fn objects(&self, refs: &[ObjectRef]) -> Result<Vec<(ObjectType, Vec<u8>)>> {
247
        Ok(wire::decode_bundle(&self.call(true, "objects", Some(&wire::encode_hashes(refs)))?)?.objects)
248
    }
2863456a Andy McCall ↶ 249
    fn checkpoint(&self, heads: &[ChangeHash]) -> Result<Bundle> {
250
        wire::decode_bundle(&self.call(true, "checkpoint", Some(&wire::encode_hashes(heads)))?)
251
    }
252
    fn shallow(&self, heads: &[ChangeHash], depth: u32) -> Result<Vec<ChangeHash>> {
253
        wire::decode_hashes(&self.call(true, "shallow", Some(&wire::encode_shallow(heads, depth)))?)
254
    }
132b884b Andy McCall ↶ 255
    fn push(&self, bundle: Bundle, updates: Vec<RefUpdate>, policy: Option<SignedPolicy>, tags: Vec<TagRef>) -> Result<Vec<RefResult>> {
256
        wire::decode_push_response(&self.call(true, "push", Some(&wire::encode_push(&bundle, &updates, policy.as_ref(), &tags)))?)
750251b2 Andy McCall ↶ 257
    }
258
}
259
260
/// Open a remote by URL: a local path (optionally `file://`), or `http(s)://`.
2b5ee371 Andy McCall ↶ 261
pub fn open_remote(url: &str, options: &RemoteOptions) -> Result<Box<dyn Remote>> {
750251b2 Andy McCall ↶ 262
    if url.starts_with("http://") || url.starts_with("https://") {
2b5ee371 Andy McCall ↶ 263
        return Ok(Box::new(HttpRemote::new(url, options)?));
750251b2 Andy McCall ↶ 264
    }
5b9c6ad4 Andy McCall ↶ 265
    let path = url.strip_prefix("file://").unwrap_or(url);
266
    if path.contains("://") {
750251b2 Andy McCall ↶ 267
        return Err(RepoError::Msg(format!("unsupported remote URL {url:?}")));
5b9c6ad4 Andy McCall ↶ 268
    }
269
    Ok(Box::new(LocalRemote::open(Path::new(path))?))
270
}
750251b2 Andy McCall ↶ 271
272
// ---------------------------------------------------------------- wire
273
274
/// CBOR encodings of the protocol messages (spec §16.1).
275
pub mod wire {
276
    use super::*;
277
278
    fn schema(msg: &str) -> RepoError {
279
        RepoError::Object(ObjectError::Schema(msg.into()))
280
    }
281
    fn sigs_value(sigs: &[Signature]) -> Value {
282
        Value::Array(sigs.iter().map(|s| s.to_value()).collect())
283
    }
284
    fn sigs_from(v: &Value) -> Result<Vec<Signature>> {
285
        Ok(o::array(v, "signatures")?.iter().map(Signature::from_value).collect::<std::result::Result<Vec<_>, _>>()?)
286
    }
287
    fn hashes_value(hs: &[ObjectRef]) -> Value {
288
        Value::Array(hs.iter().map(|h| Value::Bytes(h.0.to_vec())).collect())
289
    }
290
    fn hashes_from(v: &Value) -> Result<Vec<ObjectRef>> {
291
        Ok(o::array(v, "hashes")?.iter().map(|h| o::oref(h, "hash")).collect::<std::result::Result<Vec<_>, _>>()?)
292
    }
293
    fn attest_value(sa: &SignedAttest) -> Value {
294
        Value::Array(vec![Value::Bytes(sa.attest.encode()), sigs_value(&sa.sigs)])
295
    }
296
    fn attest_from(v: &Value) -> Result<SignedAttest> {
297
        let a = o::array(v, "signed attest")?;
298
        if a.len() != 2 {
299
            return Err(schema("signed attest: expected [attest, sigs]"));
300
        }
301
        Ok(SignedAttest { attest: Attest::decode(o::bytes(&a[0], "attest")?)?, sigs: sigs_from(&a[1])? })
302
    }
303
    fn opt_attest_value(sa: &Option<SignedAttest>) -> Value {
304
        sa.as_ref().map(attest_value).unwrap_or(Value::Null)
305
    }
306
    fn opt_attest_from(v: &Value) -> Result<Option<SignedAttest>> {
307
        if v.is_null() { Ok(None) } else { attest_from(v).map(Some) }
308
    }
83e0677b Andy McCall ↶ 309
    fn opt_policy_value(sp: Option<&SignedPolicy>) -> Value {
310
        match sp {
311
            Some(sp) => Value::Array(vec![Value::Bytes(sp.policy.encode()), sigs_value(&sp.sigs)]),
312
            None => Value::Null,
313
        }
314
    }
315
    fn opt_policy_from(v: &Value) -> Result<Option<SignedPolicy>> {
316
        if v.is_null() {
317
            return Ok(None);
318
        }
319
        let a = o::array(v, "signed policy")?;
320
        if a.len() != 2 {
321
            return Err(schema("signed policy: expected [policy, sigs]"));
322
        }
323
        Ok(Some(SignedPolicy { policy: Policy::decode(o::bytes(&a[0], "policy")?)?, sigs: sigs_from(&a[1])? }))
324
    }
750251b2 Andy McCall ↶ 325
    fn map<'a>(v: &'a Value, what: &str) -> Result<&'a o::Map> {
326
        Ok(o::map(v, what)?)
327
    }
328
    fn field<'a>(m: &'a o::Map, k: u64, what: &str) -> Result<&'a Value> {
329
        Ok(o::field(m, k, what)?)
330
    }
331
332
    pub fn bundle_value(b: &Bundle) -> Value {
333
        Value::map([
334
            (
335
                0,
336
                Value::Array(b.changes.iter().map(|(c, s)| Value::Array(vec![Value::Bytes(c.encode()), sigs_value(s)])).collect()),
337
            ),
338
            (1, Value::Array(b.attests.iter().map(attest_value).collect())),
339
            (
340
                2,
341
                Value::Array(
342
                    b.objects.iter().map(|(t, body)| Value::Array(vec![Value::Text(t.name().into()), Value::Bytes(body.clone())])).collect(),
343
                ),
344
            ),
345
        ])
346
    }
347
348
    pub fn bundle_from_value(v: &Value) -> Result<Bundle> {
349
        let m = map(v, "bundle")?;
350
        let mut b = Bundle::default();
351
        for c in o::array(field(m, 0, "changes")?, "changes")? {
352
            let pair = o::array(c, "change entry")?;
353
            if pair.len() != 2 {
354
                return Err(schema("change entry: expected [change, sigs]"));
355
            }
356
            b.changes.push((Change::decode(o::bytes(&pair[0], "change")?)?, sigs_from(&pair[1])?));
357
        }
358
        for a in o::array(field(m, 1, "attests")?, "attests")? {
359
            b.attests.push(attest_from(a)?);
360
        }
361
        for ob in o::array(field(m, 2, "objects")?, "objects")? {
362
            let pair = o::array(ob, "object")?;
363
            if pair.len() != 2 {
364
                return Err(schema("object: expected [type, body]"));
365
            }
366
            let ty = ObjectType::from_name(o::text(&pair[0], "object type")?).ok_or_else(|| schema("unknown object type"))?;
367
            b.objects.push((ty, o::bytes(&pair[1], "object body")?.to_vec()));
368
        }
369
        Ok(b)
370
    }
371
372
    pub fn encode_bundle(b: &Bundle) -> Vec<u8> {
373
        cbor::encode(&bundle_value(b))
374
    }
375
    pub fn decode_bundle(bytes: &[u8]) -> Result<Bundle> {
376
        bundle_from_value(&cbor::decode(bytes).map_err(ObjectError::from)?)
377
    }
378
379
    pub fn encode_capabilities(id: [u8; 16]) -> Vec<u8> {
380
        cbor::encode(&Value::map([
381
            (0, Value::Array(vec![Value::Uint(PROTOCOL_VERSION)])),
382
            (1, Value::Bytes(id.to_vec())),
383
            (2, Value::Array(vec![Value::Text("seal".into())])),
384
        ]))
385
    }
386
    pub fn decode_capabilities(bytes: &[u8]) -> Result<[u8; 16]> {
387
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
388
        let m = map(&v, "capabilities")?;
389
        let versions = o::array(field(m, 0, "versions")?, "versions")?;
390
        if !versions.iter().any(|x| x.as_uint() == Some(PROTOCOL_VERSION)) {
391
            return Err(RepoError::Msg("remote does not speak protocol version 1".into()));
392
        }
393
        o::bytes(field(m, 1, "repo id")?, "repo id")?.try_into().map_err(|_| schema("repo id: expected 16 bytes"))
394
    }
395
132b884b Andy McCall ↶ 396
    fn tags_value(tags: &[TagRef]) -> Value {
397
        Value::Array(
398
            tags.iter()
399
                .map(|t| {
400
                    Value::map([
401
                        (0, Value::Text(t.name.clone())),
402
                        (1, Value::Bytes(t.state.0.to_vec())),
403
                        (2, hashes_value(&t.heads)),
404
                        (3, opt_attest_value(&t.attestation)),
405
                    ])
406
                })
407
                .collect(),
408
        )
409
    }
410
    fn tags_from(v: &Value) -> Result<Vec<TagRef>> {
411
        let mut out = Vec::new();
412
        for t in o::array(v, "tags")? {
413
            let tm = map(t, "tag")?;
414
            out.push(TagRef {
415
                name: o::text(field(tm, 0, "name")?, "name")?.to_owned(),
416
                state: o::oref(field(tm, 1, "state")?, "state")?,
417
                heads: hashes_from(field(tm, 2, "heads")?)?,
418
                attestation: opt_attest_from(field(tm, 3, "attestation")?)?,
419
            });
420
        }
421
        Ok(out)
422
    }
423
83e0677b Andy McCall ↶ 424
    pub fn encode_refs(id: [u8; 16], resp: &RefsResponse) -> Vec<u8> {
750251b2 Andy McCall ↶ 425
        cbor::encode(&Value::map([
426
            (
427
                0,
428
                Value::Array(
83e0677b Andy McCall ↶ 429
                    resp.refs
430
                        .iter()
750251b2 Andy McCall ↶ 431
                        .map(|r| {
432
                            Value::map([
433
                                (0, Value::Text(r.name.clone())),
434
                                (1, Value::Bytes(r.state.0.to_vec())),
435
                                (2, hashes_value(&r.heads)),
436
                                (3, opt_attest_value(&r.attestation)),
437
                                (4, r.last_serial.map(Value::Uint).unwrap_or(Value::Null)),
438
                            ])
439
                        })
440
                        .collect(),
441
                ),
442
            ),
443
            (1, Value::Bytes(id.to_vec())),
83e0677b Andy McCall ↶ 444
            (2, opt_policy_value(resp.policy.as_ref())),
132b884b Andy McCall ↶ 445
            (3, tags_value(&resp.tags)),
750251b2 Andy McCall ↶ 446
        ]))
447
    }
83e0677b Andy McCall ↶ 448
    pub fn decode_refs(bytes: &[u8]) -> Result<([u8; 16], RefsResponse)> {
750251b2 Andy McCall ↶ 449
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
450
        let m = map(&v, "refs")?;
451
        let id: [u8; 16] = o::bytes(field(m, 1, "repo id")?, "repo id")?.try_into().map_err(|_| schema("repo id: expected 16 bytes"))?;
452
        let mut refs = Vec::new();
453
        for r in o::array(field(m, 0, "refs")?, "refs")? {
454
            let rm = map(r, "ref")?;
455
            let ls = field(rm, 4, "last serial")?;
456
            refs.push(RemoteRef {
457
                name: o::text(field(rm, 0, "name")?, "name")?.to_owned(),
458
                state: o::oref(field(rm, 1, "state")?, "state")?,
459
                heads: hashes_from(field(rm, 2, "heads")?)?,
460
                attestation: opt_attest_from(field(rm, 3, "attestation")?)?,
461
                last_serial: if ls.is_null() { None } else { Some(o::uint(ls, "last serial")?) },
462
            });
463
        }
83e0677b Andy McCall ↶ 464
        let policy = match m.get(&2) {
465
            Some(p) => opt_policy_from(p)?,
466
            None => None,
467
        };
132b884b Andy McCall ↶ 468
        let tags = match m.get(&3) {
469
            Some(t) => tags_from(t)?,
470
            None => Vec::new(),
471
        };
472
        Ok((id, RefsResponse { refs, policy, tags }))
750251b2 Andy McCall ↶ 473
    }
474
475
    pub fn encode_negotiate(have: &[ChangeHash], want: &[ChangeHash]) -> Vec<u8> {
476
        cbor::encode(&Value::map([(0, hashes_value(have)), (1, hashes_value(want))]))
477
    }
478
    pub fn decode_negotiate(bytes: &[u8]) -> Result<(Vec<ChangeHash>, Vec<ChangeHash>)> {
479
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
480
        let m = map(&v, "negotiate")?;
481
        Ok((hashes_from(field(m, 0, "have")?)?, hashes_from(field(m, 1, "want")?)?))
482
    }
483
b3c5a59a Andy McCall ↶ 484
    /// `fetch` request: `{0: [changes], 1: max blob size or null}`.
485
    pub fn encode_fetch(hs: &[ChangeHash], max_blob: Option<u64>) -> Vec<u8> {
486
        cbor::encode(&Value::map([(0, hashes_value(hs)), (1, max_blob.map(Value::Uint).unwrap_or(Value::Null))]))
487
    }
488
    pub fn decode_fetch(bytes: &[u8]) -> Result<(Vec<ChangeHash>, Option<u64>)> {
489
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
490
        let m = map(&v, "fetch")?;
491
        let max = match m.get(&1) {
492
            Some(x) if !x.is_null() => Some(o::uint(x, "max blob")?),
493
            _ => None,
494
        };
495
        Ok((hashes_from(field(m, 0, "changes")?)?, max))
496
    }
497
2863456a Andy McCall ↶ 498
    /// `shallow` request: `{0: [heads], 1: depth}`.
499
    pub fn encode_shallow(hs: &[ChangeHash], depth: u32) -> Vec<u8> {
500
        cbor::encode(&Value::map([(0, hashes_value(hs)), (1, Value::Uint(depth as u64))]))
501
    }
502
    pub fn decode_shallow(bytes: &[u8]) -> Result<(Vec<ChangeHash>, u32)> {
503
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
504
        let m = map(&v, "shallow")?;
505
        Ok((hashes_from(field(m, 0, "heads")?)?, o::u32_(field(m, 1, "depth")?, "depth")?))
506
    }
507
750251b2 Andy McCall ↶ 508
    pub fn encode_hashes(hs: &[ChangeHash]) -> Vec<u8> {
509
        cbor::encode(&Value::map([(0, hashes_value(hs))]))
510
    }
511
    pub fn decode_hashes(bytes: &[u8]) -> Result<Vec<ChangeHash>> {
512
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
513
        hashes_from(field(map(&v, "hashes")?, 0, "hashes")?)
514
    }
515
132b884b Andy McCall ↶ 516
    pub fn encode_push(bundle: &Bundle, updates: &[RefUpdate], policy: Option<&SignedPolicy>, tags: &[TagRef]) -> Vec<u8> {
750251b2 Andy McCall ↶ 517
        cbor::encode(&Value::map([
518
            (0, bundle_value(bundle)),
83e0677b Andy McCall ↶ 519
            (2, opt_policy_value(policy)),
132b884b Andy McCall ↶ 520
            (3, tags_value(tags)),
750251b2 Andy McCall ↶ 521
            (
522
                1,
523
                Value::Array(
524
                    updates
525
                        .iter()
526
                        .map(|u| {
527
                            Value::map([
528
                                (0, Value::Text(u.name.clone())),
529
                                (1, Value::Bytes(u.old_state.0.to_vec())),
530
                                (2, Value::Bytes(u.new_state.0.to_vec())),
531
                                (3, Value::Bool(u.force)),
532
                                (4, opt_attest_value(&u.attestation)),
533
                            ])
534
                        })
535
                        .collect(),
536
                ),
537
            ),
538
        ]))
539
    }
132b884b Andy McCall ↶ 540
    /// A decoded push: bundle, bookmark updates, policy, tags.
541
    pub type PushParts = (Bundle, Vec<RefUpdate>, Option<SignedPolicy>, Vec<TagRef>);
542
543
    pub fn decode_push(bytes: &[u8]) -> Result<PushParts> {
750251b2 Andy McCall ↶ 544
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
545
        let m = map(&v, "push")?;
546
        let bundle = bundle_from_value(field(m, 0, "bundle")?)?;
547
        let mut updates = Vec::new();
548
        for u in o::array(field(m, 1, "updates")?, "updates")? {
549
            let um = map(u, "update")?;
550
            updates.push(RefUpdate {
551
                name: o::text(field(um, 0, "name")?, "name")?.to_owned(),
552
                old_state: o::oref(field(um, 1, "old_state")?, "old_state")?,
553
                new_state: o::oref(field(um, 2, "new_state")?, "new_state")?,
554
                force: field(um, 3, "force")?.as_bool().ok_or_else(|| schema("force: expected bool"))?,
555
                attestation: opt_attest_from(field(um, 4, "attestation")?)?,
556
            });
557
        }
83e0677b Andy McCall ↶ 558
        let policy = match m.get(&2) {
559
            Some(p) => opt_policy_from(p)?,
560
            None => None,
561
        };
132b884b Andy McCall ↶ 562
        let tags = match m.get(&3) {
563
            Some(t) => tags_from(t)?,
564
            None => Vec::new(),
565
        };
566
        Ok((bundle, updates, policy, tags))
750251b2 Andy McCall ↶ 567
    }
568
569
    pub fn encode_push_response(results: &[RefResult]) -> Vec<u8> {
570
        cbor::encode(&Value::map([(
571
            0,
572
            Value::Array(
573
                results
574
                    .iter()
575
                    .map(|r| Value::map([(0, Value::Text(r.name.clone())), (1, Value::Bool(r.ok)), (2, Value::Text(r.reason.clone()))]))
576
                    .collect(),
577
            ),
578
        )]))
579
    }
580
    pub fn decode_push_response(bytes: &[u8]) -> Result<Vec<RefResult>> {
581
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
582
        let m = map(&v, "push response")?;
583
        let mut out = Vec::new();
584
        for r in o::array(field(m, 0, "results")?, "results")? {
585
            let rm = map(r, "result")?;
586
            out.push(RefResult {
587
                name: o::text(field(rm, 0, "name")?, "name")?.to_owned(),
588
                ok: field(rm, 1, "ok")?.as_bool().ok_or_else(|| schema("ok: expected bool"))?,
589
                reason: o::text(field(rm, 2, "reason")?, "reason")?.to_owned(),
590
            });
591
        }
592
        Ok(out)
593
    }
594
}
595
596
#[cfg(test)]
597
mod tests {
598
    use super::*;
599
    use crate::attest::AttestBody;
600
    use crate::objects::Hlc;
601
602
    #[test]
603
    fn wire_round_trips() {
604
        let c = crate::objects::tests::sample_change();
605
        let sk = crate::identity::SecretKey { ed_seed: [1; 32], ml_seed: [2; 32] };
606
        let id = sk.identity("a", "b", 0);
607
        let key = id.hash();
608
        let sig = sk.sign(crate::identity::Domain::Change, &key, &c.hash());
609
        let seal = Attest::seal([3; 16], vec![c.hash()]);
610
        let seal_sig = sk.sign(crate::identity::Domain::Attest, &key, &seal.hash());
611
        let bundle = Bundle {
612
            changes: vec![(c.clone(), vec![sig.clone()])],
613
            attests: vec![SignedAttest { attest: seal.clone(), sigs: vec![seal_sig] }],
614
            objects: vec![(ObjectType::Identity, id.encode()), (ObjectType::Chunk, b"xyz".to_vec())],
615
        };
616
        let d = wire::decode_bundle(&wire::encode_bundle(&bundle)).unwrap();
617
        assert_eq!(d.changes, bundle.changes);
618
        assert_eq!(d.attests, bundle.attests);
619
        assert_eq!(d.objects, bundle.objects);
620
621
        let att = Attest { repo: [3; 16], hlc: Hlc::default(), body: AttestBody::Ref { name: "main".into(), old_state: ObjectRef([1; 32]), new_state: ObjectRef([2; 32]), serial: 4 } };
622
        let refs = vec![
623
            RemoteRef { name: "main".into(), state: ObjectRef([2; 32]), heads: vec![c.hash()], attestation: Some(SignedAttest { attest: att.clone(), sigs: vec![sig.clone()] }), last_serial: Some(4) },
624
            RemoteRef { name: "dev".into(), state: ObjectRef([5; 32]), heads: vec![], attestation: None, last_serial: None },
625
        ];
83e0677b Andy McCall ↶ 626
        let policy = Policy::single_root([3; 16], id.clone(), 99);
627
        let psig = sk.sign(crate::identity::Domain::Policy, &key, &policy.hash());
132b884b Andy McCall ↶ 628
        let tag = TagRef { name: "v1".into(), state: ObjectRef([2; 32]), heads: vec![c.hash()], attestation: None };
629
        let resp = RefsResponse { refs, policy: Some(SignedPolicy { policy: policy.clone(), sigs: vec![psig.clone()] }), tags: vec![tag.clone()] };
83e0677b Andy McCall ↶ 630
        let (id_back, back) = wire::decode_refs(&wire::encode_refs([3; 16], &resp)).unwrap();
750251b2 Andy McCall ↶ 631
        assert_eq!(id_back, [3; 16]);
83e0677b Andy McCall ↶ 632
        assert_eq!(back.refs.len(), 2);
633
        assert_eq!(back.refs[0].attestation.as_ref().unwrap().attest, att);
634
        assert_eq!(back.refs[1].last_serial, None);
635
        assert_eq!(back.policy.as_ref().unwrap().policy, policy);
132b884b Andy McCall ↶ 636
        assert_eq!(back.tags, vec![tag.clone()]);
750251b2 Andy McCall ↶ 637
638
        let (h, w) = wire::decode_negotiate(&wire::encode_negotiate(&[ObjectRef([1; 32])], &[ObjectRef([2; 32])])).unwrap();
639
        assert_eq!((h, w), (vec![ObjectRef([1; 32])], vec![ObjectRef([2; 32])]));
640
        assert_eq!(wire::decode_hashes(&wire::encode_hashes(&[c.hash()])).unwrap(), vec![c.hash()]);
b3c5a59a Andy McCall ↶ 641
        assert_eq!(wire::decode_fetch(&wire::encode_fetch(&[c.hash()], Some(4096))).unwrap(), (vec![c.hash()], Some(4096)));
642
        assert_eq!(wire::decode_fetch(&wire::encode_fetch(&[], None)).unwrap(), (vec![], None));
2863456a Andy McCall ↶ 643
        assert_eq!(wire::decode_shallow(&wire::encode_shallow(&[c.hash()], 3)).unwrap(), (vec![c.hash()], 3));
b3c5a59a Andy McCall ↶ 644
        // An old-style fetch request without the filter field still decodes.
645
        assert_eq!(wire::decode_fetch(&wire::encode_hashes(&[c.hash()])).unwrap(), (vec![c.hash()], None));
750251b2 Andy McCall ↶ 646
647
        let up = RefUpdate { name: "main".into(), old_state: ObjectRef([1; 32]), new_state: ObjectRef([2; 32]), force: true, attestation: Some(SignedAttest { attest: att, sigs: vec![sig] }) };
83e0677b Andy McCall ↶ 648
        let sp = SignedPolicy { policy, sigs: vec![psig] };
132b884b Andy McCall ↶ 649
        let (b2, ups, pol, tags) = wire::decode_push(&wire::encode_push(&bundle, std::slice::from_ref(&up), Some(&sp), std::slice::from_ref(&tag))).unwrap();
83e0677b Andy McCall ↶ 650
        assert_eq!(pol, Some(sp));
132b884b Andy McCall ↶ 651
        assert_eq!(tags, vec![tag]);
750251b2 Andy McCall ↶ 652
        assert_eq!(b2.changes.len(), 1);
653
        assert_eq!(ups[0].name, "main");
654
        assert!(ups[0].force);
655
        assert_eq!(ups[0].attestation, up.attestation);
656
        let res = vec![RefResult { name: "main".into(), ok: false, reason: "stale".into() }];
657
        assert_eq!(wire::decode_push_response(&wire::encode_push_response(&res)).unwrap(), res);
658
        assert_eq!(wire::decode_capabilities(&wire::encode_capabilities([7; 16])).unwrap(), [7; 16]);
659
    }
660
}