| 1 | |
|
| 2 | |
|
| 3 | |
|
| 4 | |
|
| 5 | |
|
| 6 | |
|
| 7 | |
|
| 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 | |
|
| 23 | | #[derive(Clone, Debug, PartialEq, Eq)] |
| 24 | | pub struct SignedAttest { |
| 25 | | pub attest: Attest, |
| 26 | | pub sigs: Vec<Signature>, |
| 27 | | } |
| 28 | |
|
| 29 | |
|
| 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 | | |
| 38 | 1× | pub fn encode(&self) -> Vec<u8> { |
| 39 | 1× | crate::cbor::encode(&wire::policy_value(self)) |
| 40 | 1× | } |
| 41 | 1× | pub fn decode(b: &[u8]) -> Result<SignedPolicy> { |
| 42 | 1× | wire::policy_from( |
| 43 | 1× | &crate::cbor::decode(b).map_err(|e| RepoError::Object(ObjectError::from(e)))?, |
| 44 | | ) |
| 45 | 1× | } |
| 46 | | } |
| 47 | |
|
| 48 | |
|
| 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 | | |
| 55 | | |
| 56 | | pub history: Vec<SignedPolicy>, |
| 57 | | |
| 58 | | pub default_bookmark: Option<String>, |
| 59 | | |
| 60 | | |
| 61 | | |
| 62 | | pub log: Option<String>, |
| 63 | | |
| 64 | | |
| 65 | | |
| 66 | | pub witnesses: Vec<(String, Vec<u8>)>, |
| 67 | | } |
| 68 | |
|
| 69 | |
|
| 70 | |
|
| 71 | |
|
| 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 | |
|
| 80 | |
|
| 81 | |
|
| 82 | | #[derive(Clone, Debug, PartialEq, Eq)] |
| 83 | | pub struct Integration { |
| 84 | | pub note: String, |
| 85 | | pub proof: Vec<[u8; 32]>, |
| 86 | | } |
| 87 | |
|
| 88 | |
|
| 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 | | } |
| 96 | |
|
| 97 | |
|
| 98 | | #[derive(Clone, Debug)] |
| 99 | | pub struct RemoteRef { |
| 100 | | pub name: String, |
| 101 | | pub state: ObjectRef, |
| 102 | | pub heads: Vec<ChangeHash>, |
| 103 | | |
| 104 | | |
| 105 | | pub attestation: Option<SignedAttest>, |
| 106 | | |
| 107 | | |
| 108 | | pub last_serial: Option<u64>, |
| 109 | | |
| 110 | | |
| 111 | | pub accepted: Option<SignedAttest>, |
| 112 | | |
| 113 | | |
| 114 | | pub logged: Option<Logged>, |
| 115 | | |
| 116 | | |
| 117 | | pub integration: Vec<Integration>, |
| 118 | | } |
| 119 | |
|
| 120 | |
|
| 121 | | #[derive(Clone, Debug, Default)] |
| 122 | | pub struct Bundle { |
| 123 | | |
| 124 | | pub changes: Vec<(Change, Vec<Signature>)>, |
| 125 | | |
| 126 | | pub attests: Vec<SignedAttest>, |
| 127 | | |
| 128 | | pub objects: Vec<(ObjectType, Vec<u8>)>, |
| 129 | | |
| 130 | | |
| 131 | | pub policies: Vec<SignedPolicy>, |
| 132 | | |
| 133 | | |
| 134 | | |
| 135 | | pub hashes: Vec<ChangeHash>, |
| 136 | | |
| 137 | | |
| 138 | | |
| 139 | | pub raw_changes: Vec<(Vec<u8>, Vec<Signature>)>, |
| 140 | | |
| 141 | | |
| 142 | | pub certificates: Vec<crate::cert::SignedCertificate>, |
| 143 | | } |
| 144 | |
|
| 145 | | impl Bundle { |
| 146 | 27× | pub fn is_empty(&self) -> bool { |
| 147 | 27× | self.changes.is_empty() && self.attests.is_empty() && self.objects.is_empty() |
| 148 | 27× | } |
| 149 | | } |
| 150 | |
|
| 151 | |
|
| 152 | | #[derive(Clone, Debug)] |
| 153 | | pub struct RefUpdate { |
| 154 | | pub name: String, |
| 155 | | pub old_state: ObjectRef, |
| 156 | | pub new_state: ObjectRef, |
| 157 | | pub force: bool, |
| 158 | | pub attestation: Option<SignedAttest>, |
| 159 | | } |
| 160 | |
|
| 161 | | #[derive(Clone, Debug, PartialEq, Eq)] |
| 162 | | pub struct RefResult { |
| 163 | | pub name: String, |
| 164 | | pub ok: bool, |
| 165 | | pub reason: String, |
| 166 | | } |
| 167 | |
|
| 168 | | pub trait Remote { |
| 169 | | fn repo_id(&self) -> Result<[u8; 16]>; |
| 170 | | fn refs(&self) -> Result<RefsResponse>; |
| 171 | | |
| 172 | | fn negotiate(&self, have: &[ChangeHash], want: &[ChangeHash]) -> Result<Vec<ChangeHash>>; |
| 173 | | |
| 174 | | |
| 175 | | fn fetch(&self, changes: &[ChangeHash], max_blob: Option<u64>) -> Result<Bundle>; |
| 176 | | |
| 177 | | |
| 178 | | fn objects(&self, refs: &[ObjectRef]) -> Result<Vec<(ObjectType, Vec<u8>)>>; |
| 179 | | |
| 180 | | |
| 181 | | fn checkpoint(&self, heads: &[ChangeHash]) -> Result<Bundle>; |
| 182 | | |
| 183 | | fn shallow(&self, heads: &[ChangeHash], depth: u32) -> Result<Vec<ChangeHash>>; |
| 184 | | |
| 185 | | |
| 186 | | |
| 187 | | fn push( |
| 188 | | &self, |
| 189 | | bundle: Bundle, |
| 190 | | updates: Vec<RefUpdate>, |
| 191 | | policy: Option<SignedPolicy>, |
| 192 | | tags: Vec<TagRef>, |
| 193 | | ) -> Result<Vec<RefResult>>; |
| 194 | | } |
| 195 | |
|
| 196 | |
|
| 197 | |
|
| 198 | |
|
| 199 | | pub struct LocalRemote { |
| 200 | | pub repo: Repo, |
| 201 | | |
| 202 | | |
| 203 | | pub claimed_id: Option<[u8; 16]>, |
| 204 | | } |
| 205 | |
|
| 206 | | impl LocalRemote { |
| 207 | 1079× | pub fn open(path: &Path) -> Result<LocalRemote> { |
| 208 | | Ok(LocalRemote { |
| 209 | 1079× | repo: Repo::open(path)?, |
| 210 | 1079× | claimed_id: None, |
| 211 | | }) |
| 212 | 1079× | } |
| 213 | | } |
| 214 | |
|
| 215 | | impl Remote for LocalRemote { |
| 216 | 848× | fn repo_id(&self) -> Result<[u8; 16]> { |
| 217 | 848× | self.repo.id() |
| 218 | 848× | } |
| 219 | 847× | fn refs(&self) -> Result<RefsResponse> { |
| 220 | 847× | self.repo.remote_refs() |
| 221 | 847× | } |
| 222 | 319× | fn negotiate(&self, have: &[ChangeHash], want: &[ChangeHash]) -> Result<Vec<ChangeHash>> { |
| 223 | 319× | self.repo.negotiate(have, want) |
| 224 | 319× | } |
| 225 | 322× | fn fetch(&self, changes: &[ChangeHash], max_blob: Option<u64>) -> Result<Bundle> { |
| 226 | 322× | self.repo.bundle_raw_for(changes, max_blob) |
| 227 | 322× | } |
| 228 | 3× | fn objects(&self, refs: &[ObjectRef]) -> Result<Vec<(ObjectType, Vec<u8>)>> { |
| 229 | 3× | self.repo.objects_for(refs) |
| 230 | 3× | } |
| 231 | 1× | fn checkpoint(&self, heads: &[ChangeHash]) -> Result<Bundle> { |
| 232 | 1× | self.repo.checkpoint_bundle_for(heads) |
| 233 | 1× | } |
| 234 | 3× | fn shallow(&self, heads: &[ChangeHash], depth: u32) -> Result<Vec<ChangeHash>> { |
| 235 | 3× | self.repo.shallow_changes(heads, depth) |
| 236 | 3× | } |
| 237 | 249× | fn push( |
| 238 | 249× | &self, |
| 239 | 249× | bundle: Bundle, |
| 240 | 249× | updates: Vec<RefUpdate>, |
| 241 | 249× | policy: Option<SignedPolicy>, |
| 242 | 249× | tags: Vec<TagRef>, |
| 243 | 249× | ) -> Result<Vec<RefResult>> { |
| 244 | 249× | if self.repo.is_unbound() { |
| 245 | 11× | match self.claimed_id { |
| 246 | 11× | Some(id) => self.repo.bind_id(id)?, |
| 247 | | None => { |
| 248 | 0× | return Err(RepoError::Msg( |
| 249 | 0× | "the remote is unbound and this client did not say which repository it is" |
| 250 | 0× | .into(), |
| 251 | 0× | )) |
| 252 | | } |
| 253 | | } |
| 254 | 238× | } |
| 255 | 249× | self.repo.receive_push(bundle, updates, policy, tags) |
| 256 | 249× | } |
| 257 | | } |
| 258 | |
|
| 259 | |
|
| 260 | |
|
| 261 | |
|
| 262 | | #[derive(Clone, Debug, Default)] |
| 263 | | pub struct RemoteOptions { |
| 264 | | |
| 265 | | pub token: Option<String>, |
| 266 | | |
| 267 | | |
| 268 | | pub ca: Option<PathBuf>, |
| 269 | | |
| 270 | | |
| 271 | | pub repo_id: Option<[u8; 16]>, |
| 272 | | |
| 273 | | |
| 274 | | |
| 275 | | |
| 276 | | pub cache_dir: Option<PathBuf>, |
| 277 | | |
| 278 | | |
| 279 | | |
| 280 | | |
| 281 | | pub fallback_tokens: Vec<String>, |
| 282 | | } |
| 283 | |
|
| 284 | |
|
| 285 | |
|
| 286 | |
|
| 287 | | pub type StoreOpener = |
| 288 | | fn(&str, &RemoteOptions) -> Option<crate::strata::Result<Box<dyn crate::strata::Store>>>; |
| 289 | |
|
| 290 | | static STORE_OPENERS: Mutex<Vec<StoreOpener>> = Mutex::new(Vec::new()); |
| 291 | |
|
| 292 | 155× | pub fn register_store_opener(opener: StoreOpener) { |
| 293 | 155× | STORE_OPENERS |
| 294 | 155× | .lock() |
| 295 | 155× | .unwrap_or_else(|p| p.into_inner()) |
| 296 | 155× | .push(opener); |
| 297 | 155× | } |
| 298 | |
|
| 299 | |
|
| 300 | 1139× | pub fn open_store( |
| 301 | 1139× | url: &str, |
| 302 | 1139× | options: &RemoteOptions, |
| 303 | 1139× | ) -> Option<crate::strata::Result<Box<dyn crate::strata::Store>>> { |
| 304 | 1139× | if let Some(path) = url.strip_prefix("dir://") { |
| 305 | | return Some( |
| 306 | 59× | crate::strata::LocalStore::open(path) |
| 307 | 59× | .map(|s| Box::new(s) as Box<dyn crate::strata::Store>), |
| 308 | | ); |
| 309 | 1080× | } |
| 310 | 1080× | let openers = STORE_OPENERS.lock().unwrap_or_else(|p| p.into_inner()); |
| 311 | 1080× | openers.iter().find_map(|open| open(url, options)) |
| 312 | 1139× | } |
| 313 | |
|
| 314 | |
|
| 315 | | pub const REPO_ID_HEADER: &str = "Oxy-Repo-Id"; |
| 316 | |
|
| 317 | |
|
| 318 | | pub const UNBOUND_ID: [u8; 16] = [0; 16]; |
| 319 | |
|
| 320 | |
|
| 321 | | pub struct HttpRemote { |
| 322 | | base: String, |
| 323 | | |
| 324 | | token: Mutex<Option<String>>, |
| 325 | | fallbacks: Mutex<Vec<String>>, |
| 326 | | repo_id: Option<[u8; 16]>, |
| 327 | | agent: ureq::Agent, |
| 328 | | } |
| 329 | |
|
| 330 | |
|
| 331 | |
|
| 332 | 151× | pub fn tls_client_config(ca: Option<&Path>) -> Result<Arc<rustls::ClientConfig>> { |
| 333 | 151× | let mut roots = rustls::RootCertStore::empty(); |
| 334 | 151× | roots.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned()); |
| 335 | 151× | if let Some(path) = ca { |
| 336 | 70× | let pem = std::fs::read(path) |
| 337 | 70× | .map_err(|e| RepoError::Msg(format!("reading CA file {}: {e}", path.display())))?; |
| 338 | 70× | let certs = rustls_pemfile::certs(&mut pem.as_slice()) |
| 339 | 70× | .collect::<std::result::Result<Vec<_>, _>>() |
| 340 | 70× | .map_err(|e| RepoError::Msg(format!("parsing CA file {}: {e}", path.display())))?; |
| 341 | 70× | if certs.is_empty() { |
| 342 | 0× | return Err(RepoError::Msg(format!( |
| 343 | 0× | "CA file {} holds no certificates", |
| 344 | 0× | path.display() |
| 345 | 0× | ))); |
| 346 | 70× | } |
| 347 | 70× | for c in certs { |
| 348 | 70× | roots |
| 349 | 70× | .add(c) |
| 350 | 70× | .map_err(|e| RepoError::Msg(format!("CA file {}: {e}", path.display())))?; |
| 351 | | } |
| 352 | 81× | } |
| 353 | 151× | let cfg = rustls::ClientConfig::builder_with_provider(Arc::new( |
| 354 | 151× | rustls::crypto::ring::default_provider(), |
| 355 | | )) |
| 356 | 151× | .with_safe_default_protocol_versions() |
| 357 | 151× | .map_err(|e| RepoError::Msg(e.to_string()))? |
| 358 | 151× | .with_root_certificates(roots) |
| 359 | 151× | .with_no_client_auth(); |
| 360 | 151× | Ok(Arc::new(cfg)) |
| 361 | 151× | } |
| 362 | |
|
| 363 | | impl HttpRemote { |
| 364 | 147× | pub fn new(base: &str, options: &RemoteOptions) -> Result<HttpRemote> { |
| 365 | 147× | refuse_plain_token(base, options)?; |
| 366 | 147× | let agent = ureq::AgentBuilder::new() |
| 367 | 147× | .tls_config(tls_client_config(options.ca.as_deref())?) |
| 368 | 147× | .build(); |
| 369 | 147× | Ok(HttpRemote { |
| 370 | 147× | base: base.trim_end_matches('/').to_string(), |
| 371 | 147× | token: Mutex::new(options.token.clone()), |
| 372 | 147× | fallbacks: Mutex::new(options.fallback_tokens.iter().rev().cloned().collect()), |
| 373 | 147× | repo_id: options.repo_id, |
| 374 | 147× | agent, |
| 375 | 147× | }) |
| 376 | 147× | } |
| 377 | |
|
| 378 | | |
| 379 | | |
| 380 | 370× | fn call(&self, post: bool, endpoint: &str, body: Option<&[u8]>) -> Result<Vec<u8>> { |
| 381 | | loop { |
| 382 | 371× | let token = self.token.lock().unwrap_or_else(|p| p.into_inner()).clone(); |
| 383 | 371× | match self.call_once(post, endpoint, body, token.as_deref()) { |
| 384 | 11× | Err(RepoError::Msg(m)) if token.is_some() && refused(&m) => { |
| 385 | 3× | let next = self |
| 386 | 3× | .fallbacks |
| 387 | 3× | .lock() |
| 388 | 3× | .unwrap_or_else(|p| p.into_inner()) |
| 389 | 3× | .pop(); |
| 390 | 3× | let Some(next) = next else { |
| 391 | 2× | return Err(RepoError::Msg(m)); |
| 392 | | }; |
| 393 | 1× | crate::credentials::warn_once(&format!( |
| 394 | 1× | "{}: the stored token was refused; using the one an enclosing checkout has for this hub", |
| 395 | 1× | self.base |
| 396 | 1× | )); |
| 397 | 1× | *self.token.lock().unwrap_or_else(|p| p.into_inner()) = Some(next); |
| 398 | | } |
| 399 | 368× | other => return other, |
| 400 | | } |
| 401 | | } |
| 402 | 370× | } |
| 403 | |
|
| 404 | 371× | fn call_once( |
| 405 | 371× | &self, |
| 406 | 371× | post: bool, |
| 407 | 371× | endpoint: &str, |
| 408 | 371× | body: Option<&[u8]>, |
| 409 | 371× | token: Option<&str>, |
| 410 | 371× | ) -> Result<Vec<u8>> { |
| 411 | 371× | let url = format!("{}/oxy/v1/{endpoint}", self.base); |
| 412 | 371× | let mut req = if post { |
| 413 | 128× | self.agent.post(&url) |
| 414 | | } else { |
| 415 | 243× | self.agent.get(&url) |
| 416 | | }; |
| 417 | 371× | req = req.set("Accept", CONTENT_TYPE); |
| 418 | 371× | if let Some(t) = token { |
| 419 | 22× | req = req.set("Authorization", &format!("Bearer {t}")); |
| 420 | 349× | } |
| 421 | 371× | if let Some(id) = &self.repo_id { |
| 422 | 346× | req = req.set(REPO_ID_HEADER, &hex::encode(id)); |
| 423 | 346× | } |
| 424 | 371× | let resp = match body { |
| 425 | 128× | Some(b) => req.set("Content-Type", CONTENT_TYPE).send_bytes(b), |
| 426 | 243× | None => req.call(), |
| 427 | | }; |
| 428 | 11× | match resp { |
| 429 | 360× | Ok(r) => { |
| 430 | 360× | let mut out = Vec::new(); |
| 431 | 360× | r.into_reader() |
| 432 | 360× | .read_to_end(&mut out) |
| 433 | 360× | .map_err(|e| RepoError::Msg(format!("{url}: {e}")))?; |
| 434 | 360× | Ok(out) |
| 435 | | } |
| 436 | 8× | Err(ureq::Error::Status(code, r)) => { |
| 437 | 8× | let text = r.into_string().unwrap_or_default(); |
| 438 | 8× | let msg = format!("{url}: HTTP {code}: {}", text.trim()); |
| 439 | 8× | Err(RepoError::Msg(with_hint(msg))) |
| 440 | | } |
| 441 | | |
| 442 | 3× | Err(e) => Err(RepoError::Msg(with_hint(e.to_string()))), |
| 443 | | } |
| 444 | 371× | } |
| 445 | | } |
| 446 | |
|
| 447 | |
|
| 448 | |
|
| 449 | |
|
| 450 | 4× | fn refused(message: &str) -> bool { |
| 451 | 4× | [": HTTP 401", ": HTTP 403", ": HTTP 404"] |
| 452 | 4× | .iter() |
| 453 | 6× | .any(|c| message.contains(c)) |
| 454 | 4× | } |
| 455 | |
|
| 456 | |
|
| 457 | |
|
| 458 | 147× | fn refuse_plain_token(url: &str, options: &RemoteOptions) -> Result<()> { |
| 459 | 147× | if options.token.is_some() && !crate::credentials::token_allowed(url) { |
| 460 | 0× | return Err(RepoError::Msg(format!( |
| 461 | 0× | "{url}: refusing to send a token over plain http; use https" |
| 462 | 0× | ))); |
| 463 | 147× | } |
| 464 | 147× | Ok(()) |
| 465 | 147× | } |
| 466 | |
|
| 467 | |
|
| 468 | 19× | pub fn hint_for(message: &str) -> Option<&'static str> { |
| 469 | 19× | let m = message.to_ascii_lowercase(); |
| 470 | 19× | let hint = if m.contains("http 401") { |
| 471 | 6× | "the hub needs you signed in, or did not accept the token: run `oxy auth login HUB` (pushing needs repo:write)" |
| 472 | 13× | } else if m.contains("http 403") { |
| 473 | 1× | "the token or account lacks permission: pushing needs a token with repo:write and write access to the repository" |
| 474 | 12× | } else if m.contains("http 404") { |
| 475 | 4× | "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`)" |
| 476 | 8× | } else if m.contains("unknownissuer") |
| 477 | 6× | || m.contains("unknown issuer") |
| 478 | 6× | || m.contains("certificate") |
| 479 | 5× | || m.contains("invalidcertificate") |
| 480 | | { |
| 481 | 3× | "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`" |
| 482 | 5× | } else if m.contains("connection refused") { |
| 483 | 3× | "nothing is listening there: check the URL and port, and that the server is running" |
| 484 | 2× | } else if m.contains("dns") |
| 485 | 1× | || m.contains("failed to lookup") |
| 486 | 1× | || m.contains("name or service not known") |
| 487 | | { |
| 488 | 1× | "the host name does not resolve: check the URL" |
| 489 | 1× | } else if m.contains("timed out") || m.contains("timeout") { |
| 490 | 0× | "the server did not answer in time: check the network, or try again" |
| 491 | | } else { |
| 492 | 1× | return None; |
| 493 | | }; |
| 494 | 18× | Some(hint) |
| 495 | 19× | } |
| 496 | |
|
| 497 | |
|
| 498 | 11× | pub fn with_hint(message: String) -> String { |
| 499 | 11× | match hint_for(&message) { |
| 500 | 11× | Some(h) => format!("{message}\n hint: {h}"), |
| 501 | 0× | None => message, |
| 502 | | } |
| 503 | 11× | } |
| 504 | |
|
| 505 | |
|
| 506 | |
|
| 507 | |
|
| 508 | 0× | pub fn http_json( |
| 509 | 0× | method: &str, |
| 510 | 0× | url: &str, |
| 511 | 0× | body: Option<&str>, |
| 512 | 0× | options: &RemoteOptions, |
| 513 | 0× | ) -> Result<(u16, String)> { |
| 514 | 0× | refuse_plain_token(url, options)?; |
| 515 | 0× | let agent = ureq::AgentBuilder::new() |
| 516 | 0× | .tls_config(tls_client_config(options.ca.as_deref())?) |
| 517 | 0× | .timeout(std::time::Duration::from_secs(60)) |
| 518 | 0× | .build(); |
| 519 | 0× | let mut req = agent.request(method, url).set("Accept", "application/json"); |
| 520 | 0× | if let Some(t) = &options.token { |
| 521 | 0× | req = req.set("Authorization", &format!("Bearer {t}")); |
| 522 | 0× | } |
| 523 | 0× | let resp = match body { |
| 524 | 0× | Some(b) => req.set("Content-Type", "application/json").send_string(b), |
| 525 | 0× | None => req.call(), |
| 526 | | }; |
| 527 | 0× | match resp { |
| 528 | 0× | Ok(r) => { |
| 529 | 0× | let code = r.status(); |
| 530 | 0× | Ok((code, r.into_string().unwrap_or_default())) |
| 531 | | } |
| 532 | 0× | Err(ureq::Error::Status(code, r)) => Ok((code, r.into_string().unwrap_or_default())), |
| 533 | 0× | Err(e) => Err(RepoError::Msg(with_hint(e.to_string()))), |
| 534 | | } |
| 535 | 0× | } |
| 536 | |
|
| 537 | |
|
| 538 | |
|
| 539 | 0× | pub fn http_get(url: &str, options: &RemoteOptions) -> Result<Vec<u8>> { |
| 540 | 0× | refuse_plain_token(url, options)?; |
| 541 | 0× | let agent = ureq::AgentBuilder::new() |
| 542 | 0× | .tls_config(tls_client_config(options.ca.as_deref())?) |
| 543 | 0× | .build(); |
| 544 | 0× | let mut req = agent.get(url).set("Accept", "application/json"); |
| 545 | 0× | if let Some(t) = &options.token { |
| 546 | 0× | req = req.set("Authorization", &format!("Bearer {t}")); |
| 547 | 0× | } |
| 548 | 0× | match req.call() { |
| 549 | 0× | Ok(r) => { |
| 550 | 0× | let mut out = Vec::new(); |
| 551 | 0× | r.into_reader() |
| 552 | 0× | .read_to_end(&mut out) |
| 553 | 0× | .map_err(|e| RepoError::Msg(format!("{url}: {e}")))?; |
| 554 | 0× | Ok(out) |
| 555 | | } |
| 556 | 0× | Err(ureq::Error::Status(code, r)) => { |
| 557 | 0× | let text = r.into_string().unwrap_or_default(); |
| 558 | 0× | Err(RepoError::Msg(with_hint(format!( |
| 559 | 0× | "{url}: HTTP {code}: {}", |
| 560 | 0× | text.trim() |
| 561 | 0× | )))) |
| 562 | | } |
| 563 | | |
| 564 | 0× | Err(e) => Err(RepoError::Msg(with_hint(e.to_string()))), |
| 565 | | } |
| 566 | 0× | } |
| 567 | |
|
| 568 | | impl Remote for HttpRemote { |
| 569 | 126× | fn repo_id(&self) -> Result<[u8; 16]> { |
| 570 | 126× | wire::decode_capabilities(&self.call(false, "capabilities", None)?) |
| 571 | 126× | } |
| 572 | 117× | fn refs(&self) -> Result<RefsResponse> { |
| 573 | 117× | Ok(wire::decode_refs(&self.call(false, "refs", None)?)?.1) |
| 574 | 117× | } |
| 575 | 46× | fn negotiate(&self, have: &[ChangeHash], want: &[ChangeHash]) -> Result<Vec<ChangeHash>> { |
| 576 | 46× | wire::decode_hashes(&self.call( |
| 577 | | true, |
| 578 | 46× | "negotiate", |
| 579 | 46× | Some(&wire::encode_negotiate(have, want)), |
| 580 | 0× | )?) |
| 581 | 46× | } |
| 582 | 46× | fn fetch(&self, changes: &[ChangeHash], max_blob: Option<u64>) -> Result<Bundle> { |
| 583 | 46× | wire::decode_bundle(&self.call( |
| 584 | | true, |
| 585 | 46× | "fetch", |
| 586 | 46× | Some(&wire::encode_fetch(changes, max_blob)), |
| 587 | 0× | )?) |
| 588 | 46× | } |
| 589 | 1× | fn objects(&self, refs: &[ObjectRef]) -> Result<Vec<(ObjectType, Vec<u8>)>> { |
| 590 | | Ok( |
| 591 | 1× | wire::decode_bundle(&self.call(true, "objects", Some(&wire::encode_hashes(refs)))?)? |
| 592 | | .objects, |
| 593 | | ) |
| 594 | 1× | } |
| 595 | 0× | fn checkpoint(&self, heads: &[ChangeHash]) -> Result<Bundle> { |
| 596 | 0× | wire::decode_bundle(&self.call(true, "checkpoint", Some(&wire::encode_hashes(heads)))?) |
| 597 | 0× | } |
| 598 | 0× | fn shallow(&self, heads: &[ChangeHash], depth: u32) -> Result<Vec<ChangeHash>> { |
| 599 | 0× | wire::decode_hashes(&self.call( |
| 600 | | true, |
| 601 | 0× | "shallow", |
| 602 | 0× | Some(&wire::encode_shallow(heads, depth)), |
| 603 | 0× | )?) |
| 604 | 0× | } |
| 605 | 34× | fn push( |
| 606 | 34× | &self, |
| 607 | 34× | bundle: Bundle, |
| 608 | 34× | updates: Vec<RefUpdate>, |
| 609 | 34× | policy: Option<SignedPolicy>, |
| 610 | 34× | tags: Vec<TagRef>, |
| 611 | 34× | ) -> Result<Vec<RefResult>> { |
| 612 | 34× | wire::decode_push_response(&self.call( |
| 613 | | true, |
| 614 | 34× | "push", |
| 615 | 34× | Some(&wire::encode_push( |
| 616 | 34× | &bundle, |
| 617 | 34× | &updates, |
| 618 | 34× | policy.as_ref(), |
| 619 | 34× | &tags, |
| 620 | 34× | )), |
| 621 | 4× | )?) |
| 622 | 34× | } |
| 623 | | } |
| 624 | |
|
| 625 | |
|
| 626 | |
|
| 627 | |
|
| 628 | 262× | pub fn stored_url(url: &str) -> String { |
| 629 | | |
| 630 | | |
| 631 | 262× | let (prefix, path) = match (url.strip_prefix("file://"), url.strip_prefix("dir://")) { |
| 632 | 1× | (Some(p), _) => ("file://", p), |
| 633 | 11× | (_, Some(p)) => ("dir://", p), |
| 634 | 250× | _ if url.contains("://") => return url.to_string(), |
| 635 | 227× | _ => ("", url), |
| 636 | | }; |
| 637 | 239× | match std::path::absolute(path) { |
| 638 | 239× | Ok(abs) => format!("{prefix}{}", abs.display()), |
| 639 | 0× | Err(_) => url.to_string(), |
| 640 | | } |
| 641 | 262× | } |
| 642 | |
|
| 643 | |
|
| 644 | |
|
| 645 | 1274× | pub fn open_remote(url: &str, options: &RemoteOptions) -> Result<Box<dyn Remote>> { |
| 646 | 1274× | if url.starts_with("http://") || url.starts_with("https://") { |
| 647 | 147× | return Ok(Box::new(HttpRemote::new(url, options)?)); |
| 648 | 1127× | } |
| 649 | 1127× | if let Some(store) = open_store(url, options) { |
| 650 | 48× | return crate::repo::strata::open_store_remote(store?, options); |
| 651 | 1079× | } |
| 652 | 1079× | let path = url.strip_prefix("file://").unwrap_or(url); |
| 653 | 1079× | if path.contains("://") { |
| 654 | 0× | return Err(RepoError::Msg(format!("unsupported remote URL {url:?}"))); |
| 655 | 1079× | } |
| 656 | 1079× | let mut local = LocalRemote::open(Path::new(path))?; |
| 657 | 1079× | local.claimed_id = options.repo_id; |
| 658 | 1079× | Ok(Box::new(local)) |
| 659 | 1274× | } |
| 660 | |
|
| 661 | |
|
| 662 | |
|
| 663 | |
|
| 664 | | pub mod wire { |
| 665 | | use super::*; |
| 666 | |
|
| 667 | 0× | fn schema(msg: &str) -> RepoError { |
| 668 | 0× | RepoError::Object(ObjectError::Schema(msg.into())) |
| 669 | 0× | } |
| 670 | 150× | fn sigs_value(sigs: &[Signature]) -> Value { |
| 671 | 150× | Value::Array(sigs.iter().map(|s| s.to_value()).collect()) |
| 672 | 150× | } |
| 673 | 145× | fn sigs_from(v: &Value) -> Result<Vec<Signature>> { |
| 674 | 145× | Ok(o::array(v, "signatures")? |
| 675 | 145× | .iter() |
| 676 | 145× | .map(Signature::from_value) |
| 677 | 145× | .collect::<std::result::Result<Vec<_>, _>>()?) |
| 678 | 145× | } |
| 679 | 351× | fn hashes_value(hs: &[ObjectRef]) -> Value { |
| 680 | 493× | Value::Array(hs.iter().map(|h| Value::Bytes(h.0.to_vec())).collect()) |
| 681 | 351× | } |
| 682 | 410× | fn hashes_from(v: &Value) -> Result<Vec<ObjectRef>> { |
| 683 | 410× | Ok(o::array(v, "hashes")? |
| 684 | 410× | .iter() |
| 685 | 553× | .map(|h| o::oref(h, "hash")) |
| 686 | 410× | .collect::<std::result::Result<Vec<_>, _>>()?) |
| 687 | 410× | } |
| 688 | 25× | fn attest_value(sa: &SignedAttest) -> Value { |
| 689 | 25× | Value::Array(vec![Value::Bytes(sa.attest.encode()), sigs_value(&sa.sigs)]) |
| 690 | 25× | } |
| 691 | 39× | fn attest_from(v: &Value) -> Result<SignedAttest> { |
| 692 | 39× | let a = o::array(v, "signed attest")?; |
| 693 | 39× | if a.len() != 2 { |
| 694 | 0× | return Err(schema("signed attest: expected [attest, sigs]")); |
| 695 | 39× | } |
| 696 | | Ok(SignedAttest { |
| 697 | 39× | attest: Attest::decode(o::bytes(&a[0], "attest")?)?, |
| 698 | 39× | sigs: sigs_from(&a[1])?, |
| 699 | | }) |
| 700 | 39× | } |
| 701 | 194× | fn opt_attest_value(sa: &Option<SignedAttest>) -> Value { |
| 702 | 194× | sa.as_ref().map(attest_value).unwrap_or(Value::Null) |
| 703 | 194× | } |
| 704 | 249× | fn opt_attest_from(v: &Value) -> Result<Option<SignedAttest>> { |
| 705 | 249× | if v.is_null() { |
| 706 | 221× | Ok(None) |
| 707 | | } else { |
| 708 | 28× | attest_from(v).map(Some) |
| 709 | | } |
| 710 | 249× | } |
| 711 | | |
| 712 | | |
| 713 | 12× | pub fn policy_value(sp: &SignedPolicy) -> Value { |
| 714 | 12× | Value::Array(vec![Value::Bytes(sp.policy.encode()), sigs_value(&sp.sigs)]) |
| 715 | 12× | } |
| 716 | 10× | pub fn policy_from(v: &Value) -> Result<SignedPolicy> { |
| 717 | 10× | let a = o::array(v, "signed policy")?; |
| 718 | 10× | if a.len() != 2 { |
| 719 | 0× | return Err(schema("signed policy: expected [policy, sigs]")); |
| 720 | 10× | } |
| 721 | | Ok(SignedPolicy { |
| 722 | 10× | policy: Policy::decode(o::bytes(&a[0], "policy")?)?, |
| 723 | 10× | sigs: sigs_from(&a[1])?, |
| 724 | | }) |
| 725 | 10× | } |
| 726 | 181× | fn opt_policy_value(sp: Option<&SignedPolicy>) -> Value { |
| 727 | 181× | sp.map(policy_value).unwrap_or(Value::Null) |
| 728 | 181× | } |
| 729 | 220× | fn opt_policy_from(v: &Value) -> Result<Option<SignedPolicy>> { |
| 730 | 220× | if v.is_null() { |
| 731 | 216× | Ok(None) |
| 732 | | } else { |
| 733 | 4× | policy_from(v).map(Some) |
| 734 | | } |
| 735 | 220× | } |
| 736 | 905× | fn map<'a>(v: &'a Value, what: &str) -> Result<&'a o::Map> { |
| 737 | 905× | Ok(o::map(v, what)?) |
| 738 | 905× | } |
| 739 | 2544× | fn field<'a>(m: &'a o::Map, k: u64, what: &str) -> Result<&'a Value> { |
| 740 | 2544× | Ok(o::field(m, k, what)?) |
| 741 | 2544× | } |
| 742 | |
|
| 743 | | |
| 744 | | |
| 745 | | |
| 746 | 117× | pub fn bundle_value(b: &Bundle) -> Value { |
| 747 | 117× | let mut changes = Vec::with_capacity(b.raw_changes.len() + b.changes.len()); |
| 748 | | |
| 749 | | |
| 750 | 117× | for (bytes, s) in &b.raw_changes { |
| 751 | 0× | changes.push(Value::Array(vec![ |
| 752 | 0× | Value::Bytes(bytes.clone()), |
| 753 | 0× | sigs_value(s), |
| 754 | 0× | ])); |
| 755 | 0× | } |
| 756 | 117× | let mut texts: Vec<(ObjectType, Vec<u8>)> = Vec::new(); |
| 757 | 117× | let mut listed: Option<std::collections::HashSet<ObjectRef>> = None; |
| 758 | 117× | for (c, s) in &b.changes { |
| 759 | 113× | let (bytes, stored) = c.encode_parts(); |
| 760 | 113× | for t in stored { |
| 761 | 0× | let listed = listed.get_or_insert_with(|| { |
| 762 | 0× | b.objects |
| 763 | 0× | .iter() |
| 764 | 0× | .map(|(ty, body)| crate::hash::hash_object(*ty, body)) |
| 765 | 0× | .collect() |
| 766 | 0× | }); |
| 767 | 0× | if !listed.insert(t.blob.hash()) { |
| 768 | 0× | continue; |
| 769 | 0× | } |
| 770 | 0× | for chunk in crate::chunk::chunks(&t.content) { |
| 771 | 0× | if listed.insert(crate::hash::hash_object(ObjectType::Chunk, chunk)) { |
| 772 | 0× | texts.push((ObjectType::Chunk, chunk.to_vec())); |
| 773 | 0× | } |
| 774 | | } |
| 775 | 0× | texts.push((ObjectType::Blob, t.blob.encode())); |
| 776 | | } |
| 777 | 113× | changes.push(Value::Array(vec![Value::Bytes(bytes), sigs_value(s)])); |
| 778 | | } |
| 779 | 117× | let mut v = Value::map([ |
| 780 | 117× | (0, Value::Array(changes)), |
| 781 | 117× | ( |
| 782 | 117× | 1, |
| 783 | 117× | Value::Array(b.attests.iter().map(attest_value).collect()), |
| 784 | 117× | ), |
| 785 | | ( |
| 786 | | 2, |
| 787 | | Value::Array( |
| 788 | 117× | b.objects |
| 789 | 117× | .iter() |
| 790 | 117× | .chain(&texts) |
| 791 | 117× | .map(|(t, body)| { |
| 792 | 88× | Value::Array(vec![ |
| 793 | 88× | Value::Text(t.name().into()), |
| 794 | 88× | Value::Bytes(body.clone()), |
| 795 | 88× | ]) |
| 796 | 88× | }) |
| 797 | 117× | .collect(), |
| 798 | | ), |
| 799 | | ), |
| 800 | 117× | ( |
| 801 | 117× | 3, |
| 802 | 117× | Value::Array(b.policies.iter().map(policy_value).collect()), |
| 803 | 117× | ), |
| 804 | | ]); |
| 805 | | |
| 806 | 117× | if !b.certificates.is_empty() { |
| 807 | 1× | if let Value::Map(m) = &mut v { |
| 808 | 1× | m.insert( |
| 809 | | 4, |
| 810 | | Value::Array( |
| 811 | 1× | b.certificates |
| 812 | 1× | .iter() |
| 813 | 1× | .map(|c| Value::Bytes(c.encode())) |
| 814 | 1× | .collect(), |
| 815 | | ), |
| 816 | | ); |
| 817 | 0× | } |
| 818 | 116× | } |
| 819 | 117× | v |
| 820 | 117× | } |
| 821 | |
|
| 822 | 107× | pub fn bundle_from_value(v: &Value) -> Result<Bundle> { |
| 823 | 107× | let m = map(v, "bundle")?; |
| 824 | 107× | let mut b = Bundle::default(); |
| 825 | 107× | for ob in o::array(field(m, 2, "objects")?, "objects")? { |
| 826 | 77× | let pair = o::array(ob, "object")?; |
| 827 | 77× | if pair.len() != 2 { |
| 828 | 0× | return Err(schema("object: expected [type, body]")); |
| 829 | 77× | } |
| 830 | 77× | let ty = ObjectType::from_name(o::text(&pair[0], "object type")?) |
| 831 | 77× | .ok_or_else(|| schema("unknown object type"))?; |
| 832 | 77× | b.objects |
| 833 | 77× | .push((ty, o::bytes(&pair[1], "object body")?.to_vec())); |
| 834 | | } |
| 835 | | |
| 836 | 107× | let mut by_ref: Option<std::collections::HashMap<ObjectRef, usize>> = None; |
| 837 | 107× | for c in o::array(field(m, 0, "changes")?, "changes")? { |
| 838 | 96× | let pair = o::array(c, "change entry")?; |
| 839 | 96× | if pair.len() != 2 { |
| 840 | 0× | return Err(schema("change entry: expected [change, sigs]")); |
| 841 | 96× | } |
| 842 | 96× | let encoded = o::bytes(&pair[0], "change")?; |
| 843 | 96× | b.hashes |
| 844 | 96× | .push(crate::hash::hash_object(ObjectType::Change, encoded)); |
| 845 | 96× | let change = Change::decode_with(encoded, &mut |text, count, form| { |
| 846 | 0× | let by_ref = by_ref.get_or_insert_with(|| { |
| 847 | 0× | b.objects |
| 848 | 0× | .iter() |
| 849 | 0× | .enumerate() |
| 850 | 0× | .map(|(i, (ty, body))| (crate::hash::hash_object(*ty, body), i)) |
| 851 | 0× | .collect() |
| 852 | 0× | }); |
| 853 | 0× | let get = |
| 854 | 0× | |r: &ObjectRef, want: ObjectType| match by_ref.get(r).map(|i| &b.objects[*i]) { |
| 855 | 0× | Some((ty, body)) if *ty == want => Ok(body), |
| 856 | 0× | _ => Err(ObjectError::Schema(format!( |
| 857 | 0× | "the bundle lacks {} {}", |
| 858 | 0× | want.name(), |
| 859 | 0× | r.short(12) |
| 860 | 0× | ))), |
| 861 | 0× | }; |
| 862 | 0× | let blob = crate::objects::Blob::decode(get(text, ObjectType::Blob)?)?; |
| 863 | 0× | let mut content = Vec::with_capacity(blob.length as usize); |
| 864 | 0× | for chunk in &blob.chunks { |
| 865 | 0× | content.extend_from_slice(get(chunk, ObjectType::Chunk)?); |
| 866 | | } |
| 867 | 0× | crate::objects::text_lines(&content, count, form) |
| 868 | 0× | })?; |
| 869 | 96× | b.changes.push((change, sigs_from(&pair[1])?)); |
| 870 | | } |
| 871 | 107× | for a in o::array(field(m, 1, "attests")?, "attests")? { |
| 872 | 11× | b.attests.push(attest_from(a)?); |
| 873 | | } |
| 874 | 107× | if let Some(ps) = m.get(&3) { |
| 875 | 107× | for p in o::array(ps, "policies")? { |
| 876 | 3× | b.policies.push(policy_from(p)?); |
| 877 | | } |
| 878 | 0× | } |
| 879 | 107× | if let Some(cs) = m.get(&4) { |
| 880 | 1× | for c in o::array(cs, "certificates")? { |
| 881 | 1× | b.certificates.push( |
| 882 | 1× | crate::cert::SignedCertificate::decode(o::bytes(c, "certificate")?) |
| 883 | 1× | .map_err(|e| schema(&format!("certificate: {e}")))?, |
| 884 | | ); |
| 885 | | } |
| 886 | 106× | } |
| 887 | 107× | Ok(b) |
| 888 | 107× | } |
| 889 | |
|
| 890 | 82× | pub fn encode_bundle(b: &Bundle) -> Vec<u8> { |
| 891 | 82× | cbor::encode(&bundle_value(b)) |
| 892 | 82× | } |
| 893 | 76× | pub fn decode_bundle(bytes: &[u8]) -> Result<Bundle> { |
| 894 | 76× | bundle_from_value(&cbor::decode(bytes).map_err(ObjectError::from)?) |
| 895 | 76× | } |
| 896 | |
|
| 897 | 121× | pub fn encode_capabilities(id: [u8; 16]) -> Vec<u8> { |
| 898 | 121× | cbor::encode(&Value::map([ |
| 899 | 121× | (0, Value::Array(vec![Value::Uint(PROTOCOL_VERSION)])), |
| 900 | 121× | (1, Value::Bytes(id.to_vec())), |
| 901 | 121× | (2, Value::Array(vec![Value::Text("seal".into())])), |
| 902 | 121× | ])) |
| 903 | 121× | } |
| 904 | 121× | pub fn decode_capabilities(bytes: &[u8]) -> Result<[u8; 16]> { |
| 905 | 121× | let v = cbor::decode(bytes).map_err(ObjectError::from)?; |
| 906 | 121× | let m = map(&v, "capabilities")?; |
| 907 | 121× | let versions = o::array(field(m, 0, "versions")?, "versions")?; |
| 908 | 121× | if !versions |
| 909 | 121× | .iter() |
| 910 | 121× | .any(|x| x.as_uint() == Some(PROTOCOL_VERSION)) |
| 911 | | { |
| 912 | 0× | return Err(RepoError::Msg( |
| 913 | 0× | "remote does not speak protocol version 1".into(), |
| 914 | 0× | )); |
| 915 | 121× | } |
| 916 | 121× | o::bytes(field(m, 1, "repo id")?, "repo id")? |
| 917 | 121× | .try_into() |
| 918 | 121× | .map_err(|_| schema("repo id: expected 16 bytes")) |
| 919 | 121× | } |
| 920 | |
|
| 921 | 181× | fn tags_value(tags: &[TagRef]) -> Value { |
| 922 | | Value::Array( |
| 923 | 181× | tags.iter() |
| 924 | 181× | .map(|t| { |
| 925 | 8× | Value::map([ |
| 926 | 8× | (0, Value::Text(t.name.clone())), |
| 927 | 8× | (1, Value::Bytes(t.state.0.to_vec())), |
| 928 | 8× | (2, hashes_value(&t.heads)), |
| 929 | 8× | (3, opt_attest_value(&t.attestation)), |
| 930 | 8× | ]) |
| 931 | 8× | }) |
| 932 | 181× | .collect(), |
| 933 | | ) |
| 934 | 181× | } |
| 935 | 220× | fn tags_from(v: &Value) -> Result<Vec<TagRef>> { |
| 936 | 220× | let mut out = Vec::new(); |
| 937 | 220× | for t in o::array(v, "tags")? { |
| 938 | 24× | let tm = map(t, "tag")?; |
| 939 | 24× | out.push(TagRef { |
| 940 | 24× | name: o::text(field(tm, 0, "name")?, "name")?.to_owned(), |
| 941 | 24× | state: o::oref(field(tm, 1, "state")?, "state")?, |
| 942 | 24× | heads: hashes_from(field(tm, 2, "heads")?)?, |
| 943 | 24× | attestation: opt_attest_from(field(tm, 3, "attestation")?)?, |
| 944 | | }); |
| 945 | | } |
| 946 | 220× | Ok(out) |
| 947 | 220× | } |
| 948 | |
|
| 949 | 146× | pub fn encode_refs(id: [u8; 16], resp: &RefsResponse) -> Vec<u8> { |
| 950 | 146× | let mut v = Value::map([ |
| 951 | | ( |
| 952 | | 0, |
| 953 | | Value::Array( |
| 954 | 146× | resp.refs |
| 955 | 146× | .iter() |
| 956 | 151× | .map(|r| { |
| 957 | 151× | let mut v = Value::map([ |
| 958 | 151× | (0, Value::Text(r.name.clone())), |
| 959 | 151× | (1, Value::Bytes(r.state.0.to_vec())), |
| 960 | 151× | (2, hashes_value(&r.heads)), |
| 961 | 151× | (3, opt_attest_value(&r.attestation)), |
| 962 | 151× | (4, r.last_serial.map(Value::Uint).unwrap_or(Value::Null)), |
| 963 | 151× | ]); |
| 964 | | |
| 965 | 151× | if let Value::Map(m) = &mut v { |
| 966 | 151× | if r.accepted.is_some() { |
| 967 | 0× | m.insert(5, opt_attest_value(&r.accepted)); |
| 968 | 151× | } |
| 969 | 151× | if let Some(l) = &r.logged { |
| 970 | 1× | m.insert( |
| 971 | 1× | 6, |
| 972 | 1× | Value::Array(vec![ |
| 973 | 1× | Value::Uint(l.index), |
| 974 | 1× | Value::Bytes(l.entry.clone()), |
| 975 | 1× | proof_value(&l.proof), |
| 976 | 1× | ]), |
| 977 | 1× | ); |
| 978 | 150× | } |
| 979 | 151× | if !r.integration.is_empty() { |
| 980 | 1× | m.insert( |
| 981 | | 7, |
| 982 | | Value::Array( |
| 983 | 1× | r.integration |
| 984 | 1× | .iter() |
| 985 | 1× | .map(|i| { |
| 986 | 1× | Value::Array(vec![ |
| 987 | 1× | Value::Text(i.note.clone()), |
| 988 | 1× | proof_value(&i.proof), |
| 989 | 1× | ]) |
| 990 | 1× | }) |
| 991 | 1× | .collect(), |
| 992 | | ), |
| 993 | | ); |
| 994 | 150× | } |
| 995 | 0× | } |
| 996 | 151× | v |
| 997 | 151× | }) |
| 998 | 146× | .collect(), |
| 999 | | ), |
| 1000 | | ), |
| 1001 | 146× | (1, Value::Bytes(id.to_vec())), |
| 1002 | 146× | (2, opt_policy_value(resp.policy.as_ref())), |
| 1003 | 146× | (3, tags_value(&resp.tags)), |
| 1004 | 146× | ( |
| 1005 | 146× | 4, |
| 1006 | 146× | Value::Array(resp.history.iter().map(policy_value).collect()), |
| 1007 | 146× | ), |
| 1008 | 146× | ( |
| 1009 | 146× | 5, |
| 1010 | 146× | resp.default_bookmark |
| 1011 | 146× | .clone() |
| 1012 | 146× | .map(Value::Text) |
| 1013 | 146× | .unwrap_or(Value::Null), |
| 1014 | 146× | ), |
| 1015 | | ]); |
| 1016 | 146× | if let Value::Map(m) = &mut v { |
| 1017 | 146× | if let Some(log) = &resp.log { |
| 1018 | 2× | m.insert(6, Value::Text(log.clone())); |
| 1019 | 144× | } |
| 1020 | 146× | if !resp.witnesses.is_empty() { |
| 1021 | 1× | m.insert( |
| 1022 | | 7, |
| 1023 | | Value::Array( |
| 1024 | 1× | resp.witnesses |
| 1025 | 1× | .iter() |
| 1026 | 1× | .map(|(name, id)| { |
| 1027 | 1× | Value::Array(vec![ |
| 1028 | 1× | Value::Text(name.clone()), |
| 1029 | 1× | Value::Bytes(id.clone()), |
| 1030 | 1× | ]) |
| 1031 | 1× | }) |
| 1032 | 1× | .collect(), |
| 1033 | | ), |
| 1034 | | ); |
| 1035 | 145× | } |
| 1036 | 0× | } |
| 1037 | 146× | cbor::encode(&v) |
| 1038 | 146× | } |
| 1039 | 189× | pub fn decode_refs(bytes: &[u8]) -> Result<([u8; 16], RefsResponse)> { |
| 1040 | 189× | let v = cbor::decode(bytes).map_err(ObjectError::from)?; |
| 1041 | 189× | let m = map(&v, "refs")?; |
| 1042 | 189× | let id: [u8; 16] = o::bytes(field(m, 1, "repo id")?, "repo id")? |
| 1043 | 189× | .try_into() |
| 1044 | 189× | .map_err(|_| schema("repo id: expected 16 bytes"))?; |
| 1045 | 189× | let mut refs = Vec::new(); |
| 1046 | 194× | for r in o::array(field(m, 0, "refs")?, "refs")? { |
| 1047 | 194× | let rm = map(r, "ref")?; |
| 1048 | 194× | let ls = field(rm, 4, "last serial")?; |
| 1049 | 194× | refs.push(RemoteRef { |
| 1050 | 194× | name: o::text(field(rm, 0, "name")?, "name")?.to_owned(), |
| 1051 | 194× | state: o::oref(field(rm, 1, "state")?, "state")?, |
| 1052 | 194× | heads: hashes_from(field(rm, 2, "heads")?)?, |
| 1053 | 194× | attestation: opt_attest_from(field(rm, 3, "attestation")?)?, |
| 1054 | 194× | last_serial: if ls.is_null() { |
| 1055 | 177× | None |
| 1056 | | } else { |
| 1057 | 17× | Some(o::uint(ls, "last serial")?) |
| 1058 | | }, |
| 1059 | 194× | accepted: match rm.get(&5) { |
| 1060 | 0× | Some(a) => opt_attest_from(a)?, |
| 1061 | 194× | None => None, |
| 1062 | | }, |
| 1063 | 194× | logged: match rm.get(&6) { |
| 1064 | 1× | Some(l) => { |
| 1065 | 1× | let a = o::array(l, "logged")?; |
| 1066 | 1× | if a.len() != 3 { |
| 1067 | 0× | return Err(schema("logged: expected [index, entry, proof]")); |
| 1068 | 1× | } |
| 1069 | | Some(Logged { |
| 1070 | 1× | index: o::uint(&a[0], "index")?, |
| 1071 | 1× | entry: o::bytes(&a[1], "entry")?.to_vec(), |
| 1072 | 1× | proof: proof_from(&a[2])?, |
| 1073 | | }) |
| 1074 | | } |
| 1075 | 193× | None => None, |
| 1076 | | }, |
| 1077 | 194× | integration: match rm.get(&7) { |
| 1078 | 1× | Some(l) => { |
| 1079 | 1× | let mut out = Vec::new(); |
| 1080 | 1× | for i in o::array(l, "integration")? { |
| 1081 | 1× | let a = o::array(i, "integration")?; |
| 1082 | 1× | if a.len() != 2 { |
| 1083 | 0× | return Err(schema("integration: expected [note, proof]")); |
| 1084 | 1× | } |
| 1085 | 1× | out.push(Integration { |
| 1086 | 1× | note: o::text(&a[0], "note")?.to_owned(), |
| 1087 | 1× | proof: proof_from(&a[1])?, |
| 1088 | | }); |
| 1089 | | } |
| 1090 | 1× | out |
| 1091 | | } |
| 1092 | 193× | None => Vec::new(), |
| 1093 | | }, |
| 1094 | | }); |
| 1095 | | } |
| 1096 | 189× | let policy = match m.get(&2) { |
| 1097 | 189× | Some(p) => opt_policy_from(p)?, |
| 1098 | 0× | None => None, |
| 1099 | | }; |
| 1100 | 189× | let tags = match m.get(&3) { |
| 1101 | 189× | Some(t) => tags_from(t)?, |
| 1102 | 0× | None => Vec::new(), |
| 1103 | | }; |
| 1104 | 189× | let mut history = Vec::new(); |
| 1105 | 189× | if let Some(h) = m.get(&4) { |
| 1106 | 189× | for p in o::array(h, "history")? { |
| 1107 | 2× | history.push(policy_from(p)?); |
| 1108 | | } |
| 1109 | 0× | } |
| 1110 | 189× | let default_bookmark = match m.get(&5) { |
| 1111 | 120× | Some(Value::Text(t)) => Some(t.clone()), |
| 1112 | 69× | _ => None, |
| 1113 | | }; |
| 1114 | 189× | let log = match m.get(&6) { |
| 1115 | 2× | Some(Value::Text(t)) => Some(t.clone()), |
| 1116 | 187× | _ => None, |
| 1117 | | }; |
| 1118 | 189× | let mut witnesses = Vec::new(); |
| 1119 | 189× | if let Some(w) = m.get(&7) { |
| 1120 | 1× | for x in o::array(w, "witnesses")? { |
| 1121 | 1× | let a = o::array(x, "witness")?; |
| 1122 | 1× | if a.len() != 2 { |
| 1123 | 0× | return Err(schema("witness: expected [name, identity]")); |
| 1124 | 1× | } |
| 1125 | 1× | witnesses.push(( |
| 1126 | 1× | o::text(&a[0], "witness name")?.to_owned(), |
| 1127 | 1× | o::bytes(&a[1], "witness identity")?.to_vec(), |
| 1128 | | )); |
| 1129 | | } |
| 1130 | 188× | } |
| 1131 | 189× | Ok(( |
| 1132 | 189× | id, |
| 1133 | 189× | RefsResponse { |
| 1134 | 189× | refs, |
| 1135 | 189× | policy, |
| 1136 | 189× | tags, |
| 1137 | 189× | history, |
| 1138 | 189× | default_bookmark, |
| 1139 | 189× | log, |
| 1140 | 189× | witnesses, |
| 1141 | 189× | }, |
| 1142 | 189× | )) |
| 1143 | 189× | } |
| 1144 | |
|
| 1145 | | |
| 1146 | 2× | fn proof_value(proof: &[[u8; 32]]) -> Value { |
| 1147 | 3× | Value::Array(proof.iter().map(|h| Value::Bytes(h.to_vec())).collect()) |
| 1148 | 2× | } |
| 1149 | |
|
| 1150 | 2× | fn proof_from(v: &Value) -> Result<Vec<[u8; 32]>> { |
| 1151 | 2× | let mut proof = Vec::new(); |
| 1152 | 3× | for h in o::array(v, "proof")? { |
| 1153 | 3× | proof.push( |
| 1154 | 3× | o::bytes(h, "proof hash")? |
| 1155 | 3× | .try_into() |
| 1156 | 3× | .map_err(|_| schema("proof hash: expected 32 bytes"))?, |
| 1157 | | ); |
| 1158 | | } |
| 1159 | 2× | Ok(proof) |
| 1160 | 2× | } |
| 1161 | |
|
| 1162 | 47× | pub fn encode_negotiate(have: &[ChangeHash], want: &[ChangeHash]) -> Vec<u8> { |
| 1163 | 47× | cbor::encode(&Value::map([ |
| 1164 | 47× | (0, hashes_value(have)), |
| 1165 | 47× | (1, hashes_value(want)), |
| 1166 | 47× | ])) |
| 1167 | 47× | } |
| 1168 | 47× | pub fn decode_negotiate(bytes: &[u8]) -> Result<(Vec<ChangeHash>, Vec<ChangeHash>)> { |
| 1169 | 47× | let v = cbor::decode(bytes).map_err(ObjectError::from)?; |
| 1170 | 47× | let m = map(&v, "negotiate")?; |
| 1171 | | Ok(( |
| 1172 | 47× | hashes_from(field(m, 0, "have")?)?, |
| 1173 | 47× | hashes_from(field(m, 1, "want")?)?, |
| 1174 | | )) |
| 1175 | 47× | } |
| 1176 | |
|
| 1177 | | |
| 1178 | 48× | pub fn encode_fetch(hs: &[ChangeHash], max_blob: Option<u64>) -> Vec<u8> { |
| 1179 | 48× | cbor::encode(&Value::map([ |
| 1180 | 48× | (0, hashes_value(hs)), |
| 1181 | 48× | (1, max_blob.map(Value::Uint).unwrap_or(Value::Null)), |
| 1182 | 48× | ])) |
| 1183 | 48× | } |
| 1184 | 49× | pub fn decode_fetch(bytes: &[u8]) -> Result<(Vec<ChangeHash>, Option<u64>)> { |
| 1185 | 49× | let v = cbor::decode(bytes).map_err(ObjectError::from)?; |
| 1186 | 49× | let m = map(&v, "fetch")?; |
| 1187 | 49× | let max = match m.get(&1) { |
| 1188 | 48× | Some(x) if !x.is_null() => Some(o::uint(x, "max blob")?), |
| 1189 | 47× | _ => None, |
| 1190 | | }; |
| 1191 | 49× | Ok((hashes_from(field(m, 0, "changes")?)?, max)) |
| 1192 | 49× | } |
| 1193 | |
|
| 1194 | | |
| 1195 | 1× | pub fn encode_shallow(hs: &[ChangeHash], depth: u32) -> Vec<u8> { |
| 1196 | 1× | cbor::encode(&Value::map([ |
| 1197 | 1× | (0, hashes_value(hs)), |
| 1198 | 1× | (1, Value::Uint(depth as u64)), |
| 1199 | 1× | ])) |
| 1200 | 1× | } |
| 1201 | 1× | pub fn decode_shallow(bytes: &[u8]) -> Result<(Vec<ChangeHash>, u32)> { |
| 1202 | 1× | let v = cbor::decode(bytes).map_err(ObjectError::from)?; |
| 1203 | 1× | let m = map(&v, "shallow")?; |
| 1204 | | Ok(( |
| 1205 | 1× | hashes_from(field(m, 0, "heads")?)?, |
| 1206 | 1× | o::u32_(field(m, 1, "depth")?, "depth")?, |
| 1207 | | )) |
| 1208 | 1× | } |
| 1209 | |
|
| 1210 | 49× | pub fn encode_hashes(hs: &[ChangeHash]) -> Vec<u8> { |
| 1211 | 49× | cbor::encode(&Value::map([(0, hashes_value(hs))])) |
| 1212 | 49× | } |
| 1213 | 48× | pub fn decode_hashes(bytes: &[u8]) -> Result<Vec<ChangeHash>> { |
| 1214 | 48× | let v = cbor::decode(bytes).map_err(ObjectError::from)?; |
| 1215 | 48× | hashes_from(field(map(&v, "hashes")?, 0, "hashes")?) |
| 1216 | 48× | } |
| 1217 | |
|
| 1218 | 35× | pub fn encode_push( |
| 1219 | 35× | bundle: &Bundle, |
| 1220 | 35× | updates: &[RefUpdate], |
| 1221 | 35× | policy: Option<&SignedPolicy>, |
| 1222 | 35× | tags: &[TagRef], |
| 1223 | 35× | ) -> Vec<u8> { |
| 1224 | 35× | cbor::encode(&Value::map([ |
| 1225 | 35× | (0, bundle_value(bundle)), |
| 1226 | 35× | (2, opt_policy_value(policy)), |
| 1227 | 35× | (3, tags_value(tags)), |
| 1228 | | ( |
| 1229 | | 1, |
| 1230 | | Value::Array( |
| 1231 | 35× | updates |
| 1232 | 35× | .iter() |
| 1233 | 35× | .map(|u| { |
| 1234 | 35× | Value::map([ |
| 1235 | 35× | (0, Value::Text(u.name.clone())), |
| 1236 | 35× | (1, Value::Bytes(u.old_state.0.to_vec())), |
| 1237 | 35× | (2, Value::Bytes(u.new_state.0.to_vec())), |
| 1238 | 35× | (3, Value::Bool(u.force)), |
| 1239 | 35× | (4, opt_attest_value(&u.attestation)), |
| 1240 | 35× | ]) |
| 1241 | 35× | }) |
| 1242 | 35× | .collect(), |
| 1243 | | ), |
| 1244 | | ), |
| 1245 | | ])) |
| 1246 | 35× | } |
| 1247 | | |
| 1248 | | pub type PushParts = (Bundle, Vec<RefUpdate>, Option<SignedPolicy>, Vec<TagRef>); |
| 1249 | |
|
| 1250 | 31× | pub fn decode_push(bytes: &[u8]) -> Result<PushParts> { |
| 1251 | 31× | let v = cbor::decode(bytes).map_err(ObjectError::from)?; |
| 1252 | 31× | let m = map(&v, "push")?; |
| 1253 | 31× | let bundle = bundle_from_value(field(m, 0, "bundle")?)?; |
| 1254 | 31× | let mut updates = Vec::new(); |
| 1255 | 31× | for u in o::array(field(m, 1, "updates")?, "updates")? { |
| 1256 | 31× | let um = map(u, "update")?; |
| 1257 | 31× | updates.push(RefUpdate { |
| 1258 | 31× | name: o::text(field(um, 0, "name")?, "name")?.to_owned(), |
| 1259 | 31× | old_state: o::oref(field(um, 1, "old_state")?, "old_state")?, |
| 1260 | 31× | new_state: o::oref(field(um, 2, "new_state")?, "new_state")?, |
| 1261 | 31× | force: field(um, 3, "force")? |
| 1262 | 31× | .as_bool() |
| 1263 | 31× | .ok_or_else(|| schema("force: expected bool"))?, |
| 1264 | 31× | attestation: opt_attest_from(field(um, 4, "attestation")?)?, |
| 1265 | | }); |
| 1266 | | } |
| 1267 | 31× | let policy = match m.get(&2) { |
| 1268 | 31× | Some(p) => opt_policy_from(p)?, |
| 1269 | 0× | None => None, |
| 1270 | | }; |
| 1271 | 31× | let tags = match m.get(&3) { |
| 1272 | 31× | Some(t) => tags_from(t)?, |
| 1273 | 0× | None => Vec::new(), |
| 1274 | | }; |
| 1275 | 31× | Ok((bundle, updates, policy, tags)) |
| 1276 | 31× | } |
| 1277 | |
|
| 1278 | 31× | pub fn encode_push_response(results: &[RefResult]) -> Vec<u8> { |
| 1279 | 31× | cbor::encode(&Value::map([( |
| 1280 | | 0, |
| 1281 | | Value::Array( |
| 1282 | 31× | results |
| 1283 | 31× | .iter() |
| 1284 | 32× | .map(|r| { |
| 1285 | 32× | Value::map([ |
| 1286 | 32× | (0, Value::Text(r.name.clone())), |
| 1287 | 32× | (1, Value::Bool(r.ok)), |
| 1288 | 32× | (2, Value::Text(r.reason.clone())), |
| 1289 | 32× | ]) |
| 1290 | 32× | }) |
| 1291 | 31× | .collect(), |
| 1292 | | ), |
| 1293 | | )])) |
| 1294 | 31× | } |
| 1295 | 31× | pub fn decode_push_response(bytes: &[u8]) -> Result<Vec<RefResult>> { |
| 1296 | 31× | let v = cbor::decode(bytes).map_err(ObjectError::from)?; |
| 1297 | 31× | let m = map(&v, "push response")?; |
| 1298 | 31× | let mut out = Vec::new(); |
| 1299 | 32× | for r in o::array(field(m, 0, "results")?, "results")? { |
| 1300 | 32× | let rm = map(r, "result")?; |
| 1301 | 32× | out.push(RefResult { |
| 1302 | 32× | name: o::text(field(rm, 0, "name")?, "name")?.to_owned(), |
| 1303 | 32× | ok: field(rm, 1, "ok")? |
| 1304 | 32× | .as_bool() |
| 1305 | 32× | .ok_or_else(|| schema("ok: expected bool"))?, |
| 1306 | 32× | reason: o::text(field(rm, 2, "reason")?, "reason")?.to_owned(), |
| 1307 | | }); |
| 1308 | | } |
| 1309 | 31× | Ok(out) |
| 1310 | 31× | } |
| 1311 | | } |
| 1312 | |
|
| 1313 | | #[cfg(test)] |
| 1314 | | mod tests { |
| 1315 | | use super::*; |
| 1316 | | use crate::attest::AttestBody; |
| 1317 | | use crate::objects::Hlc; |
| 1318 | |
|
| 1319 | | #[test] |
| 1320 | 1× | fn wire_round_trips() { |
| 1321 | 1× | let c = crate::objects::tests::sample_change(); |
| 1322 | 1× | let sk = crate::identity::SecretKey { |
| 1323 | 1× | ed_seed: [1; 32], |
| 1324 | 1× | ml_seed: [2; 32], |
| 1325 | 1× | }; |
| 1326 | 1× | let id = sk.identity("a", "b", 0); |
| 1327 | 1× | let key = id.hash(); |
| 1328 | 1× | let sig = sk.sign(crate::identity::Domain::Change, &key, &c.hash()); |
| 1329 | 1× | let seal = Attest::seal([3; 16], vec![c.hash()]); |
| 1330 | 1× | let seal_sig = sk.sign(crate::identity::Domain::Attest, &key, &seal.hash()); |
| 1331 | 1× | let policy = Policy::single_root([3; 16], id.clone(), 99); |
| 1332 | 1× | let psig = sk.sign(crate::identity::Domain::Policy, &key, &policy.hash()); |
| 1333 | 1× | let bundle = Bundle { |
| 1334 | 1× | changes: vec![(c.clone(), vec![sig.clone()])], |
| 1335 | 1× | attests: vec![SignedAttest { |
| 1336 | 1× | attest: seal.clone(), |
| 1337 | 1× | sigs: vec![seal_sig], |
| 1338 | 1× | }], |
| 1339 | 1× | objects: vec![ |
| 1340 | 1× | (ObjectType::Identity, id.encode()), |
| 1341 | 1× | (ObjectType::Chunk, b"xyz".to_vec()), |
| 1342 | 1× | ], |
| 1343 | 1× | policies: vec![SignedPolicy { |
| 1344 | 1× | policy: policy.clone(), |
| 1345 | 1× | sigs: vec![psig.clone()], |
| 1346 | 1× | }], |
| 1347 | 1× | hashes: vec![], |
| 1348 | 1× | raw_changes: vec![], |
| 1349 | 1× | certificates: vec![], |
| 1350 | 1× | }; |
| 1351 | 1× | let d = wire::decode_bundle(&wire::encode_bundle(&bundle)).unwrap(); |
| 1352 | 1× | assert_eq!( |
| 1353 | | d.hashes, |
| 1354 | 1× | vec![c.hash()], |
| 1355 | | "the receiver hashes what it was sent" |
| 1356 | | ); |
| 1357 | 1× | assert_eq!(d.changes, bundle.changes); |
| 1358 | 1× | assert_eq!(d.attests, bundle.attests); |
| 1359 | 1× | assert_eq!(d.objects, bundle.objects); |
| 1360 | 1× | assert_eq!(d.policies, bundle.policies); |
| 1361 | 1× | assert!(d.certificates.is_empty()); |
| 1362 | | |
| 1363 | | |
| 1364 | 1× | let plain = wire::encode_bundle(&bundle); |
| 1365 | 1× | let mut with = bundle.clone(); |
| 1366 | 1× | let issuer_sk = crate::identity::SecretKey::generate(); |
| 1367 | 1× | let issuer = issuer_sk.identity("hub", "h@x", 1); |
| 1368 | 1× | with.certificates.push(crate::cert::SignedCertificate::sign( |
| 1369 | 1× | crate::cert::Certificate { |
| 1370 | 1× | key: id.clone(), |
| 1371 | 1× | issuer: issuer.hash(), |
| 1372 | 1× | subject: "agent:a@b".into(), |
| 1373 | 1× | claims: vec![], |
| 1374 | 1× | scope: crate::identity::Scope::CHANGES, |
| 1375 | 1× | not_before: 1, |
| 1376 | 1× | expires: 2, |
| 1377 | 1× | grant: None, |
| 1378 | 1× | }, |
| 1379 | 1× | &issuer, |
| 1380 | 1× | &issuer_sk, |
| 1381 | | )); |
| 1382 | 1× | let encoded = wire::encode_bundle(&with); |
| 1383 | 1× | assert_ne!(encoded, plain); |
| 1384 | 1× | assert_eq!( |
| 1385 | 1× | wire::decode_bundle(&encoded).unwrap().certificates, |
| 1386 | | with.certificates |
| 1387 | | ); |
| 1388 | 1× | with.certificates.clear(); |
| 1389 | 1× | assert_eq!(wire::encode_bundle(&with), plain); |
| 1390 | |
|
| 1391 | 1× | let att = Attest { |
| 1392 | 1× | repo: [3; 16], |
| 1393 | 1× | hlc: Hlc::default(), |
| 1394 | 1× | body: AttestBody::Ref { |
| 1395 | 1× | name: "main".into(), |
| 1396 | 1× | old_state: ObjectRef([1; 32]), |
| 1397 | 1× | new_state: ObjectRef([2; 32]), |
| 1398 | 1× | serial: 4, |
| 1399 | 1× | }, |
| 1400 | 1× | }; |
| 1401 | 1× | let refs = vec![ |
| 1402 | 1× | RemoteRef { |
| 1403 | 1× | name: "main".into(), |
| 1404 | 1× | state: ObjectRef([2; 32]), |
| 1405 | 1× | heads: vec![c.hash()], |
| 1406 | 1× | attestation: Some(SignedAttest { |
| 1407 | 1× | attest: att.clone(), |
| 1408 | 1× | sigs: vec![sig.clone()], |
| 1409 | 1× | }), |
| 1410 | 1× | last_serial: Some(4), |
| 1411 | 1× | accepted: None, |
| 1412 | 1× | logged: None, |
| 1413 | 1× | integration: vec![], |
| 1414 | 1× | }, |
| 1415 | 1× | RemoteRef { |
| 1416 | 1× | name: "dev".into(), |
| 1417 | 1× | state: ObjectRef([5; 32]), |
| 1418 | 1× | heads: vec![], |
| 1419 | 1× | attestation: None, |
| 1420 | 1× | last_serial: None, |
| 1421 | 1× | accepted: None, |
| 1422 | 1× | logged: None, |
| 1423 | 1× | integration: vec![], |
| 1424 | 1× | }, |
| 1425 | | ]; |
| 1426 | 1× | let tag = TagRef { |
| 1427 | 1× | name: "v1".into(), |
| 1428 | 1× | state: ObjectRef([2; 32]), |
| 1429 | 1× | heads: vec![c.hash()], |
| 1430 | 1× | attestation: None, |
| 1431 | 1× | }; |
| 1432 | 1× | let mut resp = RefsResponse { |
| 1433 | 1× | refs, |
| 1434 | 1× | policy: Some(SignedPolicy { |
| 1435 | 1× | policy: policy.clone(), |
| 1436 | 1× | sigs: vec![psig.clone()], |
| 1437 | 1× | }), |
| 1438 | 1× | tags: vec![tag.clone()], |
| 1439 | 1× | history: vec![SignedPolicy { |
| 1440 | 1× | policy: policy.clone(), |
| 1441 | 1× | sigs: vec![], |
| 1442 | 1× | }], |
| 1443 | 1× | default_bookmark: Some("develop".into()), |
| 1444 | 1× | log: Some("hub.example/log\n2\nroot\n\n- sig\n".into()), |
| 1445 | 1× | witnesses: vec![], |
| 1446 | 1× | }; |
| 1447 | | |
| 1448 | | |
| 1449 | 1× | let old = wire::encode_refs([3; 16], &resp); |
| 1450 | 1× | let back = wire::decode_refs(&old).unwrap().1; |
| 1451 | 2× | assert!(back.witnesses.is_empty() && back.refs.iter().all(|r| r.integration.is_empty())); |
| 1452 | 1× | resp.refs[1].logged = Some(Logged { |
| 1453 | 1× | index: 41, |
| 1454 | 1× | entry: vec![1, 2, 3], |
| 1455 | 1× | proof: vec![[9; 32], [8; 32]], |
| 1456 | 1× | }); |
| 1457 | 1× | resp.refs[1].integration = vec![Integration { |
| 1458 | 1× | note: "hub.example/log\n42\nroot\n\n- sig\n".into(), |
| 1459 | 1× | proof: vec![[7; 32]], |
| 1460 | 1× | }]; |
| 1461 | 1× | resp.witnesses = vec![("w.example".into(), vec![4, 5, 6])]; |
| 1462 | 1× | let new = wire::encode_refs([3; 16], &resp); |
| 1463 | 1× | let (id_back, back) = wire::decode_refs(&new).unwrap(); |
| 1464 | 1× | assert_eq!(back.log, resp.log); |
| 1465 | 1× | assert_eq!(back.refs[1].logged, resp.refs[1].logged); |
| 1466 | 1× | assert_eq!(back.refs[1].integration, resp.refs[1].integration); |
| 1467 | 1× | assert_eq!(back.witnesses, resp.witnesses); |
| 1468 | 1× | assert_eq!(back.refs[0].logged, None); |
| 1469 | | |
| 1470 | 1× | let crate::cbor::Value::Map(m) = crate::cbor::decode(&new).unwrap() else { |
| 1471 | 0× | panic!() |
| 1472 | | }; |
| 1473 | 1× | assert!(m.contains_key(&7)); |
| 1474 | 1× | assert_eq!(id_back, [3; 16]); |
| 1475 | 1× | assert_eq!(back.refs.len(), 2); |
| 1476 | 1× | assert_eq!(back.refs[0].attestation.as_ref().unwrap().attest, att); |
| 1477 | 1× | assert_eq!(back.refs[1].last_serial, None); |
| 1478 | 1× | assert_eq!(back.policy.as_ref().unwrap().policy, policy); |
| 1479 | 1× | assert_eq!(back.history, resp.history); |
| 1480 | 1× | assert_eq!(back.tags, vec![tag.clone()]); |
| 1481 | |
|
| 1482 | 1× | let (h, w) = wire::decode_negotiate(&wire::encode_negotiate( |
| 1483 | 1× | &[ObjectRef([1; 32])], |
| 1484 | 1× | &[ObjectRef([2; 32])], |
| 1485 | 1× | )) |
| 1486 | 1× | .unwrap(); |
| 1487 | 1× | assert_eq!((h, w), (vec![ObjectRef([1; 32])], vec![ObjectRef([2; 32])])); |
| 1488 | 1× | assert_eq!( |
| 1489 | 1× | wire::decode_hashes(&wire::encode_hashes(&[c.hash()])).unwrap(), |
| 1490 | 1× | vec![c.hash()] |
| 1491 | | ); |
| 1492 | 1× | assert_eq!( |
| 1493 | 1× | wire::decode_fetch(&wire::encode_fetch(&[c.hash()], Some(4096))).unwrap(), |
| 1494 | 1× | (vec![c.hash()], Some(4096)) |
| 1495 | | ); |
| 1496 | 1× | assert_eq!( |
| 1497 | 1× | wire::decode_fetch(&wire::encode_fetch(&[], None)).unwrap(), |
| 1498 | 1× | (vec![], None) |
| 1499 | | ); |
| 1500 | 1× | assert_eq!( |
| 1501 | 1× | wire::decode_shallow(&wire::encode_shallow(&[c.hash()], 3)).unwrap(), |
| 1502 | 1× | (vec![c.hash()], 3) |
| 1503 | | ); |
| 1504 | | |
| 1505 | 1× | assert_eq!( |
| 1506 | 1× | wire::decode_fetch(&wire::encode_hashes(&[c.hash()])).unwrap(), |
| 1507 | 1× | (vec![c.hash()], None) |
| 1508 | | ); |
| 1509 | |
|
| 1510 | 1× | let up = RefUpdate { |
| 1511 | 1× | name: "main".into(), |
| 1512 | 1× | old_state: ObjectRef([1; 32]), |
| 1513 | 1× | new_state: ObjectRef([2; 32]), |
| 1514 | 1× | force: true, |
| 1515 | 1× | attestation: Some(SignedAttest { |
| 1516 | 1× | attest: att, |
| 1517 | 1× | sigs: vec![sig], |
| 1518 | 1× | }), |
| 1519 | 1× | }; |
| 1520 | 1× | let sp = SignedPolicy { |
| 1521 | 1× | policy, |
| 1522 | 1× | sigs: vec![psig], |
| 1523 | 1× | }; |
| 1524 | 1× | let (b2, ups, pol, tags) = wire::decode_push(&wire::encode_push( |
| 1525 | 1× | &bundle, |
| 1526 | 1× | std::slice::from_ref(&up), |
| 1527 | 1× | Some(&sp), |
| 1528 | 1× | std::slice::from_ref(&tag), |
| 1529 | 1× | )) |
| 1530 | 1× | .unwrap(); |
| 1531 | 1× | assert_eq!(pol, Some(sp)); |
| 1532 | 1× | assert_eq!(tags, vec![tag]); |
| 1533 | 1× | assert_eq!(b2.changes.len(), 1); |
| 1534 | 1× | assert_eq!(ups[0].name, "main"); |
| 1535 | 1× | assert!(ups[0].force); |
| 1536 | 1× | assert_eq!(ups[0].attestation, up.attestation); |
| 1537 | 1× | let res = vec![RefResult { |
| 1538 | 1× | name: "main".into(), |
| 1539 | 1× | ok: false, |
| 1540 | 1× | reason: "stale".into(), |
| 1541 | 1× | }]; |
| 1542 | 1× | assert_eq!( |
| 1543 | 1× | wire::decode_push_response(&wire::encode_push_response(&res)).unwrap(), |
| 1544 | | res |
| 1545 | | ); |
| 1546 | 1× | assert_eq!( |
| 1547 | 1× | wire::decode_capabilities(&wire::encode_capabilities([7; 16])).unwrap(), |
| 1548 | | [7; 16] |
| 1549 | | ); |
| 1550 | 1× | } |
| 1551 | | } |