Initial public release

Luxe 0.1.0: a coding agent harness for the terminal. See README.md to get started and CHANGELOG.md for releases.
This commit is contained in:
Evan Whittaker
2026-10-17 12:08:30 -05:00
commit 09a7de2520
1730 changed files with 412952 additions and 0 deletions

View File

@@ -0,0 +1,237 @@
//! Discovery paths — where the specifications put each metadata document, and how to read
//! what a server's challenge points at.
use serde_json::Value;
use super::endpoints::{endpoints_from, is_loopback, require_secure, Endpoints};
use super::{OAuthClient, OAuthError, Resolved};
impl OAuthClient {
/// Endpoints and resource: configured ones win, then discovery.
pub(super) async fn resolve(&self) -> Result<Resolved, OAuthError> {
let configured = Endpoints {
authorization: self.config.authorization_endpoint.clone(),
token: self.config.token_endpoint.clone(),
registration: self.config.registration_endpoint.clone(),
}
.checked()?;
if configured.authorization.is_some() && configured.token.is_some() {
return Ok(Resolved { endpoints: configured, resource: self.server_url.clone() });
}
let (discovered, resource) = match self.discover().await? {
Some((endpoints, resource)) => (endpoints, resource),
None => (Endpoints::default(), None),
};
Ok(Resolved {
endpoints: Endpoints {
authorization: configured.authorization.or(discovered.authorization),
token: configured.token.or(discovered.token),
registration: configured.registration.or(discovered.registration),
},
resource: resource.unwrap_or_else(|| self.server_url.clone()),
})
}
/// Discovery in the specification's order; see the module docs for why the order matters.
///
/// `Err` when metadata was found and failed its checks, or pointed at an authorization server
/// that would not describe itself: falling back from there would be exactly how the wrong server
/// gets used.
async fn discover(&self) -> Result<Option<(Endpoints, Option<String>)>, OAuthError> {
require_secure(&self.server_url, "the MCP server")?;
let server = url::Url::parse(&self.server_url)
.map_err(|e| OAuthError::Discovery(format!("bad server url: {e}")))?;
if let Some((resource, issuer)) = self.protected_resource(&server).await? {
let endpoints = self.authorization_server(&issuer).await?;
return Ok(Some((endpoints, Some(resource))));
}
Ok(self.origin_metadata(&server).await?.map(|endpoints| (endpoints, None)))
}
/// The protected-resource document (RFC 9728): `(resource, first authorization server)`.
async fn protected_resource(
&self,
server: &url::Url,
) -> Result<Option<(String, String)>, OAuthError> {
// The server's own pointer is an instruction, not a hint: when it names a document, that
// document or nothing
if let Some(pointed) = self.resource_metadata_pointer().await {
return match self.fetch_protected_resource(&pointed, server).await? {
Some(found) => Ok(Some(found)),
None => Err(OAuthError::Discovery(format!(
"{pointed} did not return protected-resource metadata"
))),
};
}
for candidate in protected_resource_candidates(server) {
if let Some(found) = self.fetch_protected_resource(&candidate, server).await? {
return Ok(Some(found));
}
}
Ok(None)
}
/// `resource_metadata` from the `WWW-Authenticate` header an unauthenticated request draws.
async fn resource_metadata_pointer(&self) -> Option<String> {
let initialize = serde_json::json!({
"jsonrpc": "2.0", "id": 0, "method": "initialize",
"params": {
"protocolVersion": luxe_core::mcp_client::MCP_PROTOCOL_VERSION,
"capabilities": {},
"clientInfo": { "name": "luxe", "version": env!("CARGO_PKG_VERSION") }
}
});
let response = self
.http
.post(&self.server_url)
.header(reqwest::header::ACCEPT, "application/json, text/event-stream")
.json(&initialize)
.send()
.await
.ok()?;
if response.status() != reqwest::StatusCode::UNAUTHORIZED {
return None;
}
let header = response.headers().get(reqwest::header::WWW_AUTHENTICATE)?.to_str().ok()?;
auth_param(header, "resource_metadata")
}
/// One protected-resource document, checked. `Ok(None)` when there is none at `url`.
async fn fetch_protected_resource(
&self,
url: &str,
server: &url::Url,
) -> Result<Option<(String, String)>, OAuthError> {
let Some(doc) = self.fetch_json(url).await else {
return Ok(None);
};
let Some(issuer) = doc
.get("authorization_servers")
.and_then(Value::as_array)
.and_then(|servers| servers.first())
.and_then(Value::as_str)
else {
return Ok(None);
};
let resource = doc.get("resource").and_then(Value::as_str).unwrap_or_default();
if !names_the_server(resource, server) {
return Err(OAuthError::Discovery(format!(
"{url} describes {resource:?}, not {server} — refusing to send a token for it"
)));
}
Ok(Some((resource.to_string(), issuer.to_string())))
}
/// Authorization-server metadata for `issuer` (RFC 8414, then OpenID discovery), checked.
async fn authorization_server(&self, issuer: &str) -> Result<Endpoints, OAuthError> {
let url = url::Url::parse(issuer)
.map_err(|e| OAuthError::Discovery(format!("bad authorization server: {e}")))?;
if url.scheme() != "https" && !is_loopback(&url) {
return Err(OAuthError::Insecure(format!(
"the authorization server {issuer} is not https"
)));
}
for candidate in authorization_server_candidates(&url) {
let Some(doc) = self.fetch_json(&candidate).await else {
continue;
};
let endpoints = endpoints_from(&doc, &candidate, issuer)?;
if endpoints.authorization.is_some() || endpoints.token.is_some() {
return Ok(endpoints);
}
}
Err(OAuthError::Discovery(format!("{issuer} publishes no authorization server metadata")))
}
/// The origin lookup, for a server that publishes no protected-resource metadata.
async fn origin_metadata(&self, server: &url::Url) -> Result<Option<Endpoints>, OAuthError> {
let Some(origin) = origin_of(server) else { return Ok(None) };
for suffix in
["/.well-known/oauth-authorization-server", "/.well-known/openid-configuration"]
{
let candidate = format!("{origin}{suffix}");
let Some(doc) = self.fetch_json(&candidate).await else {
continue;
};
let endpoints = endpoints_from(&doc, &candidate, &origin)?;
if endpoints.authorization.is_some() || endpoints.token.is_some() {
return Ok(Some(endpoints));
}
}
Ok(None)
}
/// GET `url` as JSON, or `None` for anything other than a successful JSON answer.
async fn fetch_json(&self, url: &str) -> Option<Value> {
let response = self.http.get(url).send().await.ok()?;
if !response.status().is_success() {
return None;
}
response.json::<Value>().await.ok()
}
}
/// Where RFC 9728 puts the protected-resource document for `server`: the path form, then the root.
pub(super) fn protected_resource_candidates(server: &url::Url) -> Vec<String> {
let Some(origin) = origin_of(server) else {
return Vec::new();
};
let path = server.path().trim_end_matches('/');
let mut candidates = Vec::new();
if !path.is_empty() {
candidates.push(format!("{origin}/.well-known/oauth-protected-resource{path}"));
}
candidates.push(format!("{origin}/.well-known/oauth-protected-resource"));
candidates
}
/// Where RFC 8414 and OpenID discovery put an issuer's metadata, in that order.
pub(super) fn authorization_server_candidates(issuer: &url::Url) -> Vec<String> {
let Some(origin) = origin_of(issuer) else {
return Vec::new();
};
let path = issuer.path().trim_end_matches('/');
let mut candidates = vec![format!("{origin}/.well-known/oauth-authorization-server{path}")];
candidates.push(format!("{origin}{path}/.well-known/openid-configuration"));
if !path.is_empty() {
candidates.push(format!("{origin}/.well-known/openid-configuration{path}"));
}
candidates.dedup();
candidates
}
/// Whether a protected-resource document's `resource` names the server it was fetched for: the
/// same origin, and the server's path at or under the resource's, a whole segment at a time.
pub(super) fn names_the_server(resource: &str, server: &url::Url) -> bool {
let Ok(resource) = url::Url::parse(resource) else {
return false;
};
if origin_of(&resource) != origin_of(server) {
return false;
}
let owned = resource.path().trim_end_matches('/');
let path = server.path().trim_end_matches('/');
owned.is_empty() || path == owned || path.starts_with(&format!("{owned}/"))
}
/// `scheme://host[:port]`, the part of a URL two documents must share to describe one server.
pub(super) fn origin_of(url: &url::Url) -> Option<String> {
// Already bracketed for an IPv6 literal
let host = url.host_str()?;
Some(format!(
"{}://{host}{}",
url.scheme(),
url.port().map(|port| format!(":{port}")).unwrap_or_default()
))
}
/// One parameter of a `WWW-Authenticate` challenge: `resource_metadata="…"`, quoted or bare.
pub(super) fn auth_param(header: &str, name: &str) -> Option<String> {
let at = header.find(&format!("{name}="))? + name.len() + 1;
let rest = &header[at..];
let value = match rest.strip_prefix('"') {
Some(quoted) => quoted.split('"').next()?,
None => rest.split([',', ' ']).next()?,
};
(!value.is_empty()).then(|| value.to_string())
}

View File

@@ -0,0 +1,77 @@
//! Endpoints — where an authorization code, a client secret or a token may be sent.
//!
//! Every endpoint is checked before it is used, discovered or configured: https, or plain http on
//! this machine. A metadata document must also name its issuer and be the one it was asked for,
//! so a document served from one place cannot send a token somewhere else.
use serde_json::Value;
use super::OAuthError;
/// The resolved OAuth endpoints for a server.
#[derive(Debug, Clone, Default)]
pub(super) struct Endpoints {
pub(super) authorization: Option<String>,
pub(super) token: Option<String>,
pub(super) registration: Option<String>,
}
impl Endpoints {
/// These endpoints, once every one of them is somewhere a secret may go.
pub(super) fn checked(self) -> Result<Self, OAuthError> {
for (endpoint, what) in [
(&self.authorization, "the authorization endpoint"),
(&self.token, "the token endpoint"),
(&self.registration, "the registration endpoint"),
] {
if let Some(endpoint) = endpoint {
require_secure(endpoint, what)?;
}
}
Ok(self)
}
}
/// `url` is somewhere a code or a token may go: https, or plain http on this machine.
pub(crate) fn require_secure(url: &str, what: &str) -> Result<(), OAuthError> {
let parsed = url::Url::parse(url)
.map_err(|e| OAuthError::Insecure(format!("{what} {url} is not a URL: {e}")))?;
match parsed.scheme() {
"https" => Ok(()),
"http" if is_loopback(&parsed) => Ok(()),
_ => Err(OAuthError::Insecure(format!(
"{what} {url} is not https, so nothing will be sent to it"
))),
}
}
pub(super) fn is_loopback(url: &url::Url) -> bool {
matches!(url.host_str(), Some("127.0.0.1" | "localhost" | "[::1]"))
}
/// The endpoints the authorization-server document at `candidate` describes, refused unless it
/// names `issuer` as itself (RFC 8414 requires the field) and every endpoint is secure.
pub(super) fn endpoints_from(
doc: &Value,
candidate: &str,
issuer: &str,
) -> Result<Endpoints, OAuthError> {
match doc.get("issuer").and_then(Value::as_str) {
Some(claimed) if claimed.trim_end_matches('/') == issuer.trim_end_matches('/') => {}
Some(claimed) => {
return Err(OAuthError::Discovery(format!(
"{candidate} says it is {claimed:?}, not {issuer} — refusing it"
)))
}
None => {
return Err(OAuthError::Discovery(format!("{candidate} names no issuer — refusing it")))
}
}
let field = |k: &str| doc.get(k).and_then(Value::as_str).map(str::to_string);
Endpoints {
authorization: field("authorization_endpoint"),
token: field("token_endpoint"),
registration: field("registration_endpoint"),
}
.checked()
}

View File

@@ -0,0 +1,40 @@
//! Errors — why a sign-in, a refresh or a discovery produced no token.
use crate::secret::SecretError;
use crate::token_store::TokenStoreError;
/// Why an OAuth step did not work out.
///
/// Each variant carries the sentence the reader sees, so a caller shows it as it is. What the
/// variants are for is the caller that has to act differently: a refresh the server
/// [refused](Self::Refused) sends the reader back to `luxe mcp login`, and nothing else does.
#[derive(Debug, thiserror::Error)]
pub enum OAuthError {
/// Discovery found nothing, or a document that failed its checks
#[error("{0}")]
Discovery(String),
/// An endpoint that would send a code or a token somewhere it could be read
#[error("{0}")]
Insecure(String),
/// The redirect was not an answer to this login's request
#[error("state mismatch — possible CSRF; login aborted")]
StateMismatch,
/// The server answered and said no: an error redirect, an error status from the token endpoint
#[error("{0}")]
Refused(String),
/// The server could not be reached, or its answer could not be read
#[error("{0}")]
Network(String),
/// The login cannot go on as configured or as called
#[error("{0}")]
Config(String),
/// The browser leg: the loopback listener, or nobody coming back to it
#[error("{0}")]
Callback(String),
/// The token store could not be written
#[error(transparent)]
Storage(#[from] TokenStoreError),
/// A configured secret did not resolve
#[error(transparent)]
Secret(#[from] SecretError),
}

View File

@@ -0,0 +1,159 @@
//! Grants — the token endpoint: a code exchange, client credentials and a refresh.
use serde_json::Value;
use super::endpoints::require_secure;
use super::{now_secs, Client, OAuthClient, OAuthError, Pending};
use crate::token_store::StoredToken;
impl OAuthClient {
/// Exchange an authorization code for tokens.
pub(super) async fn exchange_code(
&self,
code: &str,
pending: &Pending,
) -> Result<StoredToken, OAuthError> {
let mut form = vec![
("grant_type", "authorization_code".to_string()),
("code", code.to_string()),
("redirect_uri", pending.redirect_uri.clone()),
("client_id", pending.client.id.clone()),
("code_verifier", pending.verifier.clone()),
("resource", pending.resource.clone()),
];
if let Some(secret) = &pending.client.secret {
form.push(("client_secret", secret.clone()));
}
self.token_request(&pending.token_endpoint, &form, &pending.client, &pending.resource).await
}
/// The client-credentials grant.
pub(super) async fn client_credentials(&self) -> Result<String, OAuthError> {
let resolved = self.resolve().await?;
let token_endpoint = resolved
.endpoints
.token
.ok_or_else(|| OAuthError::Discovery("no token endpoint".into()))?;
let id = self
.config
.client_id
.clone()
.ok_or_else(|| OAuthError::Config("client_credentials needs a client_id".into()))?;
let client = Client { id, secret: self.configured_secret().await?, issued_secret: None };
let mut form = vec![
("grant_type", "client_credentials".to_string()),
("client_id", client.id.clone()),
("resource", resolved.resource.clone()),
];
if let Some(secret) = &client.secret {
form.push(("client_secret", secret.clone()));
}
if let Some(scope) = &self.config.scope {
form.push(("scope", scope.clone()));
}
let token = self.token_request(&token_endpoint, &form, &client, &resolved.resource).await?;
self.store.put(&self.server_id, token.clone())?;
Ok(token.access_token.clone())
}
/// Refresh an access token; stores and returns the new access token.
///
/// Against the token endpoint and resource the token was issued for, when it recorded them:
/// a refresh that re-ran discovery could land somewhere the token never came from.
pub(super) async fn refresh(
&self,
refresh_token: &str,
prior: &StoredToken,
) -> Result<String, OAuthError> {
let (token_endpoint, resource) = match (&prior.token_endpoint, &prior.resource) {
(Some(endpoint), Some(resource)) => {
require_secure(endpoint, "the token endpoint")?;
(endpoint.clone(), resource.clone())
}
_ => {
let resolved = self.resolve().await?;
let token = resolved
.endpoints
.token
.ok_or_else(|| OAuthError::Discovery("no token endpoint".into()))?;
(token, resolved.resource)
}
};
let id = self
.config
.client_id
.clone()
.or_else(|| prior.client_id.clone())
.ok_or_else(|| OAuthError::Config("no client_id for refresh".into()))?;
// A configured client's secret comes from the config; only a registered one's is stored
let issued =
if self.config.client_id.is_some() { None } else { prior.client_secret.clone() };
let secret = self.configured_secret().await?.or_else(|| issued.clone());
let client = Client { id, secret, issued_secret: issued };
let mut form = vec![
("grant_type", "refresh_token".to_string()),
("refresh_token", refresh_token.to_string()),
("client_id", client.id.clone()),
("resource", resource.clone()),
];
if let Some(secret) = &client.secret {
form.push(("client_secret", secret.clone()));
}
let mut token = self.token_request(&token_endpoint, &form, &client, &resource).await?;
// Providers may omit a new refresh token; keep the old one.
if token.refresh_token.is_none() {
token.refresh_token = Some(refresh_token.to_string());
}
let access = token.access_token.clone();
self.store.put(&self.server_id, token)?;
Ok(access)
}
/// POST a token request and parse the response into a [`StoredToken`], recording where it came
/// from and carrying a registration's issued secret forward.
async fn token_request(
&self,
endpoint: &str,
form: &[(&str, String)],
client: &Client,
resource: &str,
) -> Result<StoredToken, OAuthError> {
use OAuthError::{Network, Refused};
let resp = self
.http
.post(endpoint)
.form(form)
.send()
.await
.map_err(|e| Network(format!("token request failed: {e}")))?;
let status = resp.status();
// An error status is a refusal whatever its body, so the body is read leniently for it
let doc: Result<Value, _> = resp.json().await;
if !status.is_success() {
let doc = doc.unwrap_or_default();
let err = doc.get("error").and_then(Value::as_str).unwrap_or(status.as_str());
return Err(Refused(match doc.get("error_description").and_then(Value::as_str) {
Some(description) => format!("token endpoint error: {err} — {description}"),
None => format!("token endpoint error: {err}"),
}));
}
let doc = doc.map_err(|e| Network(format!("bad token response: {e}")))?;
let access_token = doc
.get("access_token")
.and_then(Value::as_str)
.ok_or_else(|| Network("token response missing access_token".into()))?
.to_string();
let refresh_token = doc.get("refresh_token").and_then(Value::as_str).map(str::to_string);
let expires_at_secs =
doc.get("expires_in").and_then(Value::as_u64).map(|secs| now_secs() + secs);
Ok(StoredToken {
access_token,
refresh_token,
expires_at_secs,
client_id: Some(client.id.clone()),
client_secret: client.issued_secret.clone(),
token_endpoint: Some(endpoint.to_string()),
resource: Some(resource.to_string()),
})
}
}

View File

@@ -0,0 +1,98 @@
//! Registration — which client the login is, and registering one when it has none.
use serde_json::Value;
use super::endpoints::Endpoints;
use super::{Client, OAuthClient, OAuthError};
use crate::secret::SecretError;
impl OAuthClient {
/// Use the configured client id, a previously-registered one from the store, or register a new
/// client dynamically (RFC 7591).
pub(super) async fn ensure_client(
&self,
endpoints: &Endpoints,
redirect_uri: &str,
) -> Result<Client, OAuthError> {
if let Some(id) = self.config.client_id.clone() {
return Ok(Client { id, secret: self.configured_secret().await?, issued_secret: None });
}
if let Some(token) = self.store.get(&self.server_id) {
if let Some(id) = token.client_id.clone() {
let issued = token.client_secret.clone();
return Ok(Client { id, secret: issued.clone(), issued_secret: issued });
}
}
let endpoint = endpoints.registration.clone().ok_or_else(|| {
OAuthError::Config(
"no client_id configured and no dynamic registration endpoint — register a \
client with the provider and set `client_id` (and `client_secret`) in the \
server's auth"
.into(),
)
})?;
self.register_client(&endpoint, redirect_uri).await
}
/// The configured secret, resolved ([`crate::secret::resolve_secret`]), or `None` when there
/// is none.
///
/// The one place a configured secret is read, so every flow — the code exchange, a refresh,
/// client credentials — sends the same thing, with `${VAR}` expanded rather than the reference
/// itself.
pub(super) async fn configured_secret(&self) -> Result<Option<String>, SecretError> {
let Some(secret) = &self.config.client_secret else {
return Ok(None);
};
let what = format!("the client secret for '{}'", self.server_id);
crate::secret::resolve_secret(secret.as_written(), self.secret_commands, &what)
.await
.map(Some)
}
/// Dynamic client registration (RFC 7591). Persists the issued client id/secret in the store.
async fn register_client(
&self,
endpoint: &str,
redirect_uri: &str,
) -> Result<Client, OAuthError> {
let body = serde_json::json!({
"client_name": "luxe",
"redirect_uris": [redirect_uri],
"grant_types": ["authorization_code", "refresh_token"],
"response_types": ["code"],
"token_endpoint_auth_method": "none",
});
let resp = self
.http
.post(endpoint)
.json(&body)
.send()
.await
.map_err(|e| OAuthError::Network(format!("client registration failed: {e}")))?;
if !resp.status().is_success() {
return Err(OAuthError::Refused(format!(
"client registration returned HTTP {}",
resp.status()
)));
}
let doc: Value = resp
.json()
.await
.map_err(|e| OAuthError::Network(format!("bad registration response: {e}")))?;
let client_id = doc
.get("client_id")
.and_then(Value::as_str)
.ok_or_else(|| OAuthError::Network("registration response missing client_id".into()))?
.to_string();
let client_secret = doc.get("client_secret").and_then(Value::as_str).map(str::to_string);
// Remember the registration so we don't re-register on every login.
let mut token = self.store.get(&self.server_id).unwrap_or_default();
token.client_id = Some(client_id.clone());
token.client_secret = client_secret.clone();
if let Err(error) = self.store.put(&self.server_id, token) {
tracing::warn!(server = %self.server_id, %error, "mcp: could not remember the registered client");
}
Ok(Client { id: client_id, secret: client_secret.clone(), issued_secret: client_secret })
}
}

View File

@@ -0,0 +1,284 @@
use super::discovery::{
auth_param, authorization_server_candidates, names_the_server, origin_of,
protected_resource_candidates,
};
use super::endpoints::is_loopback;
use super::*;
use crate::token_store::StoredToken;
fn url(text: &str) -> url::Url {
url::Url::parse(text).expect("a URL")
}
/// RFC 9728 puts the document between the host and the path, and the path form is tried before
/// the root — which is the whole of the Asana case: its root describes a retired server.
#[test]
fn protected_resource_is_looked_for_at_the_path_first() {
assert_eq!(
protected_resource_candidates(&url("https://mcp.asana.com/v2/mcp")),
[
"https://mcp.asana.com/.well-known/oauth-protected-resource/v2/mcp",
"https://mcp.asana.com/.well-known/oauth-protected-resource",
]
);
assert_eq!(
protected_resource_candidates(&url("http://127.0.0.1:9000/")),
["http://127.0.0.1:9000/.well-known/oauth-protected-resource"],
"a server at the root has one place to look, with its port"
);
}
#[test]
fn authorization_server_metadata_follows_rfc_8414_then_openid() {
assert_eq!(
authorization_server_candidates(&url("https://app.asana.com")),
[
"https://app.asana.com/.well-known/oauth-authorization-server",
"https://app.asana.com/.well-known/openid-configuration",
]
);
assert_eq!(
authorization_server_candidates(&url("https://id.example.com/tenant/7")),
[
"https://id.example.com/.well-known/oauth-authorization-server/tenant/7",
"https://id.example.com/tenant/7/.well-known/openid-configuration",
"https://id.example.com/.well-known/openid-configuration/tenant/7",
]
);
}
/// A document may describe the server or a resource above it, never a different one.
#[test]
fn a_resource_must_name_the_server_it_was_fetched_for() {
let server = url("https://mcp.asana.com/v2/mcp");
for resource in
["https://mcp.asana.com/v2/mcp", "https://mcp.asana.com/v2", "https://mcp.asana.com"]
{
assert!(names_the_server(resource, &server), "{resource}");
}
for resource in [
"https://evil.example.com/v2/mcp",
"http://mcp.asana.com/v2/mcp",
"https://mcp.asana.com:8443/v2/mcp",
"https://mcp.asana.com/v2/mcp/deeper",
"https://mcp.asana.com/v",
"not a url",
"",
] {
assert!(!names_the_server(resource, &server), "{resource}");
}
}
#[test]
fn the_metadata_pointer_is_read_from_the_challenge() {
let asana = r#"Bearer realm="Asana MCP", resource_metadata="https://mcp.asana.com/.well-known/oauth-protected-resource/v2", error="invalid_request""#;
assert_eq!(
auth_param(asana, "resource_metadata").as_deref(),
Some("https://mcp.asana.com/.well-known/oauth-protected-resource/v2")
);
assert_eq!(
auth_param("Bearer resource_metadata=https://x.example/m, realm=y", "resource_metadata")
.as_deref(),
Some("https://x.example/m"),
"an unquoted value ends at the next parameter"
);
assert_eq!(auth_param(r#"Bearer realm="x""#, "resource_metadata"), None);
assert_eq!(auth_param(r#"Bearer resource_metadata="""#, "resource_metadata"), None);
}
#[test]
fn loopback_is_the_three_hosts_a_browser_can_hand_a_code_to() {
for host in ["http://127.0.0.1:1/", "http://localhost:1/", "http://[::1]:1/"] {
assert!(is_loopback(&url(host)), "{host}");
}
for host in ["http://127.0.0.2:1/", "http://example.com:1/", "http://0.0.0.0:1/"] {
assert!(!is_loopback(&url(host)), "{host}");
}
assert_eq!(origin_of(&url("http://[::1]:8765/x")).as_deref(), Some("http://[::1]:8765"));
}
/// What the tab says is what happened, and what a provider wrote in an error cannot become markup.
#[test]
fn the_landing_page_says_what_happened() {
let (status, _, signed_in) = landing("asana", &Ok(()));
assert_eq!(status, 200);
assert!(signed_in.contains("signed in to asana"), "{signed_in}");
let (status, title, refused) = landing(
"asana",
&Err(OAuthError::Refused("the server refused: <script>x</script>".into())),
);
assert_eq!(status, 400);
assert!(refused.contains("could not sign in"), "{refused}");
let page = luxe_core::oauth_loopback::page(title, &refused, "#b45309");
assert!(page.contains("&lt;script&gt;") && !page.contains("<script>"), "{page}");
}
/// https anywhere, plain http only on this machine, and nothing else.
#[test]
fn only_https_or_loopback_http_is_secure() {
for ok in [
"https://auth.example.com/t",
"http://127.0.0.1:9/t",
"http://localhost/t",
"http://[::1]:8/t",
] {
assert!(require_secure(ok, "the token endpoint").is_ok(), "{ok}");
}
for bad in ["http://auth.example.com/t", "ftp://auth.example.com/t", "not a url"] {
let error = require_secure(bad, "the token endpoint").unwrap_err();
assert!(matches!(error, OAuthError::Insecure(_)), "{error:?}");
assert!(error.to_string().contains("the token endpoint"), "{error}");
}
}
/// A loopback server answering every authorization-server metadata path with `doc`, and nothing
/// else; returns its base URL.
async fn serve_origin_metadata(doc: impl Fn(&str) -> serde_json::Value + Send + 'static) -> String {
use tokio::io::{AsyncReadExt, AsyncWriteExt};
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let base = format!("http://{}", listener.local_addr().unwrap());
let served = base.clone();
tokio::spawn(async move {
while let Ok((mut socket, _)) = listener.accept().await {
let mut request = [0u8; 4096];
let read = socket.read(&mut request).await.unwrap_or(0);
let request = String::from_utf8_lossy(&request[..read]).into_owned();
let (status, body) = if request.contains("/.well-known/oauth-authorization-server") {
("200 OK", doc(&served).to_string())
} else {
("404 Not Found", "{}".to_string())
};
let response = format!(
"HTTP/1.1 {status}\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\
Connection: close\r\n\r\n{body}",
body.len()
);
let _ = socket.write_all(response.as_bytes()).await;
}
});
base
}
/// The origin fallback gets the checks discovery gets: a document must name its issuer, and an
/// endpoint in it must be secure.
#[tokio::test]
async fn the_origin_fallback_is_checked_like_discovery() {
for (doc, refusal) in [
(
(|base: &str| serde_json::json!({"issuer": base, "token_endpoint": "http://evil.example/t"}))
as fn(&str) -> serde_json::Value,
"not https",
),
(
|base: &str| serde_json::json!({"token_endpoint": format!("{base}/t")}),
"names no issuer",
),
] {
let base = serve_origin_metadata(doc).await;
let client =
OAuthClient::new("legacy".into(), format!("{base}/v2/mcp"), OAuthConfig::default());
let error = client.auth_start("http://127.0.0.1:9/callback").await.unwrap_err().to_string();
assert!(error.contains(refusal), "{error}");
}
}
/// A server reached over plain http off this machine has nothing it says trusted: its metadata
/// could be anyone's, so sign-in stops before discovery.
#[tokio::test]
async fn a_plain_http_server_is_not_signed_in_to() {
let client = OAuthClient::new(
"plain".into(),
"http://mcp.example.test/v2/mcp".into(),
OAuthConfig::default(),
);
let error = client.auth_start("http://127.0.0.1:9/callback").await.unwrap_err().to_string();
assert!(error.contains("not https"), "{error}");
}
/// A sign-in stored before endpoints were checked is checked on refresh: its refresh token does
/// not go to a plain-http endpoint.
#[tokio::test]
async fn a_stored_plain_http_token_endpoint_is_not_refreshed_against() {
let dir = tempfile::tempdir().unwrap();
let store = TokenStore::new(dir.path().join("t.json"));
let token = StoredToken {
access_token: "AT-old".into(),
refresh_token: Some("RT-old".into()),
expires_at_secs: Some(1),
client_id: Some("1234".into()),
client_secret: None,
token_endpoint: Some("http://evil.example/t".into()),
resource: Some("https://mcp.example.test/v2/mcp".into()),
};
store.put("old", token).unwrap();
let client = OAuthClient::new(
"old".into(),
"https://mcp.example.test/v2/mcp".into(),
OAuthConfig::default(),
)
.with_store(store);
let TokenState::Unavailable(reason) = client.access_token().await else {
panic!("a plain-http endpoint must not be refreshed against");
};
assert!(reason.contains("not https"), "{reason}");
}
/// Two calls that find the token expired refresh it once: the second waits for the first and reads
/// what it stored. A server rotating refresh tokens would refuse the second use of the old one and
/// send the reader to sign in again for nothing.
#[tokio::test]
async fn two_concurrent_refreshes_hit_the_endpoint_once() {
use std::sync::atomic::{AtomicUsize, Ordering};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let base = format!("http://{}", listener.local_addr().unwrap());
let refreshes = std::sync::Arc::new(AtomicUsize::new(0));
let counted = refreshes.clone();
tokio::spawn(async move {
while let Ok((mut socket, _)) = listener.accept().await {
let mut request = [0u8; 4096];
let read = socket.read(&mut request).await.unwrap_or(0);
let request = String::from_utf8_lossy(&request[..read]).into_owned();
// the old refresh token is good once, as a rotating server has it
let body = if request.contains("refresh_token=RT-1")
&& counted.fetch_add(1, Ordering::SeqCst) == 0
{
r#"{"access_token":"AT-2","token_type":"Bearer","expires_in":3600,"refresh_token":"RT-2"}"#
} else {
r#"{"error":"invalid_grant"}"#
};
let status = if body.contains("AT-2") { "200 OK" } else { "400 Bad Request" };
let response = format!(
"HTTP/1.1 {status}\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\
Connection: close\r\n\r\n{body}",
body.len()
);
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
let _ = socket.write_all(response.as_bytes()).await;
}
});
let dir = tempfile::tempdir().unwrap();
let store = TokenStore::new(dir.path().join("t.json"));
let token = StoredToken {
access_token: "AT-1".into(),
refresh_token: Some("RT-1".into()),
expires_at_secs: Some(1),
client_id: Some("1234".into()),
client_secret: None,
token_endpoint: Some(format!("{base}/token")),
resource: Some("https://mcp.example.test/v2/mcp".into()),
};
store.put("rotating", token).unwrap();
let client = OAuthClient::new(
"rotating".into(),
"https://mcp.example.test/v2/mcp".into(),
OAuthConfig::default(),
)
.with_store(store);
let (one, two) = tokio::join!(client.access_token(), client.access_token());
for state in [one, two] {
let TokenState::Have(token) = state else { panic!("a refresh was refused") };
assert_eq!(token, "AT-2");
}
assert_eq!(refreshes.load(Ordering::SeqCst), 1);
}