swarmctl login: find the sso provider from the gateway's published metadata
This commit is contained in:
parent
c1851f37cc
commit
cd040afa0e
2 changed files with 421 additions and 16 deletions
|
|
@ -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:
|
||||
`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
|
||||
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:
|
||||
|
|
|
|||
|
|
@ -6,6 +6,9 @@
|
|||
//! 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
|
||||
//! 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::time::Duration;
|
||||
|
|
@ -129,8 +132,19 @@ struct ParResponse {
|
|||
request_uri: String,
|
||||
}
|
||||
|
||||
/// authelia's origin, read off the login redirect the gateway gives a
|
||||
/// request that carries no credential.
|
||||
/// The gateway's OAuth protected-resource metadata (RFC 9728).
|
||||
#[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> {
|
||||
let url = swarm.origin.join("api/")?;
|
||||
let resp = http
|
||||
|
|
@ -138,20 +152,86 @@ async fn discover_auth(http: &reqwest::Client, swarm: &Swarm) -> Result<String>
|
|||
.send()
|
||||
.await
|
||||
.with_context(|| format!("reaching {url}"))?;
|
||||
let location = resp
|
||||
let status = resp.status();
|
||||
let metadata_url = resp
|
||||
.headers()
|
||||
.get(reqwest::header::LOCATION)
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.and_then(|v| url::Url::parse(v).ok())
|
||||
.filter(|l| resp.status().is_redirection() && l.scheme() == "https");
|
||||
let Some(location) = location else {
|
||||
.get_all(reqwest::header::WWW_AUTHENTICATE)
|
||||
.iter()
|
||||
.filter_map(|v| v.to_str().ok())
|
||||
.find_map(|v| challenge_param(v, "resource_metadata"))
|
||||
.filter(|_| status == reqwest::StatusCode::UNAUTHORIZED);
|
||||
let Some(metadata_url) = metadata_url else {
|
||||
bail!(
|
||||
"{url} answered {} without an https redirect to the swarm's login, so its SSO \
|
||||
provider is unknown",
|
||||
resp.status()
|
||||
"{url} answered {status} without a `resource_metadata` challenge, so its SSO \
|
||||
provider is unknown"
|
||||
);
|
||||
};
|
||||
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
|
||||
|
|
@ -473,3 +553,239 @@ mod tests {
|
|||
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