diff --git a/README.md b/README.md index adf8d00..5c8a9ef 100644 --- a/README.md +++ b/README.md @@ -74,6 +74,7 @@ script. |---|---| | `pullpen` | open the queue | | `pullpen setup` | sign in, and answer what pullpen needs to know | +| `pullpen setup ` | sign in to one forge again, when its token expires | | `pullpen settings` | see and change any setting | | `pullpen config check` | what works, and what to type to fix what does not | diff --git a/crates/pullpen-forge/src/auth.rs b/crates/pullpen-forge/src/auth.rs index d360b44..6d1b490 100644 --- a/crates/pullpen-forge/src/auth.rs +++ b/crates/pullpen-forge/src/auth.rs @@ -17,15 +17,48 @@ pub fn token( token_cmd: Option<&str>, env: impl Fn(&str) -> Option, ) -> Result { - let vars: &[&str] = match kind { + found(kind, host, stored, token_cmd, env).map(|(_, t)| t) +} + +/// Where a token came from, which decides what renews it. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Source { + Env(&'static str), + Stored, + Cli, + Cmd, +} + +impl Source { + /// What to do when the forge rejects a token from here. + pub fn renew(self, kind: Forge, host: &str) -> String { + let cli = if kind == Forge::GitHub { "gh" } else { "glab" }; + match self { + Source::Env(var) => format!("replace the token in ${var}"), + Source::Stored => format!("run `pullpen setup {host}`"), + Source::Cli => format!("run `{cli} auth login --hostname {host}`"), + Source::Cmd => "make token_cmd in config.toml print a token that works".into(), + } + } +} + +/// The token, and where it was found. +pub fn found( + kind: Forge, + host: &str, + stored: Option<&str>, + token_cmd: Option<&str>, + env: impl Fn(&str) -> Option, +) -> Result<(Source, String)> { + let vars: &[&'static str] = match kind { Forge::GitHub => &["PULLPEN_GITHUB_TOKEN", "GITHUB_TOKEN"], Forge::GitLab => &["PULLPEN_GITLAB_TOKEN", "GITLAB_TOKEN"], }; - if let Some(t) = vars.iter().find_map(|v| env(v).filter(|t| !t.trim().is_empty())) { - return Ok(t.trim().to_string()); + if let Some((v, t)) = vars.iter().find_map(|v| env(v).filter(|t| !t.trim().is_empty()).map(|t| (*v, t))) { + return Ok((Source::Env(v), t.trim().to_string())); } if let Some(t) = stored.filter(|t| !t.is_empty()) { - return Ok(t.to_string()); + return Ok((Source::Stored, t.to_string())); } let from_cli = match kind { Forge::GitHub => output("gh", &["auth", "token", "--hostname", host]), @@ -36,12 +69,12 @@ pub fn token( }), }; if let Some(t) = from_cli.filter(|t| !t.is_empty() && !t.contains(' ')) { - return Ok(t); + return Ok((Source::Cli, t)); } if let Some(cmd) = token_cmd && let Some(t) = shell(cmd).map(|o| o.trim().to_string()).filter(|t| !t.is_empty()) { - return Ok(t); + return Ok((Source::Cmd, t)); } Err(Error::Auth(host.into())) } diff --git a/crates/pullpen-forge/src/github/tests.rs b/crates/pullpen-forge/src/github/tests.rs index 2a8e75a..bb4be24 100644 --- a/crates/pullpen-forge/src/github/tests.rs +++ b/crates/pullpen-forge/src/github/tests.rs @@ -228,7 +228,7 @@ async fn http_failures_map_to_what_the_ui_does_with_them() { .await; let g = gh(&server); let at = |n| PrId { number: n, ..id() }; - assert_eq!(g.approve(&at(1)).await.unwrap_err(), Error::Auth("github.com".into())); + assert_eq!(g.approve(&at(1)).await.unwrap_err(), Error::Rejected { host: "github.com".into(), why: "x".into() }); assert_eq!(g.approve(&at(2)).await.unwrap_err(), Error::Server { host: "github.com".into(), status: 502 }); assert_eq!(g.approve(&at(3)).await.unwrap_err(), Error::RateLimited { retry_in: 8 }); assert_eq!(g.approve(&at(4)).await.unwrap_err(), Error::RateLimited { retry_in: 3 }); diff --git a/crates/pullpen-forge/src/gitlab/tests.rs b/crates/pullpen-forge/src/gitlab/tests.rs index 2d688f0..3688751 100644 --- a/crates/pullpen-forge/src/gitlab/tests.rs +++ b/crates/pullpen-forge/src/gitlab/tests.rs @@ -136,7 +136,10 @@ async fn refusals_carry_gitlabs_message_in_either_shape() { let g = gl(&server, &[]); assert_eq!(g.merge(&id(), MergeMethod::Merge).await.unwrap_err(), Error::Refused("405 Method Not Allowed".into())); assert_eq!(g.comment(&id(), "").await.unwrap_err(), Error::Refused("body can't be blank".into())); - assert_eq!(g.approve(&id()).await.unwrap_err(), Error::Auth("gitlab.com".into())); + assert_eq!( + g.approve(&id()).await.unwrap_err(), + Error::Rejected { host: "gitlab.com".into(), why: "401 Unauthorized".into() } + ); } #[tokio::test] diff --git a/crates/pullpen-forge/src/http.rs b/crates/pullpen-forge/src/http.rs index c8bb32b..dec152d 100644 --- a/crates/pullpen-forge/src/http.rs +++ b/crates/pullpen-forge/src/http.rs @@ -29,7 +29,8 @@ pub fn client() -> reqwest::Client { /// The forge's own explanation from an error body: GitHub's `errors` (each a /// string or an object with a `message`) in preference to its generic -/// `message`, GitLab's `message` (a string, or an object of lists) or `error`. +/// `message`, GitLab's `message` (a string, or an object of lists) or `error`, +/// whose `error_description` is the sentence where there is one. fn explanation(body: &Value) -> Option { let specific: Vec = body .get("errors") @@ -56,7 +57,7 @@ fn explanation(body: &Value) -> Option { Some(Value::Array(a)) => parts.extend(a.iter().filter_map(Value::as_str).map(String::from)), _ => {} } - if let Some(e) = body.get("error").and_then(Value::as_str) { + if let Some(e) = body.get("error_description").or(body.get("error")).and_then(Value::as_str) { parts.push(e.to_string()); } (!parts.is_empty()).then(|| parts.join("; ")) @@ -114,7 +115,9 @@ async fn check(host: &str, resp: Response) -> Result { let body: Value = serde_json::from_str(&text).unwrap_or(Value::String(text)); let why = explanation(&body); Err(match status { - StatusCode::UNAUTHORIZED => Error::Auth(host.into()), + StatusCode::UNAUTHORIZED => { + Error::Rejected { host: host.into(), why: why.unwrap_or_else(|| "401 Unauthorized".into()) } + } StatusCode::TOO_MANY_REQUESTS => Error::RateLimited { retry_in: retry_after.unwrap_or(60) }, StatusCode::FORBIDDEN if exhausted || retry_after.is_some() => { let now = pullpen_core::time::Timestamp::now().0 as u64; diff --git a/crates/pullpen-forge/src/lib.rs b/crates/pullpen-forge/src/lib.rs index 8386e88..138af93 100644 --- a/crates/pullpen-forge/src/lib.rs +++ b/crates/pullpen-forge/src/lib.rs @@ -16,8 +16,12 @@ use pullpen_core::{ #[derive(Debug, thiserror::Error, Clone, PartialEq, Eq)] pub enum Error { + /// No token was found for the host. #[error("not signed in to {0}; set a token or run its CLI's login")] Auth(String), + /// The forge refused the token it was sent. The reason is the forge's own. + #[error("{host} rejected the token: {why}")] + Rejected { host: String, why: String }, /// The words are for an action, which nothing retries; the sync loop, /// which does retry, has its own. #[error("rate limited; try again in {retry_in}s")] diff --git a/crates/pullpen-forge/src/tests.rs b/crates/pullpen-forge/src/tests.rs index 88339f7..948be5b 100644 --- a/crates/pullpen-forge/src/tests.rs +++ b/crates/pullpen-forge/src/tests.rs @@ -18,6 +18,37 @@ fn only_retryable_failures_are_transient() { assert!(Error::Network("reset".into()).transient()); assert!(!Error::Refused("no".into()).transient()); assert!(!Error::Auth("h".into()).transient()); + assert!(!Error::Rejected { host: "h".into(), why: "expired".into() }.transient()); +} + +/// GitLab's answer to an expired token, as it sent it. +#[tokio::test] +async fn a_rejected_token_keeps_the_forges_reason() { + let server = wiremock::MockServer::start().await; + wiremock::Mock::given(wiremock::matchers::any()) + .respond_with(wiremock::ResponseTemplate::new(401).set_body_json(serde_json::json!({ + "error": "invalid_token", + "error_description": "Token is expired. You can either do re-authorization or token refresh." + }))) + .mount(&server) + .await; + let err = http::send("gitlab.com", http::client().get(server.uri())).await.unwrap_err(); + assert_eq!( + err.to_string(), + "gitlab.com rejected the token: Token is expired. You can either do re-authorization or token refresh." + ); +} + +#[test] +fn the_fix_names_where_the_token_came_from() { + use pullpen_core::Forge::{GitHub, GitLab}; + let env = |k: &str| (k == "GITLAB_TOKEN").then(|| "t".to_string()); + let (from, _) = auth::found(GitLab, "gitlab.com", Some("stored"), None, env).unwrap(); + assert_eq!(from.renew(GitLab, "gitlab.com"), "replace the token in $GITLAB_TOKEN"); + let (from, _) = auth::found(GitLab, "gitlab.com", Some("stored"), None, |_| None).unwrap(); + assert_eq!(from.renew(GitLab, "gitlab.com"), "run `pullpen setup gitlab.com`"); + assert_eq!(auth::Source::Cli.renew(GitHub, "ghe.example"), "run `gh auth login --hostname ghe.example`"); + assert_eq!(auth::Source::Cli.renew(GitLab, "gitlab.com"), "run `glab auth login --hostname gitlab.com`"); } #[test] diff --git a/crates/pullpen/src/cli.rs b/crates/pullpen/src/cli.rs index ec78355..c3f4fb0 100644 --- a/crates/pullpen/src/cli.rs +++ b/crates/pullpen/src/cli.rs @@ -32,7 +32,10 @@ pub struct Args { #[derive(Subcommand, Debug)] pub enum Command { /// Sign in to your forges and answer what pullpen needs to know. - Setup, + Setup { + /// Sign in again to this one forge, such as gitlab.com, and ask nothing else. + host: Option, + }, /// See and change every setting; `get` and `set` do it from a script. Settings { #[command(subcommand)] diff --git a/crates/pullpen/src/commands.rs b/crates/pullpen/src/commands.rs index 902c54d..f60842d 100644 --- a/crates/pullpen/src/commands.rs +++ b/crates/pullpen/src/commands.rs @@ -20,16 +20,26 @@ pub fn interactive() -> bool { io::stdin().is_terminal() && io::stdout().is_terminal() } +fn forge(f: Forge, host: &str, token: &str) -> Box { + let t = token.to_string(); + match f { + Forge::GitHub => Box::new(pullpen_forge::github::GitHub::new(host, t, Agents::default(), "", false)), + Forge::GitLab => Box::new(pullpen_forge::gitlab::GitLab::new(host, t, Agents::default(), vec![], false)), + } +} + +/// The login a token belongs to, for `pullpen config check`. +pub fn login(f: Forge, host: &str, token: &str) -> pullpen_forge::Result { + let rt = tokio::runtime::Builder::new_current_thread().enable_all().build(); + rt.map_err(|e| pullpen_forge::Error::Network(e.to_string()))?.block_on(forge(f, host, token).viewer()) +} + /// Asks the forge whose token this is: its answer is the only proof a /// token works. fn verify(f: Forge, host: &str, token: &str) -> Result { let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().map_err(|e| e.to_string())?; - let t = token.to_string(); + let forge = forge(f, host, token); rt.block_on(async move { - let forge: Box = match f { - Forge::GitHub => Box::new(pullpen_forge::github::GitHub::new(host, t, Agents::default(), "", false)), - Forge::GitLab => Box::new(pullpen_forge::gitlab::GitLab::new(host, t, Agents::default(), vec![], false)), - }; let login = forge.viewer().await?; // Knowing where someone can watch is a help, not a requirement; a // token that cannot list groups still signs in. @@ -39,8 +49,8 @@ fn verify(f: Forge, host: &str, token: &str) -> Result .map_err(|e| e.to_string()) } -pub fn setup(cfg_path: &Path, creds_path: &Path, cfg: Config) -> Result<()> { - let creds = credentials::load(creds_path).unwrap_or_default(); +pub fn setup(cfg_path: &Path, creds_path: &Path, cfg: Config, host: Option<&str>) -> Result<()> { + let mut creds = credentials::load(creds_path).unwrap_or_default(); let stdin = io::stdin(); let (mut input, mut out) = (stdin.lock(), io::stdout()); let mut secret = read_hidden; @@ -49,6 +59,13 @@ pub fn setup(cfg_path: &Path, creds_path: &Path, cfg: Config) -> Result<()> { let cli = |f: Forge, host: &str| auth::token(f, host, None, None, |_| None).ok(); let env = |k: &str| std::env::var(k).ok().filter(|v| !v.is_empty()); let mut deps = setup::Deps { verify: &mut check, cli: &cli, env: &env }; + if let Some(host) = host { + if setup::renew(&mut io, &mut deps, &cfg, host, &mut creds)? && (!creds.token.is_empty() || creds_path.exists()) + { + credentials::save(creds_path, &creds).with_context(|| format!("writing {}", creds_path.display()))?; + } + return Ok(()); + } let (cfg, creds) = setup::run(&mut io, &mut deps, cfg, creds)?; if cfg.forge.is_empty() { return Ok(()); @@ -122,7 +139,7 @@ fn menu(cfg_path: &Path, creds_path: &Path, mut cfg: Config) -> Result { settings::Leave::Done => return Ok(0), settings::Leave::Setup => { drop(input); - setup(cfg_path, creds_path, cfg)?; + setup(cfg_path, creds_path, cfg, None)?; } settings::Leave::Edit => { drop(input); @@ -136,8 +153,14 @@ fn menu(cfg_path: &Path, creds_path: &Path, mut cfg: Config) -> Result { eprintln!("starting {editor}: {e}"); } let (fresh, err) = Config::load(cfg_path); - let found = - config::check::check(cfg_path, &fresh, err.as_deref(), Ok(&creds), &|k| std::env::var(k).ok()); + let found = config::check::check( + cfg_path, + &fresh, + err.as_deref(), + Ok(&creds), + &|k| std::env::var(k).ok(), + &login, + ); config::check::report(&found); } } diff --git a/crates/pullpen/src/config/check.rs b/crates/pullpen/src/config/check.rs index a40cfcb..bfecda3 100644 --- a/crates/pullpen/src/config/check.rs +++ b/crates/pullpen/src/config/check.rs @@ -5,7 +5,7 @@ use std::path::Path; use pullpen_core::Forge; use pullpen_core::query::{Query, Term}; -use pullpen_forge::auth; +use pullpen_forge::{Error, auth}; use super::{Config, Kind, expand}; use crate::credentials::Credentials; @@ -31,6 +31,8 @@ pub fn check( load_err: Option<&str>, creds: Result<&Credentials, &str>, env: &dyn Fn(&str) -> Option, + // Having a token proves nothing: only the forge can say it works. + verify: &dyn Fn(Forge, &str, &str) -> pullpen_forge::Result, ) -> Vec { let mut out = vec![match load_err { Some(e) => bad(e.to_string(), "correct the line it names, or move the file aside to use the defaults"), @@ -50,8 +52,14 @@ pub fn check( Kind::Github => Forge::GitHub, Kind::Gitlab => Forge::GitLab, }; - out.push(match auth::token(kind, f.host(), creds.get(f.host()), f.token_cmd.as_deref(), env) { - Ok(_) => ok(format!("{}: signed in", f.host())), + let host = f.host(); + let found = auth::found(kind, host, creds.get(host), f.token_cmd.as_deref(), env); + out.push(match found.map(|(from, t)| (from, verify(kind, host, &t))) { + Ok((_, Ok(login))) => ok(format!("{host}: signed in as {login}")), + Ok((from, Err(Error::Rejected { why, .. }))) => { + bad(format!("{host}: token rejected ({why})"), &from.renew(kind, host)) + } + Ok((_, Err(e))) => bad(format!("{host}: token not checked ({e})"), "run it again when the forge answers"), Err(_) => bad( format!("{}: no token", f.host()), match kind { diff --git a/crates/pullpen/src/config/tests.rs b/crates/pullpen/src/config/tests.rs index 34cb379..b38ac22 100644 --- a/crates/pullpen/src/config/tests.rs +++ b/crates/pullpen/src/config/tests.rs @@ -78,12 +78,45 @@ fn every_failed_check_says_how_to_fix_it() { None, Ok(&crate::credentials::Credentials::default()), &|_| None, + &|_, _, _| Ok("mara".into()), ); let failed: Vec<&check::Finding> = found.iter().filter(|f| !f.ok).collect(); assert_eq!(failed.len(), 4, "token, section term, key, palette"); assert!(failed.iter().all(|f| f.fix.is_some()), "a failure without a fix line"); } +/// The forge's line from a check of a GitLab whose stored token the forge +/// answers with `answer`. +fn sign_in_line(answer: pullpen_forge::Result) -> (bool, String, Option) { + let mut creds = crate::credentials::Credentials::default(); + creds.set("gitlab.com", "glpat-stored".into()); + let c = Config { + forge: vec![ForgeCfg { kind: Kind::Gitlab, host: None, token_cmd: None, scope: None, groups: vec![] }], + ..Config::default() + }; + let found = + check::check(Path::new("/nonexistent/config.toml"), &c, None, Ok(&creds), &|_| None, &|_, _, _| answer.clone()); + let f = found.into_iter().find(|f| f.what.starts_with("gitlab.com")).unwrap(); + (f.ok, f.what, f.fix) +} + +#[test] +fn a_token_the_forge_rejects_fails_the_check_with_its_fix() { + let rejected = pullpen_forge::Error::Rejected { host: "gitlab.com".into(), why: "Token is expired.".into() }; + assert_eq!( + sign_in_line(Err(rejected)), + (false, "gitlab.com: token rejected (Token is expired.)".into(), Some("run `pullpen setup gitlab.com`".into())) + ); + assert_eq!(sign_in_line(Ok("mara".into())), (true, "gitlab.com: signed in as mara".into(), None)); +} + +#[test] +fn an_unreachable_forge_is_not_called_signed_in() { + let (ok, what, fix) = sign_in_line(Err(pullpen_forge::Error::Network("gitlab.com: timed out".into()))); + assert!(!ok && fix.is_some()); + assert_eq!(what, "gitlab.com: token not checked (gitlab.com: timed out)"); +} + #[test] fn the_example_config_file_matches_the_plan() { let root = concat!(env!("CARGO_MANIFEST_DIR"), "/../.."); diff --git a/crates/pullpen/src/live/mod.rs b/crates/pullpen/src/live/mod.rs index a28fb04..d2c84ed 100644 --- a/crates/pullpen/src/live/mod.rs +++ b/crates/pullpen/src/live/mod.rs @@ -32,6 +32,8 @@ pub type Unreachable = (Kind, String); struct Entry { forge: Arc, me: OnceCell, + /// What renews this forge's token, for when the forge rejects it. + renew: String, } pub struct Live { @@ -63,10 +65,10 @@ impl Live { CfgKind::Github => Kind::GitHub, CfgKind::Gitlab => Kind::GitLab, }; - let token = match auth::token(kind, f.host(), creds.get(f.host()), f.token_cmd.as_deref(), |k| { + let (from, token) = match auth::found(kind, f.host(), creds.get(f.host()), f.token_cmd.as_deref(), |k| { std::env::var(k).ok() }) { - Ok(t) => t, + Ok(found) => found, // An unconfigured forge without a token is one the user does // not use; only a configured one is worth a complaint. Err(_) => { @@ -96,7 +98,7 @@ impl Live { )), }; kinds.push(kind); - forges.push(Entry { forge, me: OnceCell::new() }); + forges.push(Entry { forge, me: OnceCell::new(), renew: from.renew(kind, f.host()) }); } let (tx, rx) = channel(); let groups = shared(sections); @@ -141,6 +143,7 @@ impl Live { let mut backoff = 0u64; loop { let (mut prs, mut total, mut failed, mut caps) = (Vec::new(), 0, None, HashMap::new()); + let mut answered = false; for e in forges.iter().filter(|e| q.reaches(e.forge.kind())) { let kind = e.forge.kind(); let page = match e.me.get_or_try_init(|| e.forge.viewer()).await { @@ -149,6 +152,7 @@ impl Live { }; match page { Ok(p) => { + answered = true; total += p.total; prs.extend(p.prs); // The receiver is gone only once the app has quit. @@ -157,7 +161,7 @@ impl Live { None => Msg::Up(kind), }); } - Err(err) => failed = Some((kind, e.forge.host().to_string(), err)), + Err(err) => failed = Some((e, err)), } caps.extend(e.forge.capabilities()); } @@ -169,25 +173,31 @@ impl Live { total = prs.len(); } let _ = tx.send(Msg::Caps(caps)); + // One forge failing must not hide what another returned, so + // those rows are shown; the status line marks the failure. + // Only a pass every forge answered is cached, so the next + // start never paints a partial list as the section. + for (i, section) in members.iter().filter(|_| answered) { + let mut prs = prs.clone(); + sort(&mut prs, section.sort); + if failed.is_none() { + // A cache that will not write costs only a slower + // first paint next time. + let _ = cache::store(&cache_dir, section, &prs, total); + } + let _ = tx.send(Msg::Synced { section: *i, prs, total }); + } let wait = match failed { None => { backoff = 0; if let Ok(mut l) = last.lock() { *l = Some(Instant::now()); } - for (i, section) in &members { - let mut prs = prs.clone(); - sort(&mut prs, section.sort); - // A cache that will not write costs only a - // slower first paint next time. - let _ = cache::store(&cache_dir, section, &prs, total); - let _ = tx.send(Msg::Synced { section: *i, prs, total }); - } every } - Some((kind, host, err)) => { + Some((e, err)) => { backoff = if err.transient() { (backoff * 2).clamp(1, BACKOFF_MAX) } else { every.as_secs() }; - let _ = tx.send(Msg::Down(kind, describe(&host, &err, backoff))); + let _ = tx.send(Msg::Down(e.forge.kind(), describe(e, &err, backoff))); Duration::from_secs(backoff) } }; @@ -242,12 +252,18 @@ fn shared(sections: &[Section]) -> Vec> { } /// The status line's words for a background failure. -fn describe(host: &str, e: &Error, retry: u64) -> String { - match e { +fn describe(e: &Entry, err: &Error, retry: u64) -> String { + let host = e.forge.host(); + match err { Error::Server { status, .. } => format!("{host} {status} · retrying in {retry}s"), Error::RateLimited { retry_in } => format!("{host} rate limited · retrying in {retry_in}s"), Error::Network(_) => format!("{host} unreachable · retrying in {retry}s"), Error::Auth(_) => format!("not signed in to {host}"), + // The forge's first sentence says why; the rest is advice for an + // OAuth client, and the line has room for one fix. + Error::Rejected { why, .. } => { + format!("{host} rejected the token: {} · {}", why.split(". ").next().unwrap_or(why), e.renew) + } Error::Refused(why) | Error::Decode(why) => format!("{host}: {why}"), } } diff --git a/crates/pullpen/src/live/tests.rs b/crates/pullpen/src/live/tests.rs index be6ec2c..aeb3c86 100644 --- a/crates/pullpen/src/live/tests.rs +++ b/crates/pullpen/src/live/tests.rs @@ -5,6 +5,7 @@ use std::sync::Mutex; use pullpen_core::query::Query; use pullpen_core::{Section, Sort, View}; use pullpen_forge::github::GitHub; +use pullpen_forge::gitlab::GitLab; use serde_json::json; use wiremock::matchers::{body_string_contains, method, path}; use wiremock::{Mock, MockServer, ResponseTemplate}; @@ -74,6 +75,88 @@ fn a_token_never_reaches_a_file() { fs::remove_dir_all(dir).unwrap(); } +#[test] +fn one_forge_failing_does_not_hide_the_others_prs() { + let dir = std::env::temp_dir().join(format!("pullpen-partial-{}", std::process::id())); + let rt = tokio::runtime::Runtime::new().unwrap(); + let (github, gitlab) = rt.block_on(async { + let (github, gitlab) = (MockServer::start().await, MockServer::start().await); + Mock::given(body_string_contains("search(")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ "data": { "search": { + "issueCount": 1, "pageInfo": { "hasNextPage": false }, + "nodes": [ { "id": "PR_1", "number": 1, "title": "t", "state": "OPEN", + "repository": { "nameWithOwner": "o/r" }, "baseRefName": "main", "author": { "login": "a" } } ] + } } }))) + .mount(&github) + .await; + Mock::given(body_string_contains("nodes(ids")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ "data": { "nodes": [ { "id": "PR_1" } ] } }))) + .mount(&github) + .await; + Mock::given(body_string_contains("viewer")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ "data": { "viewer": { "login": "me" } } }))) + .mount(&github) + .await; + Mock::given(method("POST")) + .respond_with(ResponseTemplate::new(401).set_body_json(json!({ + "error": "invalid_token", + "error_description": "Token is expired. You can either do re-authorization or token refresh." + }))) + .mount(&gitlab) + .await; + (github, gitlab) + }); + let entry = + |forge: Arc| Entry { forge, me: OnceCell::new(), renew: "run `pullpen setup gitlab.com`".into() }; + let (tx, rx) = channel(); + let live = Live { + rt, + forges: Arc::new(vec![ + entry(Arc::new(GitHub::with_api("github.com", &github.uri(), TOKEN.into(), Agents::default(), "", false))), + entry(Arc::new(GitLab::with_base( + "gitlab.com", + &gitlab.uri(), + TOKEN.into(), + Agents::default(), + vec![], + false, + ))), + ]), + tx, + rx, + wake: vec![Arc::default()], + last: Arc::default(), + repos: Arc::default(), + worktree: false, + }; + let section = Section { + name: "Open".into(), + short: "Open".into(), + query: "is:open".into(), + sort: Sort::Updated, + view: View::List, + counts: true, + }; + live.spawn_group(vec![(0, section)], Duration::from_secs(60), dir.clone()); + + let (mut shown, mut down) = (None, None); + let until = Instant::now() + Duration::from_secs(10); + while down.is_none() && Instant::now() < until { + match live.rx.recv_timeout(Duration::from_millis(100)) { + Ok(Msg::Synced { prs, .. }) => shown = Some(prs), + Ok(Msg::Down(kind, why)) => down = Some((kind, why)), + _ => {} + } + } + let said = "gitlab.com rejected the token: Token is expired · run `pullpen setup gitlab.com`"; + assert_eq!(down, Some((Kind::GitLab, said.into())), "the failing forge says why and what to run"); + let shown = shown.expect("GitHub answered, so its PR is shown"); + assert_eq!(shown.iter().map(|p| (p.id.forge, p.id.number)).collect::>(), [(Kind::GitHub, 1)]); + let mut written = Vec::new(); + files(&dir, &mut written); + assert!(written.is_empty(), "a partial list is not cached as the section: {written:?}"); +} + /// Ages count from the moment drawn, not from launch: the loop sets /// `App::now` from this before every frame. #[test] diff --git a/crates/pullpen/src/main.rs b/crates/pullpen/src/main.rs index 4d72ad1..8b81a27 100644 --- a/crates/pullpen/src/main.rs +++ b/crates/pullpen/src/main.rs @@ -48,10 +48,11 @@ fn main() -> Result<()> { cfg_err.as_deref(), creds.as_ref().map_err(String::as_str), &|k| env::var(k).ok(), + &commands::login, ); std::process::exit(if config::check::report(&found) { 0 } else { 1 }); } - Some(cli::Command::Setup) => return commands::setup(&cfg_path, &creds_path, cfg), + Some(cli::Command::Setup { host }) => return commands::setup(&cfg_path, &creds_path, cfg, host.as_deref()), Some(cli::Command::Settings { action }) => { std::process::exit(commands::settings(&cfg_path, &creds_path, cfg, action)?) } @@ -61,7 +62,7 @@ fn main() -> Result<()> { // empty list. Without a terminal, start anyway; the defaults may suffice. if !args.fixtures && !cfg_path.exists() && commands::interactive() { println!("No config yet, so pullpen setup runs first.\n"); - commands::setup(&cfg_path, &creds_path, Config::default())?; + commands::setup(&cfg_path, &creds_path, Config::default(), None)?; (cfg, cfg_err) = Config::load(&cfg_path); } let theme = theme(&args, &cfg); diff --git a/crates/pullpen/src/setup/mod.rs b/crates/pullpen/src/setup/mod.rs index 7cd8dc9..b5bb139 100644 --- a/crates/pullpen/src/setup/mod.rs +++ b/crates/pullpen/src/setup/mod.rs @@ -101,6 +101,17 @@ fn sign_in(io: &mut Io, d: &mut Deps, f: Forge, host: &str, creds: &mut Credenti } } +/// Signs in again to the configured forge at `host` and asks nothing else +/// (ADR-030). False when there is nothing to save. +pub fn renew(io: &mut Io, d: &mut Deps, cfg: &Config, host: &str, creds: &mut Credentials) -> io::Result { + let Some(f) = cfg.forges().into_iter().find(|f| f.host() == host) else { + io.say(&format!("pullpen is not set up for {host}; `pullpen setup` adds a forge"))?; + return Ok(false); + }; + let kind = if f.kind == Kind::Github { Forge::GitHub } else { Forge::GitLab }; + Ok(sign_in(io, d, kind, host, creds)?.is_some()) +} + fn check(io: &mut Io, d: &mut Deps, f: Forge, host: &str, token: &str) -> io::Result, String>> { match (d.verify)(f, host, token) { Ok((login, places)) => { diff --git a/crates/pullpen/src/setup/tests.rs b/crates/pullpen/src/setup/tests.rs index 45e4cb3..256d1a0 100644 --- a/crates/pullpen/src/setup/tests.rs +++ b/crates/pullpen/src/setup/tests.rs @@ -29,6 +29,48 @@ fn run_with(script: &str, cfg: Config, gh_login: bool, verify_ok: bool) -> (Conf (c, k, String::from_utf8(out).unwrap()) } +/// `renew` for `host`, with a stored GitLab token the forge now refuses and +/// a typed one it accepts. +fn renew_with(host: &str) -> (bool, Credentials, String) { + let cfg = Config { + forge: vec![ForgeCfg { kind: Kind::Gitlab, host: None, token_cmd: None, scope: None, groups: vec![] }], + ..Config::default() + }; + let mut creds = Credentials::default(); + creds.set("gitlab.com", "glpat_expired".into()); + // Enter keeps the stored token, which the forge then refuses. + let mut input = Cursor::new(b"\n".to_vec()); + let mut out = Vec::new(); + let mut secret = || Ok("glpat_typed".to_string()); + let mut verify = |_: Forge, _: &str, t: &str| match t { + "glpat_typed" => Ok(("mara".to_string(), vec![])), + _ => Err("gitlab.com rejected the token: Token is expired.".to_string()), + }; + let (cli, env) = (|_: Forge, _: &str| None, |_: &str| None); + let mut d = Deps { verify: &mut verify, cli: &cli, env: &env }; + let mut io = Io { input: &mut input, out: &mut out, secret: &mut secret }; + let saved = renew(&mut io, &mut d, &cfg, host, &mut creds).unwrap(); + (saved, creds, String::from_utf8(out).unwrap()) +} + +#[test] +fn renewing_one_host_asks_nothing_else_and_stores_the_new_token() { + let (saved, creds, out) = renew_with("gitlab.com"); + assert!(saved); + assert_eq!(creds.get("gitlab.com"), Some("glpat_typed")); + assert!(out.contains("Token is expired") && out.contains("signed in to gitlab.com as mara"), "{out}"); + assert!(!out.contains("Watch") && !out.contains("Merg") && !out.contains("Use GitHub"), "{out}"); + assert!(!out.contains("glpat_"), "a token is never printed"); +} + +#[test] +fn renewing_a_host_that_is_not_configured_says_so() { + let (saved, creds, out) = renew_with("gitlab.example"); + assert!(!saved); + assert_eq!(creds.get("gitlab.com"), Some("glpat_expired"), "nothing changed"); + assert_eq!(out.trim(), "pullpen is not set up for gitlab.example; `pullpen setup` adds a forge"); +} + #[test] fn both_forges_with_the_gh_login_and_a_typed_gitlab_token() { // both; GitHub: host, use gh, scope; GitLab: host, (token is typed), groups; diff --git a/docs/decisions.md b/docs/decisions.md index 4ce70de..e2d2773 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -689,3 +689,27 @@ The cap rises to 11,500 lines. This record is written before those three groups are, so the figure is an estimate from one measured group, not a measurement of all four; the pull request that adds them states what they came to. + +## ADR-030 — `pullpen setup ` signs in to one forge again + +A token expires on its own schedule, and the fix for it has to be one +command. `pullpen setup` already replaces a token, but it is the first-run +walk: every forge, what to watch, how to merge, where the clones are. A fix +line that sends someone through all of that to change one token is not one +they will trust. + +The counter-argument is that this is a second way to do what setup does, +and every argument a command takes is something to document and keep +working. It would win if the short form asked anything of its own. It does +not: it is the sign-in step of setup, for the one configured forge named, +and it saves only the credentials. A host that is not configured is told to +run `pullpen setup`, which is where forges are added. + +`pullpen setup ` is what the status line and `pullpen config check` +name when the forge rejects a token pullpen stored. A token from the +environment, a CLI login or `token_cmd` is renewed where it came from, and +the fix line says so. + +Proved by `renewing_one_host_asks_nothing_else_and_stores_the_new_token`, +`renewing_a_host_that_is_not_configured_says_so` and +`the_fix_names_where_the_token_came_from`. diff --git a/wiki/Commands.md b/wiki/Commands.md index 3501eb6..b8e7912 100644 --- a/wiki/Commands.md +++ b/wiki/Commands.md @@ -8,6 +8,7 @@ | `pullpen --fixtures` | the design's sample data, offline | | `pullpen --section ` | open on a section | | `pullpen setup` | sign in and answer what pullpen needs | +| `pullpen setup ` | sign in to one forge again and ask nothing else | | `pullpen settings` | the settings menu | | `pullpen settings get ` | one setting's value | | `pullpen settings set ` | change one setting | diff --git a/wiki/Setup-and-settings.md b/wiki/Setup-and-settings.md index b05f72f..2a7dcf4 100644 --- a/wiki/Setup-and-settings.md +++ b/wiki/Setup-and-settings.md @@ -21,6 +21,9 @@ Setup asks, in order: Every question shows its default in brackets; Enter takes it. Running setup again starts from your last answers. +`pullpen setup gitlab.com` asks only the sign-in question, for that one +forge, and saves only the token. It is what to run when a token expires. + ## pullpen settings `pullpen settings` lists every setting with its current value. Type its diff --git a/wiki/Troubleshooting.md b/wiki/Troubleshooting.md index 47c6121..aff087f 100644 --- a/wiki/Troubleshooting.md +++ b/wiki/Troubleshooting.md @@ -1,14 +1,19 @@ # Troubleshooting -Start with `pullpen config check`. It checks the config, each forge's sign-in, -section queries, key remaps and the palette file, and prints the fix for -anything that fails. +Start with `pullpen config check`. It checks the config, asks each forge +whether its token still works, checks section queries, key remaps and the +palette file, and prints the fix for anything that fails. **The status line says `not signed in to github.com`, and the forge shows ✗.** pullpen found no token. If you use `gh`, check it is installed and signed in where you run pullpen: on an image-based system, a `gh` inside a toolbox is not on the host. Otherwise run `pullpen setup` and give it a token. +**The status line says a forge `rejected the token`, and the forge shows ✗.** +The forge refused a token it used to accept, most often because it expired. +The line gives the forge's reason and what to run, which depends on where the +token came from. The other forge's PRs stay listed meanwhile. + **A section says 0, or fewer than you expect.** Its query may be narrower than you think: its text is on the right of the tabs. A section such as *Open* searches what you chose to watch in setup; change it with `pullpen settings`.