diff --git a/src/config.rs b/src/config.rs index 5a376a9..4098b0e 100644 --- a/src/config.rs +++ b/src/config.rs @@ -131,9 +131,15 @@ pub(crate) async fn call( name: &'static str, arguments: Value, ) -> anyhow::Result { - let credential = credentials::load(&origin, token, org) - .await - .with_context(|| format!("sign in for configuration with `{LOGIN}`"))?; + let credential = match credentials::load(&origin, token, org).await { + // `proofline login` refuses while PROOFLINE_TOKEN is set, so a + // variable that holds no usable token gets no sign-in hint. + Err( + error @ (credentials::CredentialError::BlankToken + | credentials::CredentialError::MalformedToken), + ) => return Err(error.into()), + loaded => loaded.with_context(|| format!("sign in for configuration with `{LOGIN}`"))?, + }; let value = match mcp::call(&Http::new(origin)?, &credential, name, arguments).await { // MCP admission refuses a sign-in without `reviews:read` before any // tool runs, so no tool refusal names the missing scope. diff --git a/src/credentials.rs b/src/credentials.rs index 794005b..ea5a9f4 100644 --- a/src/credentials.rs +++ b/src/credentials.rs @@ -62,6 +62,22 @@ pub enum CredentialError { Keychain(String), #[error("the stored Proofline credential is unreadable; run `proofline login` again")] Corrupt, + #[error( + "PROOFLINE_TOKEN is set but holds only whitespace; set it to the token, or unset it to use the stored sign-in" + )] + BlankToken, + #[error( + "PROOFLINE_TOKEN contains whitespace or a control character inside the token, such as a line break, so it is not a token; set it to the token alone" + )] + MalformedToken, +} + +/// `PROOFLINE_TOKEN` as the environment holds it, for [`load`]. An empty +/// variable is unset, as a workflow passes a secret it does not have. Any +/// other value is set, one that holds only whitespace included: [`load`] +/// refuses that one, so no other credential answers for it. +pub fn environment_token(raw: &str) -> Option { + (!raw.is_empty()).then(|| SecretString::from(raw)) } /// The keychain entry for a console origin. Opening the Linux Secret Service @@ -105,7 +121,26 @@ pub async fn load( environment_token: Option, organization: Option, ) -> Result { - if let Some(token) = environment_token { + if let Some(given) = environment_token { + // Whitespace around the token is not part of it: a secret saved with + // its line break, or read from a file with CRLF line endings, is the + // token followed by `\n` or `\r`. What is left is checked before the + // organization lookup and every other request that carries the + // token. An HTTP header cannot carry a control character, so the + // client would refuse to build each request and report the console + // as unreachable; whitespace inside the token would be sent, and no + // token contains any. + let trimmed = given.expose_secret().trim(); + if trimmed.is_empty() { + return Err(CredentialError::BlankToken); + } + if trimmed + .chars() + .any(|character| character.is_control() || character.is_whitespace()) + { + return Err(CredentialError::MalformedToken); + } + let token = SecretString::from(trimmed); let organization_id = match organization { Some(organization) => organization, None => sole_organization(origin, &token).await?, @@ -240,6 +275,96 @@ async fn blocking( .unwrap_or_else(|join| Err(Error::PlatformFailure(Box::new(join)))) } +#[cfg(test)] +mod environment_token_tests { + use super::*; + + /// Nothing listens here; a request would fail as unreachable instead. + fn origin() -> Origin { + Origin::parse("http://127.0.0.1:1").unwrap() + } + + /// The token as a caller of [`load`] holds it, read from the environment + /// or not. + fn given(raw: &str) -> Option { + Some(SecretString::from(raw)) + } + + #[test] + fn only_an_empty_environment_variable_is_unset() { + assert!(environment_token("").is_none()); + for raw in ["pl_token", "pl_token\n", " ", "\r\n", "\u{a0}"] { + assert_eq!( + environment_token(raw).unwrap().expose_secret(), + raw, + "{raw:?}" + ); + } + } + + #[tokio::test] + async fn whitespace_around_the_token_is_not_part_of_it() { + // `\u{a0}` is a no-break space, as a token copied from a page can + // carry, and `\u{2003}` an em space. + for raw in [ + "pl_token", + "pl_token\n", + "pl_token\r\n", + " \tpl_token ", + "\u{a0}pl_token\u{a0}", + "\u{2003}pl_token\u{2003}", + ] { + for token in [given(raw), environment_token(raw)] { + let credential = load(&origin(), token, Some(Uuid::nil())).await.unwrap(); + assert_eq!(credential.token.expose_secret(), "pl_token", "{raw:?}"); + assert_eq!(credential.source, Source::Environment); + } + } + } + + #[tokio::test] + async fn a_whitespace_only_token_is_refused_before_any_request() { + for blank in [" ", "\n", "\r\n", " \t ", "\u{a0}", "\u{a0} \u{2003}"] { + for organization in [Some(Uuid::nil()), None] { + for token in [given(blank), environment_token(blank)] { + let error = load(&origin(), token, organization).await.unwrap_err(); + assert!( + matches!(error, CredentialError::BlankToken), + "{blank:?}: {error}" + ); + } + } + } + // A caller that passes an empty token has still set one. + let error = load(&origin(), given(""), None).await.unwrap_err(); + assert!(matches!(error, CredentialError::BlankToken), "{error}"); + } + + #[tokio::test] + async fn whitespace_or_a_control_character_inside_the_token_is_refused_before_any_request() { + for raw in [ + "pl_to\nken", + "pl_to\rken", + "pl_to\u{7f}ken", + "pl_to\tken", + "pl_to ken", + "pl_to\u{a0}ken", + "\u{a0}pl_to ken\n", + // A C1 control: not ASCII and not whitespace. + "pl_to\u{81}ken", + ] { + for organization in [Some(Uuid::nil()), None] { + let error = load(&origin(), given(raw), organization).await.unwrap_err(); + assert!( + matches!(error, CredentialError::MalformedToken), + "{raw:?}: {error}" + ); + assert!(!error.to_string().contains("pl_to"), "{error}"); + } + } + } +} + #[cfg(all(test, target_os = "linux"))] mod tests { use super::*; diff --git a/src/lib.rs b/src/lib.rs index 8c6f1d6..c6f2ac8 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -429,7 +429,10 @@ pub enum Verdict { Regressed, } -/// Runs one command. `token` is `PROOFLINE_TOKEN`, read by the caller. +/// Runs one command. `token` is `PROOFLINE_TOKEN`, read by the caller as +/// [`credentials::environment_token`] reads it: `None` when the variable is +/// unset or empty, so a GitHub Actions job can sign in with its own identity. +/// Any other value is `Some`, and one that holds only whitespace is refused. pub async fn run(cli: Cli, token: Option) -> anyhow::Result { if let Some(path) = &cli.ca_cert { tls::trust(path)?; diff --git a/src/main.rs b/src/main.rs index 04ae422..322ea71 100644 --- a/src/main.rs +++ b/src/main.rs @@ -4,7 +4,6 @@ use std::process::ExitCode; use clap::Parser as _; use proofline_cli::{Cli, Verdict, run}; -use secrecy::SecretString; fn main() -> ExitCode { if let Err(error) = use_user_session_bus() { @@ -31,8 +30,7 @@ fn main() -> ExitCode { // Read here rather than through clap, so the value never appears in help. let token = std::env::var("PROOFLINE_TOKEN") .ok() - .filter(|value| !value.trim().is_empty()) - .map(SecretString::from); + .and_then(|value| proofline_cli::credentials::environment_token(&value)); let runtime = match tokio::runtime::Builder::new_current_thread() .enable_all() .build() diff --git a/tests/http.rs b/tests/http.rs index 940dc12..984ffbe 100644 --- a/tests/http.rs +++ b/tests/http.rs @@ -1780,16 +1780,18 @@ async fn ci_review_in_github_actions_exchanges_the_jobs_oidc_token_for_its_crede ci_console("PULL_REQUEST", StatusCode::OK, "COMPLETED", None, None).await; // A refused exchange is the caller's error. One Proofline could not serve // is an outage, like any other request it fails. - let cases = [ - (console, 0), - (failing_exchange(StatusCode::NOT_FOUND).await, 1), - (failing_exchange(StatusCode::SERVICE_UNAVAILABLE).await, 4), - ]; - for (origin, code) in cases { - let directory = tempfile::tempdir().unwrap(); - let output = tokio::time::timeout( - std::time::Duration::from_secs(15), - tokio::process::Command::new(env!("CARGO_BIN_EXE_proofline")) + // A workflow that passes a secret it does not have sets the variable to + // the empty string, which is unset: the job's identity still answers. + for empty_token in [false, true] { + let cases = [ + (console.clone(), 0), + (failing_exchange(StatusCode::NOT_FOUND).await, 1), + (failing_exchange(StatusCode::SERVICE_UNAVAILABLE).await, 4), + ]; + for (origin, code) in cases { + let directory = tempfile::tempdir().unwrap(); + let mut command = tokio::process::Command::new(env!("CARGO_BIN_EXE_proofline")); + command .args(["--base-url", &origin, "ci", "review", "--repo", "acme/app"]) .args(["--timeout", "0", "--commit", CI_HEAD]) .env_remove("PROOFLINE_TOKEN") @@ -1802,17 +1804,24 @@ async fn ci_review_in_github_actions_exchanges_the_jobs_oidc_token_for_its_crede .env("GITHUB_EVENT_NAME", "pull_request") .env("PATH", "") .current_dir(directory.path()) - .kill_on_drop(true) - .output(), - ) - .await - .unwrap() - .unwrap(); - let stderr = String::from_utf8_lossy(&output.stderr); - assert_eq!(output.status.code(), Some(code), "{stderr}"); - for secret in ["runner-secret", "signed-job-identity", TOKEN] { - assert!(!stderr.contains(secret)); - assert!(!String::from_utf8_lossy(&output.stdout).contains(secret)); + .kill_on_drop(true); + if empty_token { + command.env("PROOFLINE_TOKEN", ""); + } + let output = tokio::time::timeout(std::time::Duration::from_secs(15), command.output()) + .await + .unwrap() + .unwrap(); + let stderr = String::from_utf8_lossy(&output.stderr); + assert_eq!( + output.status.code(), + Some(code), + "empty token {empty_token}: {stderr}" + ); + for secret in ["runner-secret", "signed-job-identity", TOKEN] { + assert!(!stderr.contains(secret)); + assert!(!String::from_utf8_lossy(&output.stdout).contains(secret)); + } } } let requests = requests.lock().unwrap(); @@ -1824,6 +1833,10 @@ async fn ci_review_in_github_actions_exchanges_the_jobs_oidc_token_for_its_crede ], "{requests:?}" ); + // The job with the empty variable made the requests of the job without + // it, the exchange of its identity among them. + let (unset, empty) = requests.split_at(requests.len() / 2); + assert_eq!(unset, empty, "{requests:?}"); } #[tokio::test] @@ -3647,3 +3660,255 @@ async fn config_proposal_targets_must_match_the_selected_organization() { assert_eq!(server.requests()[0]["arguments"]["organization_id"], ORG); assert_eq!(server.frames.load(Ordering::SeqCst), 3); } + +/// Runs the binary with `PROOFLINE_TOKEN` exactly as `raw`, no organization +/// in the environment, and `environment` added last. +async fn cli_with_token( + origin: &str, + raw: &str, + args: &[&str], + environment: &[(&str, &str)], +) -> std::process::Output { + let directory = tempfile::tempdir().unwrap(); + let mut command = tokio::process::Command::new(env!("CARGO_BIN_EXE_proofline")); + command + .args(["--base-url", origin]) + .env("PROOFLINE_TOKEN", raw) + .env_remove("PROOFLINE_ORGANIZATION_ID") + .env_remove("ACTIONS_ID_TOKEN_REQUEST_URL") + .env_remove("ACTIONS_ID_TOKEN_REQUEST_TOKEN") + .env_remove("GITHUB_EVENT_NAME") + .env( + "DBUS_SESSION_BUS_ADDRESS", + "unix:path=/proofline-test-unavailable-bus", + ) + .env("PROOFLINE_NO_UPDATE_CHECK", "1") + .env("PATH", "") + .envs(environment.iter().copied()) + .current_dir(directory.path()); + tokio::time::timeout( + std::time::Duration::from_secs(15), + command.args(args).kill_on_drop(true).output(), + ) + .await + .unwrap() + .unwrap() +} + +/// A console that records the `Authorization` header of every request, on +/// any route, and answers the review list. +async fn serve_recording_bearers() -> (String, Arc>>) { + serve_recording_bearers_answering(StatusCode::OK).await +} + +/// As [`serve_recording_bearers`], answering every request with `status`. +async fn serve_recording_bearers_answering( + status: StatusCode, +) -> (String, Arc>>) { + let bearers = Arc::new(Mutex::new(Vec::new())); + let recorded = Arc::clone(&bearers); + let app = Router::new().fallback(move |headers: HeaderMap| { + let recorded = Arc::clone(&recorded); + async move { + let bearer = headers + .get(header::AUTHORIZATION) + .map(|value| String::from_utf8_lossy(value.as_bytes()).into_owned()) + .unwrap_or_default(); + recorded.lock().unwrap().push(bearer); + ( + status, + Json(json!({ + "items": [], "next_cursor": null, "truncated": false, + "filters": { "repositories": [] }, + })), + ) + } + }); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let origin = format!("http://{}", listener.local_addr().unwrap()); + tokio::spawn(async move { + axum::serve(listener, app).await.unwrap(); + }); + (origin, bearers) +} + +/// A secret saved with its line break, a CRLF `.env` file, a padded value. +fn padded_tokens() -> [String; 5] { + [ + format!("{TOKEN}\n"), + format!("{TOKEN}\r\n"), + format!("{TOKEN}\r"), + format!(" {TOKEN} "), + // No-break spaces, as a token copied from a page can carry. + format!("\u{a0}{TOKEN}\u{a0}"), + ] +} + +#[tokio::test] +async fn whitespace_around_the_environment_token_is_not_sent_to_the_review_api() { + for raw in padded_tokens() { + let (origin, bearers) = serve_recording_bearers().await; + let output = cli_with_token(&origin, &raw, &["--org", ORG, "reviews"], &[]).await; + let stderr = String::from_utf8_lossy(&output.stderr); + assert_eq!(output.status.code(), Some(0), "{raw:?}: {stderr}"); + assert_eq!( + *bearers.lock().unwrap(), + [format!("Bearer {TOKEN}")], + "{raw:?}" + ); + } +} + +#[tokio::test] +async fn whitespace_around_the_environment_token_is_not_sent_to_the_organization_lookup() { + // Without `--org` the token's organization is read over MCP first, and + // `ConfigServer` refuses any frame whose bearer is not exactly the token. + for raw in padded_tokens() { + let listed = configuration_result(json!({"organizations":[{"organization_id":ORG}]})); + let server = ConfigServer::start(listed).await; + let output = cli_with_token(&server.origin, &raw, &["setup", "status"], &[]).await; + let stderr = String::from_utf8_lossy(&output.stderr); + assert_eq!(output.status.code(), Some(0), "{raw:?}: {stderr}"); + let requests = server.requests(); + assert_eq!(requests.len(), 2, "{raw:?}"); + assert_eq!(requests[0]["name"], "list_organizations"); + assert_eq!(requests[1]["name"], "get_setup_status"); + assert_eq!(requests[1]["arguments"]["organization_id"], ORG); + } +} + +/// The commands that reach each way a token is used: a CI job, the review +/// API with and without `--org`, and a hosted tool with and without it. +fn token_commands(sha: &str) -> [Vec<&str>; 5] { + [ + vec![ + "--org", ORG, "ci", "review", "--commit", sha, "--repo", "acme/web", + ], + vec!["--org", ORG, "reviews"], + vec!["reviews"], + vec!["--org", ORG, "setup", "status"], + vec!["setup", "status"], + ] +} + +/// Asserts the command was refused as the caller's error, naming the +/// variable, before any request and without printing the token. +fn assert_refused_before_any_request( + output: &std::process::Output, + bearers: &Mutex>, + message: &str, + case: &str, +) { + let stdout = String::from_utf8_lossy(&output.stdout); + let stderr = String::from_utf8_lossy(&output.stderr); + // 1 is the caller's error; 4 would tell a CI job Proofline is down. + assert_eq!(output.status.code(), Some(1), "{case}: {stderr}"); + assert!(stderr.contains(message), "{case}: {stderr}"); + assert!(!stderr.contains("could not reach"), "{case}: {stderr}"); + assert!(!stderr.contains("--org"), "{case}: {stderr}"); + // `proofline login` refuses while the variable is set. + assert!(!stderr.contains("proofline login"), "{case}: {stderr}"); + assert!(!stderr.contains(TOKEN), "{case}: {stderr}"); + assert!(!stdout.contains(TOKEN), "{case}: {stdout}"); + let sent = bearers.lock().unwrap(); + assert!(sent.is_empty(), "{case}: {} requests were sent", sent.len()); +} + +#[tokio::test] +async fn whitespace_or_a_control_character_inside_the_environment_token_is_the_callers_error_not_an_outage() + { + let sha = "a".repeat(40); + for raw in [ + format!("{TOKEN}\nPROOFLINE_ORGANIZATION_ID={ORG}"), + format!("{TOKEN}\r\n{TOKEN}"), + format!("{TOKEN}\u{7f}"), + format!("{TOKEN} {TOKEN}"), + format!("Bearer {TOKEN}"), + format!("{TOKEN}\u{a0}{TOKEN}"), + // A C1 control: not ASCII and not whitespace. + format!("{TOKEN}\u{81}{TOKEN}"), + ] { + for args in token_commands(&sha) { + let (origin, bearers) = serve_recording_bearers().await; + let output = cli_with_token(&origin, &raw, &args, &[]).await; + assert_refused_before_any_request( + &output, + &bearers, + "PROOFLINE_TOKEN contains whitespace or a control character", + &format!("{raw:?} {args:?}"), + ); + } + } +} + +#[tokio::test] +async fn a_whitespace_only_environment_token_is_refused_and_no_other_credential_answers() { + let sha = "a".repeat(40); + for raw in [" ", "\n", "\r\n", "\u{a0}"] { + for args in token_commands(&sha) { + let (origin, bearers) = serve_recording_bearers().await; + // The environment of a GitHub Actions job granted an OIDC + // identity. The issuer address is the recording console, which + // issues nothing: a job that turned to its identity instead would + // show as a recorded request. + let issuer = format!("{origin}/github/token"); + let runner = [ + ("ACTIONS_ID_TOKEN_REQUEST_URL", issuer.as_str()), + ("ACTIONS_ID_TOKEN_REQUEST_TOKEN", "runner-secret"), + ("GITHUB_EVENT_NAME", "pull_request"), + ]; + let output = cli_with_token(&origin, raw, &args, &runner).await; + assert_refused_before_any_request( + &output, + &bearers, + "PROOFLINE_TOKEN is set but holds only whitespace", + &format!("{raw:?} {args:?}"), + ); + } + } +} + +#[tokio::test] +async fn a_console_that_cannot_be_reached_still_ends_a_ci_job_with_exit_four() { + // Bound and never listening, so connections are refused and the port + // cannot be taken by another test's server. + let socket = tokio::net::TcpSocket::new_v4().unwrap(); + socket.bind("127.0.0.1:0".parse().unwrap()).unwrap(); + let origin = format!("http://{}", socket.local_addr().unwrap()); + let sha = "a".repeat(40); + let args = [ + "--org", ORG, "ci", "review", "--commit", &sha, "--repo", "acme/web", + ]; + let output = cli_with_token(&origin, TOKEN, &args, &[]).await; + let stderr = String::from_utf8_lossy(&output.stderr); + assert_eq!(output.status.code(), Some(4), "{stderr}"); + assert!(stderr.contains("could not reach"), "{stderr}"); + assert!(!stderr.contains(TOKEN), "{stderr}"); +} + +#[tokio::test] +async fn a_console_that_fails_still_ends_a_ci_job_with_exit_four_once_the_token_was_sent() { + // The outage is the console's own answer, so the exit code cannot come + // from a request that was never built: each one arrived with the token. + let sha = "a".repeat(40); + let args = [ + "--org", ORG, "ci", "review", "--commit", &sha, "--repo", "acme/web", + ]; + for raw in [ + TOKEN.to_owned(), + format!("{TOKEN}\n"), + format!(" {TOKEN}\r\n"), + ] { + let (origin, bearers) = serve_recording_bearers_answering(StatusCode::BAD_GATEWAY).await; + let output = cli_with_token(&origin, &raw, &args, &[]).await; + let stderr = String::from_utf8_lossy(&output.stderr); + assert_eq!(output.status.code(), Some(4), "{raw:?}: {stderr}"); + assert!(stderr.contains("HTTP 502"), "{raw:?}: {stderr}"); + assert!(!stderr.contains(TOKEN), "{raw:?}: {stderr}"); + let sent = bearers.lock().unwrap(); + assert!(!sent.is_empty(), "{raw:?}: no request was sent"); + for bearer in sent.iter() { + assert_eq!(bearer, &format!("Bearer {TOKEN}"), "{raw:?}"); + } + } +}