Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ script.
|---|---|
| `pullpen` | open the queue |
| `pullpen setup` | sign in, and answer what pullpen needs to know |
| `pullpen setup <host>` | 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 |

Expand Down
45 changes: 39 additions & 6 deletions crates/pullpen-forge/src/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,48 @@ pub fn token(
token_cmd: Option<&str>,
env: impl Fn(&str) -> Option<String>,
) -> Result<String> {
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<String>,
) -> 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]),
Expand All @@ -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()))
}
Expand Down
2 changes: 1 addition & 1 deletion crates/pullpen-forge/src/github/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 });
Expand Down
5 changes: 4 additions & 1 deletion crates/pullpen-forge/src/gitlab/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down
9 changes: 6 additions & 3 deletions crates/pullpen-forge/src/http.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<String> {
let specific: Vec<String> = body
.get("errors")
Expand All @@ -56,7 +57,7 @@ fn explanation(body: &Value) -> Option<String> {
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("; "))
Expand Down Expand Up @@ -114,7 +115,9 @@ async fn check(host: &str, resp: Response) -> Result<String> {
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;
Expand Down
4 changes: 4 additions & 0 deletions crates/pullpen-forge/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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")]
Expand Down
31 changes: 31 additions & 0 deletions crates/pullpen-forge/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down
5 changes: 4 additions & 1 deletion crates/pullpen/src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<String>,
},
/// See and change every setting; `get` and `set` do it from a script.
Settings {
#[command(subcommand)]
Expand Down
43 changes: 33 additions & 10 deletions crates/pullpen/src/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<dyn pullpen_forge::Forge> {
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<String> {
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<setup::SignedIn, String> {
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<dyn pullpen_forge::Forge> = 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.
Expand All @@ -39,8 +49,8 @@ fn verify(f: Forge, host: &str, token: &str) -> Result<setup::SignedIn, String>
.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;
Expand All @@ -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(());
Expand Down Expand Up @@ -122,7 +139,7 @@ fn menu(cfg_path: &Path, creds_path: &Path, mut cfg: Config) -> Result<i32> {
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);
Expand All @@ -136,8 +153,14 @@ fn menu(cfg_path: &Path, creds_path: &Path, mut cfg: Config) -> Result<i32> {
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);
}
}
Expand Down
14 changes: 11 additions & 3 deletions crates/pullpen/src/config/check.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -31,6 +31,8 @@ pub fn check(
load_err: Option<&str>,
creds: Result<&Credentials, &str>,
env: &dyn Fn(&str) -> Option<String>,
// Having a token proves nothing: only the forge can say it works.
verify: &dyn Fn(Forge, &str, &str) -> pullpen_forge::Result<String>,
) -> Vec<Finding> {
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"),
Expand All @@ -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 {
Expand Down
33 changes: 33 additions & 0 deletions crates/pullpen/src/config/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<String>) -> (bool, String, Option<String>) {
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"), "/../..");
Expand Down
Loading
Loading