Skip to content
Draft
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
9 changes: 5 additions & 4 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ hickory-proto = "0.26.1"
pin-project-lite = "0.2"
tokio-stream = "0.1"
protoc-bin-vendored = "3.2.0"
url = "2"
url = "2.5.9"
indexmap = "2"
shell-words = "1.1.1"

Expand Down
55 changes: 53 additions & 2 deletions crates/openshell-cli/src/oidc_auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ use oauth2::{
RedirectUrl, Scope, TokenResponse, TokenUrl,
};
use openshell_bootstrap::oidc_token::OidcTokenBundle;
use openshell_core::token_endpoint::parse_auth_url;
use openshell_sdk::oidc::RefreshTokenInput;
use serde::Deserialize;
use std::convert::Infallible;
Expand Down Expand Up @@ -65,6 +66,10 @@ struct DeviceTokenErrorResponse {
error_description: String,
}

fn parse_oidc_url(raw: &str, field: &str) -> Result<reqwest::Url> {
parse_auth_url(raw).map_err(|reason| miette::miette!("OIDC {field} {reason}"))
}

/// Discover OIDC endpoints from the issuer's well-known configuration.
///
/// Validates that the discovery document's `issuer` field matches the
Expand All @@ -74,7 +79,7 @@ async fn discover(issuer: &str, insecure: bool) -> Result<OidcDiscovery> {
let url = format!("{normalized_issuer}/.well-known/openid-configuration");
let client = http_client(insecure);
let resp: OidcDiscovery = client
.get(&url)
.get(parse_oidc_url(&url, "issuer URL")?)
.send()
.await
.into_diagnostic()?
Expand All @@ -90,6 +95,7 @@ async fn discover(issuer: &str, insecure: bool) -> Result<OidcDiscovery> {
discovered_issuer
));
}
parse_oidc_url(&resp.token_endpoint, "token endpoint")?;
Ok(resp)
}

Expand Down Expand Up @@ -204,7 +210,10 @@ pub async fn oidc_browser_auth_flow(
let redirect_uri = callback_redirect_uri(&listener)?;

let client = BasicClient::new(ClientId::new(client_id.to_string()))
.set_auth_uri(AuthUrl::new(discovery.authorization_endpoint).into_diagnostic()?)
.set_auth_uri(AuthUrl::from_url(parse_oidc_url(
&discovery.authorization_endpoint,
"authorization endpoint",
)?))
.set_token_uri(TokenUrl::new(discovery.token_endpoint).into_diagnostic()?)
.set_redirect_uri(RedirectUrl::new(redirect_uri).into_diagnostic()?);

Expand Down Expand Up @@ -341,6 +350,9 @@ pub async fn oidc_device_code_flow(
)
})?;

let device_auth_endpoint =
parse_oidc_url(device_auth_endpoint, "device authorization endpoint")?;

// Step 1: Request device and user codes
let http = http_client(insecure);
let scopes_param = build_scopes(scopes)
Expand Down Expand Up @@ -897,6 +909,45 @@ mod tests {
assert!(result.is_err(), "connection to closed port should fail");
}

#[tokio::test]
async fn device_flow_refuses_ambiguous_endpoints_before_requesting_codes() {
let server = MockServer::start().await;
let issuer = server.uri();
let invalid = format!("{issuer}/private^endpoint");
for (token, device, field) in [
(invalid.as_str(), issuer.as_str(), "token endpoint"),
(
issuer.as_str(),
invalid.as_str(),
"device authorization endpoint",
),
] {
server.reset().await;
Mock::given(method("GET"))
.and(path("/.well-known/openid-configuration"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"issuer": issuer,
"authorization_endpoint": issuer,
"token_endpoint": token,
"device_authorization_endpoint": device,
})))
.expect(1)
.mount(&server)
.await;

let error = oidc_device_code_flow(&issuer, "cli", None, None, false)
.await
.unwrap_err()
.to_string();
assert!(
error.contains(field) && error.contains("literal caret"),
"{error}"
);
assert!(!error.contains("private^endpoint"), "{error}");
assert_eq!(server.received_requests().await.unwrap().len(), 1);
}
}

#[test]
fn discover_validates_issuer_mismatch() {
let rt = tokio::runtime::Runtime::new().unwrap();
Expand Down
13 changes: 12 additions & 1 deletion crates/openshell-core/src/oauth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -298,7 +298,7 @@ pub fn parse_token_endpoint_url(token_endpoint: &str) -> Result<reqwest::Url, To
TokenGrantFailureKind::Configuration,
TokenGrantStage::Configuration,
);
let url = reqwest::Url::parse(token_endpoint).map_err(|_| invalid)?;
let url = crate::token_endpoint::parse_auth_url(token_endpoint).map_err(|_| invalid)?;
if token_endpoint_transport_allowed(&url) {
return Ok(url);
}
Expand Down Expand Up @@ -1000,6 +1000,17 @@ mod tests {
}
}

#[test]
fn token_grants_require_an_explicitly_encoded_caret_endpoint() {
assert!(parse_token_endpoint_url("https://auth.example.com/a^b").is_err());
assert_eq!(
parse_token_endpoint_url("https://auth.example.com/a%5Eb")
.unwrap()
.path(),
"/a%5Eb"
);
}

#[test]
fn token_endpoint_url_rejects_plain_http_non_cluster_hosts() {
for endpoint in [
Expand Down
81 changes: 76 additions & 5 deletions crates/openshell-core/src/token_endpoint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,26 @@
//! Creation and every mint compare endpoints in this normalized form, so the
//! two checks cannot disagree about what a URL means.

/// Parse a credential or OIDC endpoint without changing its effective path.
/// Literal and percent-encoded carets can identify different HTTP resources.
///
/// # Errors
///
/// Rejects invalid URLs and paths whose destination changes under caret encoding.
/// Callers enforce the scheme and authority rules for their particular credential flow.
pub fn parse_auth_url(raw: &str) -> Result<url::Url, &'static str> {
let parse = |s: &str| url::Url::parse(s).map_err(|_| "must be an absolute URL");
let url = parse(raw)?;
// Ask the URL parser which carets survive in the path. A caret in the query
// or password, or in a removed dot segment, does not change the destination path.
if raw.contains('^') && parse(&raw.replace('^', "_"))?.path() != url.path() {
return Err(
"contains a literal caret (^) in its path. Confirm the intended destination and reconfigure the URL",
);
}
Ok(url)
}

/// Normalize a token endpoint for exact comparison.
///
/// Accepts absolute `https` URLs, or `http` URLs for loopback hosts (local
Expand All @@ -17,7 +37,7 @@
///
/// Returns a short description of why the URL is not an acceptable endpoint.
pub fn normalize_token_endpoint(raw: &str) -> Result<String, &'static str> {
parse_token_endpoint(raw).map(Into::into)
parse_token_endpoint(raw.trim()).map(Into::into)
}

/// Resolve a GitHub App profile's token endpoint while preserving GHES path prefixes.
Expand All @@ -26,6 +46,22 @@ pub fn normalize_token_endpoint(raw: &str) -> Result<String, &'static str> {
///
/// Rejects invalid installation path templates and disallowed token endpoints.
pub fn github_app_installation_url(template: &str, id: u64) -> Result<url::Url, &'static str> {
parse_token_endpoint(expand_github_app_template(template, id)?.trim())
}

/// Check a GitHub App profile template's structure while loading the catalog.
/// Existing profiles with literal carets must stay readable so owners can repair them.
///
/// # Errors
///
/// Rejects invalid installation templates, transports, and authorities.
pub fn validate_github_app_template(template: &str) -> Result<(), &'static str> {
let endpoint = expand_github_app_template(template, 1)?;
let url = url::Url::parse(endpoint.trim()).map_err(|_| "must be an absolute URL")?;
validate_token_endpoint(&url)
}

fn expand_github_app_template(template: &str, id: u64) -> Result<String, &'static str> {
const PLACEHOLDER: &str = "{installation_id}";
if !template.ends_with("/app/installations/{installation_id}/access_tokens")
|| template.matches(PLACEHOLDER).count() != 1
Expand All @@ -34,11 +70,21 @@ pub fn github_app_installation_url(template: &str, id: u64) -> Result<url::Url,
"must end with /app/installations/{installation_id}/access_tokens and contain one installation ID placeholder",
);
}
parse_token_endpoint(&template.replace(PLACEHOLDER, &id.to_string()))
Ok(template.replace(PLACEHOLDER, &id.to_string()))
}

fn parse_token_endpoint(raw: &str) -> Result<url::Url, &'static str> {
let url = url::Url::parse(raw.trim()).map_err(|_| "must be an absolute URL")?;
/// Parse the request destination when binding a workspace secret to a provider.
///
/// # Errors
///
/// Rejects endpoints with ambiguous paths or components disallowed for workspace secrets.
pub fn parse_token_endpoint(raw: &str) -> Result<url::Url, &'static str> {
let url = parse_auth_url(raw)?;
validate_token_endpoint(&url)?;
Ok(url)
}

fn validate_token_endpoint(url: &url::Url) -> Result<(), &'static str> {
let Some(host) = url.host_str().filter(|host| !host.is_empty()) else {
return Err("must include a host");
};
Expand All @@ -53,7 +99,7 @@ fn parse_token_endpoint(raw: &str) -> Result<url::Url, &'static str> {
if url.query().is_some() || url.fragment().is_some() {
return Err("must not include a query or fragment");
}
Ok(url)
Ok(())
}

/// Whether a token endpoint's URL host may use plain HTTP.
Expand All @@ -78,6 +124,31 @@ mod tests {
);
}

#[test]
fn checks_the_effective_path_before_losing_the_caret_spelling() {
for raw in [
"https://example.com/a^b",
"https://example.com/a^%5E",
r"https:\example.com\a^b",
] {
assert!(
super::parse_auth_url(raw)
.unwrap_err()
.contains("literal caret")
);
}
for raw in [
"https://example.com/%5E/%5e/%255E",
"https://example.com/a^b/../token",
"https://user:p^w@example.com/%5E?x=^#^",
] {
assert_eq!(
super::parse_auth_url(raw),
Ok(url::Url::parse(raw).unwrap())
);
}
}

#[test]
fn allows_http_only_for_loopback() {
assert!(normalize_token_endpoint("http://127.0.0.1:9000/token").is_ok());
Expand Down
1 change: 1 addition & 0 deletions crates/openshell-credential-issuer/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ url = { workspace = true }
test-support = []

[dev-dependencies]
axum = { workspace = true }
rcgen = { workspace = true }
tokio-rustls = { workspace = true }
tempfile = "3"
Expand Down
53 changes: 53 additions & 0 deletions crates/openshell-credential-issuer/src/refresh/github_app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -470,6 +470,21 @@ mod tests {
server.uri()
)]];
assert!(mint(&request).await.is_err());
let base = server.uri();
for (prefix, grant) in [("/a^b", "/a^b"), ("/a^b", "/a%5Eb"), ("/a%5Eb", "/a^b")] {
let mut request = state(&format!("{base}{prefix}"));
request.secret_endpoint_allowlists = vec![vec![format!(
"{base}{grant}/app/installations/123/access_tokens"
)]];
let failure = mint(&request).await.err().unwrap();
assert_eq!(failure.recovery_action, Recovery::FixConfiguration);
if prefix.contains('^') {
assert!(
failure.status.message().contains("literal")
&& failure.status.message().contains("caret")
);
}
}
assert!(server.received_requests().await.unwrap().is_empty());
}

Expand Down Expand Up @@ -519,6 +534,44 @@ mod tests {
assert!(!String::from_utf8_lossy(&requests[0].body).contains("PRIVATE KEY"));
}

#[tokio::test]
async fn github_app_posts_to_the_exact_encoded_installation_path() {
use axum::http::Uri;
use axum::routing::post;
use axum::{Json, Router};

let app = Router::new().fallback_service(post(|uri: Uri, headers: HeaderMap| async move {
assert!(
headers["authorization"]
.to_str()
.unwrap()
.starts_with("Bearer ")
);
(
StatusCode::CREATED,
Json(serde_json::json!({
"token": uri.path(), "expires_at": "2099-01-01T00:00:00Z"
})),
)
}));
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let base = format!("http://{}", listener.local_addr().unwrap());
let exercise = async {
for prefix in ["/a%5Eb", "/a%5eb", "/a%255Eb"] {
let mut input = state(&format!("{base}{prefix}/api/v3"));
let path = format!("{prefix}/api/v3/app/installations/123/access_tokens");
input.secret_endpoint_allowlists = vec![vec![format!("{base}{path}")]];
assert_eq!(mint(&input).await.unwrap().access_token, path);
}
};
tokio::select! {
result = axum::serve(listener, app) => panic!("loopback server stopped: {result:?}"),
result = tokio::time::timeout(Duration::from_secs(10), exercise) => {
result.expect("GitHub App token exchanges timed out");
}
}
}

#[tokio::test]
async fn github_app_mints_using_enterprise_default_api_version() {
let server = MockServer::start().await;
Expand Down
Loading
Loading