Skip to content
Open
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
12 changes: 9 additions & 3 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -131,9 +131,15 @@ pub(crate) async fn call(
name: &'static str,
arguments: Value,
) -> anyhow::Result<Verdict> {
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.
Expand Down
127 changes: 126 additions & 1 deletion src/credentials.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<SecretString> {
(!raw.is_empty()).then(|| SecretString::from(raw))
}

/// The keychain entry for a console origin. Opening the Linux Secret Service
Expand Down Expand Up @@ -105,7 +121,26 @@ pub async fn load(
environment_token: Option<SecretString>,
organization: Option<Uuid>,
) -> Result<Credential, CredentialError> {
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?,
Expand Down Expand Up @@ -240,6 +275,96 @@ async fn blocking<T: Send + 'static>(
.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<SecretString> {
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::*;
Expand Down
5 changes: 4 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<SecretString>) -> anyhow::Result<Verdict> {
if let Some(path) = &cli.ca_cert {
tls::trust(path)?;
Expand Down
4 changes: 1 addition & 3 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand All @@ -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()
Expand Down
Loading