Skip to main content

orch/github/
app.rs

1//! GitHub App authentication and the review gate that reads App reviews.
2//!
3//! The owner token resolver stays in `token.rs`. This module signs a short-lived
4//! JWT, exchanges it for an installation token, and decides which reviews count.
5
6use super::types::GitHubReview;
7use crate::config;
8use crate::github::types::ReviewIssue;
9use crate::security;
10use crate::security::secret_ref;
11use chrono::{DateTime, Duration, Utc};
12use jsonwebtoken::{Algorithm, EncodingKey, Header, encode};
13#[cfg(test)]
14use rand::rngs::OsRng;
15use reqwest::{Client, StatusCode, Url, header};
16#[cfg(test)]
17use rsa::pkcs8::EncodePrivateKey;
18#[cfg(test)]
19use rsa::pkcs8::EncodePublicKey;
20#[cfg(test)]
21use rsa::pkcs8::LineEnding;
22use serde::{Deserialize, Serialize};
23use std::collections::HashMap;
24use std::env;
25use std::fmt;
26use std::fmt::Debug;
27use std::fmt::Formatter;
28use std::fs;
29use std::sync::MutexGuard;
30#[cfg(test)]
31use std::sync::OnceLock;
32use std::sync::PoisonError;
33use std::sync::{Arc, Mutex, RwLock};
34use std::time::Duration as StdDuration;
35use tokio::sync;
36use tokio::task;
37use tokio::time;
38
39const JWT_IAT_SKEW_SECS: i64 = 60;
40const JWT_EXP_FROM_NOW_SECS: i64 = 9 * 60;
41const USER_AGENT: &str = "orch/0.1 (reqwest)";
42
43#[derive(Debug, Clone, Copy, PartialEq, Eq)]
44pub(crate) enum ReviewEvent {
45    Approve,
46    RequestChanges,
47}
48
49impl ReviewEvent {
50    fn as_str(self) -> &'static str {
51        match self {
52            Self::Approve => "APPROVE",
53            Self::RequestChanges => "REQUEST_CHANGES",
54        }
55    }
56}
57
58struct CachedToken {
59    token: String,
60    expires_at: DateTime<Utc>,
61}
62
63#[derive(Serialize, Deserialize)]
64struct Claims {
65    iss: String,
66    iat: i64,
67    exp: i64,
68}
69
70#[derive(Deserialize)]
71struct Installation {
72    id: u64,
73}
74
75#[derive(Deserialize)]
76struct AccessTokenResponse {
77    token: String,
78    expires_at: DateTime<Utc>,
79}
80
81#[derive(Deserialize)]
82struct AppInfo {
83    slug: String,
84}
85
86/// One attempt in the App's webhook delivery log. A redelivery keeps the `guid` of the original
87#[derive(Debug, Clone, Deserialize)]
88pub(crate) struct HookDelivery {
89    pub id: u64,
90    pub guid: String,
91    pub delivered_at: DateTime<Utc>,
92    #[serde(default)]
93    pub redelivery: bool,
94    #[serde(default)]
95    pub status_code: u16,
96}
97
98const REVIEW_CHECK: &str = "orch/review";
99// GitHub lists at most 3000 files of a pull request, 30 pages of 100
100const PR_FILE_PAGES: u32 = 30;
101
102pub(crate) enum CheckRunState<'a> {
103    InProgress,
104    Completed { approved: bool, summary: &'a str },
105}
106
107#[derive(Debug, Clone, PartialEq, Eq)]
108pub(crate) struct InlineComment {
109    pub path: String,
110    pub line: u32,
111    pub body: String,
112}
113
114#[derive(Deserialize)]
115struct PrFile {
116    filename: String,
117    patch: Option<String>,
118}
119
120/// Right-side `(first, last)` line of each hunk, from headers such as `@@ -10,4 +12,6 @@`
121pub(crate) fn right_side_ranges(patch: &str) -> Vec<(u32, u32)> {
122    patch
123        .lines()
124        .filter_map(|line| line.strip_prefix("@@ "))
125        .filter_map(|header| header.split_whitespace().find(|part| part.starts_with('+')))
126        .filter_map(|right| {
127            let mut parts = right.trim_start_matches('+').split(',');
128            let start: u32 = parts.next()?.parse().ok()?;
129            let count: u32 = parts.next().map_or(Some(1), |c| c.parse().ok())?;
130            (count > 0).then(|| (start, start + count - 1))
131        })
132        .collect()
133}
134
135/// Split issues into inline comments on a hunk line and the rest, which GitHub would refuse
136pub(crate) fn split_inline(
137    issues: &[ReviewIssue],
138    hunks: &HashMap<String, Vec<(u32, u32)>>,
139) -> (Vec<InlineComment>, Vec<String>) {
140    let mut inline = Vec::new();
141    let mut rest = Vec::new();
142
143    for issue in issues {
144        let body = format!("**{}:** {}", issue.severity, issue.description);
145        let in_hunk = issue.line.filter(|line| {
146            hunks
147                .get(&issue.file)
148                .is_some_and(|ranges| ranges.iter().any(|(a, b)| (a..=b).contains(&line)))
149        });
150
151        match in_hunk {
152            Some(line) => inline.push(InlineComment {
153                path: issue.file.clone(),
154                line,
155                body,
156            }),
157            None => rest.push(match issue.line {
158                Some(line) => format!("- `{}:{line}` {body}", issue.file),
159                None => format!("- `{}` {body}", issue.file),
160            }),
161        }
162    }
163
164    (inline, rest)
165}
166
167pub(crate) struct AppAuth {
168    app_id: String,
169    pem: String,
170    // `None` means the App is not installed on that repository, so it uses the owner token
171    installations: Mutex<HashMap<String, Option<u64>>>,
172    tokens: Mutex<HashMap<u64, CachedToken>>,
173    login: Mutex<Option<String>>,
174    refresh: sync::Mutex<()>,
175    http: Client,
176    api_base: String,
177}
178
179// Keeps the key and the token out of any `{:?}` that reaches a log
180impl Debug for AppAuth {
181    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
182        f.debug_struct("AppAuth")
183            .field("app_id", &self.app_id)
184            .finish_non_exhaustive()
185    }
186}
187
188fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
189    mutex.lock().unwrap_or_else(PoisonError::into_inner)
190}
191
192static SHARED: RwLock<Option<Arc<AppAuth>>> = RwLock::new(None);
193const LOAD_RETRY: StdDuration = StdDuration::from_secs(300);
194
195/// Process-wide App client, `None` until the loader has read the key or when no App is set up
196pub(crate) fn shared() -> Option<Arc<AppAuth>> {
197    SHARED
198        .read()
199        .unwrap_or_else(PoisonError::into_inner)
200        .clone()
201}
202
203fn publish(app: Arc<AppAuth>) {
204    *SHARED.write().unwrap_or_else(PoisonError::into_inner) = Some(app);
205}
206
207/// Reads the App key in the background, once per daemon start. A passbox key waits on Touch
208/// ID, so the engine runs on the owner token and comment reviews until the read succeeds
209pub fn start_loader() {
210    // `cfg(test)` is unset when tests/*.rs link the library, so check debug builds too, at run
211    // time, which keeps the release path compiled and type-checked in every build
212    if cfg!(any(test, debug_assertions)) {
213        return;
214    }
215
216    tokio::spawn(run_loader(load_from_config, publish, LOAD_RETRY));
217}
218
219// One read at a time, so at most one passbox prompt is ever pending
220async fn run_loader<L, P>(load: L, publish: P, retry: StdDuration)
221where
222    L: Fn() -> anyhow::Result<Option<AppAuth>> + Clone + Send + 'static,
223    P: Fn(Arc<AppAuth>),
224{
225    let mut warned = false;
226
227    loop {
228        let attempt = load.clone();
229        let result = task::spawn_blocking(attempt)
230            .await
231            .map_err(anyhow::Error::from)
232            .and_then(|r| r);
233
234        match result {
235            Ok(Some(app)) => {
236                tracing::info!(app_id = %app.app_id, "GitHub App loaded, App reviews are on");
237                publish(Arc::new(app));
238                return;
239            }
240            Ok(None) => return,
241            Err(err) if !warned => {
242                tracing::warn!(error = %err, "GitHub App unavailable, using the owner token and comment reviews, retrying every 5 minutes");
243                warned = true;
244            }
245            Err(_) => {}
246        }
247
248        time::sleep(retry).await;
249    }
250}
251
252/// `gh.app.id` and a private key are set. Reads no key, so it never waits on a passbox prompt
253pub(crate) fn configured() -> bool {
254    nonempty_config("gh.app.id").is_some()
255        && [
256            "gh.app.private_key",
257            "gh.app.private_key_path",
258            "gh.app.private_key_env",
259        ]
260        .into_iter()
261        .any(|key| nonempty_config(key).is_some())
262}
263
264fn load_from_config() -> anyhow::Result<Option<AppAuth>> {
265    let Some(id) = nonempty_config("gh.app.id") else {
266        return Ok(None);
267    };
268    AppAuth::from_config(id).map(Some)
269}
270
271impl AppAuth {
272    fn from_config(app_id: String) -> anyhow::Result<Self> {
273        if !app_id.chars().all(|c| c.is_ascii_digit()) {
274            anyhow::bail!("gh.app.id must be digits");
275        }
276        let pem = read_key()?;
277        // Fail at startup on a bad key, not on the first request
278        sign_jwt(&app_id, &pem, Utc::now().timestamp())?;
279        Ok(Self::new(app_id, pem, "https://api.github.com".to_string()))
280    }
281
282    pub(crate) fn new(app_id: String, pem: String, api_base: String) -> Self {
283        let http = Client::builder()
284            .user_agent(USER_AGENT)
285            .timeout(StdDuration::from_secs(30))
286            .build()
287            .unwrap_or_default();
288        Self {
289            app_id,
290            pem,
291            installations: Mutex::new(HashMap::new()),
292            tokens: Mutex::new(HashMap::new()),
293            login: Mutex::new(None),
294            refresh: sync::Mutex::new(()),
295            http,
296            api_base,
297        }
298    }
299
300    /// Drop the cached installation tokens so the next request exchanges new ones
301    pub(crate) fn invalidate(&self) {
302        lock(&self.tokens).clear();
303    }
304
305    /// The installation token for `repo`, `None` when the App is not installed on it
306    pub(crate) async fn token_for_repo(&self, repo: &str) -> anyhow::Result<Option<String>> {
307        let Some(id) = self.installation_for(repo).await? else {
308            return Ok(None);
309        };
310        self.installation_token(id).await.map(Some)
311    }
312
313    // An account and each organization are separate installations, so the lookup is per repo
314    async fn installation_for(&self, repo: &str) -> anyhow::Result<Option<u64>> {
315        if let Some(found) = lock(&self.installations).get(repo) {
316            return Ok(*found);
317        }
318        let jwt = sign_jwt(&self.app_id, &self.pem, Utc::now().timestamp())?;
319        let url = format!("{}/repos/{repo}/installation", self.api_base);
320        let found = match self.send_status(self.http.get(&url), &jwt).await? {
321            (status, body) if status.is_success() => {
322                let installation: Installation = serde_json::from_str(&body)
323                    .map_err(|_| anyhow::anyhow!("GitHub App installation could not be read"))?;
324                Some(installation.id)
325            }
326            (StatusCode::NOT_FOUND, _) => None,
327            (status, _) => {
328                anyhow::bail!("GitHub App installation lookup for {repo} failed: {status}")
329            }
330        };
331        lock(&self.installations).insert(repo.to_string(), found);
332        Ok(found)
333    }
334
335    async fn installation_token(&self, id: u64) -> anyhow::Result<String> {
336        if let Some(token) = self.cached_fresh_token(id) {
337            return Ok(token);
338        }
339        let _guard = self.refresh.lock().await;
340        if let Some(token) = self.cached_fresh_token(id) {
341            return Ok(token);
342        }
343        let jwt = sign_jwt(&self.app_id, &self.pem, Utc::now().timestamp())?;
344        let url = format!("{}/app/installations/{id}/access_tokens", self.api_base);
345        let body = self.send(self.http.post(&url), &jwt).await?;
346        let parsed: AccessTokenResponse = serde_json::from_str(&body)
347            .map_err(|_| anyhow::anyhow!("GitHub installation token response could not be read"))?;
348        if parsed.token.is_empty() {
349            anyhow::bail!("GitHub installation token response has no token");
350        }
351        lock(&self.tokens).insert(
352            id,
353            CachedToken {
354                token: parsed.token.clone(),
355                expires_at: parsed.expires_at,
356            },
357        );
358        Ok(parsed.token)
359    }
360
361    fn cached_fresh_token(&self, id: u64) -> Option<String> {
362        let tokens = lock(&self.tokens);
363        let cached = tokens.get(&id)?;
364        token_is_fresh(cached.expires_at, Utc::now()).then(|| cached.token.clone())
365    }
366
367    /// The App's user login, `<slug>[bot]`. `GET /user` rejects installation tokens, so read
368    /// the slug from `GET /app` with the JWT
369    pub(crate) async fn login(&self) -> anyhow::Result<String> {
370        if let Some(login) = lock(&self.login).clone() {
371            return Ok(login);
372        }
373        let jwt = sign_jwt(&self.app_id, &self.pem, Utc::now().timestamp())?;
374        let url = format!("{}/app", self.api_base);
375        let body = self.send(self.http.get(&url), &jwt).await?;
376        let info: AppInfo = serde_json::from_str(&body)
377            .map_err(|_| anyhow::anyhow!("GitHub App info could not be read"))?;
378        if info.slug.is_empty() {
379            anyhow::bail!("GitHub App info has no slug");
380        }
381        let login = format!("{}[bot]", info.slug);
382        *lock(&self.login) = Some(login.clone());
383        Ok(login)
384    }
385
386    /// Submit a pull request review as the App on the commit the review agent read
387    pub(crate) async fn submit_review(
388        &self,
389        repo: &str,
390        pr_number: u64,
391        event: ReviewEvent,
392        body: &str,
393        commit_id: &str,
394        comments: &[InlineComment],
395    ) -> anyhow::Result<()> {
396        let token = self.repo_token(repo).await?;
397        let url = format!("{}/repos/{repo}/pulls/{pr_number}/reviews", self.api_base);
398        let comments: Vec<serde_json::Value> = comments
399            .iter()
400            .map(|c| {
401                serde_json::json!({
402                    "path": c.path,
403                    "line": c.line,
404                    "side": "RIGHT",
405                    "body": security::redact_posted_body(&c.body),
406                })
407            })
408            .collect();
409        let payload = serde_json::json!({
410            "event": event.as_str(),
411            "body": security::redact_posted_body(body),
412            "commit_id": commit_id,
413            "comments": comments,
414        });
415        let result = self.send(self.http.post(&url).json(&payload), &token).await;
416        if result
417            .as_ref()
418            .is_err_and(|err| err.to_string().contains(StatusCode::UNAUTHORIZED.as_str()))
419        {
420            self.invalidate();
421        }
422        result.map(|_| ())
423    }
424
425    async fn repo_token(&self, repo: &str) -> anyhow::Result<String> {
426        match self.token_for_repo(repo).await? {
427            Some(token) => Ok(token),
428            None => anyhow::bail!("the GitHub App is not installed on {repo}"),
429        }
430    }
431
432    /// Post the `orch/review` check run on `head_sha`. The Checks API takes only an App token
433    pub(crate) async fn post_check_run(
434        &self,
435        repo: &str,
436        head_sha: &str,
437        state: CheckRunState<'_>,
438    ) -> anyhow::Result<()> {
439        let token = self.repo_token(repo).await?;
440        let url = format!("{}/repos/{repo}/check-runs", self.api_base);
441        let payload = match state {
442            CheckRunState::InProgress => serde_json::json!({
443                "name": REVIEW_CHECK,
444                "head_sha": head_sha,
445                "status": "in_progress",
446            }),
447            CheckRunState::Completed { approved, summary } => serde_json::json!({
448                "name": REVIEW_CHECK,
449                "head_sha": head_sha,
450                "status": "completed",
451                "conclusion": if approved { "success" } else { "failure" },
452                "output": {
453                    "title": if approved { "Approved by automated review" } else { "Automated review requested changes" },
454                    "summary": security::redact_posted_body(summary),
455                },
456            }),
457        };
458        self.send(self.http.post(&url).json(&payload), &token)
459            .await
460            .map(|_| ())
461    }
462
463    /// Right-side line ranges of every hunk in the pull request, per file path
464    pub(crate) async fn pull_request_hunks(
465        &self,
466        repo: &str,
467        pr_number: u64,
468    ) -> anyhow::Result<HashMap<String, Vec<(u32, u32)>>> {
469        let token = self.repo_token(repo).await?;
470        let mut hunks = HashMap::new();
471
472        for page in 1..=PR_FILE_PAGES {
473            let url = format!(
474                "{}/repos/{repo}/pulls/{pr_number}/files?per_page=100&page={page}",
475                self.api_base
476            );
477            let body = self.send(self.http.get(&url), &token).await?;
478            let files: Vec<PrFile> = serde_json::from_str(&body)
479                .map_err(|_| anyhow::anyhow!("pull request files could not be read"))?;
480            let last = files.len() < 100;
481
482            for file in files {
483                hunks.insert(
484                    file.filename,
485                    right_side_ranges(file.patch.as_deref().unwrap_or("")),
486                );
487            }
488
489            if last {
490                break;
491            }
492        }
493
494        Ok(hunks)
495    }
496
497    /// One page of the App's webhook delivery log and the cursor of the next page
498    pub(crate) async fn hook_deliveries(
499        &self,
500        cursor: Option<&str>,
501    ) -> anyhow::Result<(Vec<HookDelivery>, Option<String>)> {
502        let jwt = sign_jwt(&self.app_id, &self.pem, Utc::now().timestamp())?;
503        let url = format!("{}/app/hook/deliveries", self.api_base);
504        let mut query = vec![("per_page", "100")];
505        if let Some(cursor) = cursor {
506            query.push(("cursor", cursor));
507        }
508        let resp = self
509            .http
510            .get(&url)
511            .query(&query)
512            .header(header::AUTHORIZATION, format!("Bearer {jwt}"))
513            .header(header::ACCEPT, "application/vnd.github+json")
514            .header("X-GitHub-Api-Version", "2022-11-28")
515            .send()
516            .await
517            .map_err(|err| anyhow::anyhow!("GitHub App request failed to send: {err}"))?;
518        let status = resp.status();
519        let next = resp
520            .headers()
521            .get(header::LINK)
522            .and_then(|v| v.to_str().ok())
523            .and_then(next_cursor);
524        let body = resp.text().await.unwrap_or_default();
525        if !status.is_success() {
526            anyhow::bail!("GitHub App API {status}: {}", error_message(&body));
527        }
528        let deliveries = serde_json::from_str(&body)
529            .map_err(|_| anyhow::anyhow!("GitHub App delivery log could not be read"))?;
530        Ok((deliveries, next))
531    }
532
533    /// Ask GitHub to send one delivery of the App's webhook again
534    pub(crate) async fn redeliver(&self, id: u64) -> anyhow::Result<()> {
535        let jwt = sign_jwt(&self.app_id, &self.pem, Utc::now().timestamp())?;
536        let url = format!("{}/app/hook/deliveries/{id}/attempts", self.api_base);
537        self.send(self.http.post(&url), &jwt).await.map(|_| ())
538    }
539
540    async fn send(&self, builder: reqwest::RequestBuilder, bearer: &str) -> anyhow::Result<String> {
541        let (status, body) = self.send_status(builder, bearer).await?;
542        if status.is_success() {
543            return Ok(body);
544        }
545        let message = error_message(&body);
546        anyhow::bail!("GitHub App API {status}: {message}")
547    }
548
549    async fn send_status(
550        &self,
551        builder: reqwest::RequestBuilder,
552        bearer: &str,
553    ) -> anyhow::Result<(StatusCode, String)> {
554        let resp = builder
555            .header(header::AUTHORIZATION, format!("Bearer {bearer}"))
556            .header(header::ACCEPT, "application/vnd.github+json")
557            .header("X-GitHub-Api-Version", "2022-11-28")
558            .send()
559            .await
560            // The reqwest error can carry the URL, never the headers
561            .map_err(|err| anyhow::anyhow!("GitHub App request failed to send: {err}"))?;
562        let status = resp.status();
563        let body = resp.text().await.unwrap_or_default();
564        Ok((status, body))
565    }
566}
567
568/// The `message` of an error body plus its `errors` entries, which hold the real reason of a 422
569fn error_message(body: &str) -> String {
570    let Ok(value) = serde_json::from_str::<serde_json::Value>(body) else {
571        return String::new();
572    };
573    let safe = |text: String| (!security::has_leaks(&text)).then_some(text);
574    let message = value
575        .get("message")
576        .and_then(|msg| msg.as_str())
577        .map(str::to_owned)
578        .and_then(safe)
579        .unwrap_or_default();
580    let details: Vec<String> = value
581        .get("errors")
582        .and_then(|errors| errors.as_array())
583        .into_iter()
584        .flatten()
585        .filter_map(error_entry)
586        .filter_map(safe)
587        .collect();
588
589    if details.is_empty() {
590        message
591    } else {
592        format!("{message} ({})", details.join("; "))
593    }
594}
595
596fn error_entry(entry: &serde_json::Value) -> Option<String> {
597    if let Some(text) = entry.as_str() {
598        return Some(text.to_owned());
599    }
600    let field = |name: &str| entry.get(name).and_then(|v| v.as_str());
601    if let Some(text) = field("message") {
602        return Some(text.to_owned());
603    }
604    let code = field("code")?;
605    let place = [field("resource"), field("field")]
606        .into_iter()
607        .flatten()
608        .collect::<Vec<_>>()
609        .join(".");
610
611    Some(if place.is_empty() {
612        code.to_owned()
613    } else {
614        format!("{place}: {code}")
615    })
616}
617
618/// The `cursor` of the `rel="next"` link in a `Link` header
619fn next_cursor(link: &str) -> Option<String> {
620    let next = link.split(',').find(|part| part.contains("rel=\"next\""))?;
621    let url = next.split(';').next()?.trim().trim_matches(['<', '>']);
622    Url::parse(url)
623        .ok()?
624        .query_pairs()
625        .find(|(key, _)| key == "cursor")
626        .map(|(_, value)| value.into_owned())
627}
628
629fn token_is_fresh(expires_at: DateTime<Utc>, now: DateTime<Utc>) -> bool {
630    expires_at > now + Duration::minutes(10)
631}
632
633// The global config only: a project file must never point the App's key or id elsewhere
634fn nonempty_config(key: &str) -> Option<String> {
635    config::get_global(key)
636        .ok()
637        .map(|value| value.trim().to_string())
638        .filter(|value| !value.is_empty())
639}
640
641fn read_key() -> anyhow::Result<String> {
642    // A passbox or op:// reference keeps the key out of every file an agent can read
643    if let Some(reference) = nonempty_config("gh.app.private_key") {
644        return normalize_pem(&secret_ref::resolve(&reference)?);
645    }
646    if let Some(path) = nonempty_config("gh.app.private_key_path") {
647        let raw = fs::read_to_string(&path)
648            .map_err(|err| anyhow::anyhow!("failed to read GitHub App private key file: {err}"))?;
649        return normalize_pem(&raw);
650    }
651    if let Some(name) = nonempty_config("gh.app.private_key_env") {
652        let raw = env::var(&name).unwrap_or_default();
653        return normalize_pem(&raw).map_err(|_| {
654            anyhow::anyhow!("GitHub App private key variable {name} is unset or empty")
655        });
656    }
657    anyhow::bail!("set gh.app.private_key, gh.app.private_key_env or gh.app.private_key_path")
658}
659
660// A key injected through an environment variable often carries literal `\n`
661fn normalize_pem(raw: &str) -> anyhow::Result<String> {
662    let pem = raw.replace("\\n", "\n").trim().to_string();
663    if pem.is_empty() {
664        anyhow::bail!("GitHub App private key is empty");
665    }
666    Ok(pem)
667}
668
669fn sign_jwt(app_id: &str, pem: &str, now: i64) -> anyhow::Result<String> {
670    let claims = Claims {
671        iss: app_id.to_string(),
672        iat: now - JWT_IAT_SKEW_SECS,
673        exp: now + JWT_EXP_FROM_NOW_SECS,
674    };
675    let key = EncodingKey::from_rsa_pem(pem.as_bytes())
676        .map_err(|_| anyhow::anyhow!("GitHub App private key is not a usable RSA PEM"))?;
677    encode(&Header::new(Algorithm::RS256), &claims, &key)
678        .map_err(|_| anyhow::anyhow!("failed to sign GitHub App JWT"))
679}
680
681/// The App login, `None` when the App is not configured or its login cannot be read
682pub(crate) async fn bot_login() -> Option<String> {
683    let app = shared()?;
684    match app.login().await {
685        Ok(login) => Some(login),
686        Err(err) => {
687            tracing::warn!(error = %err, "GitHub App login unreadable, review gate reads comments only");
688            None
689        }
690    }
691}
692
693// REST names a bot `slug[bot]`, GraphQL names it `slug`
694pub(crate) fn same_login(left: &str, right: &str) -> bool {
695    let strip = |login: &str| login.strip_suffix("[bot]").unwrap_or(login).to_string();
696    strip(left).eq_ignore_ascii_case(&strip(right))
697}
698
699fn on_head(review: &GitHubReview, head_sha: &str) -> bool {
700    !head_sha.is_empty()
701        && review
702            .commit_id
703            .as_deref()
704            .is_some_and(|sha| sha.eq_ignore_ascii_case(head_sha))
705}
706
707/// Keep every non-App review. Keep an App review only when its commit is the current head
708pub(crate) fn reviews_for_gate(
709    reviews: &[GitHubReview],
710    head_sha: &str,
711    app_login: Option<&str>,
712) -> Vec<GitHubReview> {
713    reviews
714        .iter()
715        .filter(|review| {
716            app_login.is_none_or(|login| {
717                !same_login(&review.user.login, login) || on_head(review, head_sha)
718            })
719        })
720        .cloned()
721        .collect()
722}
723
724/// An App approval or change request on the current head replaces the comment decision
725pub(crate) fn effective_comment_flags(
726    reviews: &[GitHubReview],
727    head_sha: &str,
728    app_login: Option<&str>,
729    comment_approved: bool,
730    comment_changes_requested: bool,
731) -> (bool, bool) {
732    let replaced = app_login.is_some_and(|login| {
733        reviews.iter().any(|review| {
734            same_login(&review.user.login, login)
735                && on_head(review, head_sha)
736                && (review.state == "APPROVED" || review.state == "CHANGES_REQUESTED")
737        })
738    });
739    if replaced {
740        (false, false)
741    } else {
742        (comment_approved, comment_changes_requested)
743    }
744}
745
746/// A throwaway RSA key pair, private then public PEM, made once per test process
747#[cfg(test)]
748fn test_keys() -> &'static (String, String) {
749    static KEYS: OnceLock<(String, String)> = OnceLock::new();
750    KEYS.get_or_init(|| {
751        let key = rsa::RsaPrivateKey::new(&mut OsRng, 2048).expect("rsa");
752        let private = key.to_pkcs8_pem(LineEnding::LF).expect("pem").to_string();
753        let public = rsa::RsaPublicKey::from(&key)
754            .to_public_key_pem(LineEnding::LF)
755            .expect("public pem");
756        (private, public)
757    })
758}
759
760#[cfg(test)]
761pub(crate) fn test_pem() -> &'static str {
762    &test_keys().0
763}
764
765#[cfg(test)]
766mod tests {
767    use super::*;
768    use crate::github::types::GitHubUser;
769    use crate::github::types::ReviewIssue;
770    use jsonwebtoken::{DecodingKey, Validation, decode};
771    use std::sync::atomic::{AtomicUsize, Ordering};
772    use wiremock::matchers::{body_partial_json, header as header_is, method, path};
773    use wiremock::{Mock, MockServer, Request, ResponseTemplate};
774
775    fn app(server: &MockServer) -> AppAuth {
776        AppAuth::new("12345".to_string(), test_pem().to_string(), server.uri())
777    }
778
779    async fn installed(server: &MockServer, repo: &str, id: u64) {
780        Mock::given(method("GET"))
781            .and(path(format!("/repos/{repo}/installation")))
782            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({"id": id})))
783            .mount(server)
784            .await;
785    }
786
787    fn review(login: &str, state: &str, sha: &str, at: &str) -> GitHubReview {
788        GitHubReview {
789            id: 1,
790            user: GitHubUser {
791                login: login.to_string(),
792            },
793            body: None,
794            state: state.to_string(),
795            html_url: None,
796            submitted_at: at.to_string(),
797            commit_id: Some(sha.to_string()),
798        }
799    }
800
801    fn decode_claims(jwt: &str) -> Claims {
802        let mut validation = Validation::new(Algorithm::RS256);
803        validation.validate_exp = false;
804        let key = DecodingKey::from_rsa_pem(test_keys().1.as_bytes()).expect("decode key");
805        decode::<Claims>(jwt, &key, &validation)
806            .expect("signed with the app key")
807            .claims
808    }
809
810    #[test]
811    fn jwt_has_the_app_claims_and_is_signed_with_the_key() {
812        let now = 1_700_000_000;
813        let jwt = sign_jwt("12345", test_pem(), now).expect("sign");
814        let claims = decode_claims(&jwt);
815        assert_eq!(claims.iss, "12345");
816        assert_eq!(claims.iat, now - 60);
817        assert!(claims.exp > now && claims.exp - now <= 600);
818        assert!(security::has_leaks(&jwt), "a jwt must trip the leak scan");
819        assert!(
820            security::has_leaks(test_pem()),
821            "a key must trip the leak scan"
822        );
823    }
824
825    #[test]
826    fn error_message_includes_the_errors_entries() {
827        let body = serde_json::json!({
828            "message": "Unprocessable Entity",
829            "errors": [
830                "Can not approve your own pull request",
831                {"message": "line must be part of the diff"},
832                {"resource": "PullRequestReview", "field": "commit_id", "code": "invalid"}
833            ]
834        })
835        .to_string();
836        assert_eq!(
837            error_message(&body),
838            "Unprocessable Entity (Can not approve your own pull request; line must be part of \
839             the diff; PullRequestReview.commit_id: invalid)"
840        );
841    }
842
843    #[test]
844    fn error_message_drops_an_entry_that_trips_the_leak_scan() {
845        let body = serde_json::json!({
846            "message": "Unprocessable Entity",
847            "errors": ["still readable", test_pem()]
848        })
849        .to_string();
850        let message = error_message(&body);
851        assert_eq!(message, "Unprocessable Entity (still readable)");
852        assert!(!message.contains("PRIVATE"));
853        assert_eq!(error_message("not json"), "");
854    }
855
856    #[test]
857    fn a_bad_key_is_rejected_without_echoing_it() {
858        let pem = format!("-----{} {}-----\nMARKERMATERIAL\n", "BEGIN", "PRIVATE KEY");
859        let err = sign_jwt("12345", &pem, 0).expect_err("bad key").to_string();
860        assert!(!err.contains("MARKERMATERIAL"), "{err}");
861    }
862
863    #[test]
864    fn normalize_pem_expands_escaped_newlines() {
865        let pem = normalize_pem("  A\\nB\\nC ").expect("pem");
866        assert_eq!(pem, "A\nB\nC");
867        assert!(normalize_pem("   ").is_err());
868    }
869
870    #[tokio::test]
871    async fn installation_token_is_cached_and_refreshed_before_expiry() {
872        let server = MockServer::start().await;
873        installed(&server, "o/r", 42).await;
874        let posts = Arc::new(AtomicUsize::new(0));
875        let counter = Arc::clone(&posts);
876        Mock::given(method("POST"))
877            .and(path("/app/installations/42/access_tokens"))
878            .respond_with(move |_req: &Request| {
879                let n = counter.fetch_add(1, Ordering::SeqCst) + 1;
880                ResponseTemplate::new(201).set_body_json(serde_json::json!({
881                    "token": format!("inst-{n}"),
882                    "expires_at": "2099-01-01T00:00:00Z",
883                }))
884            })
885            .mount(&server)
886            .await;
887        let app = app(&server);
888
889        assert_eq!(
890            app.token_for_repo("o/r").await.unwrap().as_deref(),
891            Some("inst-1")
892        );
893        assert_eq!(
894            app.token_for_repo("o/r").await.unwrap().as_deref(),
895            Some("inst-1")
896        );
897        assert_eq!(posts.load(Ordering::SeqCst), 1);
898
899        let requests = server.received_requests().await.expect("requests");
900        let auth = requests[0]
901            .headers
902            .get("authorization")
903            .and_then(|value| value.to_str().ok())
904            .unwrap_or_default();
905        let claims = decode_claims(auth.trim_start_matches("Bearer "));
906        assert_eq!(claims.iss, "12345");
907
908        // Inside the 10 minute window the token is refreshed
909        lock(&app.tokens).get_mut(&42).unwrap().expires_at = Utc::now() + Duration::minutes(9);
910        assert_eq!(
911            app.token_for_repo("o/r").await.unwrap().as_deref(),
912            Some("inst-2")
913        );
914        assert_eq!(posts.load(Ordering::SeqCst), 2);
915    }
916
917    #[tokio::test]
918    async fn a_repo_without_the_app_gets_no_token_and_is_looked_up_once() {
919        let server = MockServer::start().await;
920        Mock::given(method("GET"))
921            .and(path("/repos/other-org/x/installation"))
922            .respond_with(ResponseTemplate::new(404))
923            .expect(1)
924            .mount(&server)
925            .await;
926        let app = app(&server);
927        assert_eq!(app.token_for_repo("other-org/x").await.unwrap(), None);
928        assert_eq!(app.token_for_repo("other-org/x").await.unwrap(), None);
929    }
930
931    #[tokio::test]
932    async fn an_account_and_an_organization_get_their_own_installation_tokens() {
933        let server = MockServer::start().await;
934        installed(&server, "me/a", 42).await;
935        installed(&server, "org/b", 77).await;
936        for (id, token) in [(42, "inst-me"), (77, "inst-org")] {
937            Mock::given(method("POST"))
938                .and(path(format!("/app/installations/{id}/access_tokens")))
939                .respond_with(ResponseTemplate::new(201).set_body_json(serde_json::json!({
940                    "token": token,
941                    "expires_at": "2099-01-01T00:00:00Z",
942                })))
943                .expect(1)
944                .mount(&server)
945                .await;
946        }
947        let app = app(&server);
948        assert_eq!(
949            app.token_for_repo("me/a").await.unwrap().as_deref(),
950            Some("inst-me")
951        );
952        assert_eq!(
953            app.token_for_repo("org/b").await.unwrap().as_deref(),
954            Some("inst-org")
955        );
956    }
957
958    #[tokio::test]
959    async fn a_failed_lookup_is_an_error_and_is_not_cached() {
960        let server = MockServer::start().await;
961        Mock::given(method("GET"))
962            .and(path("/repos/o/r/installation"))
963            .respond_with(ResponseTemplate::new(500))
964            .mount(&server)
965            .await;
966        let app = app(&server);
967        assert!(app.token_for_repo("o/r").await.is_err());
968        assert!(lock(&app.installations).get("o/r").is_none());
969    }
970
971    #[tokio::test]
972    async fn login_is_the_slug_with_the_bot_suffix() {
973        let server = MockServer::start().await;
974        Mock::given(method("GET"))
975            .and(path("/app"))
976            .respond_with(
977                ResponseTemplate::new(200).set_body_json(serde_json::json!({"slug": "orch-app"})),
978            )
979            .expect(1)
980            .mount(&server)
981            .await;
982        let app = app(&server);
983        assert_eq!(app.login().await.unwrap(), "orch-app[bot]");
984        assert_eq!(app.login().await.unwrap(), "orch-app[bot]");
985    }
986
987    #[tokio::test]
988    async fn a_review_is_submitted_on_the_head_sha_with_the_installation_token() {
989        let server = MockServer::start().await;
990        installed(&server, "o/r", 42).await;
991        Mock::given(method("POST"))
992            .and(path("/app/installations/42/access_tokens"))
993            .respond_with(ResponseTemplate::new(201).set_body_json(serde_json::json!({
994                "token": "inst-1",
995                "expires_at": "2099-01-01T00:00:00Z",
996            })))
997            .mount(&server)
998            .await;
999        Mock::given(method("POST"))
1000            .and(path("/repos/o/r/pulls/9/reviews"))
1001            .and(header_is("authorization", "Bearer inst-1"))
1002            .and(body_partial_json(serde_json::json!({
1003                "event": "APPROVE",
1004                "commit_id": "abc123",
1005                "body": "looks good",
1006            })))
1007            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({"id": 1})))
1008            .expect(1)
1009            .mount(&server)
1010            .await;
1011        app(&server)
1012            .submit_review("o/r", 9, ReviewEvent::Approve, "looks good", "abc123", &[])
1013            .await
1014            .expect("review submitted");
1015    }
1016
1017    #[tokio::test]
1018    async fn a_review_on_a_repo_without_the_app_fails_clearly() {
1019        let server = MockServer::start().await;
1020        Mock::given(method("GET"))
1021            .and(path("/repos/org/b/installation"))
1022            .respond_with(ResponseTemplate::new(404))
1023            .mount(&server)
1024            .await;
1025        let err = app(&server)
1026            .submit_review("org/b", 9, ReviewEvent::Approve, "ok", "abc123", &[])
1027            .await
1028            .unwrap_err()
1029            .to_string();
1030        assert!(err.contains("not installed on org/b"), "{err}");
1031    }
1032
1033    #[test]
1034    fn an_app_approval_on_an_older_sha_does_not_pass_the_gate() {
1035        let reviews = vec![review(
1036            "orch-app[bot]",
1037            "APPROVED",
1038            "old",
1039            "2026-01-01T00:00:00Z",
1040        )];
1041        assert!(reviews_for_gate(&reviews, "new", Some("orch-app[bot]")).is_empty());
1042        assert_eq!(
1043            reviews_for_gate(&reviews, "old", Some("orch-app[bot]")).len(),
1044            1
1045        );
1046        // GraphQL drops the suffix
1047        assert!(reviews_for_gate(&reviews, "new", Some("orch-app")).is_empty());
1048    }
1049
1050    #[test]
1051    fn human_reviews_stay_and_no_app_keeps_everything() {
1052        let reviews = vec![
1053            review("human", "CHANGES_REQUESTED", "old", "2026-01-01T00:00:00Z"),
1054            review("orch-app[bot]", "APPROVED", "old", "2026-01-02T00:00:00Z"),
1055        ];
1056        let kept = reviews_for_gate(&reviews, "new", Some("orch-app[bot]"));
1057        assert_eq!(kept.len(), 1);
1058        assert_eq!(kept[0].user.login, "human");
1059        assert_eq!(reviews_for_gate(&reviews, "new", None).len(), 2);
1060    }
1061
1062    #[test]
1063    fn an_app_review_on_the_head_replaces_the_comment_decision() {
1064        let on_head = vec![review(
1065            "orch-app",
1066            "CHANGES_REQUESTED",
1067            "head",
1068            "2026-01-01T00:00:00Z",
1069        )];
1070        assert_eq!(
1071            effective_comment_flags(&on_head, "head", Some("orch-app[bot]"), true, false),
1072            (false, false)
1073        );
1074        // An old App review leaves the comment fallback in charge
1075        assert_eq!(
1076            effective_comment_flags(&on_head, "new", Some("orch-app[bot]"), true, false),
1077            (true, false)
1078        );
1079        assert_eq!(
1080            effective_comment_flags(&on_head, "head", None, true, false),
1081            (true, false)
1082        );
1083    }
1084
1085    #[test]
1086    fn hunk_headers_give_the_right_side_line_ranges() {
1087        let patch =
1088            "@@ -1,2 +10,3 @@\n a\n+b\n@@ -40 +44 @@ fn x()\n-c\n+d\n@@ -60,3 +70,0 @@\n-gone";
1089        assert_eq!(right_side_ranges(patch), vec![(10, 12), (44, 44)]);
1090        assert_eq!(right_side_ranges(""), [] as [(u32, u32); 0]);
1091        assert_eq!(right_side_ranges("@@ garbage @@"), [] as [(u32, u32); 0]);
1092    }
1093
1094    #[test]
1095    fn issues_on_a_hunk_line_go_inline_and_the_rest_are_listed() {
1096        let issue = |file: &str, line: Option<u32>| ReviewIssue {
1097            file: file.to_string(),
1098            line,
1099            severity: "warning".to_string(),
1100            description: "check".to_string(),
1101        };
1102        let hunks = HashMap::from([("a.rs".to_string(), vec![(10, 12)])]);
1103        let (inline, rest) = split_inline(
1104            &[
1105                issue("a.rs", Some(12)),
1106                issue("a.rs", Some(13)),
1107                issue("b.rs", None),
1108            ],
1109            &hunks,
1110        );
1111        assert_eq!(
1112            inline,
1113            vec![InlineComment {
1114                path: "a.rs".to_string(),
1115                line: 12,
1116                body: "**warning:** check".to_string(),
1117            }]
1118        );
1119        assert_eq!(
1120            rest,
1121            vec![
1122                "- `a.rs:13` **warning:** check",
1123                "- `b.rs` **warning:** check"
1124            ]
1125        );
1126    }
1127
1128    #[tokio::test]
1129    async fn a_failed_key_read_retries_and_a_later_read_publishes_the_app() {
1130        let calls = Arc::new(AtomicUsize::new(0));
1131        let counter = Arc::clone(&calls);
1132        let load = move || {
1133            if counter.fetch_add(1, Ordering::SeqCst) == 0 {
1134                anyhow::bail!("nobody answered the prompt");
1135            }
1136            Ok(Some(AppAuth::new(
1137                "12345".to_string(),
1138                test_pem().to_string(),
1139                "http://127.0.0.1:9".to_string(),
1140            )))
1141        };
1142        let published = Arc::new(Mutex::new(Vec::new()));
1143        let sink = Arc::clone(&published);
1144
1145        run_loader(
1146            load,
1147            move |app| lock(&sink).push(app.app_id.clone()),
1148            StdDuration::from_millis(5),
1149        )
1150        .await;
1151        assert_eq!(calls.load(Ordering::SeqCst), 2);
1152        assert_eq!(*lock(&published), vec!["12345".to_string()]);
1153    }
1154
1155    #[tokio::test]
1156    async fn no_app_configured_stops_the_loader_without_publishing() {
1157        let published = Arc::new(Mutex::new(0));
1158        let sink = Arc::clone(&published);
1159        run_loader(
1160            || Ok(None),
1161            move |_| *lock(&sink) += 1,
1162            StdDuration::from_millis(5),
1163        )
1164        .await;
1165        assert_eq!(*lock(&published), 0);
1166    }
1167}