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