OXYGENHUB

Coverage / crates/oxy-core/src/protocol.rs 85.5%

1012 of 1183 lines run, 156 of 244 functions · run #363 on main · run missed

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, Mutex};
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`).
381×
    pub fn encode(&self) -> Vec<u8> {
391×
        crate::cbor::encode(&wire::policy_value(self))
401×
    }
411×
    pub fn decode(b: &[u8]) -> Result<SignedPolicy> {
421×
        wire::policy_from(
431×
            &crate::cbor::decode(b).map_err(|e| RepoError::Object(ObjectError::from(e)))?,
44
        )
451×
    }
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
    /// The bookmark a clone checks out (spec §16.1), when the remote names one.
58
    pub default_bookmark: Option<String>,
59
    /// The host's latest transparency-log checkpoint, a signed note (spec
60
    /// §14.8), against which `RemoteRef::logged` proofs are made (key 6,
61
    /// only when the host keeps a log).
62
    pub log: Option<String>,
63
    /// The witnesses the host asks to cosign its checkpoints: each one's
64
    /// name in cosignatures and its identity's bytes (key 7, only when it
65
    /// has any), which a client pins (spec §14.8, *Integrated time*).
66
    pub witnesses: Vec<(String, Vec<u8>)>,
67
}
68
69
/// Where a reference attestation sits in the host's transparency log
70
/// (spec §14.8): its entry number, the entry, and the inclusion proof
71
/// against the checkpoint served beside it.
72
#[derive(Clone, Debug, PartialEq, Eq)]
73
pub struct Logged {
74
    pub index: u64,
75
    pub entry: Vec<u8>,
76
    pub proof: Vec<[u8; 32]>,
77
}
78
79
/// A checkpoint witnesses cosigned that includes a logged entry (spec
80
/// §14.8, *Integrated time*): the cosigned note, and the entry's inclusion
81
/// proof against it.
82
#[derive(Clone, Debug, PartialEq, Eq)]
83
pub struct Integration {
84
    pub note: String,
85
    pub proof: Vec<[u8; 32]>,
86
}
87
88
/// A tag as a remote reports it (spec §10.1).
89
#[derive(Clone, Debug, PartialEq, Eq)]
90
pub struct TagRef {
91
    pub name: String,
92
    pub state: ObjectRef,
93
    pub heads: Vec<ChangeHash>,
94
    pub attestation: Option<SignedAttest>,
95
    /// The acceptance of `attestation` by its signer's certificate issuer
96
    /// when a short-lived key signed it (spec §14.7; key 4, only when there
97
    /// is one): the time a fetch checks the certificate at.
98
    pub accepted: Option<SignedAttest>,
99
    /// The attestation's place in the host's transparency log (key 5,
100
    /// only when it has one), as a bookmark's.
101
    pub logged: Option<Logged>,
102
    /// The cosigned checkpoints that first included `logged`'s entry (key
103
    /// 6, only when there are any).
104
    pub integration: Vec<Integration>,
105
}
106
107
impl TagRef {
108
    /// A tag with no acceptance or log place (yet).
10989×
    pub fn new(
11089×
        name: String,
11189×
        state: ObjectRef,
11289×
        heads: Vec<ChangeHash>,
11389×
        attestation: Option<SignedAttest>,
11489×
    ) -> TagRef {
11589×
        TagRef {
11689×
            name,
11789×
            state,
11889×
            heads,
11989×
            attestation,
12089×
            accepted: None,
12189×
            logged: None,
12289×
            integration: vec![],
12389×
        }
12489×
    }
125
}
126
127
/// One reference as a remote reports it.
128
#[derive(Clone, Debug)]
129
pub struct RemoteRef {
130
    pub name: String,
131
    pub state: ObjectRef,
132
    pub heads: Vec<ChangeHash>,
133
    /// The latest attestation, only when it describes `state`. An unattested
134
    /// push (accepted while no trust policy exists) leaves it `None`.
135
    pub attestation: Option<SignedAttest>,
136
    /// Serial of the latest attestation ever recorded, stale or not, so the
137
    /// next attestation continues the sequence.
138
    pub last_serial: Option<u64>,
139
    /// The host's acceptance of `attestation` when a short-lived key signed
140
    /// it (spec §14.7): the time its certificate is checked at.
141
    pub accepted: Option<SignedAttest>,
142
    /// The attestation's place in the host's transparency log (key 6, only
143
    /// when it has one).
144
    pub logged: Option<Logged>,
145
    /// The cosigned checkpoints that first included `logged`'s entry (key
146
    /// 7, only when there are any): what its integrated time is read from.
147
    pub integration: Vec<Integration>,
148
}
149
150
/// Everything needed to add a set of changes to a repository.
151
#[derive(Clone, Debug, Default)]
152
pub struct Bundle {
153
    /// In dependency order, each with its individual signatures.
154
    pub changes: Vec<(Change, Vec<Signature>)>,
155
    /// Seals covering the changes.
156
    pub attests: Vec<SignedAttest>,
157
    /// Chunks, blobs, identities, and state objects referenced by the changes.
158
    pub objects: Vec<(ObjectType, Vec<u8>)>,
159
    /// Policies between the receiver's and the one sent with the push,
160
    /// ascending by serial (spec §14.5).
161
    pub policies: Vec<SignedPolicy>,
162
    /// Each change's hash, in the order of `changes`, when whoever made
163
    /// the bundle knows it: the store it came from, or the bytes it was
164
    /// decoded from. Never read from the wire. Empty when unknown.
165
    pub hashes: Vec<ChangeHash>,
166
    /// Changes as stored, with their signatures, in dependency order, for a
167
    /// fetch between repositories on one machine: their text blobs and
168
    /// chunks are among `objects`. Never on the wire.
169
    pub raw_changes: Vec<(Vec<u8>, Vec<Signature>)>,
170
    /// Certificates of short-lived keys that signed what the bundle carries
171
    /// (spec §14.7), their issuers' identities among `objects`.
172
    pub certificates: Vec<crate::cert::SignedCertificate>,
173
}
174
175
impl Bundle {
17627×
    pub fn is_empty(&self) -> bool {
17727×
        self.changes.is_empty() && self.attests.is_empty() && self.objects.is_empty()
17827×
    }
179
}
180
181
/// A requested bookmark move (spec §10.2, §16.3).
182
#[derive(Clone, Debug)]
183
pub struct RefUpdate {
184
    pub name: String,
185
    pub old_state: ObjectRef,
186
    pub new_state: ObjectRef,
187
    pub force: bool,
188
    pub attestation: Option<SignedAttest>,
189
}
190
191
#[derive(Clone, Debug, PartialEq, Eq)]
192
pub struct RefResult {
193
    pub name: String,
194
    pub ok: bool,
195
    pub reason: String,
196
}
197
198
pub trait Remote {
199
    fn repo_id(&self) -> Result<[u8; 16]>;
200
    fn refs(&self) -> Result<RefsResponse>;
201
    /// Changes in the closure of `want` but not of `have`, in dependency order.
202
    fn negotiate(&self, have: &[ChangeHash], want: &[ChangeHash]) -> Result<Vec<ChangeHash>>;
203
    /// The changes with their signatures, seals, identities, and blobs; blobs
204
    /// larger than `max_blob` bytes are left out for lazy fetching (spec §13.5).
205
    fn fetch(&self, changes: &[ChangeHash], max_blob: Option<u64>) -> Result<Bundle>;
206
    /// Individual objects by reference (spec §16.1 `objects`); a blob comes
207
    /// with its chunks.
208
    fn objects(&self, refs: &[ObjectRef]) -> Result<Vec<(ObjectType, Vec<u8>)>>;
209
    /// A checkpoint of exactly `heads` (spec §16.1 `checkpoint`): the
210
    /// checkpoint object, its payload blob, and the blob's chunks.
211
    fn checkpoint(&self, heads: &[ChangeHash]) -> Result<Bundle>;
212
    /// The changes within `depth` dependency steps of `heads` (spec §17).
213
    fn shallow(&self, heads: &[ChangeHash], depth: u32) -> Result<Vec<ChangeHash>>;
214
    /// Push changes, bookmark updates, new tags, and optionally a newer
215
    /// policy. The policy is applied first; a result named `policy` reports
216
    /// it, and each tag reports as `tags/<name>`.
217
    fn push(
218
        &self,
219
        bundle: Bundle,
220
        updates: Vec<RefUpdate>,
221
        policy: Option<SignedPolicy>,
222
        tags: Vec<TagRef>,
223
    ) -> Result<Vec<RefResult>>;
224
}
225
226
// ---------------------------------------------------------------- local
227
228
/// Another repository on this machine, served in-process.
229
pub struct LocalRemote {
230
    pub repo: Repo,
231
    /// The pushing repository's id, which binds an unbound target on the
232
    /// first push, as `Oxy-Repo-Id` does over HTTP.
233
    pub claimed_id: Option<[u8; 16]>,
234
}
235
236
impl LocalRemote {
2371120×
    pub fn open(path: &Path) -> Result<LocalRemote> {
238
        Ok(LocalRemote {
2391120×
            repo: Repo::open(path)?,
2401120×
            claimed_id: None,
241
        })
2421120×
    }
243
}
244
245
impl Remote for LocalRemote {
246880×
    fn repo_id(&self) -> Result<[u8; 16]> {
247880×
        self.repo.id()
248880×
    }
249878×
    fn refs(&self) -> Result<RefsResponse> {
250878×
        self.repo.remote_refs()
251878×
    }
252349×
    fn negotiate(&self, have: &[ChangeHash], want: &[ChangeHash]) -> Result<Vec<ChangeHash>> {
253349×
        self.repo.negotiate(have, want)
254349×
    }
255353×
    fn fetch(&self, changes: &[ChangeHash], max_blob: Option<u64>) -> Result<Bundle> {
256353×
        self.repo.bundle_raw_for(changes, max_blob)
257353×
    }
2583×
    fn objects(&self, refs: &[ObjectRef]) -> Result<Vec<(ObjectType, Vec<u8>)>> {
2593×
        self.repo.objects_for(refs)
2603×
    }
2611×
    fn checkpoint(&self, heads: &[ChangeHash]) -> Result<Bundle> {
2621×
        self.repo.checkpoint_bundle_for(heads)
2631×
    }
2643×
    fn shallow(&self, heads: &[ChangeHash], depth: u32) -> Result<Vec<ChangeHash>> {
2653×
        self.repo.shallow_changes(heads, depth)
2663×
    }
267265×
    fn push(
268265×
        &self,
269265×
        bundle: Bundle,
270265×
        updates: Vec<RefUpdate>,
271265×
        policy: Option<SignedPolicy>,
272265×
        tags: Vec<TagRef>,
273265×
    ) -> Result<Vec<RefResult>> {
274265×
        if self.repo.is_unbound() {
27513×
            match self.claimed_id {
27613×
                Some(id) => self.repo.bind_id(id)?,
277
                None => {
2780×
                    return Err(RepoError::Msg(
2790×
                        "the remote is unbound and this client did not say which repository it is"
2800×
                            .into(),
2810×
                    ))
282
                }
283
            }
284252×
        }
285265×
        self.repo.receive_push(bundle, updates, policy, tags)
286265×
    }
287
}
288
289
// ---------------------------------------------------------------- http
290
291
/// How to reach a remote: credentials and trust.
292
#[derive(Clone, Debug, Default)]
293
pub struct RemoteOptions {
294
    /// Bearer token for pushes.
295
    pub token: Option<String>,
296
    /// PEM file with extra root certificates to trust for `https://` remotes
297
    /// (self-hosted servers); the system web roots are always trusted.
298
    pub ca: Option<PathBuf>,
299
    /// The local repository's id, sent as `Oxy-Repo-Id` so an unbound
300
    /// hosted repository can adopt it on the first push (spec §16.1).
301
    pub repo_id: Option<[u8; 16]>,
302
    /// Where a remote kept on a store (`dir://`, `s3://`, …) keeps its
303
    /// mirror and what it has seen: the remote's directory under
304
    /// `.oxy/remotes`. None (a clone, before there is a repository) means
305
    /// a temporary directory.
306
    pub cache_dir: Option<PathBuf>,
307
    /// Other tokens for the same hub, tried in turn when `token` is
308
    /// refused (401, 403 or 404): those of enclosing checkouts, when
309
    /// `token` came from the credential store rather than from this
310
    /// remote's own configuration (oxygen#112).
311
    pub fallback_tokens: Vec<String>,
312
}
313
314
/// Opens a store for a URL it understands, or passes (`None`). Stores that
315
/// need more than the standard library (the cloud ones) are added by the
316
/// program that links them, with [`register_store_opener`].
317
pub type StoreOpener =
318
    fn(&str, &RemoteOptions) -> Option<crate::strata::Result<Box<dyn crate::strata::Store>>>;
319
320
static STORE_OPENERS: Mutex<Vec<StoreOpener>> = Mutex::new(Vec::new());
321
322155×
pub fn register_store_opener(opener: StoreOpener) {
323155×
    STORE_OPENERS
324155×
        .lock()
325155×
        .unwrap_or_else(|p| p.into_inner())
326155×
        .push(opener);
327155×
}
328
329
/// A store for `url`, from `dir://` or any registered opener.
3301179×
pub fn open_store(
3311179×
    url: &str,
3321179×
    options: &RemoteOptions,
3331179×
) -> Option<crate::strata::Result<Box<dyn crate::strata::Store>>> {
3341179×
    if let Some(path) = url.strip_prefix("dir://") {
335
        return Some(
33659×
            crate::strata::LocalStore::open(path)
33759×
                .map(|s| Box::new(s) as Box<dyn crate::strata::Store>),
338
        );
3391120×
    }
3401120×
    let openers = STORE_OPENERS.lock().unwrap_or_else(|p| p.into_inner());
3411120×
    openers.iter().find_map(|open| open(url, options))
3421179×
}
343
344
/// The request header carrying the client's repository id.
345
pub const REPO_ID_HEADER: &str = "Oxy-Repo-Id";
346
347
/// The id of a hosted repository that has not adopted one yet.
348
pub const UNBOUND_ID: [u8; 16] = [0; 16];
349
350
/// A remote served by `oxy-server` at `<base>/oxy/v1/...`.
351
pub struct HttpRemote {
352
    base: String,
353
    /// The token in use, and those still to try when it is refused.
354
    token: Mutex<Option<String>>,
355
    fallbacks: Mutex<Vec<String>>,
356
    repo_id: Option<[u8; 16]>,
357
    agent: ureq::Agent,
358
}
359
360
/// A TLS client configuration trusting the web roots plus `ca`, if given:
361
/// the trust every oxy connection uses, shared with tools that call hub APIs.
362153×
pub fn tls_client_config(ca: Option<&Path>) -> Result<Arc<rustls::ClientConfig>> {
363153×
    let mut roots = rustls::RootCertStore::empty();
364153×
    roots.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
365153×
    if let Some(path) = ca {
36644×
        let pem = std::fs::read(path)
36744×
            .map_err(|e| RepoError::Msg(format!("reading CA file {}: {e}", path.display())))?;
36844×
        let certs = rustls_pemfile::certs(&mut pem.as_slice())
36944×
            .collect::<std::result::Result<Vec<_>, _>>()
37044×
            .map_err(|e| RepoError::Msg(format!("parsing CA file {}: {e}", path.display())))?;
37144×
        if certs.is_empty() {
3720×
            return Err(RepoError::Msg(format!(
3730×
                "CA file {} holds no certificates",
3740×
                path.display()
3750×
            )));
37644×
        }
37744×
        for c in certs {
37844×
            roots
37944×
                .add(c)
38044×
                .map_err(|e| RepoError::Msg(format!("CA file {}: {e}", path.display())))?;
381
        }
382109×
    }
383153×
    let cfg = rustls::ClientConfig::builder_with_provider(Arc::new(
384153×
        rustls::crypto::ring::default_provider(),
385
    ))
386153×
    .with_safe_default_protocol_versions()
387153×
    .map_err(|e| RepoError::Msg(e.to_string()))?
388153×
    .with_root_certificates(roots)
389153×
    .with_no_client_auth();
390153×
    Ok(Arc::new(cfg))
391153×
}
392
393
impl HttpRemote {
394149×
    pub fn new(base: &str, options: &RemoteOptions) -> Result<HttpRemote> {
395149×
        refuse_plain_token(base, options)?;
396149×
        let agent = ureq::AgentBuilder::new()
397149×
            .tls_config(tls_client_config(options.ca.as_deref())?)
398149×
            .build();
399149×
        Ok(HttpRemote {
400149×
            base: base.trim_end_matches('/').to_string(),
401149×
            token: Mutex::new(options.token.clone()),
402149×
            fallbacks: Mutex::new(options.fallback_tokens.iter().rev().cloned().collect()),
403149×
            repo_id: options.repo_id,
404149×
            agent,
405149×
        })
406149×
    }
407
408
    /// A request, tried again with the next fallback token while the
409
    /// hub refuses the one in use (oxygen#112).
410375×
    fn call(&self, post: bool, endpoint: &str, body: Option<&[u8]>) -> Result<Vec<u8>> {
411
        loop {
412376×
            let token = self.token.lock().unwrap_or_else(|p| p.into_inner()).clone();
413376×
            match self.call_once(post, endpoint, body, token.as_deref()) {
41412×
                Err(RepoError::Msg(m)) if token.is_some() && refused(&m) => {
4153×
                    let next = self
4163×
                        .fallbacks
4173×
                        .lock()
4183×
                        .unwrap_or_else(|p| p.into_inner())
4193×
                        .pop();
4203×
                    let Some(next) = next else {
4212×
                        return Err(RepoError::Msg(m));
422
                    };
4231×
                    crate::credentials::warn_once(&format!(
4241×
                        "{}: the stored token was refused; using the one an enclosing checkout has for this hub",
4251×
                        self.base
4261×
                    ));
4271×
                    *self.token.lock().unwrap_or_else(|p| p.into_inner()) = Some(next);
428
                }
429373×
                other => return other,
430
            }
431
        }
432375×
    }
433
434376×
    fn call_once(
435376×
        &self,
436376×
        post: bool,
437376×
        endpoint: &str,
438376×
        body: Option<&[u8]>,
439376×
        token: Option<&str>,
440376×
    ) -> Result<Vec<u8>> {
441376×
        let url = format!("{}/oxy/v1/{endpoint}", self.base);
442376×
        let mut req = if post {
443129×
            self.agent.post(&url)
444
        } else {
445247×
            self.agent.get(&url)
446
        };
447376×
        req = req.set("Accept", CONTENT_TYPE);
448376×
        if let Some(t) = token {
44922×
            req = req.set("Authorization", &format!("Bearer {t}"));
450354×
        }
451376×
        if let Some(id) = &self.repo_id {
452351×
            req = req.set(REPO_ID_HEADER, &hex::encode(id));
453351×
        }
454376×
        let resp = match body {
455129×
            Some(b) => req.set("Content-Type", CONTENT_TYPE).send_bytes(b),
456247×
            None => req.call(),
457
        };
45812×
        match resp {
459364×
            Ok(r) => {
460364×
                let mut out = Vec::new();
461364×
                r.into_reader()
462364×
                    .read_to_end(&mut out)
463364×
                    .map_err(|e| RepoError::Msg(format!("{url}: {e}")))?;
464364×
                Ok(out)
465
            }
4669×
            Err(ureq::Error::Status(code, r)) => {
4679×
                let text = r.into_string().unwrap_or_default();
468
                // The hint comes from the status alone: the server's text
469
                // (a host's reason for refusing a push, several lines
470
                // perhaps) is shown as it is, never read for hints.
4719×
                let status = format!("{url}: HTTP {code}");
4729×
                let msg = format!("{status}: {}", text.trim());
4739×
                Err(RepoError::Msg(match hint_for(&status) {
4748×
                    Some(h) => format!("{msg}\n  hint: {h}"),
4751×
                    None => msg,
476
                }))
477
            }
478
            // The transport error already names the URL.
4793×
            Err(e) => Err(RepoError::Msg(with_hint(e.to_string()))),
480
        }
481376×
    }
482
}
483
484
/// Whether a failed request's message says the hub refused its token:
485
/// HTTP 401, 403, or 404 (a hub hides a private repository from a token
486
/// that may not read it).
4874×
fn refused(message: &str) -> bool {
4884×
    [": HTTP 401", ": HTTP 403", ": HTTP 404"]
4894×
        .iter()
4906×
        .any(|c| message.contains(c))
4914×
}
492
493
/// Refuse to send a token where anyone on the way could read it: plain
494
/// `http` to another machine (see [`crate::credentials::token_allowed`]).
495149×
fn refuse_plain_token(url: &str, options: &RemoteOptions) -> Result<()> {
496149×
    if options.token.is_some() && !crate::credentials::token_allowed(url) {
4970×
        return Err(RepoError::Msg(format!(
4980×
            "{url}: refusing to send a token over plain http; use https"
4990×
        )));
500149×
    }
501149×
    Ok(())
502149×
}
503
504
/// What to do about a failed request, recognised from its message.
50520×
pub fn hint_for(message: &str) -> Option<&'static str> {
50620×
    let m = message.to_ascii_lowercase();
50720×
    let hint = if m.contains("http 401") {
5086×
        "the hub needs you signed in, or did not accept the token: run `oxy auth login HUB` (pushing needs repo:write)"
50914×
    } else if m.contains("http 403") {
5101×
        "the token or account lacks permission: pushing needs a token with repo:write and write access to the repository"
51113×
    } else if m.contains("http 404") {
5124×
        "nothing at this URL that you can see: check the owner and repository name; a private repository needs you signed in (`oxy auth login HUB`)"
5139×
    } else if m.contains("unknownissuer")
5147×
        || m.contains("unknown issuer")
5157×
        || m.contains("certificate")
5166×
        || m.contains("invalidcertificate")
517
    {
5183×
        "the server's certificate is not trusted: for a hub with a self-signed certificate, download it from /.well-known/oxyhub-ca.pem on the hub and run `oxy config remote.<remote>.ca FILE`"
5196×
    } else if m.contains("connection refused") {
5203×
        "nothing is listening there: check the URL and port, and that the server is running"
5213×
    } else if m.contains("dns")
5222×
        || m.contains("failed to lookup")
5232×
        || m.contains("name or service not known")
524
    {
5251×
        "the host name does not resolve: check the URL"
5262×
    } else if m.contains("timed out") || m.contains("timeout") {
5270×
        "the server did not answer in time: check the network, or try again"
528
    } else {
5292×
        return None;
530
    };
53118×
    Some(hint)
53220×
}
533
534
/// `message`, followed by what to do about it when that is known.
5353×
pub fn with_hint(message: String) -> String {
5363×
    match hint_for(&message) {
5373×
        Some(h) => format!("{message}\n  hint: {h}"),
5380×
        None => message,
539
    }
5403×
}
541
542
/// A JSON request to a hub API (`GET`, `POST` or `DELETE`), with the same
543
/// TLS trust and token rules as remotes. Returns the status and body, an
544
/// error status included; only transport failures are errors.
5450×
pub fn http_json(
5460×
    method: &str,
5470×
    url: &str,
5480×
    body: Option<&str>,
5490×
    options: &RemoteOptions,
5500×
) -> Result<(u16, String)> {
5510×
    refuse_plain_token(url, options)?;
5520×
    let agent = ureq::AgentBuilder::new()
5530×
        .tls_config(tls_client_config(options.ca.as_deref())?)
5540×
        .timeout(std::time::Duration::from_secs(60))
5550×
        .build();
5560×
    let mut req = agent.request(method, url).set("Accept", "application/json");
5570×
    if let Some(t) = &options.token {
5580×
        req = req.set("Authorization", &format!("Bearer {t}"));
5590×
    }
5600×
    let resp = match body {
5610×
        Some(b) => req.set("Content-Type", "application/json").send_string(b),
5620×
        None => req.call(),
563
    };
5640×
    match resp {
5650×
        Ok(r) => {
5660×
            let code = r.status();
5670×
            Ok((code, r.into_string().unwrap_or_default()))
568
        }
5690×
        Err(ureq::Error::Status(code, r)) => Ok((code, r.into_string().unwrap_or_default())),
5700×
        Err(e) => Err(RepoError::Msg(with_hint(e.to_string()))),
571
    }
5720×
}
573
574
/// An authenticated GET of any URL on a host, with the same TLS trust and
575
/// token as remotes use (for hub APIs: proposals). Returns the body.
5760×
pub fn http_get(url: &str, options: &RemoteOptions) -> Result<Vec<u8>> {
5770×
    refuse_plain_token(url, options)?;
5780×
    let agent = ureq::AgentBuilder::new()
5790×
        .tls_config(tls_client_config(options.ca.as_deref())?)
5800×
        .build();
5810×
    let mut req = agent.get(url).set("Accept", "application/json");
5820×
    if let Some(t) = &options.token {
5830×
        req = req.set("Authorization", &format!("Bearer {t}"));
5840×
    }
5850×
    match req.call() {
5860×
        Ok(r) => {
5870×
            let mut out = Vec::new();
5880×
            r.into_reader()
5890×
                .read_to_end(&mut out)
5900×
                .map_err(|e| RepoError::Msg(format!("{url}: {e}")))?;
5910×
            Ok(out)
592
        }
5930×
        Err(ureq::Error::Status(code, r)) => {
5940×
            let text = r.into_string().unwrap_or_default();
5950×
            Err(RepoError::Msg(with_hint(format!(
5960×
                "{url}: HTTP {code}: {}",
5970×
                text.trim()
5980×
            ))))
599
        }
600
        // The transport error already names the URL.
6010×
        Err(e) => Err(RepoError::Msg(with_hint(e.to_string()))),
602
    }
6030×
}
604
605
impl Remote for HttpRemote {
606128×
    fn repo_id(&self) -> Result<[u8; 16]> {
607128×
        wire::decode_capabilities(&self.call(false, "capabilities", None)?)
608128×
    }
609119×
    fn refs(&self) -> Result<RefsResponse> {
610119×
        Ok(wire::decode_refs(&self.call(false, "refs", None)?)?.1)
611119×
    }
61246×
    fn negotiate(&self, have: &[ChangeHash], want: &[ChangeHash]) -> Result<Vec<ChangeHash>> {
61346×
        wire::decode_hashes(&self.call(
614
            true,
61546×
            "negotiate",
61646×
            Some(&wire::encode_negotiate(have, want)),
6170×
        )?)
61846×
    }
61946×
    fn fetch(&self, changes: &[ChangeHash], max_blob: Option<u64>) -> Result<Bundle> {
62046×
        wire::decode_bundle(&self.call(
621
            true,
62246×
            "fetch",
62346×
            Some(&wire::encode_fetch(changes, max_blob)),
6240×
        )?)
62546×
    }
6261×
    fn objects(&self, refs: &[ObjectRef]) -> Result<Vec<(ObjectType, Vec<u8>)>> {
627
        Ok(
6281×
            wire::decode_bundle(&self.call(true, "objects", Some(&wire::encode_hashes(refs)))?)?
629
                .objects,
630
        )
6311×
    }
6320×
    fn checkpoint(&self, heads: &[ChangeHash]) -> Result<Bundle> {
6330×
        wire::decode_bundle(&self.call(true, "checkpoint", Some(&wire::encode_hashes(heads)))?)
6340×
    }
6350×
    fn shallow(&self, heads: &[ChangeHash], depth: u32) -> Result<Vec<ChangeHash>> {
6360×
        wire::decode_hashes(&self.call(
637
            true,
6380×
            "shallow",
6390×
            Some(&wire::encode_shallow(heads, depth)),
6400×
        )?)
6410×
    }
64235×
    fn push(
64335×
        &self,
64435×
        bundle: Bundle,
64535×
        updates: Vec<RefUpdate>,
64635×
        policy: Option<SignedPolicy>,
64735×
        tags: Vec<TagRef>,
64835×
    ) -> Result<Vec<RefResult>> {
64935×
        wire::decode_push_response(&self.call(
650
            true,
65135×
            "push",
65235×
            Some(&wire::encode_push(
65335×
                &bundle,
65435×
                &updates,
65535×
                policy.as_ref(),
65635×
                &tags,
65735×
            )),
6585×
        )?)
65935×
    }
660
}
661
662
/// A remote's URL as it is stored: an `http(s)://` URL as given, a local
663
/// path made absolute (with its `file://` kept), so it still names the same
664
/// repository from inside the clone (oxygen#57).
665271×
pub fn stored_url(url: &str) -> String {
666
    // Only a path is made absolute: a plain one, or one behind file:// or
667
    // dir://. Every other URL (a hub, a bucket) is kept as written.
668271×
    let (prefix, path) = match (url.strip_prefix("file://"), url.strip_prefix("dir://")) {
6691×
        (Some(p), _) => ("file://", p),
67011×
        (_, Some(p)) => ("dir://", p),
671259×
        _ if url.contains("://") => return url.to_string(),
672236×
        _ => ("", url),
673
    };
674248×
    match std::path::absolute(path) {
675248×
        Ok(abs) => format!("{prefix}{}", abs.display()),
6760×
        Err(_) => url.to_string(),
677
    }
678271×
}
679
680
/// Open a remote by URL: a local path (optionally `file://`), `http(s)://`
681
/// (a hub), or a store (`dir://`, and whatever openers are registered).
6821316×
pub fn open_remote(url: &str, options: &RemoteOptions) -> Result<Box<dyn Remote>> {
6831316×
    if url.starts_with("http://") || url.starts_with("https://") {
684149×
        return Ok(Box::new(HttpRemote::new(url, options)?));
6851167×
    }
6861167×
    if let Some(store) = open_store(url, options) {
68748×
        return crate::repo::strata::open_store_remote(store?, options);
6881119×
    }
6891119×
    let path = url.strip_prefix("file://").unwrap_or(url);
6901119×
    if path.contains("://") {
6910×
        return Err(RepoError::Msg(format!("unsupported remote URL {url:?}")));
6921119×
    }
6931119×
    let mut local = LocalRemote::open(Path::new(path))?;
6941119×
    local.claimed_id = options.repo_id;
6951119×
    Ok(Box::new(local))
6961316×
}
697
698
// ---------------------------------------------------------------- wire
699
700
/// CBOR encodings of the protocol messages (spec §16.1).
701
pub mod wire {
702
    use super::*;
703
7040×
    fn schema(msg: &str) -> RepoError {
7050×
        RepoError::Object(ObjectError::Schema(msg.into()))
7060×
    }
707158×
    fn sigs_value(sigs: &[Signature]) -> Value {
708158×
        Value::Array(sigs.iter().map(|s| s.to_value()).collect())
709158×
    }
710154×
    fn sigs_from(v: &Value) -> Result<Vec<Signature>> {
711154×
        Ok(o::array(v, "signatures")?
712154×
            .iter()
713154×
            .map(Signature::from_value)
714154×
            .collect::<std::result::Result<Vec<_>, _>>()?)
715154×
    }
716359×
    fn hashes_value(hs: &[ObjectRef]) -> Value {
717502×
        Value::Array(hs.iter().map(|h| Value::Bytes(h.0.to_vec())).collect())
718359×
    }
719420×
    fn hashes_from(v: &Value) -> Result<Vec<ObjectRef>> {
720420×
        Ok(o::array(v, "hashes")?
721420×
            .iter()
722564×
            .map(|h| o::oref(h, "hash"))
723420×
            .collect::<std::result::Result<Vec<_>, _>>()?)
724420×
    }
72530×
    fn attest_value(sa: &SignedAttest) -> Value {
72630×
        Value::Array(vec![Value::Bytes(sa.attest.encode()), sigs_value(&sa.sigs)])
72730×
    }
72845×
    fn attest_from(v: &Value) -> Result<SignedAttest> {
72945×
        let a = o::array(v, "signed attest")?;
73045×
        if a.len() != 2 {
7310×
            return Err(schema("signed attest: expected [attest, sigs]"));
73245×
        }
733
        Ok(SignedAttest {
73445×
            attest: Attest::decode(o::bytes(&a[0], "attest")?)?,
73545×
            sigs: sigs_from(&a[1])?,
736
        })
73745×
    }
738205×
    fn opt_attest_value(sa: &Option<SignedAttest>) -> Value {
739205×
        sa.as_ref().map(attest_value).unwrap_or(Value::Null)
740205×
    }
741262×
    fn opt_attest_from(v: &Value) -> Result<Option<SignedAttest>> {
742262×
        if v.is_null() {
743228×
            Ok(None)
744
        } else {
74534×
            attest_from(v).map(Some)
746
        }
747262×
    }
748
    /// `[policy bytes, [signature]]`: also the format of a policy proposal
749
    /// file exchanged between root holders (spec §14.5).
75014×
    pub fn policy_value(sp: &SignedPolicy) -> Value {
75114×
        Value::Array(vec![Value::Bytes(sp.policy.encode()), sigs_value(&sp.sigs)])
75214×
    }
75312×
    pub fn policy_from(v: &Value) -> Result<SignedPolicy> {
75412×
        let a = o::array(v, "signed policy")?;
75512×
        if a.len() != 2 {
7560×
            return Err(schema("signed policy: expected [policy, sigs]"));
75712×
        }
758
        Ok(SignedPolicy {
75912×
            policy: Policy::decode(o::bytes(&a[0], "policy")?)?,
76012×
            sigs: sigs_from(&a[1])?,
761
        })
76212×
    }
763186×
    fn opt_policy_value(sp: Option<&SignedPolicy>) -> Value {
764186×
        sp.map(policy_value).unwrap_or(Value::Null)
765186×
    }
766225×
    fn opt_policy_from(v: &Value) -> Result<Option<SignedPolicy>> {
767225×
        if v.is_null() {
768220×
            Ok(None)
769
        } else {
7705×
            policy_from(v).map(Some)
771
        }
772225×
    }
773926×
    fn map<'a>(v: &'a Value, what: &str) -> Result<&'a o::Map> {
774926×
        Ok(o::map(v, what)?)
775926×
    }
7762614×
    fn field<'a>(m: &'a o::Map, k: u64, what: &str) -> Result<&'a Value> {
7772614×
        Ok(o::field(m, k, what)?)
7782614×
    }
779
780
    /// A bundle's value. Each change's text blobs and their chunks (spec
781
    /// §6.1) are added to its objects when they are not already there, so a
782
    /// bundle can always be read on its own.
783119×
    pub fn bundle_value(b: &Bundle) -> Value {
784119×
        let mut changes = Vec::with_capacity(b.raw_changes.len() + b.changes.len());
785
        // Changes as stored are already their encoding, their texts among
786
        // the objects.
787119×
        for (bytes, s) in &b.raw_changes {
7880×
            changes.push(Value::Array(vec![
7890×
                Value::Bytes(bytes.clone()),
7900×
                sigs_value(s),
7910×
            ]));
7920×
        }
793119×
        let mut texts: Vec<(ObjectType, Vec<u8>)> = Vec::new();
794119×
        let mut listed: Option<std::collections::HashSet<ObjectRef>> = None;
795119×
        for (c, s) in &b.changes {
796114×
            let (bytes, stored) = c.encode_parts();
797114×
            for t in stored {
7980×
                let listed = listed.get_or_insert_with(|| {
7990×
                    b.objects
8000×
                        .iter()
8010×
                        .map(|(ty, body)| crate::hash::hash_object(*ty, body))
8020×
                        .collect()
8030×
                });
8040×
                if !listed.insert(t.blob.hash()) {
8050×
                    continue;
8060×
                }
8070×
                for chunk in crate::chunk::chunks(&t.content) {
8080×
                    if listed.insert(crate::hash::hash_object(ObjectType::Chunk, chunk)) {
8090×
                        texts.push((ObjectType::Chunk, chunk.to_vec()));
8100×
                    }
811
                }
8120×
                texts.push((ObjectType::Blob, t.blob.encode()));
813
            }
814114×
            changes.push(Value::Array(vec![Value::Bytes(bytes), sigs_value(s)]));
815
        }
816119×
        let mut v = Value::map([
817119×
            (0, Value::Array(changes)),
818119×
            (
819119×
                1,
820119×
                Value::Array(b.attests.iter().map(attest_value).collect()),
821119×
            ),
822
            (
823
                2,
824
                Value::Array(
825119×
                    b.objects
826119×
                        .iter()
827119×
                        .chain(&texts)
828119×
                        .map(|(t, body)| {
82990×
                            Value::Array(vec![
83090×
                                Value::Text(t.name().into()),
83190×
                                Value::Bytes(body.clone()),
83290×
                            ])
83390×
                        })
834119×
                        .collect(),
835
                ),
836
            ),
837119×
            (
838119×
                3,
839119×
                Value::Array(b.policies.iter().map(policy_value).collect()),
840119×
            ),
841
        ]);
842
        // Only when there are any; older peers ignore the field.
843119×
        if !b.certificates.is_empty() {
8441×
            if let Value::Map(m) = &mut v {
8451×
                m.insert(
846
                    4,
847
                    Value::Array(
8481×
                        b.certificates
8491×
                            .iter()
8501×
                            .map(|c| Value::Bytes(c.encode()))
8511×
                            .collect(),
852
                    ),
853
                );
8540×
            }
855118×
        }
856119×
        v
857119×
    }
858
859109×
    pub fn bundle_from_value(v: &Value) -> Result<Bundle> {
860109×
        let m = map(v, "bundle")?;
861109×
        let mut b = Bundle::default();
862109×
        for ob in o::array(field(m, 2, "objects")?, "objects")? {
86379×
            let pair = o::array(ob, "object")?;
86479×
            if pair.len() != 2 {
8650×
                return Err(schema("object: expected [type, body]"));
86679×
            }
86779×
            let ty = ObjectType::from_name(o::text(&pair[0], "object type")?)
86879×
                .ok_or_else(|| schema("unknown object type"))?;
86979×
            b.objects
87079×
                .push((ty, o::bytes(&pair[1], "object body")?.to_vec()));
871
        }
872
        // Stored inserts are read from the bundle's own objects.
873109×
        let mut by_ref: Option<std::collections::HashMap<ObjectRef, usize>> = None;
874109×
        for c in o::array(field(m, 0, "changes")?, "changes")? {
87597×
            let pair = o::array(c, "change entry")?;
87697×
            if pair.len() != 2 {
8770×
                return Err(schema("change entry: expected [change, sigs]"));
87897×
            }
87997×
            let encoded = o::bytes(&pair[0], "change")?;
88097×
            b.hashes
88197×
                .push(crate::hash::hash_object(ObjectType::Change, encoded));
88297×
            let change = Change::decode_with(encoded, &mut |text, count, form| {
8830×
                let by_ref = by_ref.get_or_insert_with(|| {
8840×
                    b.objects
8850×
                        .iter()
8860×
                        .enumerate()
8870×
                        .map(|(i, (ty, body))| (crate::hash::hash_object(*ty, body), i))
8880×
                        .collect()
8890×
                });
8900×
                let get =
8910×
                    |r: &ObjectRef, want: ObjectType| match by_ref.get(r).map(|i| &b.objects[*i]) {
8920×
                        Some((ty, body)) if *ty == want => Ok(body),
8930×
                        _ => Err(ObjectError::Schema(format!(
8940×
                            "the bundle lacks {} {}",
8950×
                            want.name(),
8960×
                            r.short(12)
8970×
                        ))),
8980×
                    };
8990×
                let blob = crate::objects::Blob::decode(get(text, ObjectType::Blob)?)?;
9000×
                let mut content = Vec::with_capacity(blob.length as usize);
9010×
                for chunk in &blob.chunks {
9020×
                    content.extend_from_slice(get(chunk, ObjectType::Chunk)?);
903
                }
9040×
                crate::objects::text_lines(&content, count, form)
9050×
            })?;
90697×
            b.changes.push((change, sigs_from(&pair[1])?));
907
        }
908109×
        for a in o::array(field(m, 1, "attests")?, "attests")? {
90911×
            b.attests.push(attest_from(a)?);
910
        }
911109×
        if let Some(ps) = m.get(&3) {
912109×
            for p in o::array(ps, "policies")? {
9133×
                b.policies.push(policy_from(p)?);
914
            }
9150×
        }
916109×
        if let Some(cs) = m.get(&4) {
9171×
            for c in o::array(cs, "certificates")? {
9181×
                b.certificates.push(
9191×
                    crate::cert::SignedCertificate::decode(o::bytes(c, "certificate")?)
9201×
                        .map_err(|e| schema(&format!("certificate: {e}")))?,
921
                );
922
            }
923108×
        }
924109×
        Ok(b)
925109×
    }
926
92782×
    pub fn encode_bundle(b: &Bundle) -> Vec<u8> {
92882×
        cbor::encode(&bundle_value(b))
92982×
    }
93076×
    pub fn decode_bundle(bytes: &[u8]) -> Result<Bundle> {
93176×
        bundle_from_value(&cbor::decode(bytes).map_err(ObjectError::from)?)
93276×
    }
933
934123×
    pub fn encode_capabilities(id: [u8; 16]) -> Vec<u8> {
935123×
        cbor::encode(&Value::map([
936123×
            (0, Value::Array(vec![Value::Uint(PROTOCOL_VERSION)])),
937123×
            (1, Value::Bytes(id.to_vec())),
938123×
            (2, Value::Array(vec![Value::Text("seal".into())])),
939123×
        ]))
940123×
    }
941123×
    pub fn decode_capabilities(bytes: &[u8]) -> Result<[u8; 16]> {
942123×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
943123×
        let m = map(&v, "capabilities")?;
944123×
        let versions = o::array(field(m, 0, "versions")?, "versions")?;
945123×
        if !versions
946123×
            .iter()
947123×
            .any(|x| x.as_uint() == Some(PROTOCOL_VERSION))
948
        {
9490×
            return Err(RepoError::Msg(
9500×
                "remote does not speak protocol version 1".into(),
9510×
            ));
952123×
        }
953123×
        o::bytes(field(m, 1, "repo id")?, "repo id")?
954123×
            .try_into()
955123×
            .map_err(|_| schema("repo id: expected 16 bytes"))
956123×
    }
957
958186×
    fn tags_value(tags: &[TagRef]) -> Value {
959
        Value::Array(
960186×
            tags.iter()
961186×
                .map(|t| {
96212×
                    let mut v = Value::map([
96312×
                        (0, Value::Text(t.name.clone())),
96412×
                        (1, Value::Bytes(t.state.0.to_vec())),
96512×
                        (2, hashes_value(&t.heads)),
96612×
                        (3, opt_attest_value(&t.attestation)),
96712×
                    ]);
968
                    // Only when there is one; older peers ignore them
969
                    // (oxygen#129).
97012×
                    if let Value::Map(m) = &mut v {
97112×
                        if t.accepted.is_some() {
9722×
                            m.insert(4, opt_attest_value(&t.accepted));
97310×
                        }
97412×
                        if let Some(l) = &t.logged {
9752×
                            m.insert(5, logged_value(l));
97610×
                        }
97712×
                        if !t.integration.is_empty() {
9782×
                            m.insert(6, integration_value(&t.integration));
97910×
                        }
9800×
                    }
98112×
                    v
98212×
                })
983186×
                .collect(),
984
        )
985186×
    }
986225×
    fn tags_from(v: &Value) -> Result<Vec<TagRef>> {
987225×
        let mut out = Vec::new();
988225×
        for t in o::array(v, "tags")? {
98928×
            let tm = map(t, "tag")?;
99028×
            out.push(TagRef {
99128×
                name: o::text(field(tm, 0, "name")?, "name")?.to_owned(),
99228×
                state: o::oref(field(tm, 1, "state")?, "state")?,
99328×
                heads: hashes_from(field(tm, 2, "heads")?)?,
99428×
                attestation: opt_attest_from(field(tm, 3, "attestation")?)?,
99528×
                accepted: match tm.get(&4) {
9962×
                    Some(a) => opt_attest_from(a)?,
99726×
                    None => None,
998
                },
99928×
                logged: tm.get(&5).map(logged_from).transpose()?,
100028×
                integration: match tm.get(&6) {
10012×
                    Some(l) => integration_from(l)?,
100226×
                    None => Vec::new(),
1003
                },
1004
            });
1005
        }
1006225×
        Ok(out)
1007225×
    }
1008
1009
    /// The tags of a refs answer as oxy 0.5.0 read them (and the runners
1010
    /// built with it), keys 0 to 3 only: what an older reader makes of an
1011
    /// answer with keys 4 to 6.
1012
    #[cfg(test)]
10131×
    pub(super) fn tags_as_0_5_read_them(bytes: &[u8]) -> Result<Vec<TagRef>> {
10141×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
10151×
        let m = map(&v, "refs")?;
10161×
        let mut out = Vec::new();
10172×
        for t in o::array(field(m, 3, "tags")?, "tags")? {
10182×
            let tm = map(t, "tag")?;
10192×
            out.push(TagRef::new(
10202×
                o::text(field(tm, 0, "name")?, "name")?.to_owned(),
10212×
                o::oref(field(tm, 1, "state")?, "state")?,
10222×
                hashes_from(field(tm, 2, "heads")?)?,
10232×
                opt_attest_from(field(tm, 3, "attestation")?)?,
1024
            ));
1025
        }
10261×
        Ok(out)
10271×
    }
1028
1029
    /// A log place, `[entry number, entry bytes, [proof hash]]` (spec §14.8).
10304×
    fn logged_value(l: &Logged) -> Value {
10314×
        Value::Array(vec![
10324×
            Value::Uint(l.index),
10334×
            Value::Bytes(l.entry.clone()),
10344×
            proof_value(&l.proof),
10354×
        ])
10364×
    }
10374×
    fn logged_from(v: &Value) -> Result<Logged> {
10384×
        let a = o::array(v, "logged")?;
10394×
        if a.len() != 3 {
10400×
            return Err(schema("logged: expected [index, entry, proof]"));
10414×
        }
1042
        Ok(Logged {
10434×
            index: o::uint(&a[0], "index")?,
10444×
            entry: o::bytes(&a[1], "entry")?.to_vec(),
10454×
            proof: proof_from(&a[2])?,
1046
        })
10474×
    }
1048
1049
    /// Cosigned checkpoints holding an entry, `[[note, [proof hash]]]`.
10504×
    fn integration_value(integration: &[Integration]) -> Value {
1051
        Value::Array(
10524×
            integration
10534×
                .iter()
10544×
                .map(|i| Value::Array(vec![Value::Text(i.note.clone()), proof_value(&i.proof)]))
10554×
                .collect(),
1056
        )
10574×
    }
10584×
    fn integration_from(v: &Value) -> Result<Vec<Integration>> {
10594×
        let mut out = Vec::new();
10604×
        for i in o::array(v, "integration")? {
10614×
            let a = o::array(i, "integration")?;
10624×
            if a.len() != 2 {
10630×
                return Err(schema("integration: expected [note, proof]"));
10644×
            }
10654×
            out.push(Integration {
10664×
                note: o::text(&a[0], "note")?.to_owned(),
10674×
                proof: proof_from(&a[1])?,
1068
            });
1069
        }
10704×
        Ok(out)
10714×
    }
1072
1073149×
    pub fn encode_refs(id: [u8; 16], resp: &RefsResponse) -> Vec<u8> {
1074149×
        let mut v = Value::map([
1075
            (
1076
                0,
1077
                Value::Array(
1078149×
                    resp.refs
1079149×
                        .iter()
1080155×
                        .map(|r| {
1081155×
                            let mut v = Value::map([
1082155×
                                (0, Value::Text(r.name.clone())),
1083155×
                                (1, Value::Bytes(r.state.0.to_vec())),
1084155×
                                (2, hashes_value(&r.heads)),
1085155×
                                (3, opt_attest_value(&r.attestation)),
1086155×
                                (4, r.last_serial.map(Value::Uint).unwrap_or(Value::Null)),
1087155×
                            ]);
1088
                            // Only when there is one; older peers ignore it.
1089155×
                            if let Value::Map(m) = &mut v {
1090155×
                                if r.accepted.is_some() {
10910×
                                    m.insert(5, opt_attest_value(&r.accepted));
1092155×
                                }
1093155×
                                if let Some(l) = &r.logged {
10942×
                                    m.insert(6, logged_value(l));
1095153×
                                }
1096155×
                                if !r.integration.is_empty() {
10972×
                                    m.insert(7, integration_value(&r.integration));
1098153×
                                }
10990×
                            }
1100155×
                            v
1101155×
                        })
1102149×
                        .collect(),
1103
                ),
1104
            ),
1105149×
            (1, Value::Bytes(id.to_vec())),
1106149×
            (2, opt_policy_value(resp.policy.as_ref())),
1107149×
            (3, tags_value(&resp.tags)),
1108149×
            (
1109149×
                4,
1110149×
                Value::Array(resp.history.iter().map(policy_value).collect()),
1111149×
            ),
1112149×
            (
1113149×
                5,
1114149×
                resp.default_bookmark
1115149×
                    .clone()
1116149×
                    .map(Value::Text)
1117149×
                    .unwrap_or(Value::Null),
1118149×
            ),
1119
        ]);
1120149×
        if let Value::Map(m) = &mut v {
1121149×
            if let Some(log) = &resp.log {
11223×
                m.insert(6, Value::Text(log.clone()));
1123146×
            }
1124149×
            if !resp.witnesses.is_empty() {
11252×
                m.insert(
1126
                    7,
1127
                    Value::Array(
11282×
                        resp.witnesses
11292×
                            .iter()
11302×
                            .map(|(name, id)| {
11312×
                                Value::Array(vec![
11322×
                                    Value::Text(name.clone()),
11332×
                                    Value::Bytes(id.clone()),
11342×
                                ])
11352×
                            })
11362×
                            .collect(),
1137
                    ),
1138
                );
1139147×
            }
11400×
        }
1141149×
        cbor::encode(&v)
1142149×
    }
1143192×
    pub fn decode_refs(bytes: &[u8]) -> Result<([u8; 16], RefsResponse)> {
1144192×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
1145192×
        let m = map(&v, "refs")?;
1146192×
        let id: [u8; 16] = o::bytes(field(m, 1, "repo id")?, "repo id")?
1147192×
            .try_into()
1148192×
            .map_err(|_| schema("repo id: expected 16 bytes"))?;
1149192×
        let mut refs = Vec::new();
1150198×
        for r in o::array(field(m, 0, "refs")?, "refs")? {
1151198×
            let rm = map(r, "ref")?;
1152198×
            let ls = field(rm, 4, "last serial")?;
1153198×
            refs.push(RemoteRef {
1154198×
                name: o::text(field(rm, 0, "name")?, "name")?.to_owned(),
1155198×
                state: o::oref(field(rm, 1, "state")?, "state")?,
1156198×
                heads: hashes_from(field(rm, 2, "heads")?)?,
1157198×
                attestation: opt_attest_from(field(rm, 3, "attestation")?)?,
1158198×
                last_serial: if ls.is_null() {
1159180×
                    None
1160
                } else {
116118×
                    Some(o::uint(ls, "last serial")?)
1162
                },
1163198×
                accepted: match rm.get(&5) {
11640×
                    Some(a) => opt_attest_from(a)?,
1165198×
                    None => None,
1166
                },
1167198×
                logged: rm.get(&6).map(logged_from).transpose()?,
1168198×
                integration: match rm.get(&7) {
11692×
                    Some(l) => integration_from(l)?,
1170196×
                    None => Vec::new(),
1171
                },
1172
            });
1173
        }
1174192×
        let policy = match m.get(&2) {
1175192×
            Some(p) => opt_policy_from(p)?,
11760×
            None => None,
1177
        };
1178192×
        let tags = match m.get(&3) {
1179192×
            Some(t) => tags_from(t)?,
11800×
            None => Vec::new(),
1181
        };
1182192×
        let mut history = Vec::new();
1183192×
        if let Some(h) = m.get(&4) {
1184192×
            for p in o::array(h, "history")? {
11853×
                history.push(policy_from(p)?);
1186
            }
11870×
        }
1188192×
        let default_bookmark = match m.get(&5) {
1189123×
            Some(Value::Text(t)) => Some(t.clone()),
119069×
            _ => None,
1191
        };
1192192×
        let log = match m.get(&6) {
11933×
            Some(Value::Text(t)) => Some(t.clone()),
1194189×
            _ => None,
1195
        };
1196192×
        let mut witnesses = Vec::new();
1197192×
        if let Some(w) = m.get(&7) {
11982×
            for x in o::array(w, "witnesses")? {
11992×
                let a = o::array(x, "witness")?;
12002×
                if a.len() != 2 {
12010×
                    return Err(schema("witness: expected [name, identity]"));
12022×
                }
12032×
                witnesses.push((
12042×
                    o::text(&a[0], "witness name")?.to_owned(),
12052×
                    o::bytes(&a[1], "witness identity")?.to_vec(),
1206
                ));
1207
            }
1208190×
        }
1209192×
        Ok((
1210192×
            id,
1211192×
            RefsResponse {
1212192×
                refs,
1213192×
                policy,
1214192×
                tags,
1215192×
                history,
1216192×
                default_bookmark,
1217192×
                log,
1218192×
                witnesses,
1219192×
            },
1220192×
        ))
1221192×
    }
1222
1223
    /// A proof's hashes, from the leaf upwards (spec §14.8).
12248×
    fn proof_value(proof: &[[u8; 32]]) -> Value {
12258×
        Value::Array(proof.iter().map(|h| Value::Bytes(h.to_vec())).collect())
12268×
    }
1227
12288×
    fn proof_from(v: &Value) -> Result<Vec<[u8; 32]>> {
12298×
        let mut proof = Vec::new();
12308×
        for h in o::array(v, "proof")? {
12318×
            proof.push(
12328×
                o::bytes(h, "proof hash")?
12338×
                    .try_into()
12348×
                    .map_err(|_| schema("proof hash: expected 32 bytes"))?,
1235
            );
1236
        }
12378×
        Ok(proof)
12388×
    }
1239
124047×
    pub fn encode_negotiate(have: &[ChangeHash], want: &[ChangeHash]) -> Vec<u8> {
124147×
        cbor::encode(&Value::map([
124247×
            (0, hashes_value(have)),
124347×
            (1, hashes_value(want)),
124447×
        ]))
124547×
    }
124647×
    pub fn decode_negotiate(bytes: &[u8]) -> Result<(Vec<ChangeHash>, Vec<ChangeHash>)> {
124747×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
124847×
        let m = map(&v, "negotiate")?;
1249
        Ok((
125047×
            hashes_from(field(m, 0, "have")?)?,
125147×
            hashes_from(field(m, 1, "want")?)?,
1252
        ))
125347×
    }
1254
1255
    /// `fetch` request: `{0: [changes], 1: max blob size or null}`.
125648×
    pub fn encode_fetch(hs: &[ChangeHash], max_blob: Option<u64>) -> Vec<u8> {
125748×
        cbor::encode(&Value::map([
125848×
            (0, hashes_value(hs)),
125948×
            (1, max_blob.map(Value::Uint).unwrap_or(Value::Null)),
126048×
        ]))
126148×
    }
126249×
    pub fn decode_fetch(bytes: &[u8]) -> Result<(Vec<ChangeHash>, Option<u64>)> {
126349×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
126449×
        let m = map(&v, "fetch")?;
126549×
        let max = match m.get(&1) {
126648×
            Some(x) if !x.is_null() => Some(o::uint(x, "max blob")?),
126747×
            _ => None,
1268
        };
126949×
        Ok((hashes_from(field(m, 0, "changes")?)?, max))
127049×
    }
1271
1272
    /// `shallow` request: `{0: [heads], 1: depth}`.
12731×
    pub fn encode_shallow(hs: &[ChangeHash], depth: u32) -> Vec<u8> {
12741×
        cbor::encode(&Value::map([
12751×
            (0, hashes_value(hs)),
12761×
            (1, Value::Uint(depth as u64)),
12771×
        ]))
12781×
    }
12791×
    pub fn decode_shallow(bytes: &[u8]) -> Result<(Vec<ChangeHash>, u32)> {
12801×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
12811×
        let m = map(&v, "shallow")?;
1282
        Ok((
12831×
            hashes_from(field(m, 0, "heads")?)?,
12841×
            o::u32_(field(m, 1, "depth")?, "depth")?,
1285
        ))
12861×
    }
1287
128849×
    pub fn encode_hashes(hs: &[ChangeHash]) -> Vec<u8> {
128949×
        cbor::encode(&Value::map([(0, hashes_value(hs))]))
129049×
    }
129148×
    pub fn decode_hashes(bytes: &[u8]) -> Result<Vec<ChangeHash>> {
129248×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
129348×
        hashes_from(field(map(&v, "hashes")?, 0, "hashes")?)
129448×
    }
1295
129637×
    pub fn encode_push(
129737×
        bundle: &Bundle,
129837×
        updates: &[RefUpdate],
129937×
        policy: Option<&SignedPolicy>,
130037×
        tags: &[TagRef],
130137×
    ) -> Vec<u8> {
130237×
        cbor::encode(&Value::map([
130337×
            (0, bundle_value(bundle)),
130437×
            (2, opt_policy_value(policy)),
130537×
            (3, tags_value(tags)),
1306
            (
1307
                1,
1308
                Value::Array(
130937×
                    updates
131037×
                        .iter()
131137×
                        .map(|u| {
131236×
                            Value::map([
131336×
                                (0, Value::Text(u.name.clone())),
131436×
                                (1, Value::Bytes(u.old_state.0.to_vec())),
131536×
                                (2, Value::Bytes(u.new_state.0.to_vec())),
131636×
                                (3, Value::Bool(u.force)),
131736×
                                (4, opt_attest_value(&u.attestation)),
131836×
                            ])
131936×
                        })
132037×
                        .collect(),
1321
                ),
1322
            ),
1323
        ]))
132437×
    }
1325
    /// A decoded push: bundle, bookmark updates, policy, tags.
1326
    pub type PushParts = (Bundle, Vec<RefUpdate>, Option<SignedPolicy>, Vec<TagRef>);
1327
132833×
    pub fn decode_push(bytes: &[u8]) -> Result<PushParts> {
132933×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
133033×
        let m = map(&v, "push")?;
133133×
        let bundle = bundle_from_value(field(m, 0, "bundle")?)?;
133233×
        let mut updates = Vec::new();
133333×
        for u in o::array(field(m, 1, "updates")?, "updates")? {
133432×
            let um = map(u, "update")?;
133532×
            updates.push(RefUpdate {
133632×
                name: o::text(field(um, 0, "name")?, "name")?.to_owned(),
133732×
                old_state: o::oref(field(um, 1, "old_state")?, "old_state")?,
133832×
                new_state: o::oref(field(um, 2, "new_state")?, "new_state")?,
133932×
                force: field(um, 3, "force")?
134032×
                    .as_bool()
134132×
                    .ok_or_else(|| schema("force: expected bool"))?,
134232×
                attestation: opt_attest_from(field(um, 4, "attestation")?)?,
1343
            });
1344
        }
134533×
        let policy = match m.get(&2) {
134633×
            Some(p) => opt_policy_from(p)?,
13470×
            None => None,
1348
        };
134933×
        let tags = match m.get(&3) {
135033×
            Some(t) => tags_from(t)?,
13510×
            None => Vec::new(),
1352
        };
135333×
        Ok((bundle, updates, policy, tags))
135433×
    }
1355
135631×
    pub fn encode_push_response(results: &[RefResult]) -> Vec<u8> {
135731×
        cbor::encode(&Value::map([(
1358
            0,
1359
            Value::Array(
136031×
                results
136131×
                    .iter()
136232×
                    .map(|r| {
136332×
                        Value::map([
136432×
                            (0, Value::Text(r.name.clone())),
136532×
                            (1, Value::Bool(r.ok)),
136632×
                            (2, Value::Text(r.reason.clone())),
136732×
                        ])
136832×
                    })
136931×
                    .collect(),
1370
            ),
1371
        )]))
137231×
    }
137331×
    pub fn decode_push_response(bytes: &[u8]) -> Result<Vec<RefResult>> {
137431×
        let v = cbor::decode(bytes).map_err(ObjectError::from)?;
137531×
        let m = map(&v, "push response")?;
137631×
        let mut out = Vec::new();
137732×
        for r in o::array(field(m, 0, "results")?, "results")? {
137832×
            let rm = map(r, "result")?;
137932×
            out.push(RefResult {
138032×
                name: o::text(field(rm, 0, "name")?, "name")?.to_owned(),
138132×
                ok: field(rm, 1, "ok")?
138232×
                    .as_bool()
138332×
                    .ok_or_else(|| schema("ok: expected bool"))?,
138432×
                reason: o::text(field(rm, 2, "reason")?, "reason")?.to_owned(),
1385
            });
1386
        }
138731×
        Ok(out)
138831×
    }
1389
}
1390
1391
#[cfg(test)]
1392
mod tests {
1393
    use super::*;
1394
    use crate::attest::AttestBody;
1395
    use crate::objects::Hlc;
1396
1397
    #[test]
13981×
    fn wire_round_trips() {
13991×
        let c = crate::objects::tests::sample_change();
14001×
        let sk = crate::identity::SecretKey {
14011×
            ed_seed: [1; 32],
14021×
            ml_seed: [2; 32],
14031×
        };
14041×
        let id = sk.identity("a", "b", 0);
14051×
        let key = id.hash();
14061×
        let sig = sk.sign(crate::identity::Domain::Change, &key, &c.hash());
14071×
        let seal = Attest::seal([3; 16], vec![c.hash()]);
14081×
        let seal_sig = sk.sign(crate::identity::Domain::Attest, &key, &seal.hash());
14091×
        let policy = Policy::single_root([3; 16], id.clone(), 99);
14101×
        let psig = sk.sign(crate::identity::Domain::Policy, &key, &policy.hash());
14111×
        let bundle = Bundle {
14121×
            changes: vec![(c.clone(), vec![sig.clone()])],
14131×
            attests: vec![SignedAttest {
14141×
                attest: seal.clone(),
14151×
                sigs: vec![seal_sig],
14161×
            }],
14171×
            objects: vec![
14181×
                (ObjectType::Identity, id.encode()),
14191×
                (ObjectType::Chunk, b"xyz".to_vec()),
14201×
            ],
14211×
            policies: vec![SignedPolicy {
14221×
                policy: policy.clone(),
14231×
                sigs: vec![psig.clone()],
14241×
            }],
14251×
            hashes: vec![],
14261×
            raw_changes: vec![],
14271×
            certificates: vec![],
14281×
        };
14291×
        let d = wire::decode_bundle(&wire::encode_bundle(&bundle)).unwrap();
14301×
        assert_eq!(
1431
            d.hashes,
14321×
            vec![c.hash()],
1433
            "the receiver hashes what it was sent"
1434
        );
14351×
        assert_eq!(d.changes, bundle.changes);
14361×
        assert_eq!(d.attests, bundle.attests);
14371×
        assert_eq!(d.objects, bundle.objects);
14381×
        assert_eq!(d.policies, bundle.policies);
14391×
        assert!(d.certificates.is_empty());
1440
        // Certificates (keyless, oxygenhub#241) travel as field 4, only
1441
        // when there are any: a bundle without them encodes as before.
14421×
        let plain = wire::encode_bundle(&bundle);
14431×
        let mut with = bundle.clone();
14441×
        let issuer_sk = crate::identity::SecretKey::generate();
14451×
        let issuer = issuer_sk.identity("hub", "h@x", 1);
14461×
        with.certificates.push(crate::cert::SignedCertificate::sign(
14471×
            crate::cert::Certificate {
14481×
                key: id.clone(),
14491×
                issuer: issuer.hash(),
14501×
                subject: "agent:a@b".into(),
14511×
                claims: vec![],
14521×
                scope: crate::identity::Scope::CHANGES,
14531×
                not_before: 1,
14541×
                expires: 2,
14551×
                grant: None,
14561×
            },
14571×
            &issuer,
14581×
            &issuer_sk,
1459
        ));
14601×
        let encoded = wire::encode_bundle(&with);
14611×
        assert_ne!(encoded, plain);
14621×
        assert_eq!(
14631×
            wire::decode_bundle(&encoded).unwrap().certificates,
1464
            with.certificates
1465
        );
14661×
        with.certificates.clear();
14671×
        assert_eq!(wire::encode_bundle(&with), plain);
1468
14691×
        let att = Attest {
14701×
            repo: [3; 16],
14711×
            hlc: Hlc::default(),
14721×
            body: AttestBody::Ref {
14731×
                name: "main".into(),
14741×
                old_state: ObjectRef([1; 32]),
14751×
                new_state: ObjectRef([2; 32]),
14761×
                serial: 4,
14771×
            },
14781×
        };
14791×
        let refs = vec![
14801×
            RemoteRef {
14811×
                name: "main".into(),
14821×
                state: ObjectRef([2; 32]),
14831×
                heads: vec![c.hash()],
14841×
                attestation: Some(SignedAttest {
14851×
                    attest: att.clone(),
14861×
                    sigs: vec![sig.clone()],
14871×
                }),
14881×
                last_serial: Some(4),
14891×
                accepted: None,
14901×
                logged: None,
14911×
                integration: vec![],
14921×
            },
14931×
            RemoteRef {
14941×
                name: "dev".into(),
14951×
                state: ObjectRef([5; 32]),
14961×
                heads: vec![],
14971×
                attestation: None,
14981×
                last_serial: None,
14991×
                accepted: None,
15001×
                logged: None,
15011×
                integration: vec![],
15021×
            },
1503
        ];
15041×
        let tag = TagRef::new("v1".into(), ObjectRef([2; 32]), vec![c.hash()], None);
15051×
        let mut resp = RefsResponse {
15061×
            refs,
15071×
            policy: Some(SignedPolicy {
15081×
                policy: policy.clone(),
15091×
                sigs: vec![psig.clone()],
15101×
            }),
15111×
            tags: vec![tag.clone()],
15121×
            history: vec![SignedPolicy {
15131×
                policy: policy.clone(),
15141×
                sigs: vec![],
15151×
            }],
15161×
            default_bookmark: Some("develop".into()),
15171×
            log: Some("hub.example/log\n2\nroot\n\n- sig\n".into()),
15181×
            witnesses: vec![],
15191×
        };
1520
        // Without integrated times (spec §14.8) nothing is added: an old
1521
        // peer's answer, and what it reads.
15221×
        let old = wire::encode_refs([3; 16], &resp);
15231×
        let back = wire::decode_refs(&old).unwrap().1;
15242×
        assert!(back.witnesses.is_empty() && back.refs.iter().all(|r| r.integration.is_empty()));
15251×
        resp.refs[1].logged = Some(Logged {
15261×
            index: 41,
15271×
            entry: vec![1, 2, 3],
15281×
            proof: vec![[9; 32], [8; 32]],
15291×
        });
15301×
        resp.refs[1].integration = vec![Integration {
15311×
            note: "hub.example/log\n42\nroot\n\n- sig\n".into(),
15321×
            proof: vec![[7; 32]],
15331×
        }];
15341×
        resp.witnesses = vec![("w.example".into(), vec![4, 5, 6])];
15351×
        let new = wire::encode_refs([3; 16], &resp);
15361×
        let (id_back, back) = wire::decode_refs(&new).unwrap();
15371×
        assert_eq!(back.log, resp.log);
15381×
        assert_eq!(back.refs[1].logged, resp.refs[1].logged);
15391×
        assert_eq!(back.refs[1].integration, resp.refs[1].integration);
15401×
        assert_eq!(back.witnesses, resp.witnesses);
15411×
        assert_eq!(back.refs[0].logged, None);
1542
        // The new keys are 7s an old reader never asks for.
15431×
        let crate::cbor::Value::Map(m) = crate::cbor::decode(&new).unwrap() else {
15440×
            panic!()
1545
        };
15461×
        assert!(m.contains_key(&7));
15471×
        assert_eq!(id_back, [3; 16]);
15481×
        assert_eq!(back.refs.len(), 2);
15491×
        assert_eq!(back.refs[0].attestation.as_ref().unwrap().attest, att);
15501×
        assert_eq!(back.refs[1].last_serial, None);
15511×
        assert_eq!(back.policy.as_ref().unwrap().policy, policy);
15521×
        assert_eq!(back.history, resp.history);
15531×
        assert_eq!(back.tags, vec![tag.clone()]);
1554
1555
        // A tag's acceptance and log place (oxygen#129): keys 4 to 6, only
1556
        // when there are any, so a tag without them encodes as before.
15571×
        let crate::cbor::Value::Map(m) = crate::cbor::decode(&new).unwrap() else {
15580×
            panic!()
1559
        };
15601×
        let crate::cbor::Value::Array(tags) = &m[&3] else {
15610×
            panic!()
1562
        };
15631×
        let crate::cbor::Value::Map(plain) = &tags[0] else {
15640×
            panic!()
1565
        };
15661×
        assert_eq!(plain.keys().copied().collect::<Vec<_>>(), vec![0, 1, 2, 3]);
15671×
        let mut full = tag.clone();
15681×
        full.name = "v2".into();
15691×
        full.attestation = Some(SignedAttest {
15701×
            attest: att.clone(),
15711×
            sigs: vec![sig.clone()],
15721×
        });
15731×
        full.accepted = full.attestation.clone();
15741×
        full.logged = Some(Logged {
15751×
            index: 7,
15761×
            entry: vec![4],
15771×
            proof: vec![[3; 32]],
15781×
        });
15791×
        full.integration = vec![Integration {
15801×
            note: "hub.example/log\n8\nroot\n\n- sig\n".into(),
15811×
            proof: vec![],
15821×
        }];
15831×
        resp.tags = vec![full.clone(), tag.clone()];
15841×
        let bytes = wire::encode_refs([3; 16], &resp);
15851×
        assert_eq!(wire::decode_refs(&bytes).unwrap().1.tags, resp.tags);
1586
        // In a push too.
15871×
        let pushed = wire::encode_push(&Bundle::default(), &[], None, &resp.tags);
15881×
        assert_eq!(wire::decode_push(&pushed).unwrap().3, resp.tags);
1589
        // A reader that knows only keys 0 to 3 (oxy 0.5.0 and older, and
1590
        // the runners built with it) reads the same tags from the new answer.
15911×
        let stripped: Vec<TagRef> = resp
15921×
            .tags
15931×
            .iter()
15942×
            .map(|t| {
15952×
                TagRef::new(
15962×
                    t.name.clone(),
15972×
                    t.state,
15982×
                    t.heads.clone(),
15992×
                    t.attestation.clone(),
1600
                )
16012×
            })
16021×
            .collect();
16031×
        assert_eq!(wire::tags_as_0_5_read_them(&bytes).unwrap(), stripped);
1604
16051×
        let (h, w) = wire::decode_negotiate(&wire::encode_negotiate(
16061×
            &[ObjectRef([1; 32])],
16071×
            &[ObjectRef([2; 32])],
16081×
        ))
16091×
        .unwrap();
16101×
        assert_eq!((h, w), (vec![ObjectRef([1; 32])], vec![ObjectRef([2; 32])]));
16111×
        assert_eq!(
16121×
            wire::decode_hashes(&wire::encode_hashes(&[c.hash()])).unwrap(),
16131×
            vec![c.hash()]
1614
        );
16151×
        assert_eq!(
16161×
            wire::decode_fetch(&wire::encode_fetch(&[c.hash()], Some(4096))).unwrap(),
16171×
            (vec![c.hash()], Some(4096))
1618
        );
16191×
        assert_eq!(
16201×
            wire::decode_fetch(&wire::encode_fetch(&[], None)).unwrap(),
16211×
            (vec![], None)
1622
        );
16231×
        assert_eq!(
16241×
            wire::decode_shallow(&wire::encode_shallow(&[c.hash()], 3)).unwrap(),
16251×
            (vec![c.hash()], 3)
1626
        );
1627
        // An old-style fetch request without the filter field still decodes.
16281×
        assert_eq!(
16291×
            wire::decode_fetch(&wire::encode_hashes(&[c.hash()])).unwrap(),
16301×
            (vec![c.hash()], None)
1631
        );
1632
16331×
        let up = RefUpdate {
16341×
            name: "main".into(),
16351×
            old_state: ObjectRef([1; 32]),
16361×
            new_state: ObjectRef([2; 32]),
16371×
            force: true,
16381×
            attestation: Some(SignedAttest {
16391×
                attest: att,
16401×
                sigs: vec![sig],
16411×
            }),
16421×
        };
16431×
        let sp = SignedPolicy {
16441×
            policy,
16451×
            sigs: vec![psig],
16461×
        };
16471×
        let (b2, ups, pol, tags) = wire::decode_push(&wire::encode_push(
16481×
            &bundle,
16491×
            std::slice::from_ref(&up),
16501×
            Some(&sp),
16511×
            std::slice::from_ref(&tag),
16521×
        ))
16531×
        .unwrap();
16541×
        assert_eq!(pol, Some(sp));
16551×
        assert_eq!(tags, vec![tag]);
16561×
        assert_eq!(b2.changes.len(), 1);
16571×
        assert_eq!(ups[0].name, "main");
16581×
        assert!(ups[0].force);
16591×
        assert_eq!(ups[0].attestation, up.attestation);
16601×
        let res = vec![RefResult {
16611×
            name: "main".into(),
16621×
            ok: false,
16631×
            reason: "stale".into(),
16641×
        }];
16651×
        assert_eq!(
16661×
            wire::decode_push_response(&wire::encode_push_response(&res)).unwrap(),
1667
            res
1668
        );
16691×
        assert_eq!(
16701×
            wire::decode_capabilities(&wire::encode_capabilities([7; 16])).unwrap(),
1671
            [7; 16]
1672
        );
16731×
    }
1674
}