use crate::{
api_error::ApiError, oauth, providers::Provider, security::Security, templates, AppState,
};
use axum::{
body::Bytes,
extract::{ConnectInfo, Form, OriginalUri, Query, State},
http::{header, HeaderMap, Method, StatusCode},
response::{Html, IntoResponse, Redirect, Response},
Json,
};
use axum_extra::extract::{
cookie::{Cookie, SameSite},
PrivateCookieJar,
};
use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
use rand::RngCore;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use url::Url;
const CONSENT_COOKIE: &str = "platform_consent";
const PROVIDER_COOKIE: &str = "platform_oauth";
const CONSENT_USED_COOKIE: &str = "platform_consent_used";
const ALREADY_APPROVED: &str = "You already approved this connection. Continue in the page that opened after approving; if it did not open or you closed it, start again from your hub";
const HANDOFF_AAD: &[u8] = b"platform-handoff-v2";
pub(crate) const OAUTH_CONTEXT_AAD: &[u8] = b"platform-oauth-v2";
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Request {
pub platform: String,
pub redirect_uri: String,
pub code_challenge: String,
pub code_challenge_method: String,
}
#[derive(Clone, Deserialize, Serialize)]
struct Consent {
request: Request,
csrf: String,
expires: u64,
}
#[derive(Deserialize, Serialize)]
pub struct OAuthContext {
pub request: Request,
pub binding: String,
}
#[derive(Deserialize, Serialize)]
struct Handoff {
platform: String,
credential: crate::proxy::StoredCredential,
#[serde(default, skip_serializing_if = "Option::is_none")]
label: Option<String>,
}
const MAX_KEY_LABEL: usize = 200;
const MAX_KEY_CHECK_BODY: usize = 64 * 1024;
#[derive(Debug, PartialEq, Eq)]
enum KeyCheck {
Accepted(Option<String>),
Rejected,
Undetermined,
}
async fn check_api_key(
state: &AppState,
scheme: &crate::providers::ApiKeyScheme,
key: &str,
) -> KeyCheck {
let Some(check) = &scheme.key_check else {
return KeyCheck::Accepted(None);
};
let injection = match scheme.location {
crate::providers::ApiKeyLocation::Header => crate::proxy::CredentialInjection::Header {
name: scheme.name.clone(),
value: key.to_owned(),
},
crate::providers::ApiKeyLocation::Query => {
return run_key_check(state, check, Some((&scheme.name, key)), None).await
}
crate::providers::ApiKeyLocation::Cookie => return KeyCheck::Undetermined,
};
run_key_check(state, check, None, Some(injection)).await
}
async fn check_http_credential(
state: &AppState,
scheme: &crate::providers::HttpScheme,
credential: &crate::proxy::StoredCredential,
) -> KeyCheck {
let Some(check) = &scheme.key_check else {
return KeyCheck::Accepted(None);
};
let injection = match credential {
crate::proxy::StoredCredential::HttpBearer { token, .. } => {
crate::proxy::CredentialInjection::Bearer(token.clone())
}
crate::proxy::StoredCredential::HttpBasic {
username, password, ..
} => crate::proxy::CredentialInjection::Basic {
username: username.clone(),
password: password.clone(),
},
_ => return KeyCheck::Undetermined,
};
run_key_check(state, check, None, Some(injection)).await
}
async fn run_key_check(
state: &AppState,
check: &crate::providers::KeyCheck,
query: Option<(&str, &str)>,
injection: Option<crate::proxy::CredentialInjection>,
) -> KeyCheck {
let mut url = check.url.clone();
#[cfg(test)]
if let Some(upstream) = &state.test_upstream {
url = Url::parse(&format!("{}{}", upstream.trim_end_matches('/'), url.path())).unwrap();
}
if let Some((name, value)) = query {
url.query_pairs_mut().append_pair(name, value);
}
let request = injection
.unwrap_or(crate::proxy::CredentialInjection::None)
.apply(state.http_client.get(url));
let Ok(response) = request
.timeout(std::time::Duration::from_secs(10))
.send()
.await
else {
return KeyCheck::Undetermined;
};
let status = response.status();
if status == StatusCode::UNAUTHORIZED || status == StatusCode::FORBIDDEN {
return KeyCheck::Rejected;
}
if !status.is_success() {
return KeyCheck::Undetermined;
}
let Some(pointer) = &check.label_pointer else {
return KeyCheck::Accepted(None);
};
let mut response = response;
let mut body = Vec::new();
let read = loop {
match response.chunk().await {
Ok(Some(chunk)) if body.len() + chunk.len() <= MAX_KEY_CHECK_BODY => {
body.extend_from_slice(&chunk)
}
Ok(None) => break Ok(body),
_ => break Err(()),
}
};
let label = match read {
Ok(body) => serde_json::from_slice::<serde_json::Value>(&body)
.ok()
.and_then(|body| {
body.pointer(pointer)
.and_then(serde_json::Value::as_str)
.map(|label| {
label
.chars()
.filter(|c| !c.is_control())
.take(MAX_KEY_LABEL)
.collect::<String>()
.trim()
.to_owned()
})
})
.filter(|label| !label.is_empty()),
_ => None,
};
KeyCheck::Accepted(label)
}
pub fn random() -> String {
let mut bytes = [0u8; 32];
rand::thread_rng().fill_bytes(&mut bytes);
URL_SAFE_NO_PAD.encode(bytes)
}
pub fn pkce_challenge(verifier: &str) -> Option<String> {
if !(43..=128).contains(&verifier.len())
|| !verifier
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b"-._~".contains(&b))
{
return None;
}
Some(URL_SAFE_NO_PAD.encode(Sha256::digest(verifier.as_bytes())))
}
const DEEP_LINK_SCHEME: &str = "atomic";
impl Request {
fn validate(&self) -> Result<Url, &'static str> {
let url = Url::parse(&self.redirect_uri).map_err(|_| "Invalid return address")?;
let loopback = matches!(url.host_str(), Some("localhost" | "127.0.0.1" | "[::1]"));
let scheme_ok = url.scheme() == "https"
|| (url.scheme() == "http" && loopback)
|| url.scheme() == DEEP_LINK_SCHEME;
if self.redirect_uri.len() > 1500
|| url.host_str().is_none_or(str::is_empty)
|| !scheme_ok
|| !url.username().is_empty()
|| url.password().is_some()
|| url.fragment().is_some()
|| url
.query_pairs()
.any(|(name, _)| matches!(name.as_ref(), "connection_code" | "error"))
{
return Err("Invalid return address");
}
if self.code_challenge_method != "S256"
|| self.code_challenge.len() != 43
|| URL_SAFE_NO_PAD
.decode(&self.code_challenge)
.map_or(true, |b| b.len() != 32)
|| crate::config::Config::provider_env_prefix(&self.platform).is_err()
{
return Err("Invalid connection request");
}
Ok(url)
}
}
fn destination_label(url: &Url) -> String {
if url.scheme() == DEEP_LINK_SCHEME {
format!(
"the Atomic app ({}://{})",
url.scheme(),
url.host_str().unwrap_or("")
)
} else {
url.origin().ascii_serialization()
}
}
fn form_action_source(url: &Url) -> String {
if url.scheme() == DEEP_LINK_SCHEME {
format!("{DEEP_LINK_SCHEME}:")
} else {
url.origin().ascii_serialization()
}
}
pub(crate) fn protected(response: impl IntoResponse) -> Response {
let mut response = response.into_response();
response
.headers_mut()
.insert(header::CACHE_CONTROL, "no-store".parse().unwrap());
response
.headers_mut()
.insert("referrer-policy", "no-referrer".parse().unwrap());
response.headers_mut().insert("content-security-policy", "default-src 'none'; style-src 'unsafe-inline'; img-src 'self' https:; frame-ancestors 'none'; base-uri 'none'".parse().unwrap());
response
}
fn error(message: &'static str) -> Response {
protected((StatusCode::BAD_REQUEST, message))
}
fn private_cookie(name: &'static str, value: String) -> Cookie<'static> {
Cookie::build((name, value))
.path("/")
.secure(true)
.http_only(true)
.same_site(SameSite::Lax)
.max_age(time::Duration::minutes(10))
.build()
}
pub async fn page(
State(state): State<AppState>,
OriginalUri(uri): OriginalUri,
jar: PrivateCookieJar,
) -> Response {
let request = match Query::<Request>::try_from_uri(&uri) {
Ok(Query(request)) => request,
Err(_) => return error("Invalid connection request; start again from your hub"),
};
let target = match request.validate() {
Ok(target) => target,
Err(message) => return error(message),
};
if !state.catalog.names().contains(&request.platform) {
return error("This platform is not available for connection");
}
let scheme = match state.catalog.security_scheme(&request.platform) {
Ok(scheme) => scheme,
Err(_) => return error("This platform is not available for connection"),
};
if matches!(scheme, crate::providers::SecurityScheme::OAuth(_))
&& Provider::configured(&state.catalog, &request.platform).is_err()
{
return error("This platform is not available for connection");
}
let consent = Consent {
request: request.clone(),
csrf: random(),
expires: crate::now_secs() + 600,
};
let jar = jar.add(private_cookie(
CONSENT_COOKIE,
serde_json::to_string(&consent).unwrap(),
));
consent_page(&state, jar, &consent, &target, &scheme, None)
}
fn consent_page(
state: &AppState,
jar: PrivateCookieJar,
consent: &Consent,
target: &Url,
scheme: &crate::providers::SecurityScheme,
problem: Option<&str>,
) -> Response {
let request = &consent.request;
let mut response = protected((
jar,
Html(templates::render_platform_connect(
&state.operator,
&request.platform,
&destination_label(target),
&consent.csrf,
match scheme {
crate::providers::SecurityScheme::OAuth(_) => templates::ConnectKind::OAuth,
crate::providers::SecurityScheme::ApiKey(scheme) => {
templates::ConnectKind::ApiKey(templates::ApiKeyHelp {
description: scheme.description.as_deref(),
help_url: scheme.help_url.as_deref(),
problem,
..templates::ApiKeyHelp::default()
})
}
crate::providers::SecurityScheme::Http(scheme) => {
templates::ConnectKind::ApiKey(templates::ApiKeyHelp {
description: scheme.description.as_deref(),
help_url: scheme.help_url.as_deref(),
problem,
secret: templates::SecretName::ApiToken,
username_label: match &scheme.auth {
crate::providers::HttpAuth::Basic(
crate::providers::BasicCredentials::PasswordTokenAskingUsername {
label,
},
) => Some(label.as_str()),
_ => None,
},
})
}
crate::providers::SecurityScheme::NoCredential => {
templates::ConnectKind::NoCredential
}
},
)),
));
response
.headers_mut()
.insert(header::REFERRER_POLICY, "same-origin".parse().unwrap());
let base = response.headers()["content-security-policy"]
.to_str()
.unwrap()
.to_owned();
let script = templates::consent_script_hash();
let policy = match scheme {
crate::providers::SecurityScheme::OAuth(_) => {
format!("{base}; script-src {script}; form-action 'self'")
}
crate::providers::SecurityScheme::ApiKey(_)
| crate::providers::SecurityScheme::Http(_)
| crate::providers::SecurityScheme::NoCredential => format!(
"{base}; script-src {script}; form-action 'self' {}",
form_action_source(target)
),
};
response
.headers_mut()
.insert("content-security-policy", policy.parse().unwrap());
response
}
#[derive(Deserialize)]
pub struct Approval {
csrf: String,
#[serde(default)]
api_key: Option<String>,
#[serde(default)]
username: Option<String>,
}
fn valid_api_key(approval: &Approval) -> Option<&str> {
approval
.api_key
.as_deref()
.map(str::trim)
.filter(|key| (4..=512).contains(&key.len()))
}
fn bearer_token(token: &str) -> bool {
let body = token.trim_end_matches('=');
!body.is_empty()
&& body
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b"-._~+/:".contains(&b))
}
fn http_credential(
platform: &str,
scheme: &crate::providers::HttpScheme,
approval: &Approval,
) -> Result<crate::proxy::StoredCredential, &'static str> {
use crate::providers::{BasicCredentials, HttpAuth};
use crate::proxy::StoredCredential;
let token = valid_api_key(approval).ok_or("Enter a valid API token")?;
let printable = |text: &str| !text.chars().any(char::is_control);
let provider = platform.to_owned();
match &scheme.auth {
HttpAuth::Bearer => {
if !bearer_token(token) {
return Err("Enter a valid API token");
}
Ok(StoredCredential::HttpBearer {
provider,
token: token.to_owned(),
scheme: Some(scheme.name.clone()),
})
}
HttpAuth::Basic(layout) => {
if !printable(token) {
return Err("Enter a valid API token");
}
let (username, password) = match layout {
BasicCredentials::UsernameToken { password } => {
if token.contains(':') {
return Err("Enter a valid API token");
}
(token.to_owned(), password.clone())
}
BasicCredentials::PasswordToken { username } => {
(username.clone(), token.to_owned())
}
BasicCredentials::PasswordTokenAskingUsername { .. } => {
let username = approval
.username
.as_deref()
.map(str::trim)
.filter(|name| {
(1..=256).contains(&name.chars().count())
&& printable(name)
&& !name.contains(':')
})
.ok_or("Enter a valid username and API token")?;
(username.to_owned(), token.to_owned())
}
};
Ok(StoredCredential::HttpBasic {
provider,
username,
password,
scheme: Some(scheme.name.clone()),
layout: Some(layout.layout()),
})
}
}
}
const MAX_KEY_CHECKS: u32 = 5;
const TOO_MANY_KEY_CHECKS: &str =
"Too many attempts to enter a key for this connection; start again from your hub";
fn key_check_slot(csrf: &str, n: u32) -> String {
format!("consent-key-check:{csrf}:{n}")
}
async fn take_key_check(
security: &Security,
jar: PrivateCookieJar,
csrf: &str,
) -> Result<(PrivateCookieJar, bool), Box<Response>> {
let unavailable = || error("Connections are unavailable");
match security
.nonce_used(&key_check_slot(csrf, MAX_KEY_CHECKS))
.await
{
Ok(true) => return Err(Box::new(too_many_key_checks(security, jar, csrf).await)),
Ok(false) => {}
Err(_) => return Err(Box::new(unavailable())),
}
match security.nonce_used(&format!("consent:{csrf}")).await {
Ok(true) => return Err(Box::new(error(ALREADY_APPROVED))),
Ok(false) => {}
Err(_) => return Err(Box::new(unavailable())),
}
for n in 1..=MAX_KEY_CHECKS {
match security.consume_nonce(&key_check_slot(csrf, n)).await {
Ok(true) => return Ok((jar, n == MAX_KEY_CHECKS)),
Ok(false) => {}
Err(_) => return Err(Box::new(unavailable())),
}
}
Err(Box::new(too_many_key_checks(security, jar, csrf).await))
}
async fn take_network_key_check(
state: &AppState,
security: &Security,
headers: &HeaderMap,
peer: Option<std::net::SocketAddr>,
platform: &str,
) -> Result<(), Box<Response>> {
if state.key_check_limit == 0 {
return Ok(());
}
let network = crate::client_addr::client_network(state.trust_forwarded_for, headers, peer);
let bucket = security.key_check_bucket(platform, &network);
if network == crate::client_addr::UNKNOWN || network == crate::client_addr::UNPARSEABLE {
tracing::warn!(
%bucket,
"key check without a usable client address; every such check shares one limit"
);
}
match security
.take_key_check_allowance(&bucket, state.key_check_limit, state.key_check_window)
.await
{
Ok(None) => Ok(()),
Ok(Some(retry_after)) => {
tracing::warn!(%bucket, platform, "key check limit reached");
let mut response = protected((
StatusCode::TOO_MANY_REQUESTS,
format!(
"Too many key checks from your network for {}; try again later",
templates::platform_label(platform)
),
));
response
.headers_mut()
.insert(header::RETRY_AFTER, retry_after.into());
Err(Box::new(response))
}
Err(_) => Err(Box::new(error("Connections are unavailable"))),
}
}
async fn too_many_key_checks(security: &Security, jar: PrivateCookieJar, csrf: &str) -> Response {
if security
.consume_nonce(&format!("consent:{csrf}"))
.await
.is_err()
{
return error("Connections are unavailable");
}
protected((
StatusCode::BAD_REQUEST,
jar.remove(Cookie::build(CONSENT_COOKIE).path("/").build()),
TOO_MANY_KEY_CHECKS,
))
}
pub async fn authorize(
State(state): State<AppState>,
peer: Option<ConnectInfo<std::net::SocketAddr>>,
jar: PrivateCookieJar,
headers: HeaderMap,
Form(approval): Form<Approval>,
) -> Response {
if headers
.get(header::ORIGIN)
.is_some_and(|origin| origin.to_str().ok() != Some(state.public_origin.as_str()))
{
return error("Invalid connection approval");
}
let Some(cookie) = jar.get(CONSENT_COOKIE) else {
if jar
.get(CONSENT_USED_COOKIE)
.is_some_and(|used| used.value() == approval.csrf)
{
return error(ALREADY_APPROVED);
}
return error("Connection request expired; start again from your hub");
};
let Ok(consent) = serde_json::from_str::<Consent>(cookie.value()) else {
return error("Invalid connection approval");
};
if consent.expires <= crate::now_secs()
|| consent.csrf != approval.csrf
|| consent.request.validate().is_err()
{
return error("Connection request expired or invalid; start again from your hub");
}
let Some(security) = &state.security else {
return error("Connections are unavailable");
};
let peer = peer.map(|ConnectInfo(peer)| peer);
let mut jar = jar;
let mut key_label = None;
if let Ok(scheme @ crate::providers::SecurityScheme::ApiKey(_)) =
state.catalog.security_scheme(&consent.request.platform)
{
let crate::providers::SecurityScheme::ApiKey(api_key) = &scheme else {
unreachable!("matched as ApiKey above");
};
let Some(key) = valid_api_key(&approval) else {
return error("Enter a valid API key");
};
let checks_upstream = api_key.key_check.is_some()
&& !matches!(api_key.location, crate::providers::ApiKeyLocation::Cookie);
if checks_upstream {
if let Err(response) =
take_network_key_check(&state, security, &headers, peer, &consent.request.platform)
.await
{
return *response;
}
}
let last = match take_key_check(security, jar, &consent.csrf).await {
Ok((taken, last)) => {
jar = taken;
last
}
Err(response) => return *response,
};
match check_api_key(&state, api_key, key).await {
KeyCheck::Accepted(label) => key_label = label,
KeyCheck::Rejected if last => {
return too_many_key_checks(security, jar, &consent.csrf).await
}
KeyCheck::Rejected => {
let Ok(target) = consent.request.validate() else {
return error("Connection request expired or invalid; start again from your hub");
};
let problem = format!(
"{} did not accept that API key. Check it and enter it again.",
templates::platform_label(&consent.request.platform)
);
return consent_page(&state, jar, &consent, &target, &scheme, Some(&problem));
}
KeyCheck::Undetermined => {
return error(
"Could not check the API key with the platform; nothing was stored. Try again later",
)
}
}
}
let mut http_credential_checked = None;
if let Ok(scheme @ crate::providers::SecurityScheme::Http(_)) =
state.catalog.security_scheme(&consent.request.platform)
{
let crate::providers::SecurityScheme::Http(http) = &scheme else {
unreachable!("matched as Http above");
};
let credential = match http_credential(&consent.request.platform, http, &approval) {
Ok(credential) => credential,
Err(message) => return error(message),
};
if http.key_check.is_some() {
if let Err(response) =
take_network_key_check(&state, security, &headers, peer, &consent.request.platform)
.await
{
return *response;
}
}
let last = match take_key_check(security, jar, &consent.csrf).await {
Ok((taken, last)) => {
jar = taken;
last
}
Err(response) => return *response,
};
match check_http_credential(&state, http, &credential).await {
KeyCheck::Accepted(label) => key_label = label,
KeyCheck::Rejected if last => {
return too_many_key_checks(security, jar, &consent.csrf).await
}
KeyCheck::Rejected => {
let Ok(target) = consent.request.validate() else {
return error("Connection request expired or invalid; start again from your hub");
};
let problem = format!(
"{} did not accept that API token. Check it and enter it again.",
templates::platform_label(&consent.request.platform)
);
return consent_page(&state, jar, &consent, &target, &scheme, Some(&problem));
}
KeyCheck::Undetermined => {
return error(
"Could not check the API token with the platform; nothing was stored. Try again later",
)
}
}
http_credential_checked = Some(credential);
}
match security
.consume_nonce(&format!("consent:{}", consent.csrf))
.await
{
Ok(true) => {}
Ok(false) => return error(ALREADY_APPROVED),
Err(_) => return error("Connections are unavailable"),
}
let jar = jar
.remove(Cookie::build(CONSENT_COOKIE).path("/").build())
.add(private_cookie(CONSENT_USED_COOKIE, consent.csrf.clone()));
match state.catalog.security_scheme(&consent.request.platform) {
Ok(crate::providers::SecurityScheme::ApiKey(api_key)) => {
let Some(key) = valid_api_key(&approval) else {
return error("Enter a valid API key");
};
let credential = crate::proxy::StoredCredential::ApiKey {
provider: consent.request.platform.clone(),
key: key.to_owned(),
placement: Some(api_key.placement()),
scheme: Some(api_key.scheme_name),
};
let code =
match labelled_handoff(security, &consent.request, credential, key_label).await {
Ok(code) => code,
Err(()) => return error("Could not complete connection"),
};
finish_with_connection_code(jar, &consent.request.redirect_uri, &code)
}
Ok(crate::providers::SecurityScheme::Http(_)) => {
let Some(credential) = http_credential_checked else {
return error("Enter a valid API token");
};
let code =
match labelled_handoff(security, &consent.request, credential, key_label).await {
Ok(code) => code,
Err(()) => return error("Could not complete connection"),
};
finish_with_connection_code(jar, &consent.request.redirect_uri, &code)
}
Ok(crate::providers::SecurityScheme::NoCredential) => {
let credential = crate::proxy::StoredCredential::NoCredential {
provider: consent.request.platform.clone(),
};
let code = match handoff(security, &consent.request, credential).await {
Ok(code) => code,
Err(()) => return error("Could not complete connection"),
};
finish_with_connection_code(jar, &consent.request.redirect_uri, &code)
}
Ok(crate::providers::SecurityScheme::OAuth(_)) => {
let context = OAuthContext {
request: consent.request.clone(),
binding: random(),
};
let Ok(sealed_context) =
security.seal(&serde_json::to_vec(&context).unwrap(), OAUTH_CONTEXT_AAD)
else {
return error("Could not start connection");
};
let url = match oauth::begin(&state, &consent.request.platform, sealed_context).await {
Ok(url) => url,
Err(()) => return error("Could not start platform authorization"),
};
if !Url::parse(&url).is_ok_and(|url| matches!(url.scheme(), "https" | "http")) {
return error("Could not start platform authorization");
}
protected((
jar.add(private_cookie(PROVIDER_COOKIE, context.binding)),
Html(templates::render_oauth_continue(
&state.operator,
&consent.request.platform,
&url,
)),
))
}
Err(_) => error("This platform is not available for connection"),
}
}
pub fn oauth_context(
security: &Security,
value: &str,
jar: &PrivateCookieJar,
) -> Option<OAuthContext> {
let context: OAuthContext =
serde_json::from_slice(&security.open(value, OAUTH_CONTEXT_AAD)?).ok()?;
if jar.get(PROVIDER_COOKIE)?.value() != context.binding {
return None;
}
Some(context)
}
pub fn clear_provider_cookie(jar: PrivateCookieJar) -> PrivateCookieJar {
jar.remove(Cookie::build(PROVIDER_COOKIE).path("/").build())
}
pub(crate) fn finish_with_connection_code(
jar: PrivateCookieJar,
redirect_uri: &str,
code: &str,
) -> Response {
let Ok(mut redirect) = Url::parse(redirect_uri) else {
return error("Could not complete connection");
};
redirect
.query_pairs_mut()
.append_pair("connection_code", code);
protected((clear_provider_cookie(jar), Redirect::to(redirect.as_str())))
}
pub(crate) async fn handoff(
security: &Security,
request: &Request,
credential: crate::proxy::StoredCredential,
) -> Result<String, ()> {
labelled_handoff(security, request, credential, None).await
}
async fn labelled_handoff(
security: &Security,
request: &Request,
credential: crate::proxy::StoredCredential,
label: Option<String>,
) -> Result<String, ()> {
let handoff = Handoff {
platform: request.platform.clone(),
credential,
label,
};
let envelope = security
.seal(&serde_json::to_vec(&handoff).map_err(|_| ())?, HANDOFF_AAD)
.map_err(|_| ())?;
let code = random();
security
.store_handoff(&code, &request.code_challenge, &envelope)
.await
.map_err(|_| ())?;
Ok(code)
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Redemption {
code: String,
code_verifier: String,
}
pub async fn redeem(
State(state): State<AppState>,
method: Method,
OriginalUri(uri): OriginalUri,
headers: HeaderMap,
body: Bytes,
) -> Response {
match redeem_inner(&state, &method, &uri, &headers, &body).await {
Ok(response) => protected(response),
Err(error) => error.into_response(),
}
}
async fn redeem_inner(
state: &AppState,
method: &Method,
uri: &axum::http::Uri,
headers: &HeaderMap,
body: &Bytes,
) -> Result<Json<serde_json::Value>, ApiError> {
let security = state.security.as_ref().ok_or(ApiError::Unavailable)?;
let owner = crate::signature::authenticate(state, security, method, uri, headers, body).await?;
crate::check_access(state, &owner).await?;
let request: Redemption = serde_json::from_slice(body)
.map_err(|_| ApiError::BadRequest("body must be {\"code\", \"code_verifier\"}"))?;
let challenge = pkce_challenge(&request.code_verifier).ok_or(ApiError::InvalidHandoff)?;
if request.code.len() != 43 {
return Err(ApiError::InvalidHandoff);
}
let envelope = security
.take_handoff(&request.code, &challenge)
.await
.map_err(|_| ApiError::Unavailable)?
.ok_or(ApiError::InvalidHandoff)?;
let handoff: Handoff = security
.open(&envelope, HANDOFF_AAD)
.and_then(|plaintext| serde_json::from_slice(&plaintext).ok())
.ok_or(ApiError::InvalidHandoff)?;
let credential = serde_json::to_vec(&handoff.credential).map_err(|_| ApiError::Internal)?;
let connection_id = security
.create_labelled_connection(
&handoff.platform,
owner.as_str(),
&credential,
handoff.label.as_deref(),
)
.await
.map_err(|_| ApiError::Unavailable)?;
let mut answer = serde_json::json!({
"connection_id": connection_id,
"platform": handoff.platform,
"owner": owner.as_str(),
});
if let Some(label) = handoff.label {
answer["label"] = label.into();
}
Ok(Json(answer))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::agent_id::test_signer::Agent;
use crate::test_support::{body_json, signed_request, state};
use tower::ServiceExt;
fn request() -> Request {
Request {
platform: "github-issues".into(),
redirect_uri:
"https://hub.example/app/integrations?integration_state=state&platform=github-issues"
.into(),
code_challenge: pkce_challenge(&"a".repeat(43)).unwrap(),
code_challenge_method: "S256".into(),
}
}
fn connect_uri(request: &Request) -> String {
let query = url::form_urlencoded::Serializer::new(String::new())
.append_pair("platform", &request.platform)
.append_pair("redirect_uri", &request.redirect_uri)
.append_pair("code_challenge", &request.code_challenge)
.append_pair("code_challenge_method", &request.code_challenge_method)
.finish();
format!("/connect?{query}")
}
#[test]
fn return_address_rejects_insecure_or_ambiguous_targets() {
for value in [
"http://hub.example/cb",
"javascript:alert(1)",
"https://user:pass@hub.example/cb",
"https://hub.example/cb#fragment",
"https://hub.example/cb?connection_code=evil",
"https://hub.example/cb?error=evil",
"tauri://localhost/app/integrations",
"atomic:integrations",
"atomic://user@integrations/return",
] {
let mut request = request();
request.redirect_uri = value.into();
assert!(request.validate().is_err(), "{value}");
}
for value in [
"http://localhost:6747/app/integrations",
"http://127.0.0.1:9883/app/integrations",
"atomic://integrations/return",
"atomic://integrations/return?integration_state=abc",
] {
let mut request = request();
request.redirect_uri = value.into();
assert!(request.validate().is_ok(), "{value}");
}
}
#[test]
fn pkce_uses_rfc7636_s256_and_rejects_weak_input() {
assert_eq!(
pkce_challenge("dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk").unwrap(),
"E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM"
);
assert!(pkce_challenge("short").is_none());
assert!(pkce_challenge(&"!".repeat(43)).is_none());
let mut request = request();
request.code_challenge_method = "plain".into();
assert!(request.validate().is_err());
}
#[tokio::test]
async fn the_consent_page_needs_no_login_and_names_the_destination() {
let mut s = state(None);
s.catalog = crate::catalog::Catalog::for_test("github-issues");
let response = crate::router(s)
.oneshot(
axum::http::Request::builder()
.uri(connect_uri(&request()))
.body(axum::body::Body::empty())
.unwrap(),
)
.await
.unwrap();
let status = response.status();
let body = String::from_utf8(
axum::body::to_bytes(response.into_body(), 65_536)
.await
.unwrap()
.to_vec(),
)
.unwrap();
assert!(!body.to_lowercase().contains("log in"), "{body}");
if status == StatusCode::OK {
assert!(body.contains("https://hub.example"));
} else {
assert!(body.contains("not available"));
}
}
async fn get_body(s: AppState, uri: &str) -> (StatusCode, String) {
let response = crate::router(s)
.oneshot(
axum::http::Request::builder()
.uri(uri)
.body(axum::body::Body::empty())
.unwrap(),
)
.await
.unwrap();
let status = response.status();
let body = axum::body::to_bytes(response.into_body(), 65_536)
.await
.unwrap();
(status, String::from_utf8(body.to_vec()).unwrap())
}
async fn body_text(response: Response) -> String {
let body = axum::body::to_bytes(response.into_body(), 65_536)
.await
.unwrap();
String::from_utf8(body.to_vec()).unwrap()
}
fn set_cookie(response: &Response, name: &str) -> Option<String> {
response
.headers()
.get_all(header::SET_COOKIE)
.iter()
.map(|v| v.to_str().unwrap().split(';').next().unwrap().to_string())
.find(|v| v.starts_with(&format!("{name}=")))
}
async fn continue_page(response: Response) -> Url {
assert_eq!(
response.status(),
StatusCode::OK,
"configure fixture OAUTH_GITHUB_ISSUES_CLIENT_ID and CLIENT_SECRET"
);
assert!(response.headers().get(header::LOCATION).is_none());
assert_eq!(response.headers()[header::REFERRER_POLICY], "no-referrer");
assert_eq!(response.headers()[header::CACHE_CONTROL], "no-store");
let policy = response.headers()["content-security-policy"]
.to_str()
.unwrap()
.to_owned();
assert!(policy.starts_with("default-src 'none';"), "{policy}");
assert!(!policy.contains("script-src"), "{policy}");
let html = body_text(response).await;
assert!(!html.contains("<script"), "{html}");
let attribute = |prefix: &str| {
html.split(prefix)
.nth(1)
.unwrap_or_else(|| panic!("no {prefix} in {html}"))
.split('"')
.next()
.unwrap()
.replace("&", "&")
};
let refresh = attribute(r#"<meta http-equiv="refresh" content="0;url="#);
let button = attribute(r#"<a class="button" href=""#);
assert_eq!(refresh, button);
Url::parse(&refresh).unwrap()
}
#[tokio::test]
async fn a_second_approval_says_it_was_already_approved_not_expired() {
let s = state(None);
let jar = PrivateCookieJar::new(s.key.clone())
.add(private_cookie(CONSENT_USED_COOKIE, "used".into()));
for (jar, csrf, message) in [
(jar.clone(), "used", ALREADY_APPROVED),
(
jar,
"other",
"Connection request expired; start again from your hub",
),
(
PrivateCookieJar::new(s.key.clone()),
"used",
"Connection request expired; start again from your hub",
),
] {
let response = authorize(
State(s.clone()),
None,
jar,
HeaderMap::new(),
Form(Approval {
csrf: csrf.into(),
api_key: None,
username: None,
}),
)
.await;
assert_eq!(response.status(), StatusCode::BAD_REQUEST);
assert_eq!(body_text(response).await, message, "{csrf}");
}
}
#[tokio::test]
async fn the_consent_page_allows_only_its_own_script() {
let mut s = state(None);
s.catalog = api_key_catalog();
let (status, html) = get_body(s.clone(), &connect_uri(&api_key_request())).await;
assert_eq!(status, StatusCode::OK);
let response = crate::router(s)
.oneshot(
axum::http::Request::builder()
.uri(connect_uri(&api_key_request()))
.body(axum::body::Body::empty())
.unwrap(),
)
.await
.unwrap();
let policy = response.headers()["content-security-policy"]
.to_str()
.unwrap()
.to_owned();
assert!(
policy.ends_with(&format!(
"; script-src {}; form-action 'self' https://hub.example",
templates::consent_script_hash()
)),
"{policy}"
);
assert!(
!policy.contains("unsafe-inline'; script") && !policy.contains("script-src 'self'")
);
let scripts: Vec<_> = html.split("<script>").skip(1).collect();
assert_eq!(scripts.len(), 1, "{html}");
assert_eq!(
scripts[0].split("</script>").next().unwrap(),
templates::CONSENT_SCRIPT
);
}
#[tokio::test]
async fn the_pages_name_the_configured_operator_and_the_proxy_host() {
let mut s = state(None);
s.catalog = crate::catalog::Catalog::for_test("github-issues");
s.operator = crate::templates::Operator::new(
"Example <Co>",
Some("https://operator.example/"),
&crate::config::public_host(crate::test_support::BASE_URL),
);
let (status, home) = get_body(s.clone(), "/").await;
assert_eq!(status, StatusCode::OK);
assert!(home.contains("Example <Co>"), "{home}");
assert!(home.contains("proxy.example"), "{home}");
assert!(!home.contains("LocalThought"), "{home}");
let (status, consent) = get_body(s, &connect_uri(&request())).await;
if status == StatusCode::OK {
assert!(
consent.contains(
r#"Integration proxy <strong>proxy.example</strong>, run by <a href="https://operator.example/" rel="noopener noreferrer">Example <Co></a>."#
),
"{consent}"
);
assert!(!consent.contains("LocalThought"), "{consent}");
} else {
assert!(consent.contains("not available"));
}
}
#[tokio::test]
async fn legacy_connect_parameters_are_refused() {
let s = state(None);
for query in [
"/connect?redirect_uri=https%3A%2F%2Fhub.example%2Fcb&ts=1&nonce=n&challenge=c&tenant_id=t&user_id=u&user_id_sig=s&response=r",
"/connect?redirect_uri=https%3A%2F%2Fhub.example%2Fcb",
] {
let response = crate::router(s.clone())
.oneshot(
axum::http::Request::builder()
.uri(query)
.body(axum::body::Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::BAD_REQUEST, "{query}");
}
}
#[tokio::test]
async fn removed_tenant_routes_are_gone() {
let s = state(None);
for (method, path) in [
("GET", "/session"),
("GET", "/auth/login"),
("GET", "/auth/callback"),
("POST", "/auth/logout"),
("GET", "/auth/login/github-issues"),
("POST", "/connect"),
("GET", "/proxy"),
("GET", "/oauth/github-issues/start"),
] {
let response = crate::router(s.clone())
.oneshot(
axum::http::Request::builder()
.method(method)
.uri(path)
.body(axum::body::Body::empty())
.unwrap(),
)
.await
.unwrap();
assert!(
matches!(
response.status(),
StatusCode::NOT_FOUND | StatusCode::METHOD_NOT_ALLOWED
),
"{method} {path}: {}",
response.status()
);
}
}
#[tokio::test]
async fn consent_rejects_a_missing_cookie_or_wrong_csrf() {
let s = state(None);
let jar = PrivateCookieJar::new(s.key.clone());
let result = authorize(
State(s.clone()),
None,
jar.clone(),
HeaderMap::new(),
Form(Approval {
csrf: "wrong".into(),
api_key: None,
username: None,
}),
)
.await;
assert_eq!(result.status(), StatusCode::BAD_REQUEST);
let consent = Consent {
request: request(),
csrf: "valid".into(),
expires: crate::now_secs() + 600,
};
let jar = jar.add(private_cookie(
CONSENT_COOKIE,
serde_json::to_string(&consent).unwrap(),
));
for (csrf, origin) in [
("wrong", None),
("valid", Some("https://foreign.example")),
("valid", Some("null")),
] {
let mut headers = HeaderMap::new();
if let Some(origin) = origin {
headers.insert(header::ORIGIN, origin.parse().unwrap());
}
let result = authorize(
State(s.clone()),
None,
jar.clone(),
headers,
Form(Approval {
csrf: csrf.into(),
api_key: None,
username: None,
}),
)
.await;
assert_eq!(
result.status(),
StatusCode::BAD_REQUEST,
"{csrf} {origin:?}"
);
}
}
fn api_key_catalog() -> crate::catalog::Catalog {
crate::catalog::Catalog::from_test_document(
"clockify",
serde_json::json!({
"servers": [{"url": "https://api.clockify.me/v1"}],
"components": {"securitySchemes": {"clockifyApiKey": {
"type": "apiKey", "in": "header", "name": "X-Api-Key"
}}},
"security": [{"clockifyApiKey": []}],
"paths": {"/workspaces": {"get": {}}}
}),
serde_json::json!({}),
)
}
fn api_key_request() -> Request {
Request {
platform: "clockify".into(),
redirect_uri:
"https://hub.example/app/integrations?integration_state=state&platform=clockify"
.into(),
code_challenge: pkce_challenge(&"a".repeat(43)).unwrap(),
code_challenge_method: "S256".into(),
}
}
async fn redeem_as(
s: &AppState,
agent: &Agent,
code: &str,
verifier: &str,
) -> axum::response::Response {
let body = serde_json::json!({"code": code, "code_verifier": verifier}).to_string();
crate::router(s.clone())
.oneshot(signed_request(
s,
agent,
"POST",
"/connect/redeem",
body.into_bytes(),
))
.await
.unwrap()
}
#[tokio::test]
#[ignore = "requires TEST_DATABASE_URL; CI runs with --include-ignored"]
async fn postgres_api_key_connect_makes_the_redeem_signer_the_owner() {
let security = crate::test_support::security().await;
let mut s = state(Some(security.clone()));
s.catalog = api_key_catalog();
let consent = Consent {
request: api_key_request(),
csrf: random(),
expires: crate::now_secs() + 600,
};
let jar = PrivateCookieJar::new(s.key.clone()).add(private_cookie(
CONSENT_COOKIE,
serde_json::to_string(&consent).unwrap(),
));
let blank = authorize(
State(s.clone()),
None,
jar.clone(),
HeaderMap::new(),
Form(Approval {
csrf: consent.csrf.clone(),
api_key: Some(" ".into()),
username: None,
}),
)
.await;
assert_eq!(blank.status(), StatusCode::BAD_REQUEST);
assert_eq!(body_text(blank).await, "Enter a valid API key");
let response = authorize(
State(s.clone()),
None,
jar.clone(),
HeaderMap::new(),
Form(Approval {
csrf: consent.csrf.clone(),
api_key: Some("clockify-secret".into()),
username: None,
}),
)
.await;
assert_eq!(response.status(), StatusCode::SEE_OTHER);
let location = Url::parse(response.headers()[header::LOCATION].to_str().unwrap()).unwrap();
assert_eq!(
location.origin().ascii_serialization(),
"https://hub.example"
);
let code = location
.query_pairs()
.find(|(k, _)| k == "connection_code")
.unwrap()
.1
.into_owned();
let again = authorize(
State(s.clone()),
None,
jar,
HeaderMap::new(),
Form(Approval {
csrf: consent.csrf.clone(),
api_key: Some("clockify-secret".into()),
username: None,
}),
)
.await;
assert_eq!(again.status(), StatusCode::BAD_REQUEST);
assert_eq!(body_text(again).await, ALREADY_APPROVED);
let owner = Agent::new(21);
let wrong = redeem_as(&s, &owner, &code, &"b".repeat(43)).await;
assert_eq!(wrong.status(), StatusCode::BAD_REQUEST);
assert_eq!(body_json(wrong).await["error"], "invalid_handoff");
let ok = redeem_as(&s, &owner, &code, &"a".repeat(43)).await;
assert_eq!(ok.status(), StatusCode::OK);
assert_eq!(ok.headers()[header::CACHE_CONTROL], "no-store");
let body = body_json(ok).await;
assert_eq!(body["platform"], "clockify");
assert_eq!(body["owner"], owner.id());
assert!(!body.to_string().contains("clockify-secret"));
let connection_id = body["connection_id"].as_str().unwrap();
let record = security
.load_connection(connection_id)
.await
.unwrap()
.unwrap();
assert_eq!(record.owner, owner.id());
let credential: crate::proxy::StoredCredential =
serde_json::from_slice(&record.credential).unwrap();
let crate::proxy::StoredCredential::ApiKey {
key,
scheme,
placement,
..
} = &credential
else {
panic!("{credential:?}");
};
assert_eq!(key, "clockify-secret");
assert_eq!(scheme.as_deref(), Some("clockifyApiKey"));
assert_eq!(
*placement,
Some(crate::providers::ApiKeyPlacement {
location: "header".into(),
name: "x-api-key".into(),
})
);
let reused = redeem_as(&s, &owner, &code, &"a".repeat(43)).await;
assert_eq!(reused.status(), StatusCode::BAD_REQUEST);
}
fn key_check_document(location: &str) -> serde_json::Value {
serde_json::json!({
"servers": [{"url": "https://api.service.example/api"}],
"components": {"securitySchemes": {"serviceKey": {
"type": "apiKey", "in": location, "name": "X-Api-Key",
"description": "A personal key, made under Preferences, Advanced.",
"x-api-key-details": {
"helpUrl": "https://service.example/help/api-keys",
"keyCheck": {"operationId": "getMe", "label": "$response.body#/email"}
}
}}},
"security": [{"serviceKey": []}],
"paths": {
"/v1/user": {"get": {"operationId": "getMe"}},
"/v1/workspaces": {"get": {}}
}
})
}
async fn key_check_upstream() -> (String, tokio::task::JoinHandle<()>) {
key_check_upstream_counting(Default::default()).await
}
fn counting(
app: axum::Router,
counter: std::sync::Arc<std::sync::atomic::AtomicUsize>,
) -> axum::Router {
app.layer(tower::util::MapRequestLayer::new(
move |request: axum::http::Request<axum::body::Body>| {
counter.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
request
},
))
}
async fn key_check_upstream_counting(
counter: std::sync::Arc<std::sync::atomic::AtomicUsize>,
) -> (String, tokio::task::JoinHandle<()>) {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
let app = axum::Router::new().route(
"/api/v1/user",
axum::routing::get(
|headers: HeaderMap, OriginalUri(uri): OriginalUri| async move {
let key = headers
.get("x-api-key")
.and_then(|v| v.to_str().ok())
.map(str::to_owned)
.or_else(|| {
uri.query()
.and_then(|q| q.strip_prefix("X-Api-Key="))
.map(str::to_owned)
})
.unwrap_or_default();
match key.as_str() {
"good-key" => (
StatusCode::OK,
r#"{"id":"u1","email":"ada@example.test"}"#.to_owned(),
)
.into_response(),
"long-label-key" => (
StatusCode::OK,
serde_json::json!({"email": format!("\u{7}{}", "x".repeat(300))})
.to_string(),
)
.into_response(),
"no-label-key" => (StatusCode::OK, r#"{"email":7}"#).into_response(),
"forbidden-key" => StatusCode::FORBIDDEN.into_response(),
"moving-key" => (
StatusCode::FOUND,
[(header::LOCATION, "https://elsewhere.example/")],
)
.into_response(),
"broken-key" => StatusCode::INTERNAL_SERVER_ERROR.into_response(),
_ => StatusCode::UNAUTHORIZED.into_response(),
}
},
),
);
let app = counting(app, counter);
let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
(format!("http://{address}"), server)
}
#[tokio::test]
async fn the_key_check_accepts_rejects_or_cannot_tell() {
let (upstream, server) = key_check_upstream().await;
let mut s = state(None);
s.test_upstream = Some(upstream);
let header_scheme =
crate::providers::ApiKeyScheme::from_document(&key_check_document("header"), None)
.unwrap();
for (key, expected) in [
(
"good-key",
KeyCheck::Accepted(Some("ada@example.test".into())),
),
("no-label-key", KeyCheck::Accepted(None)),
("wrong-key", KeyCheck::Rejected),
("forbidden-key", KeyCheck::Rejected),
("moving-key", KeyCheck::Undetermined),
("broken-key", KeyCheck::Undetermined),
] {
assert_eq!(
check_api_key(&s, &header_scheme, key).await,
expected,
"{key}"
);
}
assert_eq!(
check_api_key(&s, &header_scheme, "long-label-key").await,
KeyCheck::Accepted(Some("x".repeat(MAX_KEY_LABEL)))
);
let query_scheme =
crate::providers::ApiKeyScheme::from_document(&key_check_document("query"), None)
.unwrap();
assert_eq!(
check_api_key(&s, &query_scheme, "good-key").await,
KeyCheck::Accepted(Some("ada@example.test".into()))
);
let cookie_scheme =
crate::providers::ApiKeyScheme::from_document(&key_check_document("cookie"), None)
.unwrap();
assert_eq!(
check_api_key(&s, &cookie_scheme, "good-key").await,
KeyCheck::Undetermined
);
let mut plain = key_check_document("header");
plain["components"]["securitySchemes"]["serviceKey"]
.as_object_mut()
.unwrap()
.remove("x-api-key-details");
let plain = crate::providers::ApiKeyScheme::from_document(&plain, None).unwrap();
server.abort();
let _ = server.await;
assert_eq!(
check_api_key(&s, &plain, "wrong-key").await,
KeyCheck::Accepted(None)
);
let mut fresh = state(None);
fresh.test_upstream = s.test_upstream.clone();
assert_eq!(
check_api_key(&fresh, &header_scheme, "good-key").await,
KeyCheck::Undetermined
);
}
#[tokio::test]
async fn the_api_key_consent_page_shows_the_description_and_help_link() {
let mut s = state(None);
s.catalog = crate::catalog::Catalog::from_test_document(
"clockify",
key_check_document("header"),
serde_json::json!({}),
);
let (status, html) = get_body(s, &connect_uri(&api_key_request())).await;
assert_eq!(status, StatusCode::OK);
assert!(html.contains("A personal key, made under Preferences, Advanced."));
assert!(html.contains(
r#"<a href="https://service.example/help/api-keys" target="_blank" rel="noopener noreferrer">Where to find your Clockify API key</a>"#
));
}
#[tokio::test]
async fn an_api_key_profile_of_a_mixed_document_keeps_its_help_link_and_key_check() {
let mut document = key_check_document("header");
document["components"]["securitySchemes"]["userOAuth"] = serde_json::json!({
"type": "oauth2", "flows": {"authorizationCode": {
"authorizationUrl": "https://auth.service.example/authorize",
"tokenUrl": "https://auth.service.example/token",
"scopes": {"profile": "Profile"}
}}
});
document["paths"]["/v1/me"] =
serde_json::json!({"get": {"security": [{"userOAuth": ["profile"]}]}});
document["components"]["x-authentication-profiles"] = serde_json::json!({
"key": {"securityScheme": "serviceKey"},
"user": {"securityScheme": "userOAuth"}
});
let page = |selection: serde_json::Value| {
let mut s = state(None);
s.catalog = crate::catalog::Catalog::from_test_document(
"clockify",
document.clone(),
selection,
);
let uri = connect_uri(&api_key_request());
async move { get_body(s, &uri).await }
};
let (status, html) = page(serde_json::json!({"authenticationProfile": "key"})).await;
assert_eq!(status, StatusCode::OK);
assert!(html.contains("A personal key, made under Preferences, Advanced."));
assert!(html.contains(
r#"<a href="https://service.example/help/api-keys" target="_blank" rel="noopener noreferrer">Where to find your Clockify API key</a>"#
));
let catalog = crate::catalog::Catalog::from_test_document(
"clockify",
document.clone(),
serde_json::json!({"authenticationProfile": "key"}),
);
let crate::providers::SecurityScheme::ApiKey(scheme) =
catalog.security_scheme("clockify").unwrap()
else {
panic!("the key profile must resolve to an apiKey scheme");
};
let check = scheme.key_check.unwrap();
assert_eq!(
check.url.as_str(),
"https://api.service.example/api/v1/user"
);
assert_eq!(check.label_pointer.as_deref(), Some("/email"));
for selection in [
serde_json::json!({}),
serde_json::json!({"apiKeySecurityScheme": "serviceKey"}),
] {
let (_, html) = page(selection).await;
assert!(html.contains("This platform is not available for connection"));
}
}
#[tokio::test]
#[ignore = "requires TEST_DATABASE_URL; CI runs with --include-ignored"]
async fn postgres_a_rejected_key_is_asked_again_and_an_accepted_one_keeps_its_label() {
let (upstream, server) = key_check_upstream().await;
let security = crate::test_support::security().await;
let mut s = state(Some(security.clone()));
s.test_upstream = Some(upstream);
s.catalog = crate::catalog::Catalog::from_test_document(
"clockify",
key_check_document("header"),
serde_json::json!({}),
);
let consent = Consent {
request: api_key_request(),
csrf: random(),
expires: crate::now_secs() + 600,
};
let jar = PrivateCookieJar::new(s.key.clone()).add(private_cookie(
CONSENT_COOKIE,
serde_json::to_string(&consent).unwrap(),
));
let approve = |key: &str| {
authorize(
State(s.clone()),
None,
jar.clone(),
HeaderMap::new(),
Form(Approval {
csrf: consent.csrf.clone(),
api_key: Some(key.into()),
username: None,
}),
)
};
let rejected = approve("wrong-key").await;
assert_eq!(rejected.status(), StatusCode::OK);
assert!(rejected.headers()["content-security-policy"]
.to_str()
.unwrap()
.contains("form-action 'self' https://hub.example"));
let html = body_text(rejected).await;
assert!(html.contains("Clockify did not accept that API key."));
assert!(html.contains(&consent.csrf));
assert!(!html.contains("wrong-key"));
let broken = approve("broken-key").await;
assert_eq!(broken.status(), StatusCode::BAD_REQUEST);
let text = body_text(broken).await;
assert!(text.starts_with("Could not check the API key"));
assert!(!text.contains("broken-key"));
let accepted = approve("good-key").await;
assert_eq!(accepted.status(), StatusCode::SEE_OTHER);
server.abort();
let location = Url::parse(accepted.headers()[header::LOCATION].to_str().unwrap()).unwrap();
let code = location
.query_pairs()
.find(|(k, _)| k == "connection_code")
.unwrap()
.1
.into_owned();
let owner = Agent::new(22);
let ok = redeem_as(&s, &owner, &code, &"a".repeat(43)).await;
assert_eq!(ok.status(), StatusCode::OK);
let body = body_json(ok).await;
assert_eq!(body["label"], "ada@example.test");
assert!(!body.to_string().contains("good-key"));
let listed = crate::router(s.clone())
.oneshot(signed_request(
&s,
&owner,
"GET",
"/connections",
Vec::new(),
))
.await
.unwrap();
assert_eq!(listed.status(), StatusCode::OK);
let listed = body_json(listed).await;
let mine = listed["connections"]
.as_array()
.unwrap()
.iter()
.find(|c| c["connection_id"] == body["connection_id"])
.expect("the new connection is listed");
assert_eq!(mine["label"], "ada@example.test");
}
fn http_document(scheme: serde_json::Value) -> serde_json::Value {
let mut scheme = scheme;
scheme["description"] = "A personal access token, made under Settings, Tokens.".into();
scheme["x-api-key-details"]["helpUrl"] = "https://service.example/help/tokens".into();
scheme["x-api-key-details"]["keyCheck"] =
serde_json::json!({"operationId": "getMe", "label": "$response.body#/email"});
serde_json::json!({
"servers": [{"url": "https://api.service.example/api"}],
"components": {"securitySchemes": {"serviceToken": scheme}},
"security": [{"serviceToken": []}],
"paths": {
"/v1/user": {"get": {"operationId": "getMe"}},
"/v1/workspaces": {"get": {}}
}
})
}
fn bearer() -> serde_json::Value {
serde_json::json!({"type": "http", "scheme": "bearer"})
}
fn basic(layout: serde_json::Value) -> serde_json::Value {
serde_json::json!({"type": "http", "scheme": "basic",
"x-api-key-details": {"basicCredentials": layout}})
}
fn basic_header(username: &str, password: &str) -> String {
format!(
"Basic {}",
base64::engine::general_purpose::STANDARD.encode(format!("{username}:{password}"))
)
}
fn http_scheme(document: serde_json::Value) -> crate::providers::HttpScheme {
match crate::providers::SecurityScheme::from_document(&document, None, None, None) {
Ok(crate::providers::SecurityScheme::Http(scheme)) => scheme,
other => panic!("expected an http scheme, got {other:?}"),
}
}
fn token_approval(token: &str, username: Option<&str>) -> Approval {
Approval {
csrf: String::new(),
api_key: Some(token.into()),
username: username.map(str::to_owned),
}
}
async fn http_key_check_upstream() -> (String, tokio::task::JoinHandle<()>) {
http_key_check_upstream_counting(Default::default()).await
}
async fn http_key_check_upstream_counting(
counter: std::sync::Arc<std::sync::atomic::AtomicUsize>,
) -> (String, tokio::task::JoinHandle<()>) {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
let accepted = [
"Bearer good-token".to_owned(),
basic_header("good-token", "api_token"),
basic_header("ada@example.test", "good-token"),
basic_header("api", "good-token"),
];
let app = axum::Router::new().route(
"/api/v1/user",
axum::routing::get(move |headers: HeaderMap| {
let accepted = accepted.clone();
async move {
let authorization = headers
.get(header::AUTHORIZATION)
.and_then(|v| v.to_str().ok())
.unwrap_or_default();
if accepted.iter().any(|a| a == authorization) {
(StatusCode::OK, r#"{"id":"u1","email":"ada@example.test"}"#)
.into_response()
} else if authorization == "Bearer forbidden-token" {
StatusCode::FORBIDDEN.into_response()
} else if authorization == "Bearer broken-token" {
StatusCode::INTERNAL_SERVER_ERROR.into_response()
} else {
StatusCode::UNAUTHORIZED.into_response()
}
}
}),
);
let app = counting(app, counter);
let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
(format!("http://{address}"), server)
}
#[test]
fn http_tokens_are_laid_out_as_declared_and_validated() {
use crate::proxy::StoredCredential;
let bearer_scheme = http_scheme(http_document(bearer()));
let bearer_token = |token: &str, username: Option<&str>| match http_credential(
"service",
&bearer_scheme,
&token_approval(token, username),
) {
Ok(StoredCredential::HttpBearer {
provider, token, ..
}) => {
assert_eq!(provider, "service");
Ok(token)
}
Ok(other) => panic!("{other:?}"),
Err(message) => Err(message),
};
assert_eq!(bearer_token(" good-token ", None), Ok("good-token".into()));
assert_eq!(
bearer_token("good-token", Some("someone")),
Ok("good-token".into())
);
assert_eq!(bearer_token("2/12/34:ab", None), Ok("2/12/34:ab".into()));
for bad in ["abc", "has space", "tok\u{e9}n-1", "line\nbreak", ""] {
assert_eq!(
bearer_token(bad, None),
Err("Enter a valid API token"),
"{bad:?}"
);
}
assert_eq!(
bearer_token(&"x".repeat(513), None),
Err("Enter a valid API token")
);
let halves = |layout: serde_json::Value, token: &str, username: Option<&str>| {
let scheme = http_scheme(http_document(basic(layout)));
match http_credential("service", &scheme, &token_approval(token, username)) {
Ok(StoredCredential::HttpBasic {
username, password, ..
}) => Ok((username, password)),
Ok(other) => panic!("{other:?}"),
Err(message) => Err(message),
}
};
let as_username = serde_json::json!({"token": "username", "password": "api_token"});
assert_eq!(
halves(as_username.clone(), "good-token", Some("ignored")),
Ok(("good-token".into(), "api_token".into()))
);
assert_eq!(
halves(as_username, "good:token", None),
Err("Enter a valid API token")
);
assert_eq!(
halves(
serde_json::json!({"token": "password", "username": "api"}),
"pass:with:colons",
Some("ignored")
),
Ok(("api".into(), "pass:with:colons".into()))
);
let asking = serde_json::json!({"token": "password", "usernameLabel": "Email"});
assert_eq!(
halves(asking.clone(), "good-token", Some(" ada@example.test ")),
Ok(("ada@example.test".into(), "good-token".into()))
);
for username in [None, Some(""), Some(" "), Some("a:b"), Some("a\u{7}b")] {
assert_eq!(
halves(asking.clone(), "good-token", username),
Err("Enter a valid username and API token"),
"{username:?}"
);
}
assert_eq!(
halves(asking.clone(), "good-token", Some(&"u".repeat(257))),
Err("Enter a valid username and API token")
);
assert_eq!(
halves(asking, "tok\u{0}en", Some("ada@example.test")),
Err("Enter a valid API token")
);
}
#[tokio::test]
async fn the_http_key_check_sends_the_authorization_a_request_would_carry() {
let (upstream, server) = http_key_check_upstream().await;
let mut s = state(None);
s.test_upstream = Some(upstream);
let check = |layout: Option<serde_json::Value>, token: &str, username: Option<&str>| {
let scheme = http_scheme(http_document(layout.map_or_else(bearer, basic)));
let credential =
http_credential("service", &scheme, &token_approval(token, username)).unwrap();
let s = s.clone();
async move { check_http_credential(&s, &scheme, &credential).await }
};
let accepted = KeyCheck::Accepted(Some("ada@example.test".into()));
assert_eq!(check(None, "good-token", None).await, accepted);
assert_eq!(check(None, "wrong-token", None).await, KeyCheck::Rejected);
assert_eq!(
check(None, "forbidden-token", None).await,
KeyCheck::Rejected
);
assert_eq!(
check(None, "broken-token", None).await,
KeyCheck::Undetermined
);
for (layout, username) in [
(
serde_json::json!({"token": "username", "password": "api_token"}),
None,
),
(
serde_json::json!({"token": "password", "usernameLabel": "Email"}),
Some("ada@example.test"),
),
(
serde_json::json!({"token": "password", "username": "api"}),
None,
),
] {
assert_eq!(
check(Some(layout.clone()), "good-token", username).await,
accepted,
"{layout}"
);
assert_eq!(
check(Some(layout.clone()), "wrong-token", username).await,
KeyCheck::Rejected,
"{layout}"
);
}
server.abort();
}
#[tokio::test]
async fn the_http_consent_page_asks_for_a_token_and_a_declared_username() {
let page = |document: serde_json::Value| {
let mut s = state(None);
s.catalog = crate::catalog::Catalog::from_test_document(
"clockify",
document,
serde_json::json!({}),
);
let uri = connect_uri(&api_key_request());
let router = crate::router(s);
async move {
router
.oneshot(
axum::http::Request::builder()
.uri(uri)
.body(axum::body::Body::empty())
.unwrap(),
)
.await
.unwrap()
}
};
let response = page(http_document(bearer())).await;
assert_eq!(response.status(), StatusCode::OK);
assert!(response.headers()["content-security-policy"]
.to_str()
.unwrap()
.ends_with("form-action 'self' https://hub.example"));
let html = body_text(response).await;
assert!(html.contains("A personal access token, made under Settings, Tokens."));
assert!(html.contains(
r#"<a href="https://service.example/help/tokens" target="_blank" rel="noopener noreferrer">Where to find your Clockify API token</a>"#
));
assert!(html.contains(
r#"type="password" name="api_key" autocomplete="off" placeholder="API token""#
));
assert!(!html.contains(r#"name="username""#));
let html = body_text(
page(http_document(basic(
serde_json::json!({"token": "password", "usernameLabel": "Email <work>"}),
)))
.await,
)
.await;
assert!(html.contains(
r#"type="text" name="username" autocomplete="off" placeholder="Email <work>" aria-label="Email <work>" required"#
));
assert!(html.contains(r#"name="api_key""#));
let html = body_text(
page(http_document(basic(
serde_json::json!({"token": "username", "password": "api_token"}),
)))
.await,
)
.await;
assert!(!html.contains(r#"name="username""#));
assert!(!html.contains("api_token"));
let mut undeclared = http_document(basic(serde_json::json!({})));
undeclared["components"]["securitySchemes"]["serviceToken"]["x-api-key-details"]
.as_object_mut()
.unwrap()
.remove("basicCredentials");
let html = body_text(page(undeclared).await).await;
assert!(html.contains("This platform is not available for connection"));
}
#[tokio::test]
#[ignore = "requires TEST_DATABASE_URL; CI runs with --include-ignored"]
async fn postgres_http_tokens_are_checked_then_sealed_and_never_returned() {
let (upstream, server) = http_key_check_upstream().await;
let security = crate::test_support::security().await;
for (seed, scheme, username) in [
(70u8, bearer(), None),
(
71,
basic(serde_json::json!({"token": "password", "usernameLabel": "Email"})),
Some("ada@example.test"),
),
] {
let mut s = state(Some(security.clone()));
s.test_upstream = Some(upstream.clone());
s.catalog = crate::catalog::Catalog::from_test_document(
"clockify",
http_document(scheme),
serde_json::json!({}),
);
let consent = Consent {
request: api_key_request(),
csrf: random(),
expires: crate::now_secs() + 600,
};
let jar = PrivateCookieJar::new(s.key.clone()).add(private_cookie(
CONSENT_COOKIE,
serde_json::to_string(&consent).unwrap(),
));
let approve = |token: &str, username: Option<&str>| {
authorize(
State(s.clone()),
None,
jar.clone(),
HeaderMap::new(),
Form(Approval {
csrf: consent.csrf.clone(),
..token_approval(token, username)
}),
)
};
let blank = approve(" ", username).await;
assert_eq!(blank.status(), StatusCode::BAD_REQUEST);
assert!(body_text(blank).await.starts_with("Enter a valid"));
let rejected = approve("wrong-token", username).await;
assert_eq!(rejected.status(), StatusCode::OK);
let html = body_text(rejected).await;
assert!(html.contains("Clockify did not accept that API token."));
assert!(html.contains(&consent.csrf));
assert!(!html.contains("wrong-token"));
if username.is_none() {
let broken = approve("broken-token", None).await;
assert_eq!(broken.status(), StatusCode::BAD_REQUEST);
let text = body_text(broken).await;
assert!(text.starts_with("Could not check the API token"));
assert!(!text.contains("broken-token"));
}
let accepted = approve("good-token", username).await;
assert_eq!(accepted.status(), StatusCode::SEE_OTHER);
let location =
Url::parse(accepted.headers()[header::LOCATION].to_str().unwrap()).unwrap();
assert!(!location.as_str().contains("good-token"));
let code = location
.query_pairs()
.find(|(k, _)| k == "connection_code")
.unwrap()
.1
.into_owned();
let owner = Agent::new(seed);
let ok = redeem_as(&s, &owner, &code, &"a".repeat(43)).await;
assert_eq!(ok.status(), StatusCode::OK);
let body = body_json(ok).await;
assert_eq!(body["owner"], owner.id());
assert_eq!(body["label"], "ada@example.test");
assert!(!body.to_string().contains("good-token"));
let record = security
.load_connection(body["connection_id"].as_str().unwrap())
.await
.unwrap()
.unwrap();
let credential: crate::proxy::StoredCredential =
serde_json::from_slice(&record.credential).unwrap();
match (username, credential) {
(None, crate::proxy::StoredCredential::HttpBearer { token, scheme, .. }) => {
assert_eq!(token, "good-token");
assert_eq!(scheme.as_deref(), Some("serviceToken"));
}
(
Some(expected),
crate::proxy::StoredCredential::HttpBasic {
username,
password,
scheme,
layout,
..
},
) => {
assert_eq!(
(username.as_str(), password.as_str()),
(expected, "good-token")
);
assert_eq!(scheme.as_deref(), Some("serviceToken"));
assert_eq!(
layout,
Some(crate::providers::BasicLayout::Password { username: None })
);
}
(_, other) => panic!("{other:?}"),
}
}
server.abort();
}
#[test]
fn a_bearer_token_is_a_b64token_or_an_asana_style_token() {
for good in [
"good-token",
"ghp_AbC123",
"a.b_c~d+e/f",
"dG9rZW4=",
"dG9r==",
"2/1234/5678:abcdef",
] {
assert!(bearer_token(good), "{good}");
}
for bad in [
"",
"==",
"a=b",
"has space",
"quote\"d",
"semi;colon",
"comma,",
"tok\u{e9}n",
"back\\slash",
"a\tb",
"<tag>",
"50%",
] {
assert!(!bearer_token(bad), "{bad:?}");
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
#[ignore = "requires TEST_DATABASE_URL; CI runs with --include-ignored"]
async fn postgres_a_consent_allows_at_most_five_key_checks() {
use std::sync::atomic::Ordering::SeqCst;
let security = crate::test_support::security().await;
for http in [false, true] {
let checks = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
let (upstream, server) = if http {
http_key_check_upstream_counting(checks.clone()).await
} else {
key_check_upstream_counting(checks.clone()).await
};
let (document, wrong, good, asked_again) = if http {
(
http_document(bearer()),
"wrong-token",
"good-token",
"did not accept that API token",
)
} else {
(
key_check_document("header"),
"wrong-key",
"good-key",
"did not accept that API key",
)
};
let mut s = state(Some(security.clone()));
s.test_upstream = Some(upstream);
s.catalog = crate::catalog::Catalog::from_test_document(
"clockify",
document,
serde_json::json!({}),
);
let new_consent = || {
let consent = Consent {
request: api_key_request(),
csrf: random(),
expires: crate::now_secs() + 600,
};
let jar = PrivateCookieJar::new(s.key.clone()).add(private_cookie(
CONSENT_COOKIE,
serde_json::to_string(&consent).unwrap(),
));
(consent, jar)
};
let submit = |s: &AppState, jar: &PrivateCookieJar, csrf: &str, key: &str| {
authorize(
State(s.clone()),
None,
jar.clone(),
HeaderMap::new(),
Form(Approval {
csrf: csrf.to_owned(),
..token_approval(key, None)
}),
)
};
let (consent, jar) = new_consent();
let approve = |key: &str| submit(&s, &jar, &consent.csrf, key);
assert_eq!(approve(" ").await.status(), StatusCode::BAD_REQUEST);
for attempt in 1..MAX_KEY_CHECKS {
let response = approve(wrong).await;
assert_eq!(response.status(), StatusCode::OK, "{http} {attempt}");
assert!(body_text(response).await.contains(asked_again));
}
let last = approve(wrong).await;
assert_eq!(last.status(), StatusCode::BAD_REQUEST);
assert_eq!(body_text(last).await, TOO_MANY_KEY_CHECKS);
assert!(security
.nonce_used(&format!("consent:{}", consent.csrf))
.await
.unwrap());
let after = approve(good).await;
assert_eq!(after.status(), StatusCode::BAD_REQUEST);
assert_eq!(body_text(after).await, TOO_MANY_KEY_CHECKS);
assert_eq!(checks.load(SeqCst), MAX_KEY_CHECKS as usize, "{http}");
checks.store(0, SeqCst);
let (consent, jar) = new_consent();
let tasks: Vec<_> = (0..30)
.map(|_| {
let request = submit(&s, &jar, &consent.csrf, wrong);
tokio::spawn(async move { request.await.status() })
})
.collect();
for task in tasks {
let status = task.await.unwrap();
assert!(
matches!(status, StatusCode::OK | StatusCode::BAD_REQUEST),
"{status}"
);
}
assert_eq!(checks.load(SeqCst), MAX_KEY_CHECKS as usize, "{http}");
server.abort();
}
}
fn fresh_ip() -> std::net::IpAddr {
std::net::IpAddr::V4(std::net::Ipv4Addr::from(rand::random::<u32>()))
}
fn peer_at(ip: std::net::IpAddr) -> Option<ConnectInfo<std::net::SocketAddr>> {
Some(ConnectInfo(std::net::SocketAddr::new(ip, 40_000)))
}
fn forwarded_for(value: &str) -> HeaderMap {
let mut headers = HeaderMap::new();
headers.insert("x-forwarded-for", value.parse().unwrap());
headers
}
fn limited_state(
security: &Security,
upstream: &str,
platform: &str,
document: serde_json::Value,
limit: u32,
) -> AppState {
let mut s = state(Some(security.clone()));
s.test_upstream = Some(upstream.to_owned());
s.catalog =
crate::catalog::Catalog::from_test_document(platform, document, serde_json::json!({}));
s.key_check_limit = limit;
s
}
async fn submit_on_new_consent(
s: &AppState,
peer: Option<ConnectInfo<std::net::SocketAddr>>,
headers: HeaderMap,
key: &str,
) -> (Response, String) {
let platform = s.catalog.names()[0].clone();
let consent = Consent {
request: Request {
redirect_uri: format!(
"https://hub.example/app/integrations?integration_state=state&platform={platform}"
),
platform,
..api_key_request()
},
csrf: random(),
expires: crate::now_secs() + 600,
};
let jar = PrivateCookieJar::new(s.key.clone()).add(private_cookie(
CONSENT_COOKIE,
serde_json::to_string(&consent).unwrap(),
));
let response = authorize(
State(s.clone()),
peer,
jar,
headers,
Form(Approval {
csrf: consent.csrf.clone(),
..token_approval(key, None)
}),
)
.await;
(response, consent.csrf)
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
#[ignore = "requires TEST_DATABASE_URL; CI runs with --include-ignored"]
async fn postgres_key_checks_are_limited_per_network_and_platform() {
use std::sync::atomic::Ordering::SeqCst;
let security = crate::test_support::security().await;
let checks = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
let (upstream, server) = key_check_upstream_counting(checks.clone()).await;
let document = key_check_document("header");
let s = limited_state(&security, &upstream, "clockify", document.clone(), 3);
let other_platform =
limited_state(&security, &upstream, "clockify-other", document.clone(), 3);
let ip = fresh_ip();
let asked_again = "did not accept that API key";
for _ in 0..5 {
let (response, _) = submit_on_new_consent(&s, peer_at(ip), HeaderMap::new(), " ").await;
assert_eq!(response.status(), StatusCode::BAD_REQUEST);
}
assert_eq!(checks.load(SeqCst), 0);
for attempt in 1..=3 {
let (response, _) =
submit_on_new_consent(&s, peer_at(ip), HeaderMap::new(), "wrong-key").await;
assert_eq!(response.status(), StatusCode::OK, "{attempt}");
assert!(body_text(response).await.contains(asked_again));
}
assert_eq!(checks.load(SeqCst), 3);
let (limited, csrf) =
submit_on_new_consent(&s, peer_at(ip), HeaderMap::new(), "good-key").await;
assert_eq!(limited.status(), StatusCode::TOO_MANY_REQUESTS);
let retry_after: u64 = limited.headers()[header::RETRY_AFTER]
.to_str()
.unwrap()
.parse()
.unwrap();
assert!((1..=3600).contains(&retry_after), "{retry_after}");
assert_eq!(limited.headers()[header::CACHE_CONTROL], "no-store");
assert!(set_cookie(&limited, CONSENT_COOKIE).is_none());
assert_eq!(
body_text(limited).await,
"Too many key checks from your network for Clockify; try again later"
);
assert_eq!(checks.load(SeqCst), 3);
assert!(!security
.nonce_used(&format!("consent:{csrf}"))
.await
.unwrap());
assert!(!security
.nonce_used(&key_check_slot(&csrf, 1))
.await
.unwrap());
let (malformed, _) = submit_on_new_consent(&s, peer_at(ip), HeaderMap::new(), " ").await;
assert_eq!(malformed.status(), StatusCode::BAD_REQUEST);
let (response, _) =
submit_on_new_consent(&other_platform, peer_at(ip), HeaderMap::new(), "wrong-key")
.await;
assert_eq!(response.status(), StatusCode::OK);
let (response, _) =
submit_on_new_consent(&s, peer_at(fresh_ip()), HeaderMap::new(), "good-key").await;
assert_eq!(response.status(), StatusCode::SEE_OTHER);
assert_eq!(checks.load(SeqCst), 5);
let spoofed = forwarded_for(&fresh_ip().to_string());
let (response, _) = submit_on_new_consent(&s, peer_at(ip), spoofed, "good-key").await;
assert_eq!(response.status(), StatusCode::TOO_MANY_REQUESTS);
let mut heroku = s.clone();
heroku.trust_forwarded_for = crate::config::TrustForwardedFor::RightMost;
let router = peer_at(fresh_ip());
let spoofed = forwarded_for(&format!("{}, {ip}", fresh_ip()));
let (response, _) = submit_on_new_consent(&heroku, router, spoofed, "good-key").await;
assert_eq!(response.status(), StatusCode::TOO_MANY_REQUESTS);
let mut binary = HeaderMap::new();
let mut line = b"\x80, ".to_vec();
line.extend_from_slice(ip.to_string().as_bytes());
binary.insert(
"x-forwarded-for",
axum::http::HeaderValue::from_bytes(&line).unwrap(),
);
let (response, _) =
submit_on_new_consent(&heroku, peer_at(fresh_ip()), binary, "good-key").await;
assert_eq!(response.status(), StatusCode::TOO_MANY_REQUESTS);
let (response, _) = submit_on_new_consent(
&s,
peer_at(ip),
forwarded_for(&format!("{ip}, {}", fresh_ip())),
"good-key",
)
.await;
assert_eq!(response.status(), StatusCode::TOO_MANY_REQUESTS);
assert_eq!(checks.load(SeqCst), 5);
let mut unchecked_document = document.clone();
unchecked_document["components"]["securitySchemes"]["serviceKey"]
.as_object_mut()
.unwrap()
.remove("x-api-key-details");
let unchecked = limited_state(
&security,
&upstream,
&format!("p-{:x}", rand::random::<u64>()),
unchecked_document,
1,
);
for _ in 0..3 {
let (response, _) =
submit_on_new_consent(&unchecked, peer_at(ip), HeaderMap::new(), "any-key").await;
assert_eq!(response.status(), StatusCode::SEE_OTHER);
}
let bucket = security.key_check_bucket(
&unchecked.catalog.names()[0],
&crate::client_addr::network(ip),
);
assert_eq!(
security
.take_key_check_allowance(&bucket, 1, std::time::Duration::from_secs(3600))
.await
.unwrap(),
None,
"no slot was taken"
);
assert_eq!(checks.load(SeqCst), 5);
let mut unlimited = s.clone();
unlimited.key_check_limit = 0;
for _ in 0..2 {
let (response, _) =
submit_on_new_consent(&unlimited, peer_at(ip), HeaderMap::new(), "wrong-key").await;
assert_eq!(response.status(), StatusCode::OK);
}
assert_eq!(checks.load(SeqCst), 7);
let mut nowhere = limited_state(
&security,
&upstream,
&format!("p-{:x}", rand::random::<u64>()),
document.clone(),
1,
);
nowhere.trust_forwarded_for = crate::config::TrustForwardedFor::RightMost;
let (response, _) =
submit_on_new_consent(&nowhere, None, HeaderMap::new(), "wrong-key").await;
assert_eq!(response.status(), StatusCode::OK);
let (response, _) =
submit_on_new_consent(&nowhere, None, HeaderMap::new(), "wrong-key").await;
assert_eq!(response.status(), StatusCode::TOO_MANY_REQUESTS);
assert_eq!(checks.load(SeqCst), 8);
let mut short = s.clone();
short.key_check_limit = 1;
short.key_check_window = std::time::Duration::from_secs(2);
let network = fresh_ip();
let (response, _) =
submit_on_new_consent(&short, peer_at(network), HeaderMap::new(), "wrong-key").await;
assert_eq!(response.status(), StatusCode::OK);
let (response, _) =
submit_on_new_consent(&short, peer_at(network), HeaderMap::new(), "wrong-key").await;
assert_eq!(response.status(), StatusCode::TOO_MANY_REQUESTS);
assert!(
response.headers()[header::RETRY_AFTER]
.to_str()
.unwrap()
.parse::<u64>()
.unwrap()
<= 2
);
tokio::time::sleep(std::time::Duration::from_millis(2_200)).await;
let (response, _) =
submit_on_new_consent(&short, peer_at(network), HeaderMap::new(), "wrong-key").await;
assert_eq!(response.status(), StatusCode::OK);
assert_eq!(checks.load(SeqCst), 10);
checks.store(0, SeqCst);
let mut burst = s.clone();
burst.key_check_limit = 5;
let network = fresh_ip();
let tasks: Vec<_> = (0..30)
.map(|_| {
let burst = burst.clone();
tokio::spawn(async move {
submit_on_new_consent(&burst, peer_at(network), HeaderMap::new(), "wrong-key")
.await
.0
.status()
})
})
.collect();
let mut statuses = Vec::new();
for task in tasks {
statuses.push(task.await.unwrap());
}
assert_eq!(statuses.iter().filter(|s| **s == StatusCode::OK).count(), 5);
assert_eq!(
statuses
.iter()
.filter(|s| **s == StatusCode::TOO_MANY_REQUESTS)
.count(),
25
);
assert_eq!(checks.load(SeqCst), 5);
server.abort();
}
#[tokio::test]
#[ignore = "requires TEST_DATABASE_URL; CI runs with --include-ignored"]
async fn postgres_http_token_checks_share_the_network_limit() {
use std::sync::atomic::Ordering::SeqCst;
let security = crate::test_support::security().await;
let checks = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
let (upstream, server) = http_key_check_upstream_counting(checks.clone()).await;
let s = limited_state(&security, &upstream, "clockify", http_document(bearer()), 2);
let ip = fresh_ip();
for _ in 0..2 {
let (response, _) =
submit_on_new_consent(&s, peer_at(ip), HeaderMap::new(), "wrong-token").await;
assert_eq!(response.status(), StatusCode::OK);
}
let (response, _) =
submit_on_new_consent(&s, peer_at(ip), HeaderMap::new(), "good-token").await;
assert_eq!(response.status(), StatusCode::TOO_MANY_REQUESTS);
assert_eq!(checks.load(SeqCst), 2);
server.abort();
}
#[tokio::test]
#[ignore = "requires TEST_DATABASE_URL; CI runs with --include-ignored"]
async fn postgres_a_limited_key_check_logs_no_address() {
const CHILD: &str = "INTEGRATION_PROXY_LOG_CAPTURE_CHILD";
if std::env::var_os(CHILD).is_none() {
let output = std::process::Command::new(std::env::current_exe().unwrap())
.args([
"--exact",
"connect::tests::postgres_a_limited_key_check_logs_no_address",
"--include-ignored",
"--test-threads=1",
])
.env(CHILD, "1")
.output()
.unwrap();
let stdout = String::from_utf8_lossy(&output.stdout);
assert!(
output.status.success() && stdout.contains("1 passed"),
"{stdout}\n{}",
String::from_utf8_lossy(&output.stderr)
);
return;
}
let logs = LogBuffer::default();
let writer = logs.clone();
let subscriber = tracing_subscriber::fmt()
.with_max_level(tracing::Level::TRACE)
.with_ansi(false)
.with_writer(move || writer.clone())
.finish();
let _guard = tracing::subscriber::set_default(subscriber);
let security = crate::test_support::security().await;
let (upstream, server) = key_check_upstream().await;
let s = limited_state(
&security,
&upstream,
"clockify",
key_check_document("header"),
1,
);
let ip = fresh_ip();
let (response, _) =
submit_on_new_consent(&s, peer_at(ip), HeaderMap::new(), "wrong-key").await;
assert_eq!(response.status(), StatusCode::OK);
let (response, _) =
submit_on_new_consent(&s, peer_at(ip), HeaderMap::new(), "good-key").await;
assert_eq!(response.status(), StatusCode::TOO_MANY_REQUESTS);
server.abort();
let logs = String::from_utf8(logs.0.lock().unwrap().clone()).unwrap();
let bucket = security.key_check_bucket("clockify", &ip.to_string());
assert_eq!(bucket.len(), 64);
assert!(logs.contains("key check limit reached"), "{logs}");
assert!(logs.contains(&bucket), "{logs}");
for secret in [ip.to_string(), "wrong-key".into(), "good-key".into()] {
assert!(!logs.contains(&secret), "{secret} in logs:\n{logs}");
}
}
#[derive(Clone, Default)]
struct LogBuffer(std::sync::Arc<std::sync::Mutex<Vec<u8>>>);
impl std::io::Write for LogBuffer {
fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
self.0.lock().unwrap().extend_from_slice(bytes);
Ok(bytes.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
#[tokio::test]
#[ignore = "requires TEST_DATABASE_URL; CI runs with --include-ignored"]
async fn postgres_no_http_token_reaches_the_logs() {
const CHILD: &str = "INTEGRATION_PROXY_LOG_CAPTURE_CHILD";
if std::env::var_os(CHILD).is_none() {
let output = std::process::Command::new(std::env::current_exe().unwrap())
.args([
"--exact",
"connect::tests::postgres_no_http_token_reaches_the_logs",
"--include-ignored",
"--test-threads=1",
])
.env(CHILD, "1")
.output()
.unwrap();
let stdout = String::from_utf8_lossy(&output.stdout);
assert!(
output.status.success() && stdout.contains("1 passed"),
"{stdout}\n{}",
String::from_utf8_lossy(&output.stderr)
);
return;
}
let logs = LogBuffer::default();
let writer = logs.clone();
let subscriber = tracing_subscriber::fmt()
.with_max_level(tracing::Level::TRACE)
.with_ansi(false)
.with_writer(move || writer.clone())
.finish();
let _guard = tracing::subscriber::set_default(subscriber);
tracing::info!("log capture started");
let (upstream, key_server) = http_key_check_upstream().await;
let security = crate::test_support::security().await;
let layout = serde_json::json!({"token": "password", "usernameLabel": "Email"});
let mut s = state(Some(security.clone()));
s.test_upstream = Some(upstream);
s.catalog = crate::catalog::Catalog::from_test_document(
"clockify",
http_document(basic(layout.clone())),
serde_json::json!({}),
);
let consent = Consent {
request: api_key_request(),
csrf: random(),
expires: crate::now_secs() + 600,
};
let jar = PrivateCookieJar::new(s.key.clone()).add(private_cookie(
CONSENT_COOKIE,
serde_json::to_string(&consent).unwrap(),
));
let accepted = authorize(
State(s.clone()),
None,
jar,
HeaderMap::new(),
Form(Approval {
csrf: consent.csrf.clone(),
..token_approval("good-token", Some("ada@example.test"))
}),
)
.await;
assert_eq!(accepted.status(), StatusCode::SEE_OTHER);
key_server.abort();
let location = Url::parse(accepted.headers()[header::LOCATION].to_str().unwrap()).unwrap();
let code = location
.query_pairs()
.find(|(k, _)| k == "connection_code")
.unwrap()
.1
.into_owned();
let owner = Agent::new(72);
let redeemed = body_json(redeem_as(&s, &owner, &code, &"a".repeat(43)).await).await;
let connection_id = redeemed["connection_id"].as_str().unwrap();
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
let app = axum::Router::new().route(
"/api/v1/workspaces",
axum::routing::get(|| async { axum::Json(serde_json::json!([])) }),
);
let provider = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
let mut document = http_document(basic(layout));
document["servers"] = serde_json::json!([{"url": format!("http://{address}/api")}]);
document["components"]["securitySchemes"]["serviceToken"]
.as_object_mut()
.unwrap()
.remove("x-api-key-details");
document["components"]["securitySchemes"]["serviceToken"]["x-api-key-details"] = serde_json::json!({"basicCredentials": {"token": "password", "usernameLabel": "Email"}});
s.catalog = crate::catalog::Catalog::from_test_document(
"clockify",
document,
serde_json::json!({}),
);
let response = crate::router(s.clone())
.oneshot(signed_request(
&s,
&owner,
"GET",
&format!("/proxy/{connection_id}/clockify/api/v1/workspaces"),
Vec::new(),
))
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
provider.abort();
let logs = String::from_utf8(logs.0.lock().unwrap().clone()).unwrap();
assert!(logs.contains("log capture started"), "{logs}");
assert!(
logs.contains("tower_http") && logs.contains("/proxy/"),
"{logs}"
);
assert!(logs.contains("hyper_util"), "{logs}");
let encoded = basic_header("ada@example.test", "good-token");
for secret in [
"good-token",
encoded.trim_start_matches("Basic "),
"ada@example.test",
] {
assert!(!logs.contains(secret), "{secret} in logs:\n{logs}");
}
}
fn no_credential_catalog() -> crate::catalog::Catalog {
crate::catalog::Catalog::from_test_document(
"pets",
serde_json::json!({
"servers": [{"url": "https://pets.example/api"}],
"security": [],
"paths": {"/pets": {"get": {}}}
}),
serde_json::json!({}),
)
}
fn no_credential_request() -> Request {
Request {
platform: "pets".into(),
redirect_uri:
"https://hub.example/app/integrations?integration_state=state&platform=pets".into(),
code_challenge: pkce_challenge(&"a".repeat(43)).unwrap(),
code_challenge_method: "S256".into(),
}
}
#[tokio::test]
async fn no_credential_consent_page_asks_for_nothing_and_redirects_nowhere_else() {
let mut s = state(None);
s.catalog = no_credential_catalog();
let r = no_credential_request();
let uri = format!(
"/connect?platform=pets&redirect_uri={}&code_challenge={}&code_challenge_method=S256",
url::form_urlencoded::byte_serialize(r.redirect_uri.as_bytes()).collect::<String>(),
r.code_challenge
);
let response = crate::router(s)
.oneshot(
axum::http::Request::builder()
.uri(uri)
.body(axum::body::Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
let policy = response.headers()["content-security-policy"]
.to_str()
.unwrap()
.to_owned();
assert!(policy.ends_with("form-action 'self' https://hub.example"));
let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
.await
.unwrap();
let html = String::from_utf8(bytes.to_vec()).unwrap();
assert!(html.contains("Pets needs no account"));
assert!(!html.contains("api_key"));
}
#[tokio::test]
#[ignore = "requires TEST_DATABASE_URL; CI runs with --include-ignored"]
async fn postgres_no_credential_connect_seals_no_secret_and_the_signer_owns_it() {
let security = crate::test_support::security().await;
let mut s = state(Some(security.clone()));
s.catalog = no_credential_catalog();
let consent = Consent {
request: no_credential_request(),
csrf: random(),
expires: crate::now_secs() + 600,
};
let jar = PrivateCookieJar::new(s.key.clone()).add(private_cookie(
CONSENT_COOKIE,
serde_json::to_string(&consent).unwrap(),
));
let response = authorize(
State(s.clone()),
None,
jar,
HeaderMap::new(),
Form(Approval {
csrf: consent.csrf.clone(),
api_key: Some("unexpected-secret".into()),
username: None,
}),
)
.await;
assert_eq!(response.status(), StatusCode::SEE_OTHER);
let location = Url::parse(response.headers()[header::LOCATION].to_str().unwrap()).unwrap();
assert_eq!(
location.origin().ascii_serialization(),
"https://hub.example"
);
let code = location
.query_pairs()
.find(|(k, _)| k == "connection_code")
.unwrap()
.1
.into_owned();
let owner = Agent::new(25);
let ok = redeem_as(&s, &owner, &code, &"a".repeat(43)).await;
assert_eq!(ok.status(), StatusCode::OK);
let body = body_json(ok).await;
assert_eq!(body["platform"], "pets");
assert_eq!(body["owner"], owner.id());
let record = security
.load_connection(body["connection_id"].as_str().unwrap())
.await
.unwrap()
.unwrap();
assert_eq!(record.owner, owner.id());
let credential: crate::proxy::StoredCredential =
serde_json::from_slice(&record.credential).unwrap();
assert!(matches!(
credential,
crate::proxy::StoredCredential::NoCredential { ref provider } if provider == "pets"
));
assert!(!String::from_utf8_lossy(&record.credential).contains("unexpected-secret"));
}
#[tokio::test]
#[ignore = "requires TEST_DATABASE_URL; CI runs with --include-ignored"]
async fn postgres_redeem_canonicalizes_a_legacy_signer_and_refuses_unsigned_or_denied() {
let security = crate::test_support::security().await;
let s = state(Some(security.clone()));
let credential = crate::proxy::StoredCredential::ApiKey {
placement: None,
scheme: None,
provider: "github-issues".into(),
key: "k".into(),
};
let owner = Agent::new(22);
let code = handoff(&security, &request(), credential.clone())
.await
.unwrap();
let unsigned = crate::router(s.clone())
.oneshot(
axum::http::Request::builder()
.method("POST")
.uri("/connect/redeem")
.body(axum::body::Body::from(
serde_json::json!({"code": code, "code_verifier": "a".repeat(43)})
.to_string(),
))
.unwrap(),
)
.await
.unwrap();
assert_eq!(unsigned.status(), StatusCode::UNAUTHORIZED);
assert_eq!(body_json(unsigned).await["error"], "missing_signature");
let body = serde_json::json!({"code": code, "code_verifier": "a".repeat(43)}).to_string();
let mut legacy = signed_request(&s, &owner, "POST", "/connect/redeem", body.into_bytes());
legacy.headers_mut().insert(
crate::signature::AGENT_HEADER,
owner.legacy_id().parse().unwrap(),
);
let response = crate::router(s.clone()).oneshot(legacy).await.unwrap();
assert_eq!(response.status(), StatusCode::OK);
assert_eq!(body_json(response).await["owner"], owner.id());
let mut denied = state(Some(security.clone()));
denied.access =
std::sync::Arc::new(crate::access::EnvAccessPolicy::new(None, vec![owner.id()]));
let code = handoff(&security, &request(), credential.clone())
.await
.unwrap();
let response = redeem_as(&denied, &owner, &code, &"a".repeat(43)).await;
assert_eq!(response.status(), StatusCode::FORBIDDEN);
assert_eq!(body_json(response).await["error"], "access_denied");
let response = redeem_as(&s, &owner, &code, &"a".repeat(43)).await;
assert_eq!(response.status(), StatusCode::OK);
let code = handoff(&security, &request(), credential).await.unwrap();
crate::security::tests::admin()
.await
.execute(
"UPDATE connection_handoffs SET expires_at = NOW() - INTERVAL '1 second' WHERE code = $1",
&[&code],
)
.await
.unwrap();
let response = redeem_as(&s, &owner, &code, &"a".repeat(43)).await;
assert_eq!(response.status(), StatusCode::BAD_REQUEST);
}
#[tokio::test]
#[ignore = "requires TEST_DATABASE_URL; CI runs with --include-ignored"]
async fn postgres_two_simultaneous_redemptions_create_one_connection() {
let security = crate::test_support::security().await;
let s = state(Some(security.clone()));
let code = handoff(
&security,
&request(),
crate::proxy::StoredCredential::ApiKey {
placement: None,
scheme: None,
provider: "github-issues".into(),
key: "k".into(),
},
)
.await
.unwrap();
let (a, b) = (Agent::new(23), Agent::new(24));
let verifier = "a".repeat(43);
let (first, second) = tokio::join!(
redeem_as(&s, &a, &code, &verifier),
redeem_as(&s, &b, &code, &verifier)
);
let statuses = [first.status(), second.status()];
assert!(statuses.contains(&StatusCode::OK));
assert!(statuses.contains(&StatusCode::BAD_REQUEST));
}
#[tokio::test]
#[ignore = "requires TEST_DATABASE_URL and fixture OAuth credentials; CI runs it"]
async fn postgres_oauth_consent_is_bound_to_the_browser_and_cancellation_returns_home() {
let security = crate::test_support::security().await;
let s = state(Some(security.clone()));
let consent = Consent {
request: request(),
csrf: random(),
expires: crate::now_secs() + 600,
};
let jar = PrivateCookieJar::new(s.key.clone()).add(private_cookie(
CONSENT_COOKIE,
serde_json::to_string(&consent).unwrap(),
));
let response = authorize(
State(s.clone()),
None,
jar.clone(),
HeaderMap::new(),
Form(Approval {
csrf: consent.csrf.clone(),
api_key: None,
username: None,
}),
)
.await;
let binding_cookie = set_cookie(&response, "platform_oauth").unwrap();
let destination = continue_page(response).await;
assert_eq!(destination.host_str(), Some("auth.example"));
let provider_state = destination
.query_pairs()
.find(|(k, _)| k == "state")
.unwrap()
.1
.into_owned();
let foreign = crate::router(s.clone())
.oneshot(
axum::http::Request::builder()
.uri(format!(
"/oauth/github-issues/callback?state={provider_state}&error=access_denied"
))
.body(axum::body::Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(foreign.status(), StatusCode::BAD_REQUEST);
let consent = Consent {
request: request(),
csrf: random(),
expires: crate::now_secs() + 600,
};
let jar = PrivateCookieJar::new(s.key.clone()).add(private_cookie(
CONSENT_COOKIE,
serde_json::to_string(&consent).unwrap(),
));
let response = authorize(
State(s.clone()),
None,
jar,
HeaderMap::new(),
Form(Approval {
csrf: consent.csrf.clone(),
api_key: None,
username: None,
}),
)
.await;
let binding_cookie_2 = set_cookie(&response, "platform_oauth").unwrap();
let destination = continue_page(response).await;
let provider_state = destination
.query_pairs()
.find(|(k, _)| k == "state")
.unwrap()
.1
.into_owned();
assert_ne!(binding_cookie, binding_cookie_2);
let cancelled = crate::router(s.clone())
.oneshot(
axum::http::Request::builder()
.uri(format!(
"/oauth/github-issues/callback?state={provider_state}&error=access_denied"
))
.header(header::COOKIE, binding_cookie_2)
.body(axum::body::Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(cancelled.status(), StatusCode::SEE_OTHER);
let target = Url::parse(cancelled.headers()[header::LOCATION].to_str().unwrap()).unwrap();
assert_eq!(target.origin().ascii_serialization(), "https://hub.example");
assert!(target
.query_pairs()
.any(|(k, v)| k == "error" && v == "access_denied"));
assert!(!target.query_pairs().any(|(k, _)| k == "connection_code"));
assert_eq!(cancelled.headers()[header::CACHE_CONTROL], "no-store");
}
#[tokio::test]
#[ignore = "requires TEST_DATABASE_URL and fixture OAuth credentials; CI runs it"]
async fn postgres_oauth_connect_redeem_delegate_and_proxy_end_to_end() {
use std::sync::{
atomic::{AtomicUsize, Ordering},
Arc,
};
let tokens = Arc::new(AtomicUsize::new(0));
let token_counter = tokens.clone();
let upstream = axum::Router::new()
.route(
"/token",
axum::routing::post(move |body: Bytes| {
let token_counter = token_counter.clone();
async move {
token_counter.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
let body = String::from_utf8(body.to_vec()).unwrap();
assert!(body.contains("grant_type=authorization_code"));
assert!(body.contains("code=provider-code"));
assert!(body.contains(
"redirect_uri=https%3A%2F%2Fproxy.example%2Foauth%2Fgithub-issues%2Fcallback"
));
Json(serde_json::json!({"access_token": "provider-token", "refresh_token": "r", "expires_in": 3600}))
}
}),
)
.route(
"/records",
axum::routing::get(|headers: HeaderMap| async move {
Json(serde_json::json!({
"authorization": headers.get(header::AUTHORIZATION).and_then(|v| v.to_str().ok()),
}))
}),
);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let upstream_url = format!("http://{}", listener.local_addr().unwrap());
let server = tokio::spawn(async move { axum::serve(listener, upstream).await.unwrap() });
let security = crate::test_support::security().await;
let mut s = state(Some(security.clone()));
s.catalog = crate::catalog::Catalog::from_test_document(
"github-issues",
serde_json::json!({
"servers": [{"url": upstream_url}],
"components": {"securitySchemes": {"oauth": {"type": "oauth2", "flows": {
"authorizationCode": {
"authorizationUrl": "https://auth.example/authorize",
"tokenUrl": "https://auth.example/token",
"scopes": {"read": "Read records"}
}
}}}},
"security": [{"oauth": ["read"]}],
"paths": {"/records": {"get": {}}}
}),
serde_json::json!({}),
);
s.test_upstream = Some(upstream_url);
let page = crate::router(s.clone())
.oneshot(
axum::http::Request::builder()
.uri(connect_uri(&request()))
.body(axum::body::Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(page.status(), StatusCode::OK);
let consent_cookie = page
.headers()
.get_all(header::SET_COOKIE)
.iter()
.map(|v| v.to_str().unwrap().split(';').next().unwrap().to_string())
.find(|v| v.starts_with("platform_consent="))
.unwrap();
let html = String::from_utf8(
axum::body::to_bytes(page.into_body(), 65_536)
.await
.unwrap()
.to_vec(),
)
.unwrap();
let csrf = html
.split("name=\"csrf\" value=\"")
.nth(1)
.unwrap()
.split('"')
.next()
.unwrap()
.to_owned();
let approval = crate::router(s.clone())
.oneshot(
axum::http::Request::builder()
.method("POST")
.uri("/connect/authorize")
.header(header::COOKIE, &consent_cookie)
.header(header::ORIGIN, crate::test_support::PUBLIC_ORIGIN)
.header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
.body(axum::body::Body::from(format!("csrf={csrf}")))
.unwrap(),
)
.await
.unwrap();
let binding = set_cookie(&approval, "platform_oauth").unwrap();
let provider = continue_page(approval).await;
assert_eq!(provider.host_str(), Some("auth.example"));
let provider_state = provider
.query_pairs()
.find(|(k, _)| k == "state")
.unwrap()
.1
.into_owned();
let callback = crate::router(s.clone())
.oneshot(
axum::http::Request::builder()
.uri(format!(
"/oauth/github-issues/callback?state={provider_state}&code=provider-code"
))
.header(header::COOKIE, binding)
.body(axum::body::Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(callback.status(), StatusCode::SEE_OTHER);
assert_eq!(tokens.load(Ordering::SeqCst), 1);
let home = Url::parse(callback.headers()[header::LOCATION].to_str().unwrap()).unwrap();
assert_eq!(home.origin().ascii_serialization(), "https://hub.example");
assert!(home
.query_pairs()
.any(|(k, v)| k == "integration_state" && v == "state"));
let handoff = home
.query_pairs()
.find(|(k, _)| k == "connection_code")
.unwrap()
.1
.into_owned();
assert!(!home.as_str().contains("provider-token"));
let owner = Agent::new(61);
let redeemed = redeem_as(&s, &owner, &handoff, &"a".repeat(43)).await;
assert_eq!(redeemed.status(), StatusCode::OK);
let redeemed = body_json(redeemed).await;
let connection_id = redeemed["connection_id"].as_str().unwrap().to_owned();
assert_eq!(redeemed["owner"], owner.id());
let path = format!("/proxy/{connection_id}/github-issues/records");
let call = crate::router(s.clone())
.oneshot(signed_request(&s, &owner, "GET", &path, vec![]))
.await
.unwrap();
assert_eq!(call.status(), StatusCode::OK);
assert_eq!(
body_json(call).await["authorization"],
"Bearer provider-token"
);
let app = Agent::new(62);
let delegation = crate::router(s.clone())
.oneshot(signed_request(
&s,
&owner,
"POST",
&format!("/connections/{connection_id}/agents"),
serde_json::json!({"agent": app.id(), "label": "Issue tracker"})
.to_string()
.into_bytes(),
))
.await
.unwrap();
assert_eq!(delegation.status(), StatusCode::OK);
let call = crate::router(s.clone())
.oneshot(signed_request(&s, &app, "GET", &path, vec![]))
.await
.unwrap();
assert_eq!(call.status(), StatusCode::OK);
server.abort();
}
#[tokio::test]
#[ignore = "requires TEST_DATABASE_URL and fixture OAuth credentials; CI runs it"]
async fn postgres_oauth_approval_leaves_the_form_before_the_provider_redirects() {
let security = crate::test_support::security().await;
let mut s = state(Some(security));
s.catalog = crate::catalog::Catalog::from_test_document(
"github-issues",
serde_json::json!({
"servers": [{"url": "https://api.provider.example/v1"}],
"components": {"securitySchemes": {"oauth": {"type": "oauth2", "flows": {
"authorizationCode": {
"authorizationUrl": "https://api.provider.example/v1/oauth/authorize",
"tokenUrl": "https://api.provider.example/v1/oauth/token",
"scopes": {"read": "Read records"}
}
}}}},
"security": [{"oauth": ["read"]}],
"paths": {"/records": {"get": {}}}
}),
serde_json::json!({}),
);
let page = crate::router(s.clone())
.oneshot(
axum::http::Request::builder()
.uri(connect_uri(&request()))
.body(axum::body::Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(page.status(), StatusCode::OK);
let policy = page.headers()["content-security-policy"]
.to_str()
.unwrap()
.to_owned();
assert!(policy.ends_with("; form-action 'self'"), "{policy}");
assert!(!policy.contains("provider.example"), "{policy}");
let consent_cookie = set_cookie(&page, "platform_consent").unwrap();
let html = body_text(page).await;
let csrf = html
.split("name=\"csrf\" value=\"")
.nth(1)
.unwrap()
.split('"')
.next()
.unwrap()
.to_owned();
let approve = |cookie: String| {
crate::router(s.clone()).oneshot(
axum::http::Request::builder()
.method("POST")
.uri("/connect/authorize")
.header(header::COOKIE, cookie)
.header(header::ORIGIN, crate::test_support::PUBLIC_ORIGIN)
.header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
.body(axum::body::Body::from(format!("csrf={csrf}")))
.unwrap(),
)
};
let approval = approve(consent_cookie.clone()).await.unwrap();
let used = set_cookie(&approval, CONSENT_USED_COOKIE).unwrap();
assert_eq!(
set_cookie(&approval, CONSENT_COOKIE).as_deref(),
Some("platform_consent=")
);
let provider = continue_page(approval).await;
assert_eq!(provider.host_str(), Some("api.provider.example"));
assert_eq!(provider.path(), "/v1/oauth/authorize");
assert!(provider.query_pairs().any(|(k, v)| k == "redirect_uri"
&& v == "https://proxy.example/oauth/github-issues/callback"));
let again = approve(consent_cookie).await.unwrap();
assert_eq!(again.status(), StatusCode::BAD_REQUEST);
assert_eq!(body_text(again).await, ALREADY_APPROVED);
let later = approve(used).await.unwrap();
assert_eq!(later.status(), StatusCode::BAD_REQUEST);
assert_eq!(body_text(later).await, ALREADY_APPROVED);
}
}