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