swarmctl login: find the sso provider from the gateway's published metadata
This commit is contained in:
parent
c1851f37cc
commit
cd040afa0e
6 changed files with 421 additions and 16 deletions
|
|
@ -148,6 +148,21 @@ it nothing to verify. The queue's responder introspects instead — a
|
||||||
different question asked of the same token, and the reason both
|
different question asked of the same token, and the reason both
|
||||||
`/api/oidc/introspection` and `/jwks.json` have to stay reachable.
|
`/api/oidc/introspection` and `/jwks.json` have to stay reachable.
|
||||||
|
|
||||||
|
## How `swarmctl login` finds authelia
|
||||||
|
|
||||||
|
The client knows only the swarm's domain, not the auth domain. The swarm
|
||||||
|
publishes the link as OAuth protected resource metadata (RFC 9728). The
|
||||||
|
gateway's `/api/` answers a request with no login with a 401 whose
|
||||||
|
`WWW-Authenticate` challenge carries `resource_metadata`. That parameter names
|
||||||
|
`https://<swarm>/.well-known/oauth-protected-resource/api/`, a document
|
||||||
|
served with no `auth_request`. It lists the API as `resource` and authelia as
|
||||||
|
the `authorization_servers`.
|
||||||
|
|
||||||
|
The client reads the document from the swarm's own origin only. It refuses a
|
||||||
|
`resource` other than the audience it asks for, and a server that isn't
|
||||||
|
https. `swarm-ui.nix` declares the metadata beside the challenge that names
|
||||||
|
it.
|
||||||
|
|
||||||
## Machine callers must fail closed
|
## Machine callers must fail closed
|
||||||
|
|
||||||
⚠️ **An error page that answers `200` is a security bug, not a cosmetic
|
⚠️ **An error page that answers `200` is a security bug, not a cosmetic
|
||||||
|
|
|
||||||
|
|
@ -32,6 +32,17 @@ let
|
||||||
auth_request_set $target_url $scheme://$http_host$request_uri;
|
auth_request_set $target_url $scheme://$http_host$request_uri;
|
||||||
'';
|
'';
|
||||||
loginRedirect = "https://${autheliaCfg.domain}/?rd=$target_url";
|
loginRedirect = "https://${autheliaCfg.domain}/?rd=$target_url";
|
||||||
|
|
||||||
|
# What `swarmctl login` reads to find the swarm's SSO provider (RFC 9728): the
|
||||||
|
# `/api/` 401 names this document in its challenge, and the document names the
|
||||||
|
# authorization server. `resource` is the audience a `swarmctl` token carries
|
||||||
|
# (`swarmctl/src/remote.rs`, `swarm-authelia.nix`).
|
||||||
|
protectedResourcePath = "/.well-known/oauth-protected-resource/api/";
|
||||||
|
protectedResource = builtins.toJSON {
|
||||||
|
resource = "https://${apex}/api/";
|
||||||
|
authorization_servers = [ "https://${autheliaCfg.domain}" ];
|
||||||
|
};
|
||||||
|
challenge = ''Bearer realm="swarm", resource_metadata="https://${apex}${protectedResourcePath}"'';
|
||||||
swarmAuthRequest = ''
|
swarmAuthRequest = ''
|
||||||
${authRequest}
|
${authRequest}
|
||||||
error_page 401 =302 ${loginRedirect};
|
error_page 401 =302 ${loginRedirect};
|
||||||
|
|
@ -334,15 +345,23 @@ in
|
||||||
${gatewayCfg.lib.securityHeaders}
|
${gatewayCfg.lib.securityHeaders}
|
||||||
if ($http_authorization) {
|
if ($http_authorization) {
|
||||||
${gatewayCfg.lib.securityHeaders}
|
${gatewayCfg.lib.securityHeaders}
|
||||||
add_header WWW-Authenticate 'Bearer realm="swarm"' always;
|
add_header WWW-Authenticate '${challenge}' always;
|
||||||
return 401;
|
return 401;
|
||||||
}
|
}
|
||||||
if ($http_accept ~* "text/html") {
|
if ($http_accept ~* "text/html") {
|
||||||
return 302 ${loginRedirect};
|
return 302 ${loginRedirect};
|
||||||
}
|
}
|
||||||
add_header WWW-Authenticate 'Bearer realm="swarm"' always;
|
add_header WWW-Authenticate '${challenge}' always;
|
||||||
return 401;
|
return 401;
|
||||||
'';
|
'';
|
||||||
|
# The document the challenge names. Public by design: a client reads it
|
||||||
|
# before it has a login, and it holds only the names of the swarm's own
|
||||||
|
# API and its SSO provider.
|
||||||
|
"= ${protectedResourcePath}".extraConfig = ''
|
||||||
|
${gatewayCfg.lib.securityHeaders}
|
||||||
|
default_type application/json;
|
||||||
|
return 200 '${protectedResource}';
|
||||||
|
'';
|
||||||
# ⚠️ THE ONE PROXIED LOCATION ON THIS VHOST WITH NO `auth_request`,
|
# ⚠️ THE ONE PROXIED LOCATION ON THIS VHOST WITH NO `auth_request`,
|
||||||
# and that is deliberate rather than an omission.
|
# and that is deliberate rather than an omission.
|
||||||
#
|
#
|
||||||
|
|
|
||||||
|
|
@ -729,16 +729,37 @@ let
|
||||||
api = l."/api/".extraConfig;
|
api = l."/api/".extraConfig;
|
||||||
refused = l."@swarm_api_unauthorized".extraConfig;
|
refused = l."@swarm_api_unauthorized".extraConfig;
|
||||||
sec = allLocal.services.hyperhive.gateway.lib.securityHeaders;
|
sec = allLocal.services.hyperhive.gateway.lib.securityHeaders;
|
||||||
|
challenge = ''Bearer realm="swarm", resource_metadata="https://t.local/.well-known/oauth-protected-resource/api/"'';
|
||||||
in
|
in
|
||||||
lib.hasInfix "error_page 401 = @swarm_api_unauthorized;" api
|
lib.hasInfix "error_page 401 = @swarm_api_unauthorized;" api
|
||||||
&& !(lib.hasInfix "=302" api)
|
&& !(lib.hasInfix "=302" api)
|
||||||
&& lib.hasInfix ''proxy_set_header Authorization "";'' api
|
&& lib.hasInfix ''proxy_set_header Authorization "";'' api
|
||||||
&& lib.hasInfix "if ($http_authorization) {\n ${sec}\n add_header WWW-Authenticate 'Bearer realm=\"swarm\"' always;\n return 401;\n}" refused
|
&& lib.hasInfix "if ($http_authorization) {\n ${sec}\n add_header WWW-Authenticate '${challenge}' always;\n return 401;\n}" refused
|
||||||
&& lib.hasInfix "if ($http_accept ~* \"text/html\") {\n return 302 https://auth.t.local/?rd=$target_url;\n}" refused
|
&& lib.hasInfix "if ($http_accept ~* \"text/html\") {\n return 302 https://auth.t.local/?rd=$target_url;\n}" refused
|
||||||
&& lib.hasPrefix sec refused
|
&& lib.hasPrefix sec refused
|
||||||
&& lib.hasInfix "}\nadd_header WWW-Authenticate 'Bearer realm=\"swarm\"' always;\nreturn 401;" refused
|
&& lib.hasInfix "}\nadd_header WWW-Authenticate '${challenge}' always;\nreturn 401;" refused
|
||||||
&& lib.hasInfix "error_page 401 =302 https://auth.t.local/" l."/".extraConfig;
|
&& lib.hasInfix "error_page 401 =302 https://auth.t.local/" l."/".extraConfig;
|
||||||
}
|
}
|
||||||
|
{
|
||||||
|
# `swarmctl login` finds the SSO provider from the `/api/` challenge's
|
||||||
|
# `resource_metadata` document. The document is served with no
|
||||||
|
# `auth_request`, as JSON naming the API as `resource` and authelia as
|
||||||
|
# its authorization server. The `/` clause is the control: the page
|
||||||
|
# route carries an `auth_request`, so a pass means the two differ.
|
||||||
|
# Turned red by dropping `authorization_servers` from `protectedResource`
|
||||||
|
# in `swarm-ui.nix`.
|
||||||
|
name = "the swarm vhost publishes its API's authorization server without a login";
|
||||||
|
ok =
|
||||||
|
let
|
||||||
|
l = allLocal.services.nginx.virtualHosts."t.local".locations;
|
||||||
|
doc = l."= /.well-known/oauth-protected-resource/api/".extraConfig;
|
||||||
|
in
|
||||||
|
lib.hasInfix "default_type application/json;" doc
|
||||||
|
&& lib.hasInfix ''"resource":"https://t.local/api/"'' doc
|
||||||
|
&& lib.hasInfix ''"authorization_servers":["https://auth.t.local"]'' doc
|
||||||
|
&& !(lib.hasInfix "auth_request" doc)
|
||||||
|
&& lib.hasInfix "auth_request" l."/".extraConfig;
|
||||||
|
}
|
||||||
{
|
{
|
||||||
# authelia 4.39.20 refuses a bearer-scoped public client missing any of
|
# authelia 4.39.20 refuses a bearer-scoped public client missing any of
|
||||||
# these at startup, after a green deploy; and a public client must not
|
# these at startup, after a green deploy; and a public client must not
|
||||||
|
|
|
||||||
|
|
@ -333,6 +333,36 @@ with subtest(
|
||||||
assert status != 0 and f"not logged in to {SWARM_URL}" in out, (status, out)
|
assert status != 0 and f"not logged in to {SWARM_URL}" in out, (status, out)
|
||||||
machine.succeed(f"{VIA_SOCKET} swarmctl schedule list")
|
machine.succeed(f"{VIA_SOCKET} swarmctl schedule list")
|
||||||
|
|
||||||
|
with subtest("swarmctl login discovers the swarm's SSO provider from the gateway"):
|
||||||
|
# The swarm's own CA signs the gateway's leaf. A VM has no browser, so the login runs to the
|
||||||
|
# point where it prints the authorization URL and waits for the answer, which the timeout ends.
|
||||||
|
# Reaching that URL takes the gateway's 401 challenge, its published metadata, and authelia
|
||||||
|
# accepting the pushed authorization request.
|
||||||
|
ca = "/var/lib/hive-tls/swarm-services-root.pem"
|
||||||
|
auth = f"https://auth.{SWARM_URL.removeprefix('https://')}"
|
||||||
|
challenge = machine.succeed(
|
||||||
|
f"curl --silent --cacert {ca} -D - -o /dev/null {SWARM_URL}/api/"
|
||||||
|
)
|
||||||
|
assert challenge.startswith("HTTP/") and " 401" in challenge.splitlines()[0], (
|
||||||
|
challenge
|
||||||
|
)
|
||||||
|
assert (
|
||||||
|
f'resource_metadata="{SWARM_URL}/.well-known/oauth-protected-resource/api/"'
|
||||||
|
in challenge
|
||||||
|
), challenge
|
||||||
|
metadata = machine.succeed(
|
||||||
|
f"curl --fail --silent --cacert {ca} {SWARM_URL}/.well-known/oauth-protected-resource/api/"
|
||||||
|
)
|
||||||
|
assert json.loads(metadata) == {
|
||||||
|
"resource": f"{SWARM_URL}/api/",
|
||||||
|
"authorization_servers": [auth],
|
||||||
|
}, metadata
|
||||||
|
status, out = machine.execute(
|
||||||
|
f"timeout 30 swarmctl --swarm {SWARM_URL} --ca-file {ca} login --callback-port 8765 2>&1"
|
||||||
|
)
|
||||||
|
assert status == 124, (status, out)
|
||||||
|
assert f"{auth}/api/oidc/authorization?client_id=swarmctl&request_uri=" in out, out
|
||||||
|
|
||||||
with subtest("the agents are deployed and need a login"):
|
with subtest("the agents are deployed and need a login"):
|
||||||
settle(
|
settle(
|
||||||
f"curl --fail --silent --unix-socket {SOCKET} {API}/api/agents/status "
|
f"curl --fail --silent --unix-socket {SOCKET} {API}/api/agents/status "
|
||||||
|
|
|
||||||
|
|
@ -299,6 +299,10 @@ controller's socket serves nginx alone. Both are defaults, so a value you set wi
|
||||||
route sends no `Remote-User`, so the routes that name the sender answer 401. Nothing in setup needs it:
|
route sends no `Remote-User`, so the routes that name the sender answer 401. Nothing in setup needs it:
|
||||||
`swarmctl login` needs only authelia and your SSO account, both there by step 2.
|
`swarmctl login` needs only authelia and your SSO account, both there by step 2.
|
||||||
|
|
||||||
|
`login` finds the swarm's SSO provider itself: the gateway's 401 at `/api/`
|
||||||
|
names a public metadata document (RFC 9728) that names authelia, so `--swarm`
|
||||||
|
is the only thing you give it.
|
||||||
|
|
||||||
`login` opens the swarm's SSO login in a browser and receives the result on a loopback port, so
|
`login` opens the swarm's SSO login in a browser and receives the result on a loopback port, so
|
||||||
run it on the machine whose browser you use. It prints the port. On a host with no browser, forward
|
run it on the machine whose browser you use. It prints the port. On a host with no browser, forward
|
||||||
a port from the machine that has one, then give the login that port:
|
a port from the machine that has one, then give the login that port:
|
||||||
|
|
|
||||||
|
|
@ -6,6 +6,9 @@
|
||||||
//! the code arrives as a browser form POST to a loopback port this process
|
//! the code arrives as a browser form POST to a loopback port this process
|
||||||
//! listens on. The registered redirect URI carries no port; authelia matches a
|
//! listens on. The registered redirect URI carries no port; authelia matches a
|
||||||
//! loopback redirect on any port (RFC 8252 §7.3).
|
//! loopback redirect on any port (RFC 8252 §7.3).
|
||||||
|
//!
|
||||||
|
//! authelia's address comes from the gateway: its `/api/` 401 challenge names a
|
||||||
|
//! metadata document (RFC 9728) that lists the authorization server.
|
||||||
|
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
|
@ -129,8 +132,19 @@ struct ParResponse {
|
||||||
request_uri: String,
|
request_uri: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// authelia's origin, read off the login redirect the gateway gives a
|
/// The gateway's OAuth protected-resource metadata (RFC 9728).
|
||||||
/// request that carries no credential.
|
#[derive(Deserialize)]
|
||||||
|
struct ResourceMetadata {
|
||||||
|
resource: String,
|
||||||
|
#[serde(default)]
|
||||||
|
authorization_servers: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// authelia's origin, from the metadata the gateway's `/api/` challenge names.
|
||||||
|
///
|
||||||
|
/// A request with no credential gets a 401 whose `WWW-Authenticate` carries
|
||||||
|
/// `resource_metadata`, the URL of a document on the swarm's own origin that
|
||||||
|
/// names the API (`resource`) and its authorization server.
|
||||||
async fn discover_auth(http: &reqwest::Client, swarm: &Swarm) -> Result<String> {
|
async fn discover_auth(http: &reqwest::Client, swarm: &Swarm) -> Result<String> {
|
||||||
let url = swarm.origin.join("api/")?;
|
let url = swarm.origin.join("api/")?;
|
||||||
let resp = http
|
let resp = http
|
||||||
|
|
@ -138,20 +152,86 @@ async fn discover_auth(http: &reqwest::Client, swarm: &Swarm) -> Result<String>
|
||||||
.send()
|
.send()
|
||||||
.await
|
.await
|
||||||
.with_context(|| format!("reaching {url}"))?;
|
.with_context(|| format!("reaching {url}"))?;
|
||||||
let location = resp
|
let status = resp.status();
|
||||||
|
let metadata_url = resp
|
||||||
.headers()
|
.headers()
|
||||||
.get(reqwest::header::LOCATION)
|
.get_all(reqwest::header::WWW_AUTHENTICATE)
|
||||||
.and_then(|v| v.to_str().ok())
|
.iter()
|
||||||
.and_then(|v| url::Url::parse(v).ok())
|
.filter_map(|v| v.to_str().ok())
|
||||||
.filter(|l| resp.status().is_redirection() && l.scheme() == "https");
|
.find_map(|v| challenge_param(v, "resource_metadata"))
|
||||||
let Some(location) = location else {
|
.filter(|_| status == reqwest::StatusCode::UNAUTHORIZED);
|
||||||
|
let Some(metadata_url) = metadata_url else {
|
||||||
bail!(
|
bail!(
|
||||||
"{url} answered {} without an https redirect to the swarm's login, so its SSO \
|
"{url} answered {status} without a `resource_metadata` challenge, so its SSO \
|
||||||
provider is unknown",
|
provider is unknown"
|
||||||
resp.status()
|
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
Ok(location.origin().ascii_serialization())
|
let metadata_url = swarm
|
||||||
|
.origin
|
||||||
|
.join(&metadata_url)
|
||||||
|
.with_context(|| format!("{url} named {metadata_url:?} as its metadata"))?;
|
||||||
|
if metadata_url.origin() != swarm.origin.origin() {
|
||||||
|
bail!("{url} named {metadata_url}, which is not on the swarm's own origin");
|
||||||
|
}
|
||||||
|
let resp = http
|
||||||
|
.get(metadata_url.clone())
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.with_context(|| format!("reaching {metadata_url}"))?;
|
||||||
|
if !resp.status().is_success() {
|
||||||
|
bail!("{metadata_url} answered {}", resp.status());
|
||||||
|
}
|
||||||
|
let metadata: ResourceMetadata = serde_json::from_slice(&resp.bytes().await?)
|
||||||
|
.with_context(|| format!("decoding {metadata_url}"))?;
|
||||||
|
if metadata.resource != swarm.audience() {
|
||||||
|
bail!(
|
||||||
|
"{metadata_url} describes {}, not {}",
|
||||||
|
metadata.resource,
|
||||||
|
swarm.audience()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
let server = metadata
|
||||||
|
.authorization_servers
|
||||||
|
.first()
|
||||||
|
.with_context(|| format!("{metadata_url} names no authorization server"))?;
|
||||||
|
let server = url::Url::parse(server)
|
||||||
|
.ok()
|
||||||
|
.filter(|s| s.scheme() == "https" && s.host_str().is_some())
|
||||||
|
.with_context(|| format!("{metadata_url} names {server:?}, not an https origin"))?;
|
||||||
|
Ok(server.origin().ascii_serialization())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The value of auth-param `name` in the challenge `header` (RFC 9110 §11.6.1),
|
||||||
|
/// quoted or bare. `None` when it carries no such parameter.
|
||||||
|
fn challenge_param(header: &str, name: &str) -> Option<String> {
|
||||||
|
let mut rest = header.trim_start();
|
||||||
|
// The scheme is the first token; parameters follow after a space.
|
||||||
|
rest = rest.split_once(char::is_whitespace)?.1;
|
||||||
|
loop {
|
||||||
|
rest = rest.trim_start_matches(|c: char| c == ',' || c.is_whitespace());
|
||||||
|
let (key, after) = rest.split_once('=')?;
|
||||||
|
let key = key.trim();
|
||||||
|
let after = after.trim_start();
|
||||||
|
let (value, tail) = if let Some(quoted) = after.strip_prefix('"') {
|
||||||
|
let mut value = String::new();
|
||||||
|
let mut chars = quoted.char_indices();
|
||||||
|
let end = loop {
|
||||||
|
match chars.next()? {
|
||||||
|
(_, '\\') => value.push(chars.next()?.1),
|
||||||
|
(i, '"') => break i + 1,
|
||||||
|
(_, c) => value.push(c),
|
||||||
|
}
|
||||||
|
};
|
||||||
|
(value, "ed[end..])
|
||||||
|
} else {
|
||||||
|
let end = after.find(',').unwrap_or(after.len());
|
||||||
|
(after[..end].trim().to_owned(), &after[end..])
|
||||||
|
};
|
||||||
|
if key.eq_ignore_ascii_case(name) {
|
||||||
|
return Some(value);
|
||||||
|
}
|
||||||
|
rest = tail;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 32 bytes from the kernel CSPRNG, base64url: a PKCE verifier (RFC 7636 §4.1
|
/// 32 bytes from the kernel CSPRNG, base64url: a PKCE verifier (RFC 7636 §4.1
|
||||||
|
|
@ -473,3 +553,239 @@ mod tests {
|
||||||
assert_eq!(server.await.expect("join").expect("code"), "c1");
|
assert_eq!(server.await.expect("join").expect("code"), "c1");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod discovery_tests {
|
||||||
|
use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _};
|
||||||
|
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
/// One canned answer: status line, headers and body. `{origin}` in a header
|
||||||
|
/// value or the body stands for the stand-in gateway's own origin.
|
||||||
|
type Canned = (
|
||||||
|
&'static str,
|
||||||
|
Option<(&'static str, &'static str)>,
|
||||||
|
&'static str,
|
||||||
|
);
|
||||||
|
|
||||||
|
/// A gateway stand-in answering each path with its canned response (404 for
|
||||||
|
/// any other), and the `Swarm` naming it.
|
||||||
|
async fn gateway(routes: Vec<(&'static str, Canned)>) -> Swarm {
|
||||||
|
let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind");
|
||||||
|
let origin = format!(
|
||||||
|
"http://127.0.0.1:{}",
|
||||||
|
listener.local_addr().expect("addr").port()
|
||||||
|
);
|
||||||
|
let served = origin.clone();
|
||||||
|
tokio::spawn(async move {
|
||||||
|
while let Ok((mut s, _)) = listener.accept().await {
|
||||||
|
let routes = routes.clone();
|
||||||
|
let origin = served.clone();
|
||||||
|
tokio::spawn(async move {
|
||||||
|
let mut buf = vec![0u8; 4096];
|
||||||
|
let n = s.read(&mut buf).await.unwrap_or(0);
|
||||||
|
let request = String::from_utf8_lossy(&buf[..n]).into_owned();
|
||||||
|
let path = request.split_whitespace().nth(1).unwrap_or("");
|
||||||
|
let (status, headers, body) = routes
|
||||||
|
.iter()
|
||||||
|
.find(|(p, _)| *p == path)
|
||||||
|
.map_or(("404 Not Found", None, ""), |(_, c)| *c);
|
||||||
|
let body = body.replace("{origin}", &origin);
|
||||||
|
let headers = headers
|
||||||
|
.map(|(k, v)| format!("{k}: {}\r\n", v.replace("{origin}", &origin)))
|
||||||
|
.unwrap_or_default();
|
||||||
|
let answer = format!(
|
||||||
|
"HTTP/1.1 {status}\r\n{headers}Content-Length: {}\r\nConnection: close\r\n\r\n{body}",
|
||||||
|
body.len()
|
||||||
|
);
|
||||||
|
let _ = s.write_all(answer.as_bytes()).await;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
Swarm {
|
||||||
|
origin: url::Url::parse(&format!("{origin}/")).expect("origin"),
|
||||||
|
ca_file: None,
|
||||||
|
state_dir: std::path::PathBuf::from("/nonexistent"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn discover(swarm: &Swarm) -> Result<String> {
|
||||||
|
discover_auth(&swarm.http().expect("client"), swarm).await
|
||||||
|
}
|
||||||
|
|
||||||
|
const META: &str = "/.well-known/oauth-protected-resource/api/";
|
||||||
|
const CHALLENGE: &str = "Bearer realm=\"swarm\", resource_metadata=\"{origin}/.well-known/oauth-protected-resource/api/\"";
|
||||||
|
const DOC: &str = "{\"resource\":\"{origin}/api/\",\"authorization_servers\":[\"https://auth.example.test\"]}";
|
||||||
|
|
||||||
|
/// The gateway as deployed: a 401 naming the metadata, and the metadata.
|
||||||
|
fn routes(challenge: &'static str, doc: Canned) -> Vec<(&'static str, Canned)> {
|
||||||
|
vec![
|
||||||
|
(
|
||||||
|
"/api/",
|
||||||
|
(
|
||||||
|
"401 Unauthorized",
|
||||||
|
Some(("WWW-Authenticate", challenge)),
|
||||||
|
"",
|
||||||
|
),
|
||||||
|
),
|
||||||
|
(META, doc),
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
const GOOD: Canned = ("200 OK", None, DOC);
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn the_provider_comes_from_the_metadata_the_401_names() {
|
||||||
|
let swarm = gateway(routes(CHALLENGE, GOOD)).await;
|
||||||
|
assert_eq!(
|
||||||
|
discover(&swarm).await.expect("discovered"),
|
||||||
|
"https://auth.example.test"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_401_without_the_metadata_parameter_names_no_provider() {
|
||||||
|
// A bare Bearer challenge: a gateway that publishes no metadata.
|
||||||
|
for challenge in ["Bearer realm=\"swarm\"", "Bearer"] {
|
||||||
|
let swarm = gateway(routes(challenge, GOOD)).await;
|
||||||
|
let err = discover(&swarm).await.expect_err("no provider named");
|
||||||
|
assert!(
|
||||||
|
format!("{err:#}").contains("without a `resource_metadata` challenge"),
|
||||||
|
"{challenge}: {err:#}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_challenge_on_an_answer_that_is_not_a_401_is_ignored() {
|
||||||
|
let swarm = gateway(vec![(
|
||||||
|
"/api/",
|
||||||
|
("200 OK", Some(("WWW-Authenticate", CHALLENGE)), ""),
|
||||||
|
)])
|
||||||
|
.await;
|
||||||
|
let err = discover(&swarm).await.expect_err("not a challenge");
|
||||||
|
assert!(
|
||||||
|
format!("{err:#}").contains("answered 200 OK without"),
|
||||||
|
"{err:#}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_login_redirect_is_not_a_discovery() {
|
||||||
|
let swarm = gateway(vec![(
|
||||||
|
"/api/",
|
||||||
|
(
|
||||||
|
"302 Found",
|
||||||
|
Some(("Location", "https://auth.example.test/?rd=x")),
|
||||||
|
"",
|
||||||
|
),
|
||||||
|
)])
|
||||||
|
.await;
|
||||||
|
let err = discover(&swarm)
|
||||||
|
.await
|
||||||
|
.expect_err("a redirect names nothing");
|
||||||
|
assert!(
|
||||||
|
format!("{err:#}").contains("answered 302 Found without"),
|
||||||
|
"{err:#}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn metadata_that_is_off_origin_or_unusable_is_refused() {
|
||||||
|
let cases: [(&str, &str, Canned, &str); 7] = [
|
||||||
|
(
|
||||||
|
"another origin",
|
||||||
|
"Bearer resource_metadata=\"https://evil.test/.well-known/x\"",
|
||||||
|
GOOD,
|
||||||
|
"not on the swarm's own origin",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"not found",
|
||||||
|
CHALLENGE,
|
||||||
|
("404 Not Found", None, ""),
|
||||||
|
"answered 404",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"not json",
|
||||||
|
CHALLENGE,
|
||||||
|
("200 OK", None, "<html>"),
|
||||||
|
"decoding",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"another resource",
|
||||||
|
CHALLENGE,
|
||||||
|
(
|
||||||
|
"200 OK",
|
||||||
|
None,
|
||||||
|
"{\"resource\":\"https://other.test/api/\",\"authorization_servers\":[\"https://a.test\"]}",
|
||||||
|
),
|
||||||
|
"describes https://other.test/api/",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"no server",
|
||||||
|
CHALLENGE,
|
||||||
|
(
|
||||||
|
"200 OK",
|
||||||
|
None,
|
||||||
|
"{\"resource\":\"{origin}/api/\",\"authorization_servers\":[]}",
|
||||||
|
),
|
||||||
|
"names no authorization server",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"no servers key",
|
||||||
|
CHALLENGE,
|
||||||
|
("200 OK", None, "{\"resource\":\"{origin}/api/\"}"),
|
||||||
|
"names no authorization server",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"plain http server",
|
||||||
|
CHALLENGE,
|
||||||
|
(
|
||||||
|
"200 OK",
|
||||||
|
None,
|
||||||
|
"{\"resource\":\"{origin}/api/\",\"authorization_servers\":[\"http://auth.test\"]}",
|
||||||
|
),
|
||||||
|
"not an https origin",
|
||||||
|
),
|
||||||
|
];
|
||||||
|
for (what, challenge, doc, expected) in cases {
|
||||||
|
let swarm = gateway(routes(challenge, doc)).await;
|
||||||
|
let err = discover(&swarm).await.expect_err(what);
|
||||||
|
assert!(format!("{err:#}").contains(expected), "{what}: {err:#}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn challenge_params_are_read_quoted_or_bare() {
|
||||||
|
let p = challenge_param;
|
||||||
|
assert_eq!(
|
||||||
|
p(
|
||||||
|
"Bearer realm=\"a\", resource_metadata=\"https://x/y\"",
|
||||||
|
"resource_metadata"
|
||||||
|
)
|
||||||
|
.as_deref(),
|
||||||
|
Some("https://x/y")
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
p(
|
||||||
|
"Bearer resource_metadata=https://x/y, realm=a",
|
||||||
|
"resource_metadata"
|
||||||
|
)
|
||||||
|
.as_deref(),
|
||||||
|
Some("https://x/y")
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
p("Bearer Resource_Metadata=\"a\\\"b,c\"", "resource_metadata").as_deref(),
|
||||||
|
Some("a\"b,c")
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
p(
|
||||||
|
"Bearer realm=\"a, resource_metadata=\\\"x\\\"\"",
|
||||||
|
"resource_metadata"
|
||||||
|
),
|
||||||
|
None
|
||||||
|
);
|
||||||
|
assert_eq!(p("Bearer realm=\"a\"", "resource_metadata"), None);
|
||||||
|
assert_eq!(p("Bearer", "resource_metadata"), None);
|
||||||
|
assert_eq!(p("Bearer realm=\"unterminated", "resource_metadata"), None);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue