use std::io::Read;
use std::path::Path;
use std::time::{Duration, Instant};
use serde_json::{Value, json};
use ureq::tls::{RootCerts, TlsConfig};
use crate::catalog::http::proxy;
use crate::diagnostics::log;
use crate::env::Env;
use crate::error::{CoreError, ErrorCode};
use crate::fs::Fs;
use crate::local_settings::{AddressCheckHosts, LocalSettings};
use crate::model::server::Transport;
use crate::secrets::classify::classify_import;
use crate::server_input::transport_from_url;
pub const REQUEST_TIMEOUT: Duration = Duration::from_secs(5);
pub const CHECK_TIMEOUT: Duration = Duration::from_secs(20);
pub const PROTOCOL_VERSION: &str = "2026-07-28";
pub const LEGACY_PROTOCOL_VERSION: &str = "2025-11-25";
const MAX_BODY: usize = 256 * 1024;
const MAX_REDIRECTS: usize = 3;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Outcome {
OAuth,
Token,
Open,
Unreachable,
Unexpected,
HostWaiting,
}
impl Outcome {
pub const fn as_str(self) -> &'static str {
match self {
Outcome::OAuth => "oauth",
Outcome::Token => "token",
Outcome::Open => "open",
Outcome::Unreachable => "unreachable",
Outcome::Unexpected => "unexpected",
Outcome::HostWaiting => "host_waiting",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OAuthInfo {
pub authorization_server: String,
pub dynamic_registration: bool,
pub client_id_metadata_document: bool,
pub registration_known: bool,
}
impl OAuthInfo {
pub fn registration_supported(&self) -> bool {
self.dynamic_registration || self.client_id_metadata_document
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AddressCheck {
pub outcome: Outcome,
pub host: String,
pub status: Option<u16>,
pub oauth: Option<OAuthInfo>,
pub detail: String,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HostConsent {
Allowed,
Denied,
Unanswered,
}
pub fn checked_url(url: &str) -> Result<url::Url, CoreError> {
let invalid = |why: &str| CoreError::new(ErrorCode::InvalidValue, why.to_owned());
let parsed = url::Url::parse(url.trim())
.map_err(|_| invalid("the address is not a URL; use https://host/path"))?;
if !matches!(parsed.scheme(), "http" | "https") || parsed.host().is_none() {
return Err(invalid("the address must start with https://"));
}
if !parsed.username().is_empty() || parsed.password().is_some() {
return Err(invalid(
"the address holds a user name or password; remove it (the check sends no credentials)",
));
}
if parsed.scheme() == "http" && !is_loopback(&parsed) {
return Err(invalid(
"the check uses https:// only (http:// only for localhost, 127.0.0.1 and ::1)",
));
}
let flagged = url.contains("${")
|| classify_import(None, url.trim()).is_some()
|| parsed
.query_pairs()
.any(|(key, value)| classify_import(Some(&key), &value).is_some());
if flagged {
return Err(invalid(
"the address holds what looks like a credential or a reference (${...}); remove it \
first: the check sends no credentials",
));
}
Ok(parsed)
}
fn is_loopback(url: &url::Url) -> bool {
match url.host() {
Some(url::Host::Domain(domain)) => domain.eq_ignore_ascii_case("localhost"),
Some(url::Host::Ipv4(ip)) => ip.is_loopback(),
Some(url::Host::Ipv6(ip)) => ip.is_loopback(),
None => false,
}
}
pub fn host_key(url: &url::Url) -> String {
let host = match url.host() {
Some(url::Host::Ipv6(ip)) => format!("[{ip}]"),
Some(host) => host.to_string().to_ascii_lowercase(),
None => String::new(),
};
match url.port() {
Some(port) => format!("{host}:{port}"),
None => host,
}
}
fn hosts_of(settings: &LocalSettings) -> AddressCheckHosts {
settings.address_check_hosts.clone().unwrap_or_default()
}
pub fn consent(fs: &dyn Fs, state_dir: &Path, host: &str) -> Result<HostConsent, CoreError> {
let hosts = hosts_of(&LocalSettings::load(fs, state_dir)?);
Ok(if hosts.allowed.iter().any(|h| h == host) {
HostConsent::Allowed
} else if hosts.denied.iter().any(|h| h == host) {
HostConsent::Denied
} else {
HostConsent::Unanswered
})
}
pub fn answer_host(
fs: &dyn Fs,
state_dir: &Path,
host: &str,
allow: bool,
) -> Result<(), CoreError> {
let host = host.trim().to_ascii_lowercase();
if host.is_empty() || host.contains(['/', ' ']) {
return Err(CoreError::new(
ErrorCode::InvalidValue,
format!("{host:?} is not a host name"),
));
}
edit_hosts(fs, state_dir, |hosts| {
hosts.allowed.retain(|h| *h != host);
hosts.denied.retain(|h| *h != host);
if allow {
hosts.allowed.push(host.clone());
} else {
hosts.denied.push(host.clone());
}
})
}
pub fn clear_host(fs: &dyn Fs, state_dir: &Path, host: &str) -> Result<(), CoreError> {
let host = host.trim().to_ascii_lowercase();
edit_hosts(fs, state_dir, |hosts| {
hosts.allowed.retain(|h| *h != host);
hosts.denied.retain(|h| *h != host);
})
}
fn edit_hosts(
fs: &dyn Fs,
state_dir: &Path,
edit: impl FnOnce(&mut AddressCheckHosts),
) -> Result<(), CoreError> {
let mut settings = LocalSettings::load(fs, state_dir)?;
let mut hosts = hosts_of(&settings);
let before = hosts.clone();
edit(&mut hosts);
if hosts == before {
return Ok(());
}
settings.address_check_hosts =
(!hosts.allowed.is_empty() || !hosts.denied.is_empty()).then_some(hosts);
settings.save(fs, state_dir)
}
pub fn hosts(fs: &dyn Fs, state_dir: &Path) -> Result<Vec<(String, bool)>, CoreError> {
let hosts = hosts_of(&LocalSettings::load(fs, state_dir)?);
let mut out: Vec<(String, bool)> = hosts
.allowed
.into_iter()
.map(|h| (h, true))
.chain(hosts.denied.into_iter().map(|h| (h, false)))
.collect();
out.sort();
out.dedup_by(|a, b| a.0 == b.0);
Ok(out)
}
pub fn check(
env: &Env,
fs: &dyn Fs,
state_dir: &Path,
url: &str,
) -> Result<AddressCheck, CoreError> {
let parsed = checked_url(url)?;
let host = host_key(&parsed);
match consent(fs, state_dir, &host)? {
HostConsent::Allowed => {
let denied = hosts_of(&LocalSettings::load(fs, state_dir)?).denied;
Ok(probe(env, &parsed, REQUEST_TIMEOUT, CHECK_TIMEOUT, denied))
}
answer => Ok(AddressCheck {
outcome: Outcome::HostWaiting,
detail: if answer == HostConsent::Denied {
format!("You chose not to check addresses on {host}. Allow it to check this one.")
} else {
format!("Checking sends a request to {host}. Allow it first.")
},
host,
status: None,
oauth: None,
}),
}
}
pub fn probe(
env: &Env,
url: &url::Url,
per_request: Duration,
total: Duration,
denied: Vec<String>,
) -> AddressCheck {
let client = Client::new(
env,
per_request,
Instant::now() + total,
is_loopback(url),
denied,
);
client.run(url)
}
fn is_private_ip(url: &url::Url) -> bool {
match url.host() {
Some(url::Host::Ipv4(ip)) => {
ip.is_private() || ip.is_link_local() || ip.is_loopback() || ip.is_unspecified()
}
Some(url::Host::Ipv6(ip)) => {
ip.is_loopback()
|| ip.is_unspecified()
|| ip.is_unique_local()
|| ip.is_unicast_link_local()
|| ip
.to_ipv4_mapped()
.is_some_and(|v4| v4.is_private() || v4.is_loopback())
}
Some(url::Host::Domain(domain)) => domain.eq_ignore_ascii_case("localhost"),
None => false,
}
}
#[derive(Debug, Default)]
struct Answer {
status: u16,
challenges: Vec<String>,
content_type: String,
body: Vec<u8>,
}
#[derive(Debug)]
enum Failure {
Unreachable(String),
Refused(String),
}
struct Client {
https: ureq::Agent,
loopback: ureq::Agent,
https_problem: Option<String>,
per_request: Duration,
deadline: Instant,
local: bool,
denied: Vec<String>,
}
impl Client {
fn new(
env: &Env,
per_request: Duration,
deadline: Instant,
local: bool,
denied: Vec<String>,
) -> Self {
let agent = |proxy: Option<ureq::Proxy>, https_only: bool| {
ureq::Agent::config_builder()
.http_status_as_error(false)
.timeout_connect(Some(per_request))
.timeout_global(Some(per_request))
.https_only(https_only)
.max_redirects(0)
.user_agent(format!("Surjection/{}", env!("CARGO_PKG_VERSION")))
.proxy(proxy)
.tls_config(
TlsConfig::builder()
.root_certs(RootCerts::PlatformVerifier)
.build(),
)
.build()
.new_agent()
};
let https = proxy(
env,
&["HTTPS_PROXY", "https_proxy", "ALL_PROXY", "all_proxy"],
);
let (https_proxy, https_problem) = match https {
Ok(proxy) => (proxy, None),
Err(why) => (None, Some(why)),
};
Self {
https: agent(https_proxy, true),
loopback: agent(None, false),
https_problem,
per_request,
deadline,
local,
denied,
}
}
fn allowed(&self, url: &url::Url) -> bool {
url.scheme() == "https" || (url.scheme() == "http" && is_loopback(url))
}
fn send(
&self,
url: &url::Url,
body: Option<&Value>,
headers: &[(&str, &str)],
) -> Result<Answer, Failure> {
let mut current = url.clone();
for _ in 0..=MAX_REDIRECTS {
let (answer, location) = self.send_once(¤t, body, headers)?;
let redirect = matches!(answer.status, 301 | 302 | 303 | 307 | 308);
let Some(location) = location.filter(|_| redirect) else {
return Ok(answer);
};
let next = current
.join(&location)
.map_err(|_| Failure::Refused("it redirected to an invalid address".to_owned()))?;
if next.origin() != current.origin() {
return Err(Failure::Refused(format!(
"it redirected to another host ({}), which the check does not follow",
host_key(&next)
)));
}
if body.is_some() && !matches!(answer.status, 307 | 308) {
return Err(Failure::Refused(format!(
"it answered the request with a redirect ({})",
answer.status
)));
}
current = next;
}
Err(Failure::Refused("too many redirects".to_owned()))
}
fn send_once(
&self,
url: &url::Url,
body: Option<&Value>,
headers: &[(&str, &str)],
) -> Result<(Answer, Option<String>), Failure> {
if !self.allowed(url) {
return Err(Failure::Refused(
"the address must use https:// (http:// only for localhost)".to_owned(),
));
}
let remaining = self.deadline.saturating_duration_since(Instant::now());
if remaining.is_zero() {
return Err(Failure::Unreachable("the check ran out of time".to_owned()));
}
let timeout = remaining.min(self.per_request);
let agent = if url.scheme() == "http" {
&self.loopback
} else {
if let Some(why) = &self.https_problem {
return Err(Failure::Unreachable(why.clone()));
}
&self.https
};
let started = Instant::now();
let result = match body {
Some(body) => {
let mut request = agent
.post(url.as_str())
.config()
.timeout_global(Some(timeout))
.build()
.header("Content-Type", "application/json");
for (name, value) in headers {
request = request.header(*name, *value);
}
request.send(body.to_string())
}
None => {
let mut request = agent
.get(url.as_str())
.config()
.timeout_global(Some(timeout))
.build();
for (name, value) in headers {
request = request.header(*name, *value);
}
request.call()
}
};
let response = match result {
Ok(response) => response,
Err(err) => {
let failure = transport_failure(err);
log::http(
"address_check",
url.as_str(),
Err(&CoreError::new(ErrorCode::IoError, "no answer")),
started,
);
return Err(failure);
}
};
let status = response.status().as_u16();
log::http("address_check", url.as_str(), Ok(status), started);
let header = |name: &str| {
response
.headers()
.get_all(name)
.iter()
.filter_map(|value| value.to_str().ok().map(str::to_owned))
.collect::<Vec<_>>()
};
let challenges = header("www-authenticate");
let content_type = header("content-type")
.into_iter()
.next()
.unwrap_or_default()
.to_ascii_lowercase();
let location = header("location").into_iter().next();
let stream = content_type.starts_with("text/event-stream");
let body = read_body(response.into_body().into_reader(), stream);
Ok((
Answer {
status,
challenges,
content_type,
body,
},
location,
))
}
fn run(&self, url: &url::Url) -> AddressCheck {
let host = host_key(url);
let result = |outcome, status, oauth, detail: String| AddressCheck {
outcome,
host: host.clone(),
status,
oauth,
detail,
};
let sse = transport_from_url(url.as_str()) == Transport::Sse;
let first = if sse {
self.send(url, None, &[("Accept", "text/event-stream")])
} else {
self.send(url, Some(&discover_request()), &MODERN_HEADERS)
};
let answer = match first {
Ok(answer) => answer,
Err(Failure::Unreachable(why)) => {
return result(
Outcome::Unreachable,
None,
None,
format!("{host} could not be reached: {why}."),
);
}
Err(Failure::Refused(why)) => {
return result(
Outcome::Unexpected,
None,
None,
format!("Not checked: {why}."),
);
}
};
if let Some(check) = self.classify(url, &answer, sse) {
return check;
}
if !sse && matches!(answer.status, 400 | 404 | 405) && !modern_error(&answer) {
let legacy = self.send(url, Some(&initialize_request()), &LEGACY_HEADERS);
match legacy {
Ok(legacy) => {
if let Some(check) = self.classify(url, &legacy, false) {
return check;
}
return result(
Outcome::Unexpected,
Some(legacy.status),
None,
format!(
"{host} answered {} to an MCP request, without asking for credentials. \
Check the address (the path too).",
legacy.status
),
);
}
Err(Failure::Unreachable(why)) => {
return result(
Outcome::Unreachable,
None,
None,
format!("{host} could not be reached: {why}."),
);
}
Err(Failure::Refused(why)) => {
return result(
Outcome::Unexpected,
Some(answer.status),
None,
format!("Not checked: {why}."),
);
}
}
}
result(
Outcome::Unexpected,
Some(answer.status),
None,
format!(
"{host} answered {} to an MCP request, without asking for credentials. Check the \
address (the path too).",
answer.status
),
)
}
fn classify(&self, url: &url::Url, answer: &Answer, sse: bool) -> Option<AddressCheck> {
let host = host_key(url);
if answer.status == 401 || (answer.status == 403 && !answer.challenges.is_empty()) {
return Some(self.sign_in(url, answer));
}
let answered = if sse {
(200..300).contains(&answer.status) && sse_endpoint(&answer.body)
} else {
((200..300).contains(&answer.status) && json_rpc_answer(answer).is_some())
|| modern_error(answer)
};
answered.then(|| {
let name = json_rpc_answer(answer)
.as_ref()
.and_then(server_name)
.map(|name| format!(" ({name})"))
.unwrap_or_default();
AddressCheck {
outcome: Outcome::Open,
host: host.clone(),
status: Some(answer.status),
oauth: None,
detail: format!("{host} answered as an MCP server{name} without credentials."),
}
})
}
fn sign_in(&self, url: &url::Url, answer: &Answer) -> AddressCheck {
let host = host_key(url);
let challenge = Challenge::parse(&answer.challenges);
let mut notes: Vec<String> = Vec::new();
let mut candidates: Vec<url::Url> = Vec::new();
if let Some(pointer) = &challenge.resource_metadata {
match url.join(pointer) {
Ok(target) if target.origin() == url.origin() => candidates.push(target),
Ok(target) => notes.push(format!(
"its resource_metadata points to another host ({}), which the check does not \
contact",
host_key(&target)
)),
Err(_) => notes.push("its resource_metadata is not a valid address".to_owned()),
}
}
candidates.extend(well_known(url, "oauth-protected-resource"));
let metadata = candidates.iter().find_map(|candidate| {
let answer = self
.send(candidate, None, &[("Accept", "application/json")])
.ok()?;
let doc = json_body(&answer)?;
let valid = (200..300).contains(&answer.status) && resource_matches(&doc, url);
valid.then_some(doc)
});
let authorization_server = metadata.as_ref().and_then(|doc| {
doc.get("authorization_servers")?
.as_array()?
.iter()
.filter_map(Value::as_str)
.next()
.map(str::to_owned)
});
let status = Some(answer.status);
let Some(authorization_server) = authorization_server else {
let schemes = if challenge.schemes.is_empty() {
String::new()
} else {
format!(" ({})", challenge.schemes.join(", "))
};
let notes = if notes.is_empty() {
String::new()
} else {
format!(" Note: {}.", notes.join("; "))
};
return AddressCheck {
outcome: Outcome::Token,
host: host.clone(),
status,
oauth: None,
detail: format!(
"{host} asks for credentials{schemes} and publishes no OAuth metadata: it \
needs a token, usually in an Authorization header kept as a secret.{notes}"
),
};
};
let (info, detail) = self.authorization_server(&authorization_server);
AddressCheck {
outcome: Outcome::OAuth,
host,
status,
oauth: Some(info),
detail,
}
}
fn authorization_server(&self, issuer: &str) -> (OAuthInfo, String) {
let mut info = OAuthInfo {
authorization_server: issuer.to_owned(),
dynamic_registration: false,
client_id_metadata_document: false,
registration_known: false,
};
let parsed = url::Url::parse(issuer).ok().filter(|parsed| {
parsed.scheme() == "https"
|| (self.local && parsed.scheme() == "http" && is_loopback(parsed))
});
let Some(parsed) = parsed else {
return (
info,
format!(
"Signs in with OAuth. Its authorization server ({issuer}) is not an https:// \
address, so the check did not read its metadata."
),
);
};
let as_host = host_key(&parsed);
if self.denied.contains(&as_host) {
return (
info,
format!(
"Signs in with OAuth through {as_host}. You chose not to contact that host, \
so whether clients can register themselves is not known."
),
);
}
if is_private_ip(&parsed) && !self.local {
return (
info,
format!(
"Signs in with OAuth through {as_host}, a private address the check does not \
contact, so whether clients can register themselves is not known."
),
);
}
let found = authorization_server_urls(&parsed)
.into_iter()
.find_map(|candidate| {
let answer = self
.send(&candidate, None, &[("Accept", "application/json")])
.ok()?;
let doc = json_body(&answer)?;
let issued = doc.get("issuer").and_then(Value::as_str)?;
((200..300).contains(&answer.status) && same_identifier(issued, issuer))
.then_some(doc)
});
let Some(doc) = found else {
return (
info,
format!(
"Signs in with OAuth through {as_host}. Its authorization server metadata \
could not be read, so whether clients can register themselves is not known."
),
);
};
info.registration_known = true;
info.dynamic_registration = doc
.get("registration_endpoint")
.and_then(Value::as_str)
.is_some_and(|endpoint| !endpoint.is_empty());
info.client_id_metadata_document = doc
.get("client_id_metadata_document_supported")
.and_then(Value::as_bool)
.unwrap_or(false);
let how = match (info.client_id_metadata_document, info.dynamic_registration) {
(true, true) => {
"Clients can register themselves (Client ID Metadata Documents and dynamic client \
registration)."
}
(true, false) => "Clients can register themselves (Client ID Metadata Documents).",
(false, true) => "Clients can register themselves (dynamic client registration).",
(false, false) => {
"It offers no self-registration: a client may need a client id from the server's \
owner."
}
};
(
info,
format!(
"Signs in with OAuth through {as_host}. {how} Each client signs in on its own."
),
)
}
}
const MODERN_HEADERS: [(&str, &str); 3] = [
("Accept", "application/json, text/event-stream"),
("MCP-Protocol-Version", PROTOCOL_VERSION),
("Mcp-Method", "server/discover"),
];
const LEGACY_HEADERS: [(&str, &str); 1] = [("Accept", "application/json, text/event-stream")];
fn client_info() -> Value {
json!({"name": "Surjection", "version": env!("CARGO_PKG_VERSION")})
}
fn discover_request() -> Value {
json!({
"jsonrpc": "2.0",
"id": 1,
"method": "server/discover",
"params": {
"_meta": {
"io.modelcontextprotocol/protocolVersion": PROTOCOL_VERSION,
"io.modelcontextprotocol/clientCapabilities": {},
"io.modelcontextprotocol/clientInfo": client_info(),
}
}
})
}
fn initialize_request() -> Value {
json!({
"jsonrpc": "2.0",
"id": 1,
"method": "initialize",
"params": {
"protocolVersion": LEGACY_PROTOCOL_VERSION,
"capabilities": {},
"clientInfo": client_info(),
}
})
}
fn transport_failure(err: ureq::Error) -> Failure {
let why = match err {
ureq::Error::Timeout(_) => "it did not answer in time".to_owned(),
ureq::Error::HostNotFound => "the host was not found".to_owned(),
ureq::Error::ConnectionFailed => "the connection failed".to_owned(),
ureq::Error::RequireHttpsOnly(_) => {
return Failure::Refused("it needs an address without encryption".to_owned());
}
ureq::Error::Io(err) => format!("the connection failed ({})", err.kind()),
other => format!("the secure connection failed or was cut ({other})"),
};
Failure::Unreachable(why)
}
fn read_body(mut reader: impl Read, stream: bool) -> Vec<u8> {
let mut body = Vec::new();
let mut buf = [0u8; 4096];
while body.len() < MAX_BODY {
match reader.read(&mut buf) {
Ok(0) | Err(_) => break,
Ok(n) => {
body.extend_from_slice(&buf[..n.min(MAX_BODY - body.len())]);
if stream && first_event(&body).is_some() {
break;
}
}
}
}
body
}
fn first_event(body: &[u8]) -> Option<(String, String)> {
let text = String::from_utf8_lossy(body).replace("\r\n", "\n");
let mut event = String::new();
let mut data: Vec<&str> = Vec::new();
let mut lines = text.split('\n').peekable();
while let Some(line) = lines.next() {
if line.is_empty() {
if data.iter().any(|d| !d.is_empty()) {
return Some((event, data.join("\n")));
}
event.clear();
data.clear();
continue;
}
lines.peek()?;
if let Some(value) = line.strip_prefix("event:") {
event = value.trim().to_owned();
} else if let Some(value) = line.strip_prefix("data:") {
data.push(value.strip_prefix(' ').unwrap_or(value));
}
}
None
}
fn json_body(answer: &Answer) -> Option<Value> {
if answer.content_type.starts_with("text/event-stream") {
let (_, data) = first_event(&answer.body)?;
serde_json::from_str(&data).ok()
} else {
serde_json::from_slice(&answer.body).ok()
}
}
fn json_rpc_answer(answer: &Answer) -> Option<Value> {
json_body(answer).filter(|doc| {
doc.get("jsonrpc").and_then(Value::as_str) == Some("2.0")
&& (doc.get("result").is_some() || doc.get("error").is_some())
})
}
fn modern_error(answer: &Answer) -> bool {
let code = json_rpc_answer(answer).and_then(|doc| doc.get("error")?.get("code")?.as_i64());
match code {
Some(-32022..=-32020) => true,
Some(-32601) => answer.status == 404,
_ => false,
}
}
fn server_name(doc: &Value) -> Option<String> {
let result = doc.get("result")?;
let info = result.get("serverInfo").or_else(|| {
result
.get("_meta")?
.get("io.modelcontextprotocol/serverInfo")
})?;
let name = info.get("name")?.as_str()?;
let version = info.get("version").and_then(Value::as_str);
let text = match version {
Some(version) => format!("{name} {version}"),
None => name.to_owned(),
};
let clean: String = text.chars().filter(|c| !c.is_control()).take(80).collect();
(!clean.trim().is_empty()).then_some(clean)
}
fn sse_endpoint(body: &[u8]) -> bool {
first_event(body).is_some_and(|(event, _)| event == "endpoint")
}
fn well_known(url: &url::Url, suffix: &str) -> Vec<url::Url> {
let path = url.path().trim_end_matches('/');
let mut out = Vec::new();
let mut base = url.clone();
base.set_query(None);
base.set_fragment(None);
if !path.is_empty() {
let mut inserted = base.clone();
inserted.set_path(&format!("/.well-known/{suffix}{path}"));
out.push(inserted);
}
let mut root = base;
root.set_path(&format!("/.well-known/{suffix}"));
out.push(root);
out
}
fn authorization_server_urls(issuer: &url::Url) -> Vec<url::Url> {
let path = issuer.path().trim_end_matches('/');
let mut base = issuer.clone();
base.set_query(None);
base.set_fragment(None);
let at = |p: String| {
let mut url = base.clone();
url.set_path(&p);
url
};
if path.is_empty() {
vec![
at("/.well-known/oauth-authorization-server".to_owned()),
at("/.well-known/openid-configuration".to_owned()),
]
} else {
vec![
at(format!("/.well-known/oauth-authorization-server{path}")),
at(format!("/.well-known/openid-configuration{path}")),
at(format!("{path}/.well-known/openid-configuration")),
]
}
}
fn resource_matches(doc: &Value, url: &url::Url) -> bool {
let Some(resource) = doc.get("resource").and_then(Value::as_str) else {
return false;
};
let Ok(resource) = url::Url::parse(resource) else {
return false;
};
if resource.origin() != url.origin() {
return false;
}
let wanted = url.path().trim_end_matches('/');
let given = resource.path().trim_end_matches('/');
given.is_empty() || wanted == given || wanted.starts_with(&format!("{given}/"))
}
fn same_identifier(a: &str, b: &str) -> bool {
a.trim_end_matches('/') == b.trim_end_matches('/')
}
#[derive(Debug, Default, PartialEq, Eq)]
struct Challenge {
schemes: Vec<String>,
resource_metadata: Option<String>,
}
impl Challenge {
fn parse(headers: &[String]) -> Self {
let mut challenge = Self::default();
for header in headers {
for piece in split_outside_quotes(header) {
let piece = piece.trim();
let (first, rest) = piece.split_once(' ').unwrap_or((piece, ""));
let param = if first.contains('=') {
piece
} else {
if !first.is_empty() && !challenge.schemes.iter().any(|s| s == first) {
challenge.schemes.push(first.to_owned());
}
rest.trim()
};
if let Some((name, value)) = param.split_once('=')
&& name.trim().eq_ignore_ascii_case("resource_metadata")
{
let value = value.trim().trim_matches('"').to_owned();
if !value.is_empty() && challenge.resource_metadata.is_none() {
challenge.resource_metadata = Some(value);
}
}
}
}
challenge
}
}
fn split_outside_quotes(text: &str) -> Vec<&str> {
let mut out = Vec::new();
let mut start = 0;
let mut quoted = false;
let mut escaped = false;
for (i, c) in text.char_indices() {
match c {
_ if escaped => escaped = false,
'\\' if quoted => escaped = true,
'"' => quoted = !quoted,
',' if !quoted => {
out.push(&text[start..i]);
start = i + 1;
}
_ => {}
}
}
out.push(&text[start..]);
out
}
#[cfg(test)]
mod tests;