1use bynk_driver::emsg;
13use std::path::{Path, PathBuf};
14use std::time::{Duration, Instant};
15
16use bynk_project::lock::FIRST_PARTY_REGISTRY;
17use serde_json::{Value, json};
18
19use super::Client;
20use crate::fetch::{FetchError, fail};
21
22pub(crate) const ACCOUNT_REFUSED: &str = "bynk.registry.account_refused";
23
24const SLOW_DOWN: u64 = 5;
26
27const MIN_INTERVAL: u64 = 1;
30
31#[derive(Debug, Clone)]
35pub struct Target {
36 pub project: PathBuf,
37 pub registry: Option<String>,
38}
39
40pub(crate) trait Api {
42 fn call(
44 &mut self,
45 method: &str,
46 path: &str,
47 body: Option<&Value>,
48 ) -> Result<(u16, Vec<u8>), FetchError>;
49}
50
51struct Live {
54 client: Client,
55 registry: String,
56 bearer: Option<String>,
57}
58
59impl Api for Live {
60 fn call(
61 &mut self,
62 method: &str,
63 path: &str,
64 body: Option<&Value>,
65 ) -> Result<(u16, Vec<u8>), FetchError> {
66 self.client
67 .account_call(&self.registry, method, path, body, self.bearer.as_deref())
68 .map_err(|mut e| {
69 if e.code == super::UNAVAILABLE && self.registry == FIRST_PARTY_REGISTRY {
71 e.message
72 .push_str(" — or pass `--registry <name>` to use a configured registry");
73 }
74 e
75 })
76 }
77}
78
79fn open(target: &Target, org: Option<&str>) -> (Client, String) {
82 let root = bynk_project::lock::lock_root(&target.project);
83 let client = Client::new(super::commands::registries_of(&root), None);
84 let registry = match (&target.registry, org) {
85 (Some(r), _) => r.clone(),
86 (None, Some(o)) => client.route(o),
87 (None, None) => FIRST_PARTY_REGISTRY.to_string(),
88 };
89 (client, registry)
90}
91
92fn signed_in(target: &Target, org: &str) -> Result<Live, FetchError> {
94 let (client, registry) = open(target, Some(org));
95 let session = session(®istry).ok_or_else(|| {
96 fail(
97 ACCOUNT_REFUSED,
98 format!(
99 "you aren't signed in to registry `{registry}`: run `bynk login --registry {registry}`"
100 ),
101 )
102 })?;
103 if session.expires_at.is_some_and(|t| t <= now_millis()) {
104 return Err(fail(
105 ACCOUNT_REFUSED,
106 format!(
107 "your session on registry `{registry}` expired: run `bynk login --registry {registry}`"
108 ),
109 ));
110 }
111 Ok(Live {
112 client,
113 registry,
114 bearer: Some(session.token),
115 })
116}
117
118#[derive(Debug, Clone, PartialEq, Eq)]
124pub(crate) struct DeviceStart {
125 pub poll: String,
126 pub user_code: String,
127 pub verification_uri: String,
128 pub interval: u64,
129 pub expires_in: u64,
130}
131
132#[derive(Debug, Clone, PartialEq, Eq)]
134pub(crate) struct SignedIn {
135 pub token: String,
136 pub login: String,
137 pub expires_at: i64,
138}
139
140pub fn login(target: &Target) -> Result<(), FetchError> {
143 let (client, registry) = open(target, None);
144 let mut api = Live {
145 client,
146 registry: registry.clone(),
147 bearer: None,
148 };
149 let start = start(&mut api, ®istry)?;
150 eprintln!(
151 "To sign in to registry `{registry}`, open {} and enter the code {}.\nNever enter a code you didn't request. Waiting…",
152 clean(&start.verification_uri),
153 clean(&start.user_code)
154 );
155 let began = Instant::now();
156 let signed = poll(&mut api, ®istry, &start, &mut |d| {
157 std::thread::sleep(d);
158 began.elapsed()
159 })?;
160 let path = credentials_file()?;
161 let mut doc = read_doc(&path).map_err(|e| fail(ACCOUNT_REFUSED, e))?;
162 set_session(&mut doc, ®istry, &signed);
163 write_doc(&path, &doc).map_err(|e| fail(ACCOUNT_REFUSED, e))?;
164 eprintln!(
165 "Signed in to `{registry}` as {} (until {}). Saved to {}.",
166 signed.login,
167 date(signed.expires_at),
168 path.display()
169 );
170 if std::env::var_os(override_variable(®istry)).is_some() {
171 emsg!(
172 "bynk: warning: `{}` is set, and is used instead of the saved session",
173 override_variable(®istry)
174 );
175 }
176 Ok(())
177}
178
179pub fn logout(target: &Target) -> Result<(), FetchError> {
182 let (client, registry) = open(target, None);
183 let Some(session) = session(®istry) else {
184 emsg!("bynk: you aren't signed in to registry `{registry}`");
185 return Ok(());
186 };
187 let mut api = Live {
188 client,
189 registry: registry.clone(),
190 bearer: Some(session.token),
191 };
192 let (status, body) = api.call("DELETE", "session", None)?;
193 if !(200..300).contains(&status) && status != 401 {
195 return Err(refused(®istry, status, &body));
196 }
197 if let Some(path) = super::credentials_path() {
198 let mut doc = read_doc(&path).map_err(|e| fail(ACCOUNT_REFUSED, e))?;
199 if remove_session(&mut doc, ®istry) {
200 write_doc(&path, &doc).map_err(|e| fail(ACCOUNT_REFUSED, e))?;
201 }
202 }
203 emsg!("bynk: signed out of `{registry}`");
204 if session.from_env {
205 emsg!(
206 "bynk: note: `{}` still holds the token; unset it",
207 override_variable(®istry)
208 );
209 }
210 Ok(())
211}
212
213pub(crate) fn start(api: &mut dyn Api, registry: &str) -> Result<DeviceStart, FetchError> {
215 let (status, body) = api.call("POST", "login", None)?;
216 if status != 200 {
217 return Err(refused(registry, status, &body));
218 }
219 let v = parse(registry, &body)?;
220 let text = |k: &str| v.get(k).and_then(Value::as_str).map(str::to_owned);
221 let num = |k: &str| v.get(k).and_then(Value::as_u64);
222 match (
223 text("poll"),
224 text("userCode"),
225 text("verificationUri"),
226 num("interval"),
227 num("expiresIn"),
228 ) {
229 (Some(poll), Some(user_code), Some(verification_uri), Some(interval), Some(expires_in)) => {
230 Ok(DeviceStart {
231 poll,
232 user_code,
233 verification_uri,
234 interval,
235 expires_in,
236 })
237 }
238 _ => Err(malformed(registry)),
239 }
240}
241
242pub(crate) fn poll(
246 api: &mut dyn Api,
247 registry: &str,
248 start: &DeviceStart,
249 wait: &mut dyn FnMut(Duration) -> Duration,
250) -> Result<SignedIn, FetchError> {
251 let mut interval = start.interval.max(MIN_INTERVAL);
252 let deadline = Duration::from_secs(start.expires_in);
253 let expired = || {
254 fail(
255 ACCOUNT_REFUSED,
256 "the code expired before it was approved: run `bynk login` again",
257 )
258 };
259 loop {
260 if wait(Duration::from_secs(interval)) >= deadline {
261 return Err(expired());
262 }
263 let (status, body) =
264 api.call("POST", "login/poll", Some(&json!({ "poll": start.poll })))?;
265 if status == 200 {
266 let v = parse(registry, &body)?;
267 return match (
268 v.get("token").and_then(Value::as_str),
269 v.get("login").and_then(Value::as_str),
270 v.get("expiresAt").and_then(Value::as_i64),
271 ) {
272 (Some(token), Some(login), Some(expires_at)) => Ok(SignedIn {
273 token: token.to_owned(),
274 login: login.to_owned(),
275 expires_at,
276 }),
277 _ => Err(malformed(registry)),
278 };
279 }
280 match error_code(&body).as_deref() {
283 Some("authorization_pending") => {}
284 Some("slow_down") => interval += SLOW_DOWN,
285 Some("expired_token") => return Err(expired()),
286 Some("access_denied") => {
287 return Err(fail(ACCOUNT_REFUSED, "the sign-in was declined at GitHub"));
288 }
289 _ => return Err(refused(registry, status, &body)),
290 }
291 }
292}
293
294pub fn claim(
301 target: &Target,
302 org: &str,
303 block: bool,
304 owner: Option<&str>,
305) -> Result<(), FetchError> {
306 let mut api = signed_in(target, org)?;
307 let mut body = json!({ "block": block });
308 if let Some(o) = owner {
309 body["owner"] = json!(o);
310 }
311 let (status, answer) = api.call("POST", &orgs(&[org])?, Some(&body))?;
312 let registry = &api.registry;
313 match status {
314 201 => emsg!(
315 "bynk: claimed `{org}` on `{registry}`{}",
316 if block { " (blocked)" } else { "" }
317 ),
318 200 => emsg!("bynk: `{org}` on `{registry}` is already yours"),
319 _ => return Err(refused(registry, status, &answer)),
320 }
321 Ok(())
322}
323
324pub fn show(target: &Target, org: &str, json: bool) -> Result<(), FetchError> {
327 let mut api = signed_in(target, org)?;
328 let view = view(&mut api, org)?;
329 if json {
330 println!(
331 "{}",
332 serde_json::to_string_pretty(&view).expect("a JSON value")
333 );
334 } else {
335 print!("{}", render(&api.registry, &view));
336 }
337 Ok(())
338}
339
340pub fn set_blocked(target: &Target, org: &str, blocked: bool) -> Result<(), FetchError> {
342 let mut api = signed_in(target, org)?;
343 acknowledged(
344 &mut api,
345 "PUT",
346 &orgs(&[org, "blocked"])?,
347 Some(&json!({ "blocked": blocked })),
348 )?;
349 eprintln!(
350 "bynk: {} `{org}` on `{}`",
351 if blocked { "blocked" } else { "unblocked" },
352 api.registry
353 );
354 Ok(())
355}
356
357pub fn member_add(target: &Target, org: &str, login: &str) -> Result<(), FetchError> {
359 let mut api = signed_in(target, org)?;
360 acknowledged(&mut api, "PUT", &orgs(&[org, "members", login])?, None)?;
361 emsg!("bynk: added {login} to `{org}` on `{}`", api.registry);
362 Ok(())
363}
364
365pub fn member_remove(target: &Target, org: &str, who: &str) -> Result<(), FetchError> {
367 let mut api = signed_in(target, org)?;
368 let id = member_id(&mut api, org, who)?;
369 acknowledged(&mut api, "DELETE", &orgs(&[org, "members", &id])?, None)?;
370 emsg!("bynk: removed {who} from `{org}` on `{}`", api.registry);
371 Ok(())
372}
373
374#[derive(Debug, Clone)]
376pub struct Mint {
377 pub can: Vec<String>,
378 pub days: u32,
379 pub note: String,
380 pub save: bool,
383 pub force: bool,
385}
386
387pub fn token_mint(target: &Target, org: &str, mint: &Mint) -> Result<(), FetchError> {
390 let mut api = signed_in(target, org)?;
391 let registry = api.registry.clone();
392 let saving = if mint.save {
394 let path = credentials_file()?;
395 let doc = read_doc(&path).map_err(|e| fail(ACCOUNT_REFUSED, e))?;
396 check_publish_slot(&doc, ®istry, org, None, mint.force)
397 .map_err(|e| fail(ACCOUNT_REFUSED, e))?;
398 Some((path, doc))
399 } else {
400 None
401 };
402 let body = json!({ "can": mint.can, "days": mint.days, "note": mint.note });
403 let (status, answer) = api.call("POST", &orgs(&[org, "tokens"])?, Some(&body))?;
404 if status != 201 && status != 200 {
405 return Err(refused(®istry, status, &answer));
406 }
407 let v = parse(®istry, &answer)?;
408 let token = v
409 .get("token")
410 .and_then(Value::as_str)
411 .ok_or_else(|| malformed(®istry))?;
412 let info = v.get("info").cloned().unwrap_or(Value::Null);
413 let id = info.get("id").and_then(Value::as_str).unwrap_or("?");
414 let can = info
415 .get("can")
416 .and_then(Value::as_array)
417 .map(|c| {
418 c.iter()
419 .filter_map(Value::as_str)
420 .collect::<Vec<_>>()
421 .join(", ")
422 })
423 .unwrap_or_default();
424 let until = info
425 .get("expiresAt")
426 .and_then(Value::as_i64)
427 .map(date)
428 .unwrap_or_default();
429 emsg!(
430 "bynk: minted token {} for `{org}` on `{registry}` ({can}; until {until})",
431 short_id(id)
432 );
433 match saving {
434 Some((path, mut doc)) => {
435 check_publish_slot(&doc, ®istry, org, Some(token), mint.force)
436 .map_err(|e| fail(ACCOUNT_REFUSED, e))?;
437 let saved = set_publish_token(&mut doc, ®istry, org, token)
438 .and_then(|()| write_doc(&path, &doc));
439 if let Err(e) = saved {
440 emsg!(
442 "bynk: note: couldn't save it, so it is shown once, below; keep it somewhere safe, or revoke it with `bynk org token revoke {org} {}`",
443 short_id(id)
444 );
445 println!("{token}");
446 return Err(fail(ACCOUNT_REFUSED, e));
447 }
448 emsg!(
449 "bynk: saved as `[registries.{registry}.organisations.{org}] token` in {}",
450 path.display()
451 );
452 if registry_wide_token(&doc, ®istry) {
453 emsg!(
454 "bynk: `{org}` now uses its own token; `[registries.{registry}] token` still serves other organisations"
455 );
456 }
457 let var = bynk_project::manifest::registry_token_var(®istry);
458 if std::env::var_os(&var).is_some() {
459 emsg!(
460 "bynk: warning: `{var}` is set, and `bynk publish` uses it instead of any saved token"
461 );
462 }
463 }
464 None => {
465 emsg!("bynk: note: it is shown once, below; keep it somewhere safe");
466 println!("{token}");
467 }
468 }
469 Ok(())
470}
471
472pub fn token_revoke(target: &Target, org: &str, id: &str) -> Result<(), FetchError> {
475 let mut api = signed_in(target, org)?;
476 let id = token_id(&mut api, org, id)?;
477 acknowledged(&mut api, "DELETE", &orgs(&[org, "tokens", &id])?, None)?;
478 eprintln!(
479 "bynk: revoked token {} for `{org}` on `{}`",
480 short_id(&id),
481 api.registry
482 );
483 Ok(())
484}
485
486fn view(api: &mut Live, org: &str) -> Result<Value, FetchError> {
488 let (status, body) = api.call("GET", &orgs(&[org])?, None)?;
489 if status != 200 {
490 return Err(refused(&api.registry, status, &body));
491 }
492 parse(&api.registry, &body)
493}
494
495fn acknowledged(
497 api: &mut Live,
498 method: &str,
499 path: &str,
500 body: Option<&Value>,
501) -> Result<(), FetchError> {
502 let (status, answer) = api.call(method, path, body)?;
503 if (200..300).contains(&status) {
504 Ok(())
505 } else {
506 Err(refused(&api.registry, status, &answer))
507 }
508}
509
510fn member_id(api: &mut Live, org: &str, who: &str) -> Result<String, FetchError> {
514 if !who.is_empty() && who.bytes().all(|b| b.is_ascii_digit()) {
515 return Ok(who.to_owned());
516 }
517 let v = view(api, org)?;
518 find_member(&v, who)
519 .ok_or_else(|| fail(ACCOUNT_REFUSED, format!("`{org}` has no member `{who}`")))
520}
521
522pub(crate) fn find_member(view: &Value, login: &str) -> Option<String> {
525 view.get("members")?
526 .as_array()?
527 .iter()
528 .find(|m| {
529 m.get("login")
530 .and_then(Value::as_str)
531 .is_some_and(|l| l.eq_ignore_ascii_case(login))
532 })
533 .and_then(|m| m.get("id")?.as_i64())
534 .map(|id| id.to_string())
535}
536
537fn token_id(api: &mut Live, org: &str, prefix: &str) -> Result<String, FetchError> {
539 let v = view(api, org)?;
540 find_token(&v, prefix).map_err(|why| fail(ACCOUNT_REFUSED, format!("`{org}` {why}")))
541}
542
543pub(crate) fn find_token(view: &Value, prefix: &str) -> Result<String, String> {
545 let ids: Vec<&str> = view
546 .get("tokens")
547 .and_then(Value::as_array)
548 .map(|ts| {
549 ts.iter()
550 .filter_map(|t| t.get("id")?.as_str())
551 .filter(|id| !prefix.is_empty() && id.starts_with(prefix))
552 .collect()
553 })
554 .unwrap_or_default();
555 match ids.as_slice() {
556 [one] => Ok((*one).to_owned()),
557 [] => Err(format!("has no token `{prefix}` (see `bynk org show`)")),
558 _ => Err(format!(
559 "has {} tokens starting `{prefix}`: give more of the id",
560 ids.len()
561 )),
562 }
563}
564
565fn orgs(segments: &[&str]) -> Result<String, FetchError> {
568 let mut path = String::from("orgs");
569 for s in segments {
570 let plain = !s.is_empty()
571 && s.bytes()
572 .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_');
573 if !plain {
574 return Err(fail(
575 ACCOUNT_REFUSED,
576 format!("`{s}` isn't a name the account API takes"),
577 ));
578 }
579 path.push('/');
580 path.push_str(s);
581 }
582 Ok(path)
583}
584
585pub(crate) fn render(registry: &str, view: &Value) -> String {
587 let user = |u: &Value| {
588 format!(
589 "{} (#{})",
590 u.get("login").and_then(Value::as_str).unwrap_or("?"),
591 u.get("id").and_then(Value::as_i64).unwrap_or_default()
592 )
593 };
594 let members: Vec<&Value> = view
595 .get("members")
596 .and_then(Value::as_array)
597 .map(|m| m.iter().collect())
598 .unwrap_or_default();
599 let login_of = |id: i64| {
600 members
601 .iter()
602 .copied()
603 .chain(view.get("owner"))
604 .find(|m| m.get("id").and_then(Value::as_i64) == Some(id))
605 .and_then(|m| m.get("login")?.as_str())
606 .map_or_else(
607 || {
608 if id == 0 {
609 "an operator".to_owned()
610 } else {
611 format!("#{id}")
612 }
613 },
614 str::to_owned,
615 )
616 };
617 let name = view.get("name").and_then(Value::as_str).unwrap_or("?");
618 let blocked = view.get("blocked").and_then(Value::as_bool) == Some(true);
619 let mut out = format!("{name} on `{registry}`\n");
620 out.push_str(&format!(
621 " owner: {}\n",
622 view.get("owner").map(user).unwrap_or_default()
623 ));
624 out.push_str(&format!(
625 " members: {}\n",
626 members
627 .iter()
628 .map(|m| user(m))
629 .collect::<Vec<_>>()
630 .join(", ")
631 ));
632 out.push_str(&format!(
633 " blocked: {}\n",
634 if blocked { "yes" } else { "no" }
635 ));
636 let tokens: Vec<&Value> = view
637 .get("tokens")
638 .and_then(Value::as_array)
639 .map(|t| t.iter().collect())
640 .unwrap_or_default();
641 if tokens.is_empty() {
642 out.push_str(" tokens: none\n");
643 } else {
644 out.push_str(" tokens:\n");
645 for t in tokens {
646 let id = t.get("id").and_then(Value::as_str).unwrap_or("?");
647 let can = t
648 .get("can")
649 .and_then(Value::as_array)
650 .map(|c| {
651 c.iter()
652 .filter_map(Value::as_str)
653 .collect::<Vec<_>>()
654 .join(", ")
655 })
656 .unwrap_or_default();
657 let until = t
658 .get("expiresAt")
659 .and_then(Value::as_i64)
660 .map(date)
661 .unwrap_or_default();
662 let by = login_of(t.get("mintedBy").and_then(Value::as_i64).unwrap_or(-1));
663 let note = t.get("note").and_then(Value::as_str).unwrap_or_default();
664 out.push_str(&format!(
665 " {} {can} until {until} minted by {by}",
666 short_id(id)
667 ));
668 if !note.is_empty() {
669 out.push_str(&format!(" {note:?}"));
670 }
671 out.push('\n');
672 }
673 }
674 out
675}
676
677fn short_id(id: &str) -> &str {
679 id.get(..12).unwrap_or(id)
680}
681
682fn clean(text: &str) -> String {
689 text.chars().filter(|c| !c.is_control()).collect()
690}
691
692fn error_code(body: &[u8]) -> Option<String> {
694 serde_json::from_slice::<Value>(body)
695 .ok()?
696 .get("error")?
697 .as_str()
698 .map(str::to_owned)
699}
700
701fn parse(registry: &str, body: &[u8]) -> Result<Value, FetchError> {
702 serde_json::from_slice(body).map_err(|_| malformed(registry))
703}
704
705fn malformed(registry: &str) -> FetchError {
706 fail(
707 ACCOUNT_REFUSED,
708 format!("registry `{registry}` answered the account API with something unexpected"),
709 )
710}
711
712pub(crate) fn refused(registry: &str, status: u16, body: &[u8]) -> FetchError {
714 let v = serde_json::from_slice::<Value>(body).ok();
715 let field = |k: &str| v.as_ref()?.get(k)?.as_str().map(str::to_owned);
716 let mut message = match (field("error"), field("message")) {
717 (Some(code), Some(why)) => {
718 format!(
719 "registry `{registry}` refused it (HTTP {status}, `{}`): {}",
720 clean(&code),
721 clean(&why)
722 )
723 }
724 _ if status == 404 || status == 405 => format!(
726 "registry `{registry}` has no account API (HTTP {status}) — only the first-party registry service has accounts"
727 ),
728 _ => format!("registry `{registry}` refused it (HTTP {status})"),
729 };
730 if status == 401 {
731 message.push_str(&format!(
732 " — sign in again with `bynk login --registry {registry}`"
733 ));
734 }
735 fail(ACCOUNT_REFUSED, message)
736}
737
738pub fn override_variable(name: &str) -> String {
745 format!(
746 "BYNK_ACCOUNT_{}_TOKEN",
747 name.to_ascii_uppercase().replace('-', "_")
748 )
749}
750
751#[derive(Debug, Clone, PartialEq, Eq)]
753pub(crate) struct Session {
754 pub token: String,
755 pub expires_at: Option<i64>,
756 pub from_env: bool,
758}
759
760fn session(registry: &str) -> Option<Session> {
763 if let Some(t) = std::env::var(override_variable(registry))
764 .ok()
765 .filter(|t| !t.trim().is_empty())
766 {
767 return Some(Session {
768 token: t,
769 expires_at: None,
770 from_env: true,
771 });
772 }
773 let doc = read_doc(&super::credentials_path()?).ok()?;
774 saved_session(&doc, registry)
775}
776
777pub(crate) fn saved_session(doc: &toml_edit::DocumentMut, registry: &str) -> Option<Session> {
779 let entry = doc.get("accounts")?.get(registry)?;
780 Some(Session {
781 token: entry.get("token")?.as_str()?.to_owned(),
782 expires_at: entry.get("expires-at").and_then(|v| v.as_integer()),
783 from_env: false,
784 })
785}
786
787fn credentials_file() -> Result<PathBuf, FetchError> {
788 super::credentials_path().ok_or_else(|| {
789 fail(
790 ACCOUNT_REFUSED,
791 "there is no home directory to keep the credentials file in (set `XDG_CONFIG_HOME`)",
792 )
793 })
794}
795
796pub(crate) fn read_doc(path: &Path) -> Result<toml_edit::DocumentMut, String> {
798 match std::fs::read_to_string(path) {
799 Ok(text) => text
800 .parse()
801 .map_err(|e| format!("`{}` isn't valid TOML: {e}", path.display())),
802 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(toml_edit::DocumentMut::new()),
803 Err(e) => Err(format!("could not read `{}`: {e}", path.display())),
804 }
805}
806
807pub(crate) fn write_doc(path: &Path, doc: &toml_edit::DocumentMut) -> Result<(), String> {
811 let dir = path
812 .parent()
813 .ok_or("the credentials file has no directory")?;
814 std::fs::create_dir_all(dir)
815 .map_err(|e| format!("could not create `{}`: {e}", dir.display()))?;
816 let tmp = dir.join(format!(".credentials.toml.{}", std::process::id()));
817 let mut options = std::fs::OpenOptions::new();
818 let _ = std::fs::remove_file(&tmp);
821 options.write(true).create_new(true);
822 #[cfg(unix)]
823 {
824 use std::os::unix::fs::OpenOptionsExt;
825 options.mode(0o600);
826 }
827 let written = (|| {
828 use std::io::Write;
829 let mut f = options.open(&tmp)?;
830 f.write_all(doc.to_string().as_bytes())?;
831 f.sync_all()?;
832 std::fs::rename(&tmp, path)
833 })();
834 written.map_err(|e| {
835 let _ = std::fs::remove_file(&tmp);
836 format!("could not write `{}`: {e}", path.display())
837 })
838}
839
840fn entry<'d>(
842 doc: &'d mut toml_edit::DocumentMut,
843 table: &str,
844 name: &str,
845) -> &'d mut toml_edit::Table {
846 let outer = doc
847 .entry(table)
848 .or_insert_with(|| {
849 let mut t = toml_edit::Table::new();
850 t.set_implicit(true);
851 toml_edit::Item::Table(t)
852 })
853 .as_table_mut()
854 .expect("a table");
855 outer
856 .entry(name)
857 .or_insert_with(toml_edit::table)
858 .as_table_mut()
859 .expect("a table")
860}
861
862pub(crate) fn set_session(doc: &mut toml_edit::DocumentMut, registry: &str, signed: &SignedIn) {
864 let t = entry(doc, "accounts", registry);
865 t["token"] = toml_edit::value(signed.token.as_str());
866 t["login"] = toml_edit::value(signed.login.as_str());
867 t["expires-at"] = toml_edit::value(signed.expires_at);
868}
869
870pub(crate) fn remove_session(doc: &mut toml_edit::DocumentMut, registry: &str) -> bool {
872 let Some(accounts) = doc.get_mut("accounts").and_then(|a| a.as_table_mut()) else {
873 return false;
874 };
875 let removed = accounts.remove(registry).is_some();
876 if accounts.is_empty() {
877 doc.remove("accounts");
878 }
879 removed
880}
881
882pub(crate) fn check_publish_slot(
887 doc: &toml_edit::DocumentMut,
888 registry: &str,
889 org: &str,
890 token: Option<&str>,
891 force: bool,
892) -> Result<(), String> {
893 let held = doc
894 .get("registries")
895 .and_then(|r| r.get(registry))
896 .and_then(|r| r.get("organisations"))
897 .and_then(|o| o.get(org))
898 .and_then(|o| o.get("token"))
899 .and_then(|t| t.as_str());
900 match held {
901 Some(h) if !force && token != Some(h) => Err(format!(
902 "`[registries.{registry}.organisations.{org}] token` holds a token already: `--force` replaces it"
903 )),
904 _ => set_publish_token(&mut doc.clone(), registry, org, "-"),
906 }
907}
908
909pub(crate) fn set_publish_token(
913 doc: &mut toml_edit::DocumentMut,
914 registry: &str,
915 org: &str,
916 token: &str,
917) -> Result<(), String> {
918 let path = ["registries", registry, "organisations", org];
919 let mut t: &mut dyn toml_edit::TableLike = doc.as_table_mut();
920 for (i, key) in path.into_iter().enumerate() {
921 let new = !t.contains_key(key);
922 let item = t.entry(key).or_insert(toml_edit::table());
923 if new
924 && i + 1 < path.len()
925 && let Some(table) = item.as_table_mut()
926 {
927 table.set_implicit(true);
928 }
929 t = item.as_table_like_mut().ok_or_else(|| {
930 format!(
931 "`{}` in the credentials file isn't a table",
932 path[..=i].join(".")
933 )
934 })?;
935 }
936 t.insert("token", toml_edit::value(token));
937 Ok(())
938}
939
940fn registry_wide_token(doc: &toml_edit::DocumentMut, registry: &str) -> bool {
942 doc.get("registries")
943 .and_then(|r| r.get(registry))
944 .and_then(|r| r.get("token"))
945 .is_some()
946}
947
948fn now_millis() -> i64 {
949 std::time::SystemTime::now()
950 .duration_since(std::time::UNIX_EPOCH)
951 .map_or(0, |d| i64::try_from(d.as_millis()).unwrap_or(i64::MAX))
952}
953
954fn date(millis: i64) -> String {
956 time::OffsetDateTime::from_unix_timestamp(millis.div_euclid(1000))
957 .map_or_else(|_| millis.to_string(), |t| t.date().to_string())
958}
959
960#[cfg(test)]
961mod tests {
962 use super::*;
963 use std::collections::VecDeque;
964
965 struct Stub {
967 answers: VecDeque<(u16, Value)>,
968 asked: Vec<(String, String, Option<Value>)>,
969 }
970
971 impl Stub {
972 fn new(answers: &[(u16, Value)]) -> Stub {
973 Stub {
974 answers: answers.iter().cloned().collect(),
975 asked: Vec::new(),
976 }
977 }
978 }
979
980 impl Api for Stub {
981 fn call(
982 &mut self,
983 method: &str,
984 path: &str,
985 body: Option<&Value>,
986 ) -> Result<(u16, Vec<u8>), FetchError> {
987 self.asked
988 .push((method.to_owned(), path.to_owned(), body.cloned()));
989 let (status, v) = self.answers.pop_front().expect("an answer left");
990 Ok((status, v.to_string().into_bytes()))
991 }
992 }
993
994 fn problem(code: &str) -> Value {
995 json!({ "error": code, "message": "…" })
996 }
997
998 fn device(interval: u64, expires_in: u64) -> DeviceStart {
999 DeviceStart {
1000 poll: "p1".into(),
1001 user_code: "WDJB-MJHT".into(),
1002 verification_uri: "https://github.com/login/device".into(),
1003 interval,
1004 expires_in,
1005 }
1006 }
1007
1008 fn run(stub: &mut Stub, start: &DeviceStart) -> (Result<SignedIn, FetchError>, Vec<u64>) {
1010 let mut waits = Vec::new();
1011 let mut elapsed = Duration::ZERO;
1012 let got = poll(stub, "bynk", start, &mut |d| {
1013 waits.push(d.as_secs());
1014 elapsed += d;
1015 elapsed
1016 });
1017 (got, waits)
1018 }
1019
1020 #[test]
1021 fn the_start_is_read_from_its_json() {
1022 let mut stub = Stub::new(&[(
1023 200,
1024 json!({ "poll": "p1", "userCode": "WDJB-MJHT", "verificationUri": "https://github.com/login/device", "interval": 5, "expiresIn": 900 }),
1025 )]);
1026 assert_eq!(start(&mut stub, "bynk").unwrap(), device(5, 900));
1027 assert_eq!(stub.asked[0].0, "POST");
1028 assert_eq!(stub.asked[0].1, "login");
1029 }
1030
1031 #[test]
1032 fn polling_waits_the_interval_and_slows_down_by_five_seconds() {
1033 let mut stub = Stub::new(&[
1034 (400, problem("authorization_pending")),
1035 (429, problem("slow_down")),
1036 (400, problem("authorization_pending")),
1037 (
1038 200,
1039 json!({ "token": "bynka_x", "login": "ann", "expiresAt": 1_795_392_000_000_i64 }),
1040 ),
1041 ]);
1042 let (got, waits) = run(&mut stub, &device(2, 900));
1043 assert_eq!(
1044 got.unwrap(),
1045 SignedIn {
1046 token: "bynka_x".into(),
1047 login: "ann".into(),
1048 expires_at: 1_795_392_000_000,
1049 }
1050 );
1051 assert_eq!(waits, [2, 2, 7, 7]);
1052 assert!(stub.asked.iter().all(|(m, p, b)| m == "POST"
1053 && p == "login/poll"
1054 && b == &Some(json!({ "poll": "p1" }))));
1055 }
1056
1057 #[test]
1058 fn polling_stops_on_expiry_denial_and_the_local_deadline() {
1059 let (got, _) = run(
1060 &mut Stub::new(&[(410, problem("expired_token"))]),
1061 &device(1, 900),
1062 );
1063 assert!(got.unwrap_err().message.contains("expired"));
1064 let (got, _) = run(
1065 &mut Stub::new(&[(403, problem("access_denied"))]),
1066 &device(1, 900),
1067 );
1068 assert!(got.unwrap_err().message.contains("declined"));
1069 let pending = vec![(400, problem("authorization_pending")); 3];
1072 let mut stub = Stub::new(&pending);
1073 let (got, waits) = run(&mut stub, &device(5, 12));
1074 assert!(got.unwrap_err().message.contains("expired"));
1075 assert_eq!(waits, [5, 5, 5]);
1076 assert_eq!(stub.asked.len(), 2);
1077 }
1078
1079 #[test]
1080 fn a_zero_interval_still_waits() {
1081 let mut stub = Stub::new(&[
1082 (400, problem("authorization_pending")),
1083 (
1084 200,
1085 json!({ "token": "bynka_x", "login": "ann", "expiresAt": 0 }),
1086 ),
1087 ]);
1088 let (got, waits) = run(&mut stub, &device(0, 900));
1089 assert!(got.is_ok());
1090 assert_eq!(waits, [1, 1]);
1091 }
1092
1093 #[test]
1094 fn server_text_is_printed_without_control_characters() {
1095 let body = json!({ "error": "x\u{1b}[2K", "message": "ok\rerror[bynk.fake]: no" });
1096 let e = refused("bynk", 403, body.to_string().as_bytes());
1097 assert!(!e.message.chars().any(char::is_control), "{:?}", e.message);
1098 }
1099
1100 #[test]
1101 fn polling_branches_on_the_error_code_not_the_status() {
1102 let (got, _) = run(
1104 &mut Stub::new(&[(400, problem("bad_request"))]),
1105 &device(0, 900),
1106 );
1107 let e = got.unwrap_err();
1108 assert_eq!(e.code, ACCOUNT_REFUSED);
1109 assert!(e.message.contains("`bad_request`"), "{}", e.message);
1110 }
1111
1112 #[test]
1113 fn a_401_says_to_sign_in_again() {
1114 let e = refused("bynk", 401, problem("unauthorised").to_string().as_bytes());
1115 assert!(
1116 e.message.contains("bynk login --registry bynk"),
1117 "{}",
1118 e.message
1119 );
1120 let e = refused("acme", 404, b"not json");
1121 assert!(e.message.contains("no account API"), "{}", e.message);
1122 let e = refused("acme", 405, b"");
1123 assert!(
1124 e.message.contains("no account API (HTTP 405)"),
1125 "{}",
1126 e.message
1127 );
1128 }
1129
1130 #[test]
1131 fn sessions_are_kept_apart_from_publish_tokens() {
1132 let mut doc: toml_edit::DocumentMut =
1133 "# mine\n[registries.bynk]\ntoken = \"bynk_old\" # laptop\n"
1134 .parse()
1135 .unwrap();
1136 set_session(
1137 &mut doc,
1138 "bynk",
1139 &SignedIn {
1140 token: "bynka_new".into(),
1141 login: "ann".into(),
1142 expires_at: 7,
1143 },
1144 );
1145 let text = doc.to_string();
1146 assert!(
1147 text.starts_with("# mine\n[registries.bynk]\ntoken = \"bynk_old\" # laptop\n"),
1148 "{text}"
1149 );
1150 assert!(
1151 text.contains(
1152 "[accounts.bynk]\ntoken = \"bynka_new\"\nlogin = \"ann\"\nexpires-at = 7\n"
1153 ),
1154 "{text}"
1155 );
1156 assert_eq!(
1157 saved_session(&doc, "bynk"),
1158 Some(Session {
1159 token: "bynka_new".into(),
1160 expires_at: Some(7),
1161 from_env: false,
1162 })
1163 );
1164 assert!(remove_session(&mut doc, "bynk"));
1165 assert!(!remove_session(&mut doc, "bynk"));
1166 assert_eq!(
1167 doc.to_string(),
1168 "# mine\n[registries.bynk]\ntoken = \"bynk_old\" # laptop\n"
1169 );
1170 }
1171
1172 #[test]
1173 fn saving_a_publish_token_never_replaces_another_without_force() {
1174 let mut doc = toml_edit::DocumentMut::new();
1175 assert!(check_publish_slot(&doc, "bynk", "acme", None, false).is_ok());
1176 set_publish_token(&mut doc, "bynk", "acme", "bynk_a").unwrap();
1177 assert_eq!(
1178 doc.to_string(),
1179 "[registries.bynk.organisations.acme]\ntoken = \"bynk_a\"\n"
1180 );
1181 assert!(check_publish_slot(&doc, "bynk", "acme", None, false).is_err());
1182 assert!(check_publish_slot(&doc, "bynk", "acme", Some("bynk_b"), false).is_err());
1183 assert!(check_publish_slot(&doc, "bynk", "acme", Some("bynk_a"), false).is_ok());
1184 assert!(check_publish_slot(&doc, "bynk", "acme", Some("bynk_b"), true).is_ok());
1185 assert!(check_publish_slot(&doc, "bynk", "acme-labs", None, false).is_ok());
1187 assert!(check_publish_slot(&doc, "other", "acme", None, false).is_ok());
1188 }
1189
1190 #[test]
1191 fn an_organisation_s_slot_sits_beside_the_registry_wide_one() {
1192 let mut doc: toml_edit::DocumentMut =
1193 "# mine\n[registries.bynk]\ntoken = \"bynk_wide\" # laptop\n"
1194 .parse()
1195 .unwrap();
1196 assert!(check_publish_slot(&doc, "bynk", "acme", None, false).is_ok());
1198 assert!(registry_wide_token(&doc, "bynk"));
1199 set_publish_token(&mut doc, "bynk", "acme", "bynk_acme").unwrap();
1200 set_publish_token(&mut doc, "bynk", "acme-labs", "bynk_labs").unwrap();
1201 assert_eq!(
1202 doc.to_string(),
1203 "# mine\n[registries.bynk]\ntoken = \"bynk_wide\" # laptop\n\n\
1204 [registries.bynk.organisations.acme]\ntoken = \"bynk_acme\"\n\n\
1205 [registries.bynk.organisations.acme-labs]\ntoken = \"bynk_labs\"\n"
1206 );
1207 assert!(!registry_wide_token(&doc, "other"));
1208 }
1209
1210 #[test]
1211 fn an_inline_organisations_table_is_written_into_and_a_non_table_refused() {
1212 let mut doc: toml_edit::DocumentMut =
1213 "[registries.bynk]\norganisations = { globex = { token = \"bynk_g\" } }\n"
1214 .parse()
1215 .unwrap();
1216 assert!(check_publish_slot(&doc, "bynk", "acme", None, false).is_ok());
1217 set_publish_token(&mut doc, "bynk", "acme", "bynk_a").unwrap();
1218 let text = doc.to_string();
1219 let parsed: toml::Table = text.parse().unwrap();
1220 let orgs = &parsed["registries"]["bynk"]["organisations"];
1221 assert_eq!(orgs["globex"]["token"].as_str(), Some("bynk_g"), "{text}");
1222 assert_eq!(orgs["acme"]["token"].as_str(), Some("bynk_a"), "{text}");
1223 let doc: toml_edit::DocumentMut = "[registries.bynk]\norganisations = \"x\"\n"
1225 .parse()
1226 .unwrap();
1227 let err = check_publish_slot(&doc, "bynk", "acme", None, false).unwrap_err();
1228 assert_eq!(
1229 err,
1230 "`registries.bynk.organisations` in the credentials file isn't a table"
1231 );
1232 }
1233
1234 #[test]
1235 fn an_organisation_named_like_its_registry_writes_no_empty_header() {
1236 let mut doc = toml_edit::DocumentMut::new();
1237 set_publish_token(&mut doc, "bynk", "bynk", "bynk_a").unwrap();
1238 assert_eq!(
1239 doc.to_string(),
1240 "[registries.bynk.organisations.bynk]\ntoken = \"bynk_a\"\n"
1241 );
1242 }
1243
1244 #[cfg(unix)]
1245 #[test]
1246 fn the_credentials_file_is_written_private() {
1247 use std::os::unix::fs::PermissionsExt;
1248 let dir = std::env::temp_dir().join(format!("bynk-account-{}", std::process::id()));
1249 let path = dir.join("bynk").join("credentials.toml");
1250 let mut doc = read_doc(&path).unwrap();
1251 set_publish_token(&mut doc, "bynk", "acme", "bynk_a").unwrap();
1252 write_doc(&path, &doc).unwrap();
1253 let mode = std::fs::metadata(&path).unwrap().permissions().mode();
1254 assert_eq!(mode & 0o777, 0o600);
1255 assert_eq!(read_doc(&path).unwrap().to_string(), doc.to_string());
1256 std::fs::remove_dir_all(&dir).unwrap();
1257 }
1258
1259 #[test]
1260 fn members_and_tokens_are_found_by_login_and_prefix() {
1261 let view = json!({
1262 "name": "acme",
1263 "owner": { "id": 1, "login": "ann" },
1264 "members": [{ "id": 1, "login": "ann" }, { "id": 2, "login": "Bob" }],
1265 "blocked": false,
1266 "tokens": [
1267 { "id": "7f3a00", "can": ["publish"], "expiresAt": 0, "note": "", "mintedBy": 2 },
1268 { "id": "7f3b00", "can": ["publish", "yank"], "expiresAt": 0, "note": "ci", "mintedBy": 0 },
1269 ],
1270 });
1271 assert_eq!(find_member(&view, "bob").as_deref(), Some("2"));
1272 assert_eq!(find_member(&view, "cy"), None);
1273 assert_eq!(find_token(&view, "7f3a").unwrap(), "7f3a00");
1274 assert!(find_token(&view, "7f3").unwrap_err().contains("2 tokens"));
1275 assert!(find_token(&view, "00").is_err());
1276 assert!(find_token(&view, "").is_err());
1277 assert_eq!(
1278 render("bynk", &view),
1279 "acme on `bynk`\n owner: ann (#1)\n members: ann (#1), Bob (#2)\n blocked: no\n tokens:\n 7f3a00 publish until 1970-01-01 minted by Bob\n 7f3b00 publish, yank until 1970-01-01 minted by an operator \"ci\"\n"
1280 );
1281 }
1282
1283 #[test]
1284 fn a_path_segment_must_be_a_plain_name() {
1285 assert_eq!(
1286 orgs(&["acme", "members", "bob"]).unwrap(),
1287 "orgs/acme/members/bob"
1288 );
1289 assert!(orgs(&["..", "x"]).is_err());
1290 assert!(orgs(&["acme/x"]).is_err());
1291 assert!(orgs(&[""]).is_err());
1292 }
1293
1294 #[test]
1295 fn the_override_variable_cannot_collide_with_a_publish_variable() {
1296 assert_eq!(
1297 override_variable("acme-internal"),
1298 "BYNK_ACCOUNT_ACME_INTERNAL_TOKEN"
1299 );
1300 assert_ne!(
1301 override_variable("foo"),
1302 bynk_project::manifest::registry_token_var("foo-account")
1303 );
1304 assert_eq!(date(1_795_392_000_000), "2026-11-23");
1305 }
1306}