1use std::collections::{BTreeMap, HashMap};
21use std::future::Future;
22use std::sync::{Arc, OnceLock};
23
24use zeroize::Zeroizing;
25
26use crate::backend::storage::store::Store;
27use crate::muxbus::github_broker::{self, AppBot, BrokerError, InstallationRequest, LinkedInstallation};
28
29pub const REFRESH_MARGIN_SECS: i64 = 300;
31const INSTALLATIONS_TTL_SECS: i64 = 60;
33const REFUSAL_TTL_SECS: i64 = 20;
36const FALLBACK_LIFETIME_SECS: i64 = 600;
38
39pub fn permissions_for(workflows: bool) -> BTreeMap<String, String> {
42 let mut p: BTreeMap<String, String> = [("contents", "write"), ("pull_requests", "write"), ("issues", "write"), ("metadata", "read")]
43 .into_iter()
44 .map(|(k, v)| (k.to_string(), v.to_string()))
45 .collect();
46 if workflows {
47 p.insert("workflows".to_string(), "write".to_string());
48 }
49 p
50}
51
52#[derive(Debug, Clone, PartialEq, Eq, Hash)]
54pub struct Want {
55 pub agent: String,
56 pub owner: String,
57 pub repo: String,
58 pub workflows: bool,
59}
60
61impl Want {
62 fn normalized(&self) -> Self {
63 Self { agent: self.agent.clone(), owner: self.owner.to_ascii_lowercase(), repo: self.repo.to_ascii_lowercase(), workflows: self.workflows }
64 }
65
66 fn withhold_owner(&self) -> String {
68 format!("github-token:{}:{}/{}:{}", self.agent, self.owner, self.repo, self.workflows)
69 }
70}
71
72fn valid_name(name: &str) -> bool {
74 !name.is_empty() && name.len() <= 100 && name != "." && name != ".." && name.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.'))
75}
76
77#[derive(Clone)]
79pub struct Minted {
80 pub token: Zeroizing<String>,
81 pub expires_at: i64,
83 pub bot: AppBot,
84}
85
86impl std::fmt::Debug for Minted {
87 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
88 f.debug_struct("Minted").field("expires_at", &self.expires_at).field("bot", &self.bot).finish_non_exhaustive()
89 }
90}
91
92#[derive(Debug, Clone, PartialEq, Eq)]
94pub enum TokenError {
95 NoInstallation { owner: String },
97 BadTarget(String),
99 Broker(BrokerError),
101 NoGithubAccount,
103}
104
105impl std::fmt::Display for TokenError {
106 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
107 match self {
108 Self::NoInstallation { owner } => write!(
109 f,
110 "AgentMux can't act on {owner}'s repositories: the AgentMux GitHub App isn't installed there, or isn't linked to this AgentMux account. Install it in Connectors → Accounts"
111 ),
112 Self::BadTarget(what) => write!(f, "{what} isn't a GitHub owner or repository name"),
113 Self::Broker(e) => write!(f, "{e}"),
114 Self::NoGithubAccount => write!(f, "GitHub isn't connected on this AgentMux account: connect it in Connectors → Accounts"),
115 }
116 }
117}
118
119impl From<BrokerError> for TokenError {
120 fn from(e: BrokerError) -> Self {
121 Self::Broker(e)
122 }
123}
124
125#[derive(Debug, Clone)]
127pub struct MintRequest {
128 pub installation_id: u64,
129 pub repositories: Vec<String>,
130 pub permissions: BTreeMap<String, String>,
131 pub agent: String,
132}
133
134pub trait Backend {
136 fn installations(&self) -> impl Future<Output = Result<Vec<LinkedInstallation>, BrokerError>> + Send;
137 fn mint(&self, request: MintRequest) -> impl Future<Output = Result<github_broker::InstallationToken, BrokerError>> + Send;
138 fn revalidate(&self) -> impl Future<Output = Result<(), TokenError>> + Send;
140 fn connection(&self) -> impl Future<Output = Result<String, TokenError>> + Send;
143}
144
145#[derive(Default)]
146struct State {
147 connection: Option<String>,
149 cache: HashMap<Want, Minted>,
150 installations: Option<(i64, Vec<LinkedInstallation>)>,
151 refused: HashMap<Want, (i64, TokenError)>,
152 locks: HashMap<Want, Arc<tokio::sync::Mutex<()>>>,
154}
155
156#[derive(Default)]
158pub struct Tokens {
159 state: std::sync::Mutex<State>,
160}
161
162impl Tokens {
163 fn st(&self) -> std::sync::MutexGuard<'_, State> {
164 self.state.lock().unwrap_or_else(|e| e.into_inner())
165 }
166
167 pub async fn token_for<B: Backend>(&self, backend: &B, want: &Want, now: i64) -> Result<Minted, TokenError> {
169 for (what, name) in [("the owner", &want.owner), ("the repository", &want.repo)] {
170 if !valid_name(name) {
171 return Err(TokenError::BadTarget(format!("{what} {:?}", name.chars().take(40).collect::<String>())));
172 }
173 }
174 let want = want.normalized();
175 let connection = backend.connection().await;
177 self.bind(connection.as_ref().ok());
178 let connection = connection?;
179 let lock = self.st().locks.entry(want.clone()).or_default().clone();
181 let _one = lock.lock().await;
182 if let Some(found) = self.remembered(&want, now) {
183 return found;
184 }
185 let result = self.mint(backend, &want, now).await;
186 let mut st = self.st();
187 if st.connection.as_ref() != Some(&connection) {
189 return result;
190 }
191 match &result {
192 Ok(minted) => {
193 st.refused.remove(&want);
194 crate::backend::transcript::withhold::hold_until(&want.withhold_owner(), &minted.token, minted.expires_at.saturating_mul(1000));
198 st.cache.insert(want.clone(), minted.clone());
199 }
200 Err(TokenError::Broker(BrokerError::Unavailable(_))) if st.cache.get(&want).is_some_and(|m| m.expires_at > now) => {
202 let kept = st.cache[&want].clone();
203 return Ok(kept);
204 }
205 Err(error) => {
206 st.cache.remove(&want);
207 st.refused.insert(want.clone(), (now + REFUSAL_TTL_SECS, error.clone()));
208 }
209 }
210 st.cache.retain(|_, m| m.expires_at > now);
212 st.refused.retain(|_, (until, _)| *until > now);
213 let keep: Vec<Want> = st.cache.keys().chain(st.refused.keys()).cloned().collect();
214 st.locks.retain(|k, l| Arc::strong_count(l) > 1 || keep.contains(k) || *k == want);
215 result
216 }
217
218 fn bind(&self, connection: Option<&String>) {
220 let mut st = self.st();
221 if st.connection.as_ref() != connection {
222 st.cache.clear();
223 st.refused.clear();
224 st.installations = None;
225 st.connection = connection.cloned();
226 }
227 }
228
229 fn remembered(&self, want: &Want, now: i64) -> Option<Result<Minted, TokenError>> {
231 let st = self.st();
232 if let Some(minted) = st.cache.get(want) {
233 if minted.expires_at - now > REFRESH_MARGIN_SECS {
234 return Some(Ok(minted.clone()));
235 }
236 }
237 match st.refused.get(want) {
238 Some((until, error)) if now < *until => Some(Err(error.clone())),
239 _ => None,
240 }
241 }
242
243 async fn mint<B: Backend>(&self, backend: &B, want: &Want, now: i64) -> Result<Minted, TokenError> {
244 let installation = self.installation_for(backend, &want.owner, now).await?;
245 let request = MintRequest {
246 installation_id: installation.installation_id,
247 repositories: vec![want.repo.clone()],
248 permissions: permissions_for(want.workflows),
249 agent: want.agent.clone(),
250 };
251 let answer = match backend.mint(request.clone()).await {
252 Err(BrokerError::LinkStale) => {
254 backend.revalidate().await?;
255 self.st().installations = None;
256 backend.mint(request).await
257 }
258 Err(BrokerError::NotLinked) => {
259 self.st().installations = None;
260 Err(BrokerError::NotLinked)
261 }
262 other => other,
263 }?;
264 let expires_at = answer.expires_at_epoch().unwrap_or(now + FALLBACK_LIFETIME_SECS);
265 tracing::info!(target: "identity", agent = %want.agent, owner = %want.owner, repo = %want.repo, installation = installation.installation_id, "identity.github: minted an agent token");
266 Ok(Minted { token: Zeroizing::new(answer.token), expires_at, bot: answer.app })
267 }
268
269 async fn installation_for<B: Backend>(&self, backend: &B, owner: &str, now: i64) -> Result<LinkedInstallation, TokenError> {
270 let known = self.st().installations.clone();
271 let fresh = matches!(&known, Some((at, _)) if now - *at < INSTALLATIONS_TTL_SECS);
272 let list = match known {
273 Some((_, list)) if fresh => list,
274 _ => {
275 let list = backend.installations().await?;
276 self.st().installations = Some((now, list.clone()));
277 list
278 }
279 };
280 let found = |list: &[LinkedInstallation]| list.iter().find(|i| i.is_usable() && i.github_account.login.eq_ignore_ascii_case(owner)).cloned();
281 if let Some(i) = found(&list) {
282 return Ok(i);
283 }
284 if fresh {
286 let list = backend.installations().await?;
287 self.st().installations = Some((now, list.clone()));
288 if let Some(i) = found(&list) {
289 return Ok(i);
290 }
291 }
292 Err(TokenError::NoInstallation { owner: owner.to_string() })
293 }
294
295 #[cfg(any(test, feature = "test-support"))]
297 fn cached(&self) -> usize {
298 self.st().cache.len()
299 }
300
301 #[cfg(any(test, feature = "test-support"))]
303 fn locks(&self) -> usize {
304 self.st().locks.len()
305 }
306}
307
308pub const BROKER_ENV: &str = "AGENTMUX_GITHUB_BROKER";
311use agentmux_common::github_broker_shim::{GH_FUNCTION_BODY, GH_FUNCTION_NAME, GIT_FUNCTION_BODY, GIT_FUNCTION_NAME};
312const GIT_HOST_ENV: &str = "AGENTMUX_GIT_HOST";
314
315pub(crate) fn host_label() -> Option<String> {
317 let name = whoami::fallible::hostname().ok()?;
318 short_host(&name)
319}
320
321fn short_host(name: &str) -> Option<String> {
322 let short = name.trim().split('.').next().unwrap_or("").to_ascii_lowercase();
323 (!short.is_empty()).then_some(short)
324}
325
326const HELPER_KEY: &str = "credential.https://github.com.helper";
327const HELPER: &str = "!agentmux-bashwrap git-credential";
328const HTTP_PATH_KEY: &str = "credential.https://github.com.useHttpPath";
329const REWRITE_KEY: &str = "url.https://github.com/.insteadOf";
330
331pub fn apply_agent_git_in(
340 env: &mut HashMap<String, String>,
341 process: impl Fn(&str) -> Option<String> + Copy,
342 enabled: bool,
343 hooks_dir: Option<&std::path::Path>,
344) {
345 use crate::backend::publish_guard::{set_git_config_list, HOOKS_PATH_KEY};
346 if enabled {
347 if let Some(dir) = hooks_dir {
349 let dir = dir.to_string_lossy().into_owned();
350 set_git_config_list(env, process, HOOKS_PATH_KEY, &[dir.as_str()]);
351 }
352 set_git_config_list(env, process, HELPER_KEY, &["", HELPER]);
353 set_git_config_list(env, process, HTTP_PATH_KEY, &["true"]);
354 set_git_config_list(env, process, REWRITE_KEY, &["git@github.com:", "ssh://git@github.com/"]);
355 env.insert("GIT_TERMINAL_PROMPT".to_string(), "0".to_string());
356 env.insert(BROKER_ENV.to_string(), "1".to_string());
357 if let Some(host) = host_label() {
359 env.insert(GIT_HOST_ENV.to_string(), host);
360 }
361 env.insert(GH_FUNCTION_NAME.to_string(), GH_FUNCTION_BODY.to_string());
363 env.insert(GIT_FUNCTION_NAME.to_string(), GIT_FUNCTION_BODY.to_string());
365 } else if env.contains_key(BROKER_ENV) {
366 for key in [HELPER_KEY, HTTP_PATH_KEY, REWRITE_KEY, HOOKS_PATH_KEY] {
367 set_git_config_list(env, process, key, &[]);
368 }
369 env.remove(BROKER_ENV);
370 env.remove(GIT_HOST_ENV);
371 env.remove(GH_FUNCTION_NAME);
372 env.remove(GIT_FUNCTION_NAME);
373 env.remove("GIT_TERMINAL_PROMPT");
375 }
376}
377
378pub fn without_agent_git(env: &HashMap<String, String>) -> HashMap<String, String> {
381 use crate::backend::publish_guard::{without_git_config_key, HOOKS_PATH_KEY};
382 if !env.contains_key(BROKER_ENV) {
383 return env.clone();
384 }
385 let mut out = [HELPER_KEY, HTTP_PATH_KEY, REWRITE_KEY, HOOKS_PATH_KEY].iter().fold(env.clone(), |e, key| without_git_config_key(&e, key));
386 out.remove(BROKER_ENV);
387 out.remove(GIT_HOST_ENV);
388 out.remove(GH_FUNCTION_NAME);
389 out.remove(GIT_FUNCTION_NAME);
390 out.remove("GIT_TERMINAL_PROMPT");
391 out
392}
393
394static STORE: OnceLock<Arc<Store>> = OnceLock::new();
395
396pub fn attach_store(store: Arc<Store>) {
398 let _ = STORE.set(store);
399}
400
401pub(crate) fn agents_use_broker(env: &HashMap<String, String>) -> bool {
405 if crate::backend::publish_guard::hooks_dir_for(env, |k| std::env::var(k).ok()).is_some() {
406 return false;
407 }
408 broker_account_connected()
409}
410
411fn broker_account_connected() -> bool {
413 use std::sync::Mutex;
414 use std::time::{Duration, Instant};
415 static CACHE: Mutex<Option<(Instant, bool)>> = Mutex::new(None);
416 let mut cache = CACHE.lock().unwrap_or_else(|e| e.into_inner());
417 if let Some((at, answer)) = *cache {
418 if at.elapsed() < Duration::from_secs(5) {
419 return answer;
420 }
421 }
422 let answer = STORE.get().is_some_and(|store| {
423 store
424 .identity_list(Some(crate::identity::github_connect::PROVIDER))
425 .unwrap_or_default()
426 .iter()
427 .any(|a| crate::identity::github_connect::is_brokered(a) && a.status != crate::identity::oauth_tokens::STATUS_NEEDS_REAUTH)
428 });
429 *cache = Some((Instant::now(), answer));
430 answer
431}
432
433pub const CONTAINER_HOOKS_DIR: &str = "/opt/agentmux/github-hooks";
436
437pub fn container_git_hooks() -> Option<std::path::PathBuf> {
442 if cfg!(any(test, feature = "test-support")) {
444 return None;
445 }
446 if crate::identity::gh_agent_token::installed().is_none() && !broker_account_connected() {
447 return None;
448 }
449 crate::identity::github_hooks::hooks_dir()
450}
451
452pub fn apply_container_git(env: &mut HashMap<String, String>) {
456 apply_agent_git_in(env, |_| None, true, Some(std::path::Path::new(CONTAINER_HOOKS_DIR)));
457 crate::backend::publish_guard::set_git_config_list(env, |_| None, "safe.directory", &["*"]);
461}
462
463#[cfg_attr(test, allow(dead_code))]
466pub fn apply_agent_git(env: &mut HashMap<String, String>) {
467 let enabled = agents_use_broker(env);
468 let hooks = enabled.then(crate::identity::github_hooks::hooks_dir).flatten();
469 apply_agent_git_in(env, |k| std::env::var(k).ok(), enabled, hooks.as_deref());
470}
471
472pub fn global() -> &'static Tokens {
474 static TOKENS: OnceLock<Tokens> = OnceLock::new();
475 TOKENS.get_or_init(Tokens::default)
476}
477
478pub struct Live {
481 pub mstore: Arc<Store>,
482 pub identity_store: Arc<Store>,
483}
484
485impl Backend for Live {
486 async fn installations(&self) -> Result<Vec<LinkedInstallation>, BrokerError> {
487 let who = github_broker::caller(&self.mstore).await?;
488 github_broker::installations(crate::identity::oauth_client::http(), &who).await
489 }
490
491 async fn mint(&self, request: MintRequest) -> Result<github_broker::InstallationToken, BrokerError> {
492 let who = github_broker::caller(&self.mstore).await?;
493 github_broker::installation_token(
494 crate::identity::oauth_client::http(),
495 &who,
496 &InstallationRequest {
497 installation_id: request.installation_id,
498 repositories: &request.repositories,
499 permissions: &request.permissions,
500 agent_id: &request.agent,
501 },
502 )
503 .await
504 }
505
506 async fn connection(&self) -> Result<String, TokenError> {
507 let account = self
508 .mstore
509 .identity_list(Some(crate::identity::github_connect::PROVIDER))
510 .unwrap_or_default()
511 .into_iter()
512 .find(crate::identity::github_connect::is_brokered)
513 .ok_or(TokenError::NoGithubAccount)?;
514 github_broker::caller(&self.mstore).await?;
515 Ok(format!("{}/{}", account.id, account.context.get("id").map(|v| v.to_string()).unwrap_or_default()))
516 }
517
518 async fn revalidate(&self) -> Result<(), TokenError> {
519 let account = self
520 .mstore
521 .identity_list(Some(crate::identity::github_connect::PROVIDER))
522 .unwrap_or_default()
523 .into_iter()
524 .find(crate::identity::github_connect::is_brokered)
525 .ok_or(TokenError::NoGithubAccount)?;
526 let token = crate::identity::oauth_tokens::access_token_for(
527 &crate::identity::oauth_tokens::LiveHttp,
528 &crate::identity::oauth_tokens::KeychainSecrets,
529 &self.mstore,
530 &self.identity_store,
531 &account,
532 Some(&self.mstore),
533 )
534 .await
535 .map_err(|e| TokenError::Broker(BrokerError::NotSignedIn(e)))?;
536 let who = github_broker::caller(&self.mstore).await?;
537 github_broker::revalidate(crate::identity::oauth_client::http(), &who, &token).await?;
538 Ok(())
539 }
540}
541
542#[cfg(test)]
543mod tests {
544 use super::*;
545 use crate::muxbus::github_broker::{InstallationAccount, InstallationToken};
546 use std::sync::Mutex;
547
548 fn link(id: u64, login: &str, installation: &str, link: &str) -> LinkedInstallation {
549 LinkedInstallation {
550 installation_id: id,
551 github_account: InstallationAccount { id: id * 10, login: login.to_string() },
552 repository_selection: "selected".to_string(),
553 installation_status: installation.to_string(),
554 link_status: link.to_string(),
555 verified_at_ms: 0,
556 visible_count: 0,
557 linked_at_ms: 0,
558 }
559 }
560
561 fn token(expires_at: &str) -> InstallationToken {
562 InstallationToken {
563 token: "ghs_TOKEN".to_string(),
564 expires_at: expires_at.to_string(),
565 permissions: BTreeMap::new(),
566 repository_ids: vec![1],
567 app: AppBot { slug: "muxagent".to_string(), bot_user_id: 77 },
568 }
569 }
570
571 struct Fake {
573 installs: Mutex<Vec<Vec<LinkedInstallation>>>,
574 mints: Mutex<Vec<Result<InstallationToken, BrokerError>>>,
575 asked: Mutex<Vec<MintRequest>>,
576 listed: Mutex<u32>,
577 revalidated: Mutex<u32>,
578 revalidate_ok: bool,
579 connection: Mutex<Result<String, TokenError>>,
580 }
581
582 impl Fake {
583 fn new(installs: Vec<Vec<LinkedInstallation>>, mints: Vec<Result<InstallationToken, BrokerError>>) -> Self {
584 Self { installs: Mutex::new(installs), mints: Mutex::new(mints), asked: Mutex::default(), listed: Mutex::new(0), revalidated: Mutex::new(0), revalidate_ok: true, connection: Mutex::new(Ok("acct-1".to_string())) }
585 }
586 }
587
588 impl Backend for Fake {
589 async fn installations(&self) -> Result<Vec<LinkedInstallation>, BrokerError> {
590 *self.listed.lock().unwrap() += 1;
591 let mut l = self.installs.lock().unwrap();
592 Ok(if l.len() > 1 { l.remove(0) } else { l[0].clone() })
593 }
594 async fn mint(&self, request: MintRequest) -> Result<InstallationToken, BrokerError> {
595 self.asked.lock().unwrap().push(request);
596 let mut m = self.mints.lock().unwrap();
597 if m.len() > 1 { m.remove(0) } else { m[0].clone().map_err(|e| e) }
598 }
599 async fn connection(&self) -> Result<String, TokenError> {
600 self.connection.lock().unwrap().clone()
601 }
602 async fn revalidate(&self) -> Result<(), TokenError> {
603 *self.revalidated.lock().unwrap() += 1;
604 if self.revalidate_ok { Ok(()) } else { Err(TokenError::NoGithubAccount) }
605 }
606 }
607
608 fn want(owner: &str, repo: &str) -> Want {
609 Want { agent: "korp".to_string(), owner: owner.to_string(), repo: repo.to_string(), workflows: false }
610 }
611
612 const NOW: i64 = 1_793_178_000;
613
614 fn ok_for(secs: i64) -> InstallationToken {
615 let at = chrono::DateTime::from_timestamp(NOW + secs, 0).unwrap().to_rfc3339_opts(chrono::SecondsFormat::Secs, true);
616 token(&at)
617 }
618
619 fn env(pairs: &[(&str, &str)]) -> HashMap<String, String> {
620 pairs.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect()
621 }
622
623 fn entries(e: &HashMap<String, String>) -> Vec<(String, String)> {
624 let n: usize = e.get("GIT_CONFIG_COUNT").and_then(|c| c.parse().ok()).unwrap_or(0);
625 (0..n).map(|i| (e[&format!("GIT_CONFIG_KEY_{i}")].clone(), e[&format!("GIT_CONFIG_VALUE_{i}")].clone())).collect()
626 }
627
628 #[test]
629 fn an_agent_with_the_broker_gets_only_its_credential_helper_for_github() {
630 let mut e = env(&[("GIT_CONFIG_COUNT", "1"), ("GIT_CONFIG_KEY_0", "user.name"), ("GIT_CONFIG_VALUE_0", "x")]);
631 apply_agent_git_in(&mut e, |_| None, true, None);
632 let got = entries(&e);
633 let at = got.iter().position(|(k, v)| k == HELPER_KEY && v.is_empty()).expect("the reset");
635 assert_eq!(got[at + 1], (HELPER_KEY.to_string(), HELPER.to_string()));
636 assert!(got.contains(&(HTTP_PATH_KEY.to_string(), "true".to_string())));
637 assert!(got.contains(&(REWRITE_KEY.to_string(), "git@github.com:".to_string())), "ssh remotes use the token too");
638 assert!(got.contains(&("user.name".to_string(), "x".to_string())), "other settings stay");
639 assert_eq!((e["GIT_TERMINAL_PROMPT"].as_str(), e[BROKER_ENV].as_str()), ("0", "1"));
640 assert_eq!(e[GH_FUNCTION_NAME], GH_FUNCTION_BODY, "gh reaches the broker in every provider's shell");
641 let before = e.clone();
643 apply_agent_git_in(&mut e, |_| None, true, None);
644 assert_eq!(e, before);
645 }
646
647 #[test]
648 fn an_agent_with_the_broker_gets_the_agentmux_hooks_and_git_function_and_loses_them_when_disconnected() {
649 let hooks = std::path::Path::new("/agentmux/github-hooks");
650 let mut e = env(&[("GIT_CONFIG_COUNT", "1"), ("GIT_CONFIG_KEY_0", "user.name"), ("GIT_CONFIG_VALUE_0", "x")]);
651 apply_agent_git_in(&mut e, |_| None, true, Some(hooks));
652 assert!(entries(&e).contains(&("core.hooksPath".to_string(), hooks.to_string_lossy().into_owned())));
653 assert_eq!(e[GIT_FUNCTION_NAME], GIT_FUNCTION_BODY);
654 let before = e.clone();
656 apply_agent_git_in(&mut e, |_| None, true, Some(hooks));
657 assert_eq!(e, before);
658 apply_agent_git_in(&mut e, |_| None, false, None);
660 assert_eq!(entries(&e), vec![("user.name".to_string(), "x".to_string())]);
661 assert!(!e.contains_key(GIT_FUNCTION_NAME));
662 let mut c = env(&[]);
664 apply_agent_git_in(&mut c, |_| None, true, Some(hooks));
665 let out = without_agent_git(&c);
666 assert!(!out.contains_key(GIT_FUNCTION_NAME) && !out.contains_key(GH_FUNCTION_NAME));
667 }
668
669 #[test]
670 fn an_agent_without_the_broker_keeps_its_own_git_and_loses_a_stale_setup() {
671 let mut plain = env(&[("GIT_CONFIG_COUNT", "1"), ("GIT_CONFIG_KEY_0", "user.name"), ("GIT_CONFIG_VALUE_0", "x")]);
672 let before = plain.clone();
673 apply_agent_git_in(&mut plain, |_| None, false, None);
674 assert_eq!(plain, before, "nothing added when GitHub isn't connected");
675 let mut e = before.clone();
677 apply_agent_git_in(&mut e, |_| None, true, None);
678 apply_agent_git_in(&mut e, |_| None, false, None);
679 assert_eq!(entries(&e), vec![("user.name".to_string(), "x".to_string())]);
680 assert!(!e.contains_key(BROKER_ENV) && !e.contains_key("GIT_TERMINAL_PROMPT") && !e.contains_key(GH_FUNCTION_NAME), "prompts and plain gh are back too");
681 }
682
683 #[tokio::test]
684 async fn a_token_is_narrowed_to_the_repository_and_the_default_permissions() {
685 let fake = Fake::new(vec![vec![link(5, "Octo-Org", "active", "active")]], vec![Ok(ok_for(3600))]);
686 let tokens = Tokens::default();
687 let minted = tokens.token_for(&fake, &want("octo-org", "Hello"), NOW).await.unwrap();
688 assert_eq!((minted.token.as_str(), minted.bot.slug.as_str(), minted.expires_at), ("ghs_TOKEN", "muxagent", NOW + 3600));
689 let asked = fake.asked.lock().unwrap();
690 assert_eq!(asked.len(), 1);
691 assert_eq!((asked[0].installation_id, asked[0].repositories.clone(), asked[0].agent.as_str()), (5, vec!["hello".to_string()], "korp"));
692 assert_eq!(asked[0].permissions, permissions_for(false));
693 assert!(!asked[0].permissions.contains_key("workflows"), "no CI changes unless the person allowed them");
694 assert!(!format!("{minted:?}").contains("ghs_TOKEN"));
695 }
696
697 #[tokio::test]
698 async fn a_minted_token_is_withheld_from_transcripts_until_it_runs_out() {
699 use crate::backend::transcript::withhold;
700 let now = chrono::Utc::now().timestamp();
701 let answer = |value: &str, secs: i64| {
702 let at = chrono::DateTime::from_timestamp(now + secs, 0).unwrap().to_rfc3339_opts(chrono::SecondsFormat::Secs, true);
703 InstallationToken { token: value.to_string(), ..token(&at) }
704 };
705 let shown = |value: &str| withhold::text(&format!("GH_TOKEN={value}")).into_owned();
706 let w = Want { agent: "withhold-gh-agent".into(), ..want("o", "r") };
707 let fake = Fake::new(vec![vec![link(5, "o", "active", "active")]], vec![Ok(answer("ghs_canary_withhold_0001", 3600)), Ok(answer("ghs_canary_withhold_0002", 7200))]);
708 let tokens = Tokens::default();
709
710 tokens.token_for(&fake, &w, now).await.unwrap();
711 assert_eq!(shown("ghs_canary_withhold_0001"), format!("GH_TOKEN={}", withhold::MARK), "withheld from the moment it is minted");
712
713 tokens.token_for(&fake, &w, now + 3600 - 100).await.unwrap();
715 assert_eq!(shown("ghs_canary_withhold_0002"), format!("GH_TOKEN={}", withhold::MARK));
716 assert_eq!(shown("ghs_canary_withhold_0001"), format!("GH_TOKEN={}", withhold::MARK), "the token that was replaced still works");
717
718 *fake.connection.lock().unwrap() = Err(TokenError::NoGithubAccount);
720 tokens.token_for(&fake, &w, now + 3600).await.unwrap_err();
721 assert_eq!(shown("ghs_canary_withhold_0002"), format!("GH_TOKEN={}", withhold::MARK));
722 assert_eq!(shown("ghs_canary_withhold_0001"), format!("GH_TOKEN={}", withhold::MARK));
723 }
724
725 #[tokio::test]
726 async fn a_minted_token_stops_being_withheld_when_it_runs_out() {
727 use crate::backend::transcript::withhold;
728 let at = chrono::Utc::now().timestamp() - 1;
729 let stamp = chrono::DateTime::from_timestamp(at, 0).unwrap().to_rfc3339_opts(chrono::SecondsFormat::Secs, true);
730 let fake = Fake::new(vec![vec![link(5, "o", "active", "active")]], vec![Ok(InstallationToken { token: "ghs_canary_withhold_0003".to_string(), ..token(&stamp) })]);
731 let w = Want { agent: "withhold-gh-expired".into(), ..want("o", "r") };
732 Tokens::default().token_for(&fake, &w, at - 3600).await.unwrap();
733 let line = "GH_TOKEN=ghs_canary_withhold_0003";
734 assert_eq!(withhold::text(line), line, "a token whose expiry has passed is not kept");
735 }
736
737 #[test]
738 fn workflows_are_asked_for_only_when_allowed() {
739 assert_eq!(permissions_for(true).get("workflows").map(String::as_str), Some("write"));
740 assert!(!permissions_for(false).contains_key("workflows"));
741 assert_eq!(permissions_for(false).get("metadata").map(String::as_str), Some("read"));
742 }
743
744 #[tokio::test]
745 async fn the_cache_serves_a_token_until_five_minutes_remain() {
746 let fake = Fake::new(vec![vec![link(5, "o", "active", "active")]], vec![Ok(ok_for(3600)), Ok(ok_for(7200))]);
747 let tokens = Tokens::default();
748 let w = want("o", "r");
749 tokens.token_for(&fake, &w, NOW).await.unwrap();
750 tokens.token_for(&fake, &w, NOW + 3000).await.unwrap();
751 assert_eq!(fake.asked.lock().unwrap().len(), 1, "an agent's many commands share one mint");
752 let renewed = tokens.token_for(&fake, &w, NOW + 3600 - 299).await.unwrap();
754 assert_eq!(fake.asked.lock().unwrap().len(), 2);
755 assert_eq!(renewed.expires_at, NOW + 7200);
756 tokens.token_for(&fake, &Want { agent: "agenty".into(), ..w.clone() }, NOW).await.unwrap();
758 tokens.token_for(&fake, &Want { workflows: true, ..w.clone() }, NOW).await.unwrap();
759 assert_eq!(fake.asked.lock().unwrap().len(), 4);
760 assert_eq!(tokens.cached(), 3);
761 }
762
763 #[tokio::test]
764 async fn a_disconnect_or_another_account_takes_back_the_cached_tokens() {
765 let fake = Fake::new(vec![vec![link(5, "o", "active", "active")]], vec![Ok(ok_for(3600))]);
766 let tokens = Tokens::default();
767 let w = want("o", "r");
768 tokens.token_for(&fake, &w, NOW).await.unwrap();
769 tokens.token_for(&fake, &w, NOW + 10).await.unwrap();
770 assert_eq!(fake.asked.lock().unwrap().len(), 1);
771 *fake.connection.lock().unwrap() = Err(TokenError::NoGithubAccount);
773 assert_eq!(tokens.token_for(&fake, &w, NOW + 20).await.unwrap_err(), TokenError::NoGithubAccount);
774 assert_eq!(tokens.cached(), 0);
775 *fake.connection.lock().unwrap() = Ok("acct-1".to_string());
777 tokens.token_for(&fake, &w, NOW + 30).await.unwrap();
778 assert_eq!(fake.asked.lock().unwrap().len(), 2);
779 *fake.connection.lock().unwrap() = Ok("acct-2".to_string());
781 tokens.token_for(&fake, &w, NOW + 40).await.unwrap();
782 assert_eq!(fake.asked.lock().unwrap().len(), 3);
783 }
784
785 #[tokio::test]
786 async fn what_has_run_out_is_dropped_and_one_slow_token_does_not_hold_up_another() {
787 let fake = Fake::new(vec![vec![link(5, "o", "active", "active")]], vec![Ok(ok_for(3600)), Ok(ok_for(3600)), Ok(ok_for(3600)), Ok(ok_for(10_800))]);
788 let tokens = Tokens::default();
789 for repo in ["a", "b", "c"] {
790 tokens.token_for(&fake, &want("o", repo), NOW).await.unwrap();
791 }
792 assert_eq!((tokens.cached(), tokens.locks()), (3, 3));
793 tokens.token_for(&fake, &want("o", "d"), NOW + 7200).await.unwrap();
795 assert_eq!((tokens.cached(), tokens.locks()), (1, 1));
796 }
797
798 #[test]
799 fn the_host_is_the_machines_short_lower_case_name() {
800 assert_eq!(short_host("NARKO").as_deref(), Some("narko"));
801 assert_eq!(short_host(" Area54.lan. ").as_deref(), Some("area54"));
802 assert_eq!(short_host("").as_deref(), None);
803 assert_eq!(short_host(".local").as_deref(), None);
804 }
805
806 #[test]
807 fn the_host_name_rides_with_the_setup_and_leaves_with_it() {
808 let mut e = env(&[]);
809 apply_agent_git_in(&mut e, |_| None, true, None);
810 assert_eq!(e.get(GIT_HOST_ENV).map(String::as_str), host_label().as_deref());
811 assert!(!without_agent_git(&e).contains_key(GIT_HOST_ENV));
812 apply_agent_git_in(&mut e, |_| None, false, None);
813 assert!(!e.contains_key(GIT_HOST_ENV));
814 }
815
816 #[tokio::test]
817 async fn a_container_gets_none_of_the_agent_git_setup() {
818 let mut e = env(&[("GIT_CONFIG_COUNT", "1"), ("GIT_CONFIG_KEY_0", "user.name"), ("GIT_CONFIG_VALUE_0", "x"), ("OTHER", "kept")]);
819 apply_agent_git_in(&mut e, |_| None, true, None);
820 let out = without_agent_git(&e);
821 assert_eq!(entries(&out), vec![("user.name".to_string(), "x".to_string())]);
822 assert!(!out.contains_key(BROKER_ENV) && !out.contains_key("GIT_TERMINAL_PROMPT") && !out.contains_key(GH_FUNCTION_NAME));
823 assert_eq!(out["OTHER"], "kept");
824 let plain = env(&[("A", "b")]);
826 assert_eq!(without_agent_git(&plain), plain);
827 }
828
829 #[test]
830 fn a_container_gets_the_helper_the_functions_and_the_hooks_where_the_image_finds_them() {
831 let mut e = env(&[("OTHER", "kept")]);
832 apply_container_git(&mut e);
833 assert_eq!(e[BROKER_ENV], "1");
834 assert!(e.contains_key(GH_FUNCTION_NAME) && e.contains_key(GIT_FUNCTION_NAME));
835 let config = entries(&e);
836 assert!(config.contains(&("core.hooksPath".to_string(), CONTAINER_HOOKS_DIR.to_string())), "{config:?}");
837 assert!(config.iter().any(|(k, v)| k == HELPER_KEY && v == HELPER));
838 assert!(config.contains(&("safe.directory".to_string(), "*".to_string())), "{config:?}");
839 assert!(CONTAINER_HOOKS_DIR.ends_with("/github-hooks"));
841 assert_eq!(e["OTHER"], "kept");
842 assert!(!config.iter().any(|(_, v)| v.contains(":\\") || v.contains(".agentmux")));
844 }
845
846 #[tokio::test]
847 async fn an_owner_without_an_active_link_gets_a_plain_answer_and_no_mint() {
848 let fake = Fake::new(
849 vec![vec![link(5, "other", "active", "active"), link(6, "o", "suspended", "active"), link(7, "o", "active", "revoked")]],
850 vec![Ok(ok_for(3600))],
851 );
852 let tokens = Tokens::default();
853 let err = tokens.token_for(&fake, &want("o", "r"), NOW).await.unwrap_err();
854 assert_eq!(err, TokenError::NoInstallation { owner: "o".to_string() });
855 assert!(err.to_string().contains("Install it in Connectors"), "{err}");
856 assert!(fake.asked.lock().unwrap().is_empty());
857 }
858
859 #[tokio::test]
860 async fn a_refusal_is_remembered_briefly_so_a_command_does_not_ask_over_and_over() {
861 let fake = Fake::new(vec![vec![link(5, "o", "active", "active")]], vec![Err(BrokerError::RepositoryNotVisible("r".into())), Ok(ok_for(3600))]);
862 let tokens = Tokens::default();
863 let w = want("o", "r");
864 let first = tokens.token_for(&fake, &w, NOW).await.unwrap_err();
865 let again = tokens.token_for(&fake, &w, NOW + 5).await.unwrap_err();
866 assert_eq!(first, again);
867 assert_eq!(fake.asked.lock().unwrap().len(), 1);
868 assert!(tokens.token_for(&fake, &w, NOW + 25).await.is_ok(), "asked again after the refusal expires");
869 }
870
871 #[tokio::test]
872 async fn a_brief_outage_keeps_serving_a_token_that_still_works() {
873 let fake = Fake::new(vec![vec![link(5, "o", "active", "active")]], vec![Ok(ok_for(3600)), Err(BrokerError::Unavailable("503".into()))]);
874 let tokens = Tokens::default();
875 let w = want("o", "r");
876 tokens.token_for(&fake, &w, NOW).await.unwrap();
877 let served = tokens.token_for(&fake, &w, NOW + 3400).await.unwrap();
879 assert_eq!(served.expires_at, NOW + 3600);
880 assert!(tokens.token_for(&fake, &w, NOW + 3601).await.is_err());
882 }
883
884 #[tokio::test]
885 async fn a_stale_link_is_revalidated_once_and_the_mint_retried() {
886 let fake = Fake::new(vec![vec![link(5, "o", "active", "active")]], vec![Err(BrokerError::LinkStale), Ok(ok_for(3600))]);
887 let tokens = Tokens::default();
888 let minted = tokens.token_for(&fake, &want("o", "r"), NOW).await.unwrap();
889 assert_eq!(minted.expires_at, NOW + 3600);
890 assert_eq!((*fake.revalidated.lock().unwrap(), fake.asked.lock().unwrap().len()), (1, 2));
891 }
892
893 #[tokio::test]
894 async fn a_stale_link_that_cannot_be_revalidated_gives_no_token() {
895 let mut fake = Fake::new(vec![vec![link(5, "o", "active", "active")]], vec![Err(BrokerError::LinkStale)]);
896 fake.revalidate_ok = false;
897 let err = Tokens::default().token_for(&fake, &want("o", "r"), NOW).await.unwrap_err();
898 assert_eq!(err, TokenError::NoGithubAccount);
899 assert_eq!(fake.asked.lock().unwrap().len(), 1, "no second try without a fresh proof");
900 }
901
902 #[tokio::test]
903 async fn a_new_install_is_found_without_waiting_for_the_list_to_age() {
904 let fake = Fake::new(vec![vec![], vec![link(5, "o", "active", "active")]], vec![Ok(ok_for(3600))]);
905 let tokens = Tokens::default();
906 assert!(tokens.token_for(&fake, &want("nobody", "r"), NOW).await.is_err());
908 assert!(tokens.token_for(&fake, &want("o", "r"), NOW + 1).await.is_ok());
909 assert_eq!(*fake.listed.lock().unwrap(), 2);
910 }
911
912 #[tokio::test]
913 async fn names_that_are_not_github_names_never_reach_the_broker() {
914 let fake = Fake::new(vec![vec![link(5, "o", "active", "active")]], vec![Ok(ok_for(3600))]);
915 let tokens = Tokens::default();
916 for (owner, repo) in [("o", "../x"), ("o/p", "r"), ("", "r"), ("o", ""), ("o", "a b"), ("o", &"x".repeat(101))] {
917 let err = tokens.token_for(&fake, &want(owner, repo), NOW).await.unwrap_err();
918 assert!(matches!(err, TokenError::BadTarget(_)), "{owner:?}/{repo:?}: {err}");
919 }
920 assert_eq!((*fake.listed.lock().unwrap(), fake.asked.lock().unwrap().len()), (0, 0));
921 }
922
923 #[tokio::test]
924 async fn a_broker_that_cannot_mint_yet_says_so_and_gives_no_token() {
925 let fake = Fake::new(vec![vec![link(5, "o", "active", "active")]], vec![Err(BrokerError::NotConfigured)]);
926 let err = Tokens::default().token_for(&fake, &want("o", "r"), NOW).await.unwrap_err();
927 assert_eq!(err, TokenError::Broker(BrokerError::NotConfigured));
928 assert!(err.to_string().contains("can't mint GitHub tokens yet"), "{err}");
929 }
930}