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