1pub mod account;
14pub(crate) mod archive;
15pub mod commands;
16pub mod conformance;
17pub mod protocol;
18pub mod publish;
19pub mod query;
20pub(crate) mod select;
21pub mod serve;
22pub(crate) mod transport;
23
24use std::collections::BTreeMap;
25use std::path::{Path, PathBuf};
26
27use bynk_project::RegistryConfig;
28use bynk_project::lock::{FIRST_PARTY, FIRST_PARTY_REGISTRY, Lock, LockedRegistry, store_dir};
29
30use crate::fetch::{FetchError, fail};
31use protocol::{Config, ConfigTrust, IndexLine, fingerprint, verify};
32use transport::{Transport, join};
33
34pub(crate) const BAD_SIGNATURE: &str = "bynk.registry.bad_signature";
35pub(crate) const KEY_MISMATCH: &str = "bynk.registry.key_mismatch";
36pub(crate) const UNAVAILABLE: &str = "bynk.registry.unavailable";
37pub(crate) const SOURCE_MISMATCH: &str = "bynk.registry.source_mismatch";
38pub(crate) const WITHDRAWN: &str = "bynk.registry.withdrawn";
39
40struct Opened {
42 index: String,
44 mirror: Option<String>,
47 dl: String,
49 api: Option<String>,
51 id: String,
53 keys: Vec<String>,
56 revoked: Vec<String>,
59 transport: Transport,
60 token_source: Option<TokenSource>,
62 lines: BTreeMap<String, Vec<IndexLine>>,
64}
65
66pub(crate) struct Client {
68 configs: Vec<RegistryConfig>,
70 locked: Vec<LockedRegistry>,
72 opened: BTreeMap<String, Opened>,
73 pub trust: BTreeMap<String, LockedRegistry>,
75 pub notices: Vec<String>,
77 acting_for: Option<String>,
80}
81
82impl Client {
83 pub(crate) fn new(configs: Vec<RegistryConfig>, existing: Option<&Lock>) -> Client {
84 Client {
85 configs,
86 locked: existing.map(|l| l.registries.clone()).unwrap_or_default(),
87 opened: BTreeMap::new(),
88 trust: BTreeMap::new(),
89 notices: Vec::new(),
90 acting_for: None,
91 }
92 }
93
94 pub(crate) fn acting_for(mut self, org: &str) -> Client {
97 self.acting_for = Some(org.to_string());
98 self
99 }
100
101 pub(crate) fn token_source(&self, registry: &str) -> Option<&TokenSource> {
103 self.opened.get(registry)?.token_source.as_ref()
104 }
105
106 pub(crate) fn route(&self, org: &str) -> String {
109 self.configs
110 .iter()
111 .find(|c| c.organisations.iter().any(|o| o == org))
112 .map_or_else(|| FIRST_PARTY_REGISTRY.to_string(), |c| c.name.clone())
113 }
114
115 fn open(&mut self, name: &str) -> Result<&mut Opened, FetchError> {
117 if self.opened.contains_key(name) {
118 return Ok(self.opened.get_mut(name).expect("checked"));
119 }
120 if name == FIRST_PARTY_REGISTRY && FIRST_PARTY.is_none() {
123 return Err(fail(
124 UNAVAILABLE,
125 "the first-party registry isn't live yet: add a `[registries.<name>]` whose `organisations` lists the organisation",
126 ));
127 }
128 let mirror = self
130 .configs
131 .iter()
132 .find(|c| c.mirror_of.as_deref() == Some(name))
133 .cloned();
134 let own = self.configs.iter().find(|c| c.name == name).cloned();
135 let (index, pinned, reader) = match (&mirror, &own) {
136 (Some(m), _) => (
137 m.index.clone(),
138 own.as_ref()
139 .and_then(|o| o.key.clone())
140 .or_else(|| first_party_key(name)),
141 m.name.clone(),
142 ),
143 (None, Some(o)) => (o.index.clone(), o.key.clone(), o.name.clone()),
144 (None, None) if name == FIRST_PARTY_REGISTRY => match FIRST_PARTY {
145 Some((index, key)) => (index.to_string(), Some(key.to_string()), name.to_string()),
146 None => {
147 return Err(fail(
148 UNAVAILABLE,
149 "the first-party registry isn't live yet: add a `[registries.<name>]` whose `organisations` lists the organisation",
150 ));
151 }
152 },
153 (None, None) => {
154 return Err(fail(
155 UNAVAILABLE,
156 format!("no `[registries.{name}]` is configured"),
157 ));
158 }
159 };
160 let config_url = join(&index, "config.json");
161 let (token, token_source) =
164 token_for(&reader, self.acting_for.as_deref(), &mut self.notices).unzip();
165 let mut transport = Transport::new(&reader, &[&index]).with_token(token);
166 let bytes = transport.get(&config_url)?.ok_or_else(|| {
167 fail(
168 UNAVAILABLE,
169 format!("registry `{reader}` has no `config.json` at `{config_url}`"),
170 )
171 })?;
172 let config = Config::parse(&bytes)
173 .map_err(|e| fail(UNAVAILABLE, format!("registry `{reader}`: {e}")))?;
174 let locked = self.locked.iter().find(|r| r.name == name).cloned();
175 let id = match &locked {
177 Some(r) => {
178 if mirror.is_none() && r.id != config.id {
179 return Err(fail(
180 KEY_MISMATCH,
181 format!(
182 "registry `{name}` now calls itself `{}`, but `bynk.lock` trusted it as `{}`",
183 config.id, r.id
184 ),
185 ));
186 }
187 r.id.clone()
188 }
189 None => config.id.clone(),
190 };
191 let trusted = match (&pinned, &locked) {
192 (Some(key), _) => fingerprint(key).ok_or_else(|| {
193 fail(
194 KEY_MISMATCH,
195 format!("`[registries.{name}] key` isn't an `ed25519:` key"),
196 )
197 })?,
198 (None, Some(r)) => r.key.clone(),
199 (None, None) => {
200 let newest = &config.keys.last().expect("parse checks").key;
201 let fp = fingerprint(newest).ok_or_else(|| {
202 fail(
203 KEY_MISMATCH,
204 format!("registry `{name}`'s key isn't an `ed25519:` key"),
205 )
206 })?;
207 self.notices.push(format!(
208 "trusting registry `{name}` (id `{}`) key {fp} on first use — pin it with `key = \"{newest}\"` in `[registries.{name}]`",
209 config.id
210 ));
211 fp
212 }
213 };
214 let start = config
215 .keys
216 .iter()
217 .position(|k| fingerprint(&k.key).as_deref() == Some(trusted.as_str()));
218 let chained = config.follow_chain(&trusted).is_some();
219 let (Some(start), true) = (start, chained) else {
220 return Err(fail(
221 KEY_MISMATCH,
222 format!(
223 "registry `{name}`'s keys don't lead from the trusted key {trusted} — if its key was replaced deliberately, pin the new one in `[registries.{name}]`"
224 ),
225 ));
226 };
227 self.trust.insert(
232 name.to_string(),
233 LockedRegistry {
234 name: name.to_string(),
235 id: id.clone(),
236 key: trusted.clone(),
237 },
238 );
239 let dl = transport::resolve(&config_url, &config.dl);
240 let allowed = matches!(
244 (scheme(&index).as_deref(), scheme(&dl).as_deref()),
245 (Some("file"), Some("file"))
246 | (Some("https"), Some("https"))
247 | (Some("http"), Some("http" | "https"))
248 );
249 if !allowed {
250 return Err(fail(
251 UNAVAILABLE,
252 format!(
253 "registry `{reader}`'s `config.json` puts its archives at `{dl}`, which its index `{index}` doesn't allow"
254 ),
255 ));
256 }
257 transport.allow_origin(&dl);
258 let api = match &config.api {
260 None => None,
261 Some(a) => {
262 let api = transport::resolve(&config_url, a);
263 let allowed = matches!(
264 (scheme(&index).as_deref(), scheme(&api).as_deref()),
265 (Some("https"), Some("https")) | (Some("http"), Some("http" | "https"))
266 );
267 if !allowed {
268 return Err(fail(
269 UNAVAILABLE,
270 format!(
271 "registry `{reader}`'s `config.json` puts its publish API at `{api}`, which its index `{index}` doesn't allow"
272 ),
273 ));
274 }
275 transport.allow_origin(&api);
276 Some(api)
277 }
278 };
279 let chain: Vec<String> = config.keys[start..].iter().map(|k| k.key.clone()).collect();
282 let signers = config.signers(&chain);
283 for why in &signers.ignored {
284 self.notices.push(format!(
285 "registry `{name}`'s `config.json` has {why} — ignoring it"
286 ));
287 }
288 let opened = Opened {
289 index,
290 mirror: mirror.map(|m| m.name),
291 dl,
292 api,
293 id,
294 keys: signers.keys,
295 revoked: signers.revoked,
296 transport,
297 token_source,
298 lines: BTreeMap::new(),
299 };
300 Ok(self.opened.entry(name.to_string()).or_insert(opened))
301 }
302
303 pub(crate) fn lines(
305 &mut self,
306 registry: &str,
307 package: &str,
308 ) -> Result<Vec<IndexLine>, FetchError> {
309 let opened = self.open(registry)?;
310 if let Some(lines) = opened.lines.get(package) {
311 return Ok(lines.clone());
312 }
313 let url = join(&opened.index, package);
314 let Some(bytes) = opened.transport.get(&url)? else {
315 return Err(fail(
316 UNAVAILABLE,
317 format!("registry `{registry}` has no package `{package}`"),
318 ));
319 };
320 let text = String::from_utf8(bytes).map_err(|_| {
321 fail(
322 BAD_SIGNATURE,
323 format!("`{package}`'s index on `{registry}` isn't UTF-8"),
324 )
325 })?;
326 let mut lines = Vec::new();
327 for raw in text.lines().filter(|l| !l.trim().is_empty()) {
328 let line = IndexLine::parse(raw)
329 .map_err(|e| fail(BAD_SIGNATURE, format!("`{package}` on `{registry}`: {e}")))?;
330 let payload = line.payload(&opened.id);
331 let signed = opened.keys.iter().any(|k| verify(k, &payload, &line.sig));
332 if !signed
333 && line.name == package
334 && let Some(k) = opened
335 .revoked
336 .iter()
337 .find(|k| verify(k, &payload, &line.sig))
338 {
339 return Err(fail(
340 BAD_SIGNATURE,
341 format!(
342 "`{package}` {} on registry `{registry}` is signed by {k}, a key the registry revoked — the registry must re-sign it (`bynk registry resign`)",
343 line.version
344 ),
345 ));
346 }
347 if !signed || line.name != package {
348 return Err(fail(
349 BAD_SIGNATURE,
350 format!(
351 "`{package}` {} on registry `{registry}` isn't signed by its trusted key for `{package}` on `{}` — refusing it",
352 line.version, opened.id
353 ),
354 ));
355 }
356 lines.push(line);
357 }
358 opened.lines.insert(package.to_string(), lines.clone());
359 Ok(lines)
360 }
361
362 pub(crate) fn writable(&self, registry: &str) -> Result<(), FetchError> {
368 match self
369 .configs
370 .iter()
371 .find(|c| c.mirror_of.as_deref() == Some(registry))
372 {
373 Some(mirror) => Err(fail(
374 publish::PUBLISH_REFUSED,
375 format!(
376 "registry `{registry}` is read through the mirror `{}`, and a publish or yank goes only to the registry itself — run this from a project without the mirror",
377 mirror.name
378 ),
379 )),
380 None => Ok(()),
381 }
382 }
383
384 pub(crate) fn api_write(
388 &mut self,
389 registry: &str,
390 method: &str,
391 path: &str,
392 body: Option<&[u8]>,
393 ) -> Result<(u16, Vec<u8>), FetchError> {
394 self.writable(registry)?;
395 let opened = self.open(registry)?;
396 let Some(api) = opened.api.clone() else {
397 return Err(fail(
398 publish::PUBLISH_REFUSED,
399 format!(
400 "registry `{registry}` doesn't take publishes over HTTP (its `config.json` has no `api`) — publish with `bynk registry add`"
401 ),
402 ));
403 };
404 opened.transport.send(method, &join(&api, path), body)
405 }
406
407 pub(crate) fn account_call(
413 &mut self,
414 registry: &str,
415 method: &str,
416 path: &str,
417 body: Option<&serde_json::Value>,
418 bearer: Option<&str>,
419 ) -> Result<(u16, Vec<u8>), FetchError> {
420 let opened = self.open(registry)?;
421 if let Some(mirror) = &opened.mirror {
422 return Err(fail(
423 account::ACCOUNT_REFUSED,
424 format!(
425 "registry `{registry}` is read through the mirror `{mirror}`, and an account token goes only to the registry itself — run this from a project without the mirror"
426 ),
427 ));
428 }
429 let Some(api) = opened.api.clone() else {
430 return Err(fail(
431 account::ACCOUNT_REFUSED,
432 format!(
433 "registry `{registry}` has no account API (its `config.json` has no `api`)"
434 ),
435 ));
436 };
437 let url = join(&account_base(&api), path);
438 opened.transport.json(method, &url, body, bearer)
439 }
440
441 pub(crate) fn forget(&mut self, registry: &str, package: &str) {
444 if let Some(o) = self.opened.get_mut(registry) {
445 o.lines.remove(package);
446 }
447 }
448
449 pub(crate) fn withdrawn(
453 &self,
454 registry: &str,
455 package: &str,
456 version: &str,
457 reason: &str,
458 alias: &str,
459 ) -> FetchError {
460 let mut message = format!(
461 "`{package}` {version} was withdrawn by registry `{registry}`: {}\n = note: `bynk.lock` locks this version; choose another with `bynk update {alias}`",
462 sanitise_reason(reason)
463 );
464 if let Some(mirror) = self.opened.get(registry).and_then(|o| o.mirror.as_deref()) {
465 message.push_str(&format!(
466 "\n = note: read through the mirror `{mirror}` — the origin wasn't consulted"
467 ));
468 }
469 fail(WITHDRAWN, message)
470 }
471
472 pub(crate) fn fetch(
475 &mut self,
476 registry: &str,
477 line: &IndexLine,
478 home: &Path,
479 ) -> Result<PathBuf, FetchError> {
480 let entry = store_dir(home, &line.checksum).ok_or_else(|| {
481 fail(
482 BAD_SIGNATURE,
483 format!("`{}`'s checksum is malformed", line.name),
484 )
485 })?;
486 if entry.is_dir() {
487 return Ok(entry);
488 }
489 let opened = self.open(registry)?;
490 let hex = entry
491 .file_name()
492 .expect("a store path")
493 .to_string_lossy()
494 .into_owned();
495 let url = join(&opened.dl, &format!("sha256/{hex}"));
496 let bytes = opened.transport.get(&url)?.ok_or_else(|| {
497 fail(
498 UNAVAILABLE,
499 format!(
500 "registry `{registry}` has no archive for `{}` {}",
501 line.name, line.version
502 ),
503 )
504 })?;
505 let staging = crate::fetch::staging_dir(home, &hex);
506 std::fs::create_dir_all(&staging).map_err(|e| {
507 fail(
508 archive::BAD_ARCHIVE,
509 format!("could not stage `{}`: {e}", line.name),
510 )
511 })?;
512 archive::unpack(&bytes, &staging)?;
513 let got = crate::fetch::place_in_store(
514 home,
515 &staging,
516 &format!("`{}` {}", line.name, line.version),
517 archive::BAD_ARCHIVE,
518 )?;
519 if got != line.checksum {
520 if let Some(wrong) = store_dir(home, &got) {
521 let _ = crate::fetch::remove_entry(&wrong);
522 }
523 return Err(fail(
524 crate::fetch::CHECKSUM_MISMATCH,
525 format!(
526 "`{}` {}'s archive from `{registry}` unpacks to {got}, but its signed line says {}",
527 line.name, line.version, line.checksum
528 ),
529 ));
530 }
531 Ok(entry)
532 }
533}
534
535pub(crate) fn sanitise_reason(reason: &str) -> String {
540 let clean: String = reason.chars().filter(|c| !c.is_control()).collect();
541 let mut cut: String = clean.chars().take(protocol::WITHDRAWN_MAX).collect();
542 if clean.chars().count() > protocol::WITHDRAWN_MAX {
543 cut.push('…');
544 }
545 format!("{cut:?}")
546}
547
548fn account_base(api: &str) -> String {
553 let api = api.trim_end_matches('/');
554 let at_root = api
555 .split_once("://")
556 .is_some_and(|(_, rest)| !rest.contains('/'));
557 if at_root {
558 join(api, "account")
559 } else {
560 transport::resolve(api, "account")
561 }
562}
563
564fn scheme(url: &str) -> Option<String> {
566 url.split_once("://").map(|(s, _)| s.to_ascii_lowercase())
567}
568
569fn first_party_key(name: &str) -> Option<String> {
571 (name == FIRST_PARTY_REGISTRY)
572 .then_some(FIRST_PARTY)
573 .flatten()
574 .map(|(_, key)| key.to_string())
575}
576
577#[derive(Debug, Clone, PartialEq, Eq)]
580pub(crate) enum TokenSource {
581 Var(String),
583 Organisation { registry: String, org: String },
585 Registry(String),
587}
588
589impl std::fmt::Display for TokenSource {
590 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
591 match self {
592 TokenSource::Var(var) => write!(f, "`{var}`"),
593 TokenSource::Organisation { registry, org } => {
594 write!(f, "`[registries.{registry}.organisations.{org}] token`")
595 }
596 TokenSource::Registry(registry) => write!(f, "`[registries.{registry}] token`"),
597 }
598 }
599}
600
601fn token_for(
606 name: &str,
607 org: Option<&str>,
608 notices: &mut Vec<String>,
609) -> Option<(String, TokenSource)> {
610 let var = bynk_project::manifest::registry_token_var(name);
611 if let Some(t) = std::env::var(&var).ok().filter(|t| !t.trim().is_empty()) {
612 return Some((t, TokenSource::Var(var)));
613 }
614 let path = credentials_path()?;
615 let text = std::fs::read_to_string(&path).ok()?;
616 #[cfg(unix)]
617 {
618 use std::os::unix::fs::PermissionsExt;
619 if let Ok(meta) = std::fs::metadata(&path)
620 && meta.permissions().mode() & 0o077 != 0
621 {
622 notices.push(format!(
623 "`{}` is readable by others — `chmod 600` it",
624 path.display()
625 ));
626 }
627 }
628 #[cfg(not(unix))]
629 let _ = ¬ices;
630 let doc: toml::Table = text.parse().ok()?;
631 saved_token(&doc, name, org)
632}
633
634fn saved_token(doc: &toml::Table, name: &str, org: Option<&str>) -> Option<(String, TokenSource)> {
637 let entry = doc.get("registries")?.get(name)?;
638 let own = org.and_then(|org| {
639 let t = entry
640 .get("organisations")?
641 .get(org)?
642 .get("token")?
643 .as_str()?;
644 Some((
645 t.to_owned(),
646 TokenSource::Organisation {
647 registry: name.to_string(),
648 org: org.to_string(),
649 },
650 ))
651 });
652 own.or_else(|| {
653 let t = entry.get("token")?.as_str()?;
654 Some((t.to_owned(), TokenSource::Registry(name.to_string())))
655 })
656}
657
658pub(crate) fn credentials_path() -> Option<PathBuf> {
661 if let Some(c) = std::env::var_os("XDG_CONFIG_HOME").filter(|v| !v.is_empty()) {
662 return Some(PathBuf::from(c).join("bynk").join("credentials.toml"));
663 }
664 let home = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE"))?;
665 Some(
666 PathBuf::from(home)
667 .join(".config")
668 .join("bynk")
669 .join("credentials.toml"),
670 )
671}
672
673#[cfg(test)]
674mod tests {
675 use super::*;
676
677 #[test]
678 fn an_organisation_s_own_slot_is_preferred_and_only_when_acting_for_it() {
679 let doc: toml::Table = r#"
680 [registries.bynk]
681 token = "bynk_wide"
682 [registries.bynk.organisations.acme]
683 token = "bynk_acme"
684 [registries.solo.organisations.acme]
685 token = "bynk_solo_acme"
686 "#
687 .parse()
688 .unwrap();
689 let own = TokenSource::Organisation {
690 registry: "bynk".into(),
691 org: "acme".into(),
692 };
693 let wide = TokenSource::Registry("bynk".into());
694 assert_eq!(
695 saved_token(&doc, "bynk", Some("acme")),
696 Some(("bynk_acme".into(), own.clone()))
697 );
698 assert_eq!(
700 saved_token(&doc, "bynk", Some("acme-labs")),
701 Some(("bynk_wide".into(), wide.clone()))
702 );
703 assert_eq!(
704 saved_token(&doc, "bynk", None),
705 Some(("bynk_wide".into(), wide))
706 );
707 assert_eq!(saved_token(&doc, "solo", None), None);
709 assert_eq!(saved_token(&doc, "solo", Some("other")), None);
710 assert_eq!(saved_token(&doc, "other", Some("acme")), None);
711 assert_eq!(
712 own.to_string(),
713 "`[registries.bynk.organisations.acme] token`"
714 );
715 }
716
717 #[test]
718 fn the_account_base_stays_on_the_api_origin() {
719 assert_eq!(
720 account_base("https://r.example/api"),
721 "https://r.example/account"
722 );
723 assert_eq!(
724 account_base("https://r.example/api/"),
725 "https://r.example/account"
726 );
727 assert_eq!(
728 account_base("https://r.example/reg/api"),
729 "https://r.example/reg/account"
730 );
731 assert_eq!(
732 account_base("https://r.example/"),
733 "https://r.example/account"
734 );
735 assert_eq!(
736 account_base("http://localhost:8730"),
737 "http://localhost:8730/account"
738 );
739 }
740
741 #[test]
742 fn a_withdrawn_reason_is_printed_sanitised() {
743 assert_eq!(sanitise_reason("a takedown"), "\"a takedown\"");
744 assert_eq!(
746 sanitise_reason("ok\u{1b}[2K\rerror[bynk.fake]: \"x\"\n"),
747 "\"ok[2Kerror[bynk.fake]: \\\"x\\\"\""
748 );
749 let long = "x".repeat(protocol::WITHDRAWN_MAX + 10);
750 let shown = sanitise_reason(&long);
751 assert_eq!(
752 shown.chars().count(),
753 protocol::WITHDRAWN_MAX + 3,
754 "{shown}"
755 );
756 assert!(shown.ends_with("…\""));
757 }
758}