Dungeon sign-in: a begin cookie binds the attempt to its browser, the provider is a parameter, the auth routes are throttled
complete must present the HttpOnly begin cookie matching the handle, once, before expiry (the OAuth state/PKCE binding). begin takes a provider from GHOSTLIGHT_AUTH_PROVIDERS; the Discord role policy rides Discord only. The session plays as the principal sign_in returns, refusing a mismatch. Heimdall error text no longer reaches the caller. HeimdallPort lets handlers be tested against a scripted Heimdall. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
920bb3d289
commit
783fd8a288
7 changed files with 987 additions and 67 deletions
|
|
@ -5,6 +5,8 @@
|
|||
//! `PlayTable::admit`/`execute`, the only writers.
|
||||
|
||||
use crate::{
|
||||
auth_guard::{BEGIN_COOKIE, BEGIN_TTL_SECONDS},
|
||||
heimdall::AuthBeginReceipt,
|
||||
begin::{BeginRequest, begin},
|
||||
play::{Admission, OpenQuestion, PlayError, PlayRequest, PlayTurnState, PlayTurnView},
|
||||
runtime::AppState,
|
||||
|
|
@ -102,13 +104,18 @@ fn answer_token_admits(given: Option<&str>, expected: Option<&str>) -> bool {
|
|||
}
|
||||
|
||||
pub(crate) fn cookie_value(headers: &HeaderMap) -> Option<&str> {
|
||||
named_cookie(headers, COOKIE_NAME)
|
||||
}
|
||||
|
||||
fn named_cookie<'a>(headers: &'a HeaderMap, name: &str) -> Option<&'a str> {
|
||||
let prefix = format!("{name}=");
|
||||
headers
|
||||
.get(header::COOKIE)?
|
||||
.to_str()
|
||||
.ok()?
|
||||
.split(';')
|
||||
.map(str::trim)
|
||||
.find_map(|cookie| cookie.strip_prefix(&format!("{COOKIE_NAME}=")))
|
||||
.find_map(|cookie| cookie.strip_prefix(&prefix))
|
||||
}
|
||||
|
||||
fn session_cookie(raw: &str, expires_at: DateTime<Utc>, now: DateTime<Utc>) -> HeaderValue {
|
||||
|
|
@ -422,30 +429,78 @@ async fn turn_stream(
|
|||
#[serde(deny_unknown_fields)]
|
||||
struct AuthBeginBody {
|
||||
key: String,
|
||||
/// One of the providers the daemon offers (`GHOSTLIGHT_AUTH_PROVIDERS`).
|
||||
provider: String,
|
||||
}
|
||||
|
||||
async fn auth_begin(State(state): State<AppState>, Json(body): Json<AuthBeginBody>) -> Response {
|
||||
match state.heimdall.begin(&body.key).await {
|
||||
Ok(receipt)
|
||||
if receipt.status == "pending"
|
||||
&& !receipt.handle.is_empty()
|
||||
&& receipt
|
||||
.expires_at
|
||||
.parse::<DateTime<Utc>>()
|
||||
.is_ok_and(|expiry| expiry > Utc::now()) =>
|
||||
{
|
||||
reply(
|
||||
StatusCode::OK,
|
||||
json!({
|
||||
"handle": receipt.handle,
|
||||
"url": receipt.navigation.url,
|
||||
"allowedOrigins": receipt.navigation.allowed_origins,
|
||||
}),
|
||||
)
|
||||
}
|
||||
Ok(_) => refuse(StatusCode::BAD_GATEWAY, "Heimdall returned an invalid authentication attempt."),
|
||||
Err(error) => refuse(StatusCode::BAD_GATEWAY, error),
|
||||
/// The throttle's key: the address nginx sets in `X-Real-IP`. Behind the proxy
|
||||
/// the TCP peer is always loopback, so it names no one.
|
||||
fn client_key(headers: &HeaderMap) -> &str {
|
||||
headers
|
||||
.get("x-real-ip")
|
||||
.and_then(|value| value.to_str().ok())
|
||||
.map(str::trim)
|
||||
.filter(|value| !value.is_empty())
|
||||
.unwrap_or("direct")
|
||||
}
|
||||
|
||||
fn throttled() -> Response {
|
||||
refuse(StatusCode::TOO_MANY_REQUESTS, "too many sign-in requests; wait a minute")
|
||||
}
|
||||
|
||||
fn begin_cookie(secret: &str, max_age: i64) -> HeaderValue {
|
||||
HeaderValue::from_str(&format!(
|
||||
"{BEGIN_COOKIE}={secret}; Max-Age={max_age}; HttpOnly; Secure; SameSite=Lax; Path=/ghostlight/"
|
||||
))
|
||||
.expect("generated begin cookie must be valid")
|
||||
}
|
||||
|
||||
/// A pending Heimdall attempt's expiry, or `None` for a receipt that is not a
|
||||
/// live pending attempt.
|
||||
fn pending_expiry(receipt: &AuthBeginReceipt, now: DateTime<Utc>) -> Option<DateTime<Utc>> {
|
||||
let expiry = receipt.expires_at.parse::<DateTime<Utc>>().ok()?;
|
||||
(receipt.status == "pending" && !receipt.handle.is_empty() && expiry > now).then_some(expiry)
|
||||
}
|
||||
|
||||
async fn auth_begin(
|
||||
headers: HeaderMap,
|
||||
State(state): State<AppState>,
|
||||
Json(body): Json<AuthBeginBody>,
|
||||
) -> Response {
|
||||
let now = Utc::now();
|
||||
if !state.auth.allow(client_key(&headers), now) {
|
||||
return throttled();
|
||||
}
|
||||
let Some(provider) = state.heimdall.offered(&body.provider) else {
|
||||
return refuse(StatusCode::BAD_REQUEST, "that sign-in provider is not offered");
|
||||
};
|
||||
let receipt = match state.heimdall.begin(provider, &body.key).await {
|
||||
Ok(receipt) => receipt,
|
||||
Err(error) => {
|
||||
tracing::warn!(%error, "Heimdall refused to begin a sign-in");
|
||||
return refuse(StatusCode::BAD_GATEWAY, "Heimdall could not begin the sign-in.");
|
||||
}
|
||||
};
|
||||
let Some(expiry) = pending_expiry(&receipt, now) else {
|
||||
return refuse(StatusCode::BAD_GATEWAY, "Heimdall returned an invalid authentication attempt.");
|
||||
};
|
||||
let expiry = expiry.min(now + chrono::Duration::seconds(BEGIN_TTL_SECONDS));
|
||||
let Some(secret) = state.auth.start(&receipt.handle, expiry, now) else {
|
||||
return refuse(StatusCode::SERVICE_UNAVAILABLE, "too many sign-ins are open; try again shortly");
|
||||
};
|
||||
let mut response = reply(
|
||||
StatusCode::OK,
|
||||
json!({
|
||||
"handle": receipt.handle,
|
||||
"url": receipt.navigation.url,
|
||||
"allowedOrigins": receipt.navigation.allowed_origins,
|
||||
}),
|
||||
);
|
||||
response.headers_mut().insert(
|
||||
header::SET_COOKIE,
|
||||
begin_cookie(&secret, (expiry - now).num_seconds().max(0)),
|
||||
);
|
||||
response
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
|
|
@ -459,46 +514,88 @@ struct AuthCompleteBody {
|
|||
}
|
||||
|
||||
async fn auth_complete(
|
||||
headers: HeaderMap,
|
||||
State(state): State<AppState>,
|
||||
Json(body): Json<AuthCompleteBody>,
|
||||
) -> Response {
|
||||
let now = Utc::now();
|
||||
if !state.auth.allow(client_key(&headers), now) {
|
||||
return throttled();
|
||||
}
|
||||
if body.handle.is_empty() {
|
||||
return refuse(StatusCode::BAD_REQUEST, "Authentication completion omitted its opaque handle.");
|
||||
}
|
||||
// Only the browser that began the attempt may complete it.
|
||||
let Some(secret) = named_cookie(&headers, BEGIN_COOKIE)
|
||||
.filter(|secret| state.auth.matches(&body.handle, secret, now))
|
||||
else {
|
||||
return refuse(StatusCode::FORBIDDEN, "this browser did not begin that sign-in");
|
||||
};
|
||||
let completion = match state.heimdall.complete(&body.handle, &body.key).await {
|
||||
Ok(value) => value,
|
||||
Err(error) => return refuse(StatusCode::FORBIDDEN, error),
|
||||
Err(error) => {
|
||||
tracing::warn!(%error, "Heimdall refused to complete a sign-in");
|
||||
return refuse(StatusCode::FORBIDDEN, "Heimdall could not complete the sign-in.");
|
||||
}
|
||||
};
|
||||
if completion.status == "pending" {
|
||||
return reply(StatusCode::ACCEPTED, json!({"status": "pending"}));
|
||||
}
|
||||
// Any other outcome ends the attempt: the binding is spent here, once.
|
||||
if !state.auth.consume(&body.handle, secret, now) {
|
||||
return refuse(StatusCode::FORBIDDEN, "this browser did not begin that sign-in");
|
||||
}
|
||||
let spent = |mut response: Response| {
|
||||
response.headers_mut().append(header::SET_COOKIE, begin_cookie("", 0));
|
||||
response
|
||||
};
|
||||
if completion.status != "authenticated" || completion.handle.as_deref() != Some(body.handle.as_str()) {
|
||||
let message = completion
|
||||
.error
|
||||
.clone()
|
||||
.unwrap_or_else(|| "Heimdall denied access.".into());
|
||||
return reply(StatusCode::FORBIDDEN, json!({"status": "denied", "error": message}));
|
||||
return spent(reply(StatusCode::FORBIDDEN, json!({"status": "denied", "error": message})));
|
||||
}
|
||||
let admission = match state.heimdall.verify_completion(completion).await {
|
||||
Ok(admission) => admission,
|
||||
Err(error) => return reply(StatusCode::FORBIDDEN, json!({"status": "denied", "error": error.to_string()})),
|
||||
Err(error) => {
|
||||
tracing::warn!(%error, "a Heimdall completion failed verification");
|
||||
return spent(reply(
|
||||
StatusCode::FORBIDDEN,
|
||||
json!({"status": "denied", "error": "Heimdall's answer could not be verified."}),
|
||||
));
|
||||
}
|
||||
};
|
||||
// No account and no live invite: refused, never enrolled. The invite is
|
||||
// consumed only with the account it creates.
|
||||
match state
|
||||
let principal = match state
|
||||
.catalog
|
||||
.lock()
|
||||
.await
|
||||
.sign_in(admission.account_id(), body.invite.as_deref(), Utc::now())
|
||||
{
|
||||
Ok(Ok(_)) => {}
|
||||
Ok(Ok(principal)) => principal,
|
||||
Ok(Err(refusal)) => {
|
||||
return reply(StatusCode::FORBIDDEN, json!({"status": "refused", "error": refusal.to_string()}));
|
||||
return spent(reply(
|
||||
StatusCode::FORBIDDEN,
|
||||
json!({"status": "refused", "error": refusal.to_string()}),
|
||||
));
|
||||
}
|
||||
Err(error) => {
|
||||
tracing::error!(%error, "the account catalog could not record a sign-in");
|
||||
return refuse(StatusCode::INTERNAL_SERVER_ERROR, "the sign-in could not be recorded");
|
||||
}
|
||||
};
|
||||
// The session plays as the account's principal, which is the identity the
|
||||
// account was first made from. A session minted as another identity would
|
||||
// split one account across two worlds sets, so it is refused until a
|
||||
// second-identity link decides the principal (ruling
|
||||
// dungeon-account-principal-answer).
|
||||
if principal != admission.account_id() {
|
||||
return spent(reply(
|
||||
StatusCode::FORBIDDEN,
|
||||
json!({"status": "refused", "error": "this identity is linked to an account whose principal it does not carry"}),
|
||||
));
|
||||
}
|
||||
let expires_at = admission.refresh_expires_at();
|
||||
let token = {
|
||||
|
|
@ -512,14 +609,18 @@ async fn auth_complete(
|
|||
match result {
|
||||
Ok(token) => token,
|
||||
Err(error) => {
|
||||
return reply(StatusCode::FORBIDDEN, json!({"status": "denied", "error": error.to_string()}));
|
||||
tracing::warn!(%error, "an authenticated sign-in could not become a session");
|
||||
return spent(reply(
|
||||
StatusCode::FORBIDDEN,
|
||||
json!({"status": "denied", "error": "the session could not be created"}),
|
||||
));
|
||||
}
|
||||
}
|
||||
};
|
||||
let mut response = reply(StatusCode::OK, json!({"status": "authenticated"}));
|
||||
let mut response = spent(reply(StatusCode::OK, json!({"status": "authenticated"})));
|
||||
response
|
||||
.headers_mut()
|
||||
.insert(header::SET_COOKIE, session_cookie(&token, expires_at, Utc::now()));
|
||||
.append(header::SET_COOKIE, session_cookie(&token, expires_at, Utc::now()));
|
||||
response
|
||||
}
|
||||
|
||||
|
|
@ -569,7 +670,10 @@ mod tests {
|
|||
use crate::{
|
||||
app_session::AppSessionOwner,
|
||||
begin::tests::{Rig, one_vault, principal, rig},
|
||||
heimdall::{HeimdallClient, VerifiedSessionAdmission},
|
||||
heimdall::{
|
||||
AccountSummary, AuthBeginReceipt, AuthCompletionReceipt, AuthNavigation, AuthProvider,
|
||||
HeimdallPort, SessionRefresher, VerifiedSessionAdmission, VerifiedSessionRefresh,
|
||||
},
|
||||
play::{
|
||||
ASK_PLAYER_TOOL, END_TURN_TOOL,
|
||||
tests::{call_event, output, text_event},
|
||||
|
|
@ -585,9 +689,111 @@ mod tests {
|
|||
use tower::ServiceExt;
|
||||
use uuid::Uuid;
|
||||
|
||||
/// A scripted Heimdall: it offers google and discord, hands out numbered
|
||||
/// handles, answers `complete` from what the test authenticated, and
|
||||
/// counts every call.
|
||||
#[derive(Default)]
|
||||
struct FakeHeimdall {
|
||||
begun: std::sync::Mutex<Vec<AuthProvider>>,
|
||||
completed: std::sync::Mutex<usize>,
|
||||
authenticated: std::sync::Mutex<std::collections::HashMap<String, (String, String)>>,
|
||||
/// Overrides the next begin: an invalid receipt or a failure.
|
||||
begin_override: std::sync::Mutex<Option<anyhow::Result<AuthBeginReceipt>>>,
|
||||
fail_complete: std::sync::Mutex<bool>,
|
||||
}
|
||||
|
||||
impl FakeHeimdall {
|
||||
fn receipt(handle: &str, status: &str, expires_in: chrono::Duration) -> AuthBeginReceipt {
|
||||
AuthBeginReceipt {
|
||||
status: status.into(),
|
||||
handle: handle.into(),
|
||||
expires_at: (Utc::now() + expires_in).to_rfc3339(),
|
||||
navigation: AuthNavigation {
|
||||
url: "https://provider.invalid/authorize".into(),
|
||||
allowed_origins: vec!["https://provider.invalid".into()],
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// The user finished the provider's page: `complete` now answers
|
||||
/// `status` for the handle, as `account`.
|
||||
fn finish(&self, handle: &str, status: &str, account: &str) {
|
||||
self.authenticated
|
||||
.lock()
|
||||
.unwrap()
|
||||
.insert(handle.into(), (status.into(), account.into()));
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl SessionRefresher for FakeHeimdall {
|
||||
async fn refresh(&self, _: &str, _: &str) -> anyhow::Result<AuthCompletionReceipt> {
|
||||
unreachable!("the API tests run no refresh loop")
|
||||
}
|
||||
|
||||
async fn verify_refresh(&self, _: AuthCompletionReceipt) -> anyhow::Result<VerifiedSessionRefresh> {
|
||||
unreachable!("the API tests run no refresh loop")
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl HeimdallPort for FakeHeimdall {
|
||||
fn offered(&self, name: &str) -> Option<AuthProvider> {
|
||||
AuthProvider::parse(name).filter(|provider| *provider != AuthProvider::Twitch)
|
||||
}
|
||||
|
||||
async fn begin(&self, provider: AuthProvider, _: &str) -> anyhow::Result<AuthBeginReceipt> {
|
||||
let mut begun = self.begun.lock().unwrap();
|
||||
begun.push(provider);
|
||||
if let Some(forced) = self.begin_override.lock().unwrap().take() {
|
||||
return forced;
|
||||
}
|
||||
Ok(Self::receipt(&format!("handle-{}", begun.len()), "pending", chrono::Duration::minutes(15)))
|
||||
}
|
||||
|
||||
async fn complete(&self, handle: &str, _: &str) -> anyhow::Result<AuthCompletionReceipt> {
|
||||
*self.completed.lock().unwrap() += 1;
|
||||
if *self.fail_complete.lock().unwrap() {
|
||||
anyhow::bail!("private socket 10.0.0.7 refused");
|
||||
}
|
||||
let finished = self.authenticated.lock().unwrap().get(handle).cloned();
|
||||
let (status, account) = finished.unwrap_or(("pending".into(), String::new()));
|
||||
Ok(AuthCompletionReceipt {
|
||||
error: (status == "denied").then(|| "the role is missing".to_owned()),
|
||||
handle: Some(handle.into()),
|
||||
account: (status == "authenticated").then(|| AccountSummary { id: account }),
|
||||
status,
|
||||
session: None,
|
||||
access_token: None,
|
||||
refresh_token: None,
|
||||
refresh: None,
|
||||
shared_capabilities: vec![],
|
||||
})
|
||||
}
|
||||
|
||||
async fn verify_completion(
|
||||
&self,
|
||||
completion: AuthCompletionReceipt,
|
||||
) -> anyhow::Result<VerifiedSessionAdmission> {
|
||||
Ok(VerifiedSessionAdmission::fixture(
|
||||
completion.account.unwrap().id,
|
||||
"heimdall-session-fresh",
|
||||
1,
|
||||
Utc::now() + chrono::Duration::hours(1),
|
||||
Utc::now() + chrono::Duration::days(1),
|
||||
"fixture-refresh",
|
||||
))
|
||||
}
|
||||
|
||||
async fn logout(&self, _: &str, _: &str) -> anyhow::Result<crate::heimdall::AuthLogoutReceipt> {
|
||||
anyhow::bail!("Heimdall is unreachable")
|
||||
}
|
||||
}
|
||||
|
||||
struct App {
|
||||
router: Router,
|
||||
state: AppState,
|
||||
heimdall: Arc<FakeHeimdall>,
|
||||
rig: Rig,
|
||||
cookies: Vec<String>,
|
||||
}
|
||||
|
|
@ -617,13 +823,15 @@ mod tests {
|
|||
.unwrap()
|
||||
})
|
||||
.collect();
|
||||
let heimdall = Arc::new(FakeHeimdall::default());
|
||||
let (fatal, _) = tokio::sync::mpsc::unbounded_channel();
|
||||
let state = AppState {
|
||||
catalog: rig.catalog.clone(),
|
||||
timelines: rig.timelines.clone(),
|
||||
vaults: one_vault(),
|
||||
sessions: Arc::new(Mutex::new(sessions)),
|
||||
heimdall: Arc::new(HeimdallClient::fixture()),
|
||||
heimdall: heimdall.clone(),
|
||||
auth: Arc::default(),
|
||||
runtime_id: "ghostlight-test".into(),
|
||||
runtime_health: None,
|
||||
fatal,
|
||||
|
|
@ -631,6 +839,7 @@ mod tests {
|
|||
App {
|
||||
router: service_router(state.clone()),
|
||||
state,
|
||||
heimdall,
|
||||
rig,
|
||||
cookies,
|
||||
}
|
||||
|
|
@ -754,19 +963,307 @@ mod tests {
|
|||
assert_eq!(status, StatusCode::UNAUTHORIZED);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_sign_in_heimdall_cannot_confirm_mints_no_session() {
|
||||
let app = app(vec![], &[]).await;
|
||||
let (status, headers, _) = call(
|
||||
&app,
|
||||
Method::POST,
|
||||
"/api/auth/complete",
|
||||
None,
|
||||
Some(json!({"handle": "attempt", "key": "k", "invite": "any"})),
|
||||
const A_BROWSER: &str = "203.0.113.9";
|
||||
const BEGIN_FLAGS: [&str; 5] = ["HttpOnly", "Secure", "SameSite=Lax", "Path=/ghostlight/", "Max-Age="];
|
||||
|
||||
/// One request to an auth route as a browser behind nginx: its cookie jar
|
||||
/// and the `X-Real-IP` nginx stamps.
|
||||
async fn auth_call(
|
||||
app: &App,
|
||||
uri: &str,
|
||||
jar: &[(&str, &str)],
|
||||
real_ip: &str,
|
||||
body: Value,
|
||||
) -> (StatusCode, Vec<String>, Value) {
|
||||
let cookie = jar
|
||||
.iter()
|
||||
.map(|(name, value)| format!("{name}={value}"))
|
||||
.collect::<Vec<_>>()
|
||||
.join("; ");
|
||||
let mut request = Request::builder()
|
||||
.method(Method::POST)
|
||||
.uri(uri)
|
||||
.header(header::CONTENT_TYPE, "application/json")
|
||||
.header("x-real-ip", real_ip);
|
||||
if !cookie.is_empty() {
|
||||
request = request.header(header::COOKIE, cookie);
|
||||
}
|
||||
let response = app
|
||||
.router
|
||||
.clone()
|
||||
.oneshot(request.body(Body::from(body.to_string())).unwrap())
|
||||
.await
|
||||
.unwrap();
|
||||
let status = response.status();
|
||||
let cookies = response
|
||||
.headers()
|
||||
.get_all(header::SET_COOKIE)
|
||||
.iter()
|
||||
.map(|value| value.to_str().unwrap().to_owned())
|
||||
.collect();
|
||||
let bytes = to_bytes(response.into_body(), 1 << 20).await.unwrap();
|
||||
(status, cookies, serde_json::from_slice(&bytes).unwrap_or(Value::Null))
|
||||
}
|
||||
|
||||
fn cookie_named<'a>(set_cookies: &'a [String], name: &str) -> Option<&'a String> {
|
||||
set_cookies.iter().find(|cookie| cookie.starts_with(&format!("{name}=")))
|
||||
}
|
||||
|
||||
fn cookie_secret(set_cookie: &str) -> String {
|
||||
set_cookie.split(';').next().unwrap().split_once('=').unwrap().1.to_owned()
|
||||
}
|
||||
|
||||
/// Begins a sign-in from a browser; returns its handle and begin secret.
|
||||
async fn begin_sign_in(app: &App, provider: &str, real_ip: &str) -> (String, String) {
|
||||
let (status, cookies, body) = auth_call(
|
||||
app,
|
||||
"/api/auth/begin",
|
||||
&[],
|
||||
real_ip,
|
||||
json!({"key": Uuid::new_v4(), "provider": provider}),
|
||||
)
|
||||
.await;
|
||||
assert_ne!(status, StatusCode::OK);
|
||||
assert!(headers.get(header::SET_COOKIE).is_none());
|
||||
assert_eq!(status, StatusCode::OK, "{body}");
|
||||
let secret = cookie_secret(cookie_named(&cookies, "ghostlight_auth").expect("a begin cookie"));
|
||||
(body["handle"].as_str().unwrap().to_owned(), secret)
|
||||
}
|
||||
|
||||
async fn complete(app: &App, handle: &str, jar: &[(&str, &str)], invite: Option<&str>) -> (StatusCode, Vec<String>, Value) {
|
||||
auth_call(
|
||||
app,
|
||||
"/api/auth/complete",
|
||||
jar,
|
||||
A_BROWSER,
|
||||
json!({"handle": handle, "key": Uuid::new_v4(), "invite": invite}),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn invite(app: &App) -> String {
|
||||
app.state
|
||||
.catalog
|
||||
.lock()
|
||||
.await
|
||||
.mint_invite(Utc::now(), chrono::Duration::hours(1))
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn begin_returns_the_attempt_and_binds_it_to_this_browser_with_a_private_cookie() {
|
||||
let app = app(vec![], &[]).await;
|
||||
let (status, cookies, body) = auth_call(
|
||||
&app,
|
||||
"/api/auth/begin",
|
||||
&[],
|
||||
A_BROWSER,
|
||||
json!({"key": Uuid::new_v4(), "provider": "google"}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(status, StatusCode::OK, "{body}");
|
||||
assert_eq!(body["handle"], "handle-1");
|
||||
assert_eq!(body["url"], "https://provider.invalid/authorize");
|
||||
assert_eq!(body["allowedOrigins"], json!(["https://provider.invalid"]));
|
||||
assert_eq!(*app.heimdall.begun.lock().unwrap(), vec![AuthProvider::Google]);
|
||||
let cookie = cookie_named(&cookies, "ghostlight_auth").expect("a begin cookie");
|
||||
for flag in BEGIN_FLAGS {
|
||||
assert!(cookie.contains(flag), "{flag} missing from {cookie}");
|
||||
}
|
||||
let max_age: i64 = cookie.split("Max-Age=").nth(1).unwrap().split(';').next().unwrap().parse().unwrap();
|
||||
assert!((1..=BEGIN_TTL_SECONDS).contains(&max_age), "{cookie}");
|
||||
assert_eq!(cookie_secret(cookie).len(), 64);
|
||||
assert!(!body.to_string().contains(&cookie_secret(cookie)), "the secret stays in the cookie");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn begin_refuses_a_provider_the_daemon_does_not_offer_and_asks_heimdall_nothing() {
|
||||
let app = app(vec![], &[]).await;
|
||||
for provider in ["twitch", "github", "GOOGLE", "", "discord,google"] {
|
||||
let (status, cookies, _) = auth_call(
|
||||
&app,
|
||||
"/api/auth/begin",
|
||||
&[],
|
||||
A_BROWSER,
|
||||
json!({"key": Uuid::new_v4(), "provider": provider}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(status, StatusCode::BAD_REQUEST, "{provider:?}");
|
||||
assert!(cookies.is_empty());
|
||||
}
|
||||
let (status, _, _) =
|
||||
auth_call(&app, "/api/auth/begin", &[], A_BROWSER, json!({"key": Uuid::new_v4()})).await;
|
||||
assert!(status.is_client_error(), "the provider is required");
|
||||
assert!(app.heimdall.begun.lock().unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn begin_refuses_a_receipt_that_is_not_a_live_pending_attempt_and_leaks_no_error_text() {
|
||||
let app = app(vec![], &[]).await;
|
||||
let bad = [
|
||||
Ok(FakeHeimdall::receipt("h", "authenticated", chrono::Duration::minutes(5))),
|
||||
Ok(FakeHeimdall::receipt("", "pending", chrono::Duration::minutes(5))),
|
||||
Ok(FakeHeimdall::receipt("h", "pending", chrono::Duration::minutes(-1))),
|
||||
Ok(AuthBeginReceipt {
|
||||
expires_at: "not a time".into(),
|
||||
..FakeHeimdall::receipt("h", "pending", chrono::Duration::minutes(5))
|
||||
}),
|
||||
Err(anyhow::anyhow!("odin refused 10.0.0.7:17877")),
|
||||
];
|
||||
for forced in bad {
|
||||
*app.heimdall.begin_override.lock().unwrap() = Some(forced);
|
||||
let (status, cookies, body) = auth_call(
|
||||
&app,
|
||||
"/api/auth/begin",
|
||||
&[],
|
||||
A_BROWSER,
|
||||
json!({"key": Uuid::new_v4(), "provider": "discord"}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(status, StatusCode::BAD_GATEWAY, "{body}");
|
||||
assert!(cookies.is_empty());
|
||||
assert!(!body.to_string().contains("10.0.0.7"), "{body}");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_handle_begun_in_one_browser_cannot_be_completed_from_another() {
|
||||
let app = app(vec![], &[]).await;
|
||||
let invite = invite(&app).await;
|
||||
let (handle, victim_secret) = begin_sign_in(&app, "google", "198.51.100.1").await;
|
||||
let (_, attacker_secret) = begin_sign_in(&app, "google", "198.51.100.2").await;
|
||||
app.heimdall.finish(&handle, "authenticated", "victim");
|
||||
for jar in [
|
||||
vec![],
|
||||
vec![("ghostlight_auth", "")],
|
||||
vec![("ghostlight_auth", attacker_secret.as_str())],
|
||||
vec![("ghostlight_session", victim_secret.as_str())],
|
||||
] {
|
||||
let (status, cookies, _) = complete(&app, &handle, &jar, Some(&invite)).await;
|
||||
assert_eq!(status, StatusCode::FORBIDDEN, "{jar:?}");
|
||||
assert!(cookies.is_empty(), "no session for {jar:?}");
|
||||
}
|
||||
assert_eq!(*app.heimdall.completed.lock().unwrap(), 0, "Heimdall is not even asked");
|
||||
let (status, cookies, body) =
|
||||
complete(&app, &handle, &[("ghostlight_auth", &victim_secret)], Some(&invite)).await;
|
||||
assert_eq!(status, StatusCode::OK, "{body}");
|
||||
assert!(cookie_named(&cookies, "ghostlight_session").is_some());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_binding_is_single_use_and_spent_with_the_attempt() {
|
||||
let app = app(vec![], &[]).await;
|
||||
let invite = invite(&app).await;
|
||||
let (handle, secret) = begin_sign_in(&app, "discord", A_BROWSER).await;
|
||||
let jar = [("ghostlight_auth", secret.as_str())];
|
||||
let (status, cookies, _) = complete(&app, &handle, &jar, Some(&invite)).await;
|
||||
assert_eq!(status, StatusCode::ACCEPTED, "Heimdall says pending");
|
||||
assert!(cookies.is_empty());
|
||||
assert_eq!(complete(&app, &handle, &jar, Some(&invite)).await.0, StatusCode::ACCEPTED, "pending keeps the binding");
|
||||
app.heimdall.finish(&handle, "authenticated", "deru");
|
||||
let (status, cookies, body) = complete(&app, &handle, &jar, Some(&invite)).await;
|
||||
assert_eq!(status, StatusCode::OK, "{body}");
|
||||
let session = cookie_named(&cookies, "ghostlight_session").unwrap();
|
||||
for flag in ["HttpOnly", "Secure", "SameSite=Lax", "Path=/ghostlight/"] {
|
||||
assert!(session.contains(flag), "{session}");
|
||||
}
|
||||
let spent = cookie_named(&cookies, "ghostlight_auth").expect("the begin cookie is cleared");
|
||||
assert!(spent.contains("Max-Age=0"), "{spent}");
|
||||
let (status, cookies, _) = complete(&app, &handle, &jar, None).await;
|
||||
assert_eq!(status, StatusCode::FORBIDDEN, "replay");
|
||||
assert!(cookies.is_empty());
|
||||
let (_, _, me) = call(&app, Method::GET, "/api/me", Some(&cookie_secret(session)), None).await;
|
||||
assert_eq!(me["signedIn"], true);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_denied_or_mismatched_completion_mints_no_session_and_spends_the_binding() {
|
||||
let app = app(vec![], &[]).await;
|
||||
let (handle, secret) = begin_sign_in(&app, "discord", A_BROWSER).await;
|
||||
let jar = [("ghostlight_auth", secret.as_str())];
|
||||
app.heimdall.finish(&handle, "denied", "");
|
||||
let (status, cookies, body) = complete(&app, &handle, &jar, None).await;
|
||||
assert_eq!(status, StatusCode::FORBIDDEN);
|
||||
assert_eq!(body["status"], "denied");
|
||||
assert_eq!(body["error"], "the role is missing", "Heimdall's own denial reaches the player");
|
||||
assert!(cookie_named(&cookies, "ghostlight_session").is_none());
|
||||
app.heimdall.finish(&handle, "authenticated", "deru");
|
||||
assert_eq!(complete(&app, &handle, &jar, None).await.0, StatusCode::FORBIDDEN, "spent");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_failed_heimdall_completion_names_nothing_of_the_failure() {
|
||||
let app = app(vec![], &[]).await;
|
||||
let (handle, secret) = begin_sign_in(&app, "discord", A_BROWSER).await;
|
||||
*app.heimdall.fail_complete.lock().unwrap() = true;
|
||||
let (status, _, body) = complete(&app, &handle, &[("ghostlight_auth", &secret)], None).await;
|
||||
assert_eq!(status, StatusCode::FORBIDDEN);
|
||||
assert!(!body.to_string().contains("10.0.0.7"), "{body}");
|
||||
let (status, _, _) = complete(&app, "", &[("ghostlight_auth", &secret)], None).await;
|
||||
assert_eq!(status, StatusCode::BAD_REQUEST);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_unknown_identity_needs_a_live_invite_and_a_known_one_does_not() {
|
||||
let app = app(vec![], &[]).await;
|
||||
let (handle, secret) = begin_sign_in(&app, "google", A_BROWSER).await;
|
||||
app.heimdall.finish(&handle, "authenticated", "deru");
|
||||
let (status, cookies, body) = complete(&app, &handle, &[("ghostlight_auth", &secret)], None).await;
|
||||
assert_eq!(status, StatusCode::FORBIDDEN);
|
||||
assert_eq!(body["status"], "refused");
|
||||
assert!(cookie_named(&cookies, "ghostlight_session").is_none());
|
||||
let invite = invite(&app).await;
|
||||
let (handle, secret) = begin_sign_in(&app, "google", A_BROWSER).await;
|
||||
app.heimdall.finish(&handle, "authenticated", "deru");
|
||||
let jar = [("ghostlight_auth", secret.as_str())];
|
||||
assert_eq!(complete(&app, &handle, &jar, Some(&invite)).await.0, StatusCode::OK);
|
||||
let (handle, secret) = begin_sign_in(&app, "google", A_BROWSER).await;
|
||||
app.heimdall.finish(&handle, "authenticated", "deru");
|
||||
let (status, _, _) = complete(&app, &handle, &[("ghostlight_auth", &secret)], None).await;
|
||||
assert_eq!(status, StatusCode::OK, "the second device needs no invite");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_identity_linked_to_another_principal_gets_no_session() {
|
||||
let app = app(vec![], &[]).await;
|
||||
let invite = invite(&app).await;
|
||||
{
|
||||
let mut catalog = app.state.catalog.lock().await;
|
||||
catalog.sign_in("first", Some(&invite), Utc::now()).unwrap().unwrap();
|
||||
catalog.link_identity("first", "second").unwrap();
|
||||
}
|
||||
let (handle, secret) = begin_sign_in(&app, "google", A_BROWSER).await;
|
||||
app.heimdall.finish(&handle, "authenticated", "second");
|
||||
let (status, cookies, body) = complete(&app, &handle, &[("ghostlight_auth", &secret)], None).await;
|
||||
assert_eq!(status, StatusCode::FORBIDDEN, "{body}");
|
||||
assert!(cookie_named(&cookies, "ghostlight_session").is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_auth_routes_throttle_a_client_by_its_real_ip_alone() {
|
||||
let app = app(vec![], &[]).await;
|
||||
let begin = |ip: &'static str| {
|
||||
auth_call(&app, "/api/auth/begin", &[], ip, json!({"key": Uuid::new_v4(), "provider": "discord"}))
|
||||
};
|
||||
let mut throttled = None;
|
||||
for attempt in 0..70 {
|
||||
if begin("198.51.100.7").await.0 == StatusCode::TOO_MANY_REQUESTS {
|
||||
throttled = Some(attempt);
|
||||
break;
|
||||
}
|
||||
}
|
||||
assert!(throttled.is_some_and(|attempt| attempt >= 30), "{throttled:?}");
|
||||
assert_eq!(begin("198.51.100.8").await.0, StatusCode::OK, "another address is not throttled");
|
||||
let (status, _, _) = complete(&app, "x", &[], None).await;
|
||||
assert_ne!(status, StatusCode::TOO_MANY_REQUESTS, "A_BROWSER has its own count");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_throttle_key_is_the_real_ip_header_or_a_shared_direct_bucket() {
|
||||
let mut headers = HeaderMap::new();
|
||||
assert_eq!(client_key(&headers), "direct");
|
||||
headers.insert("x-real-ip", HeaderValue::from_static(" "));
|
||||
assert_eq!(client_key(&headers), "direct");
|
||||
headers.insert("x-real-ip", HeaderValue::from_static(" 203.0.113.9 "));
|
||||
assert_eq!(client_key(&headers), "203.0.113.9");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
|
|
|
|||
184
crates/ghostlight-dungeon/src/auth_guard.rs
Normal file
184
crates/ghostlight-dungeon/src/auth_guard.rs
Normal file
|
|
@ -0,0 +1,184 @@
|
|||
//! What stands between the unauthenticated sign-in routes and the open internet.
|
||||
//!
|
||||
//! Browser binding. A Heimdall attempt handle is redeemable by whoever holds
|
||||
//! it, so `begin` also mints a random secret, returns it to the beginning
|
||||
//! browser as an HttpOnly cookie, and keeps only its hash against the handle.
|
||||
//! `complete` must present that cookie, once, before the attempt expires: a
|
||||
//! handle begun in one browser cannot be completed from another. This is the
|
||||
//! OAuth `state` pattern (RFC 6749 section 10.12, CSRF on the redirect) and
|
||||
//! the same binding PKCE (RFC 7636) gives a code: the party that starts the
|
||||
//! flow holds a secret the interceptor never sees.
|
||||
//!
|
||||
//! Throttle. A fixed-window per-client counter on the same routes. Clients are
|
||||
//! keyed by what the caller passes, which behind the reverse proxy is the
|
||||
//! `X-Real-IP` value nginx sets.
|
||||
|
||||
use crate::app_session::secret_hash;
|
||||
use chrono::{DateTime, Utc};
|
||||
use rand::RngCore;
|
||||
use std::{collections::HashMap, sync::Mutex};
|
||||
|
||||
pub(crate) const BEGIN_COOKIE: &str = "ghostlight_auth";
|
||||
/// How long a begun sign-in may stay open, whatever Heimdall allows.
|
||||
pub(crate) const BEGIN_TTL_SECONDS: i64 = 600;
|
||||
const MAX_PENDING: usize = 4096;
|
||||
const WINDOW_SECONDS: i64 = 60;
|
||||
const MAX_PER_WINDOW: u32 = 30;
|
||||
const MAX_CLIENTS: usize = 8192;
|
||||
|
||||
struct Pending {
|
||||
secret_hash: String,
|
||||
expires_at: DateTime<Utc>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct AuthGuard {
|
||||
pending: Mutex<HashMap<String, Pending>>,
|
||||
windows: Mutex<HashMap<String, (i64, u32)>>,
|
||||
}
|
||||
|
||||
impl AuthGuard {
|
||||
/// Opens a binding for `handle` and returns the secret for the browser's
|
||||
/// cookie, or `None` when too many sign-ins are already open.
|
||||
pub(crate) fn start(&self, handle: &str, expires_at: DateTime<Utc>, now: DateTime<Utc>) -> Option<String> {
|
||||
let mut pending = self.pending.lock().expect("auth guard");
|
||||
pending.retain(|_, attempt| attempt.expires_at > now);
|
||||
if pending.len() >= MAX_PENDING {
|
||||
return None;
|
||||
}
|
||||
let mut bytes = [0_u8; 32];
|
||||
rand::rng().fill_bytes(&mut bytes);
|
||||
let secret: String = bytes.iter().map(|byte| format!("{byte:02x}")).collect();
|
||||
pending.insert(
|
||||
handle.to_owned(),
|
||||
Pending {
|
||||
secret_hash: secret_hash(&secret),
|
||||
expires_at,
|
||||
},
|
||||
);
|
||||
Some(secret)
|
||||
}
|
||||
|
||||
/// Whether `secret` is the live binding for `handle`; spends nothing.
|
||||
pub(crate) fn matches(&self, handle: &str, secret: &str, now: DateTime<Utc>) -> bool {
|
||||
self.pending
|
||||
.lock()
|
||||
.expect("auth guard")
|
||||
.get(handle)
|
||||
.is_some_and(|attempt| attempt.expires_at > now && attempt.secret_hash == secret_hash(secret))
|
||||
}
|
||||
|
||||
/// Spends the binding: true exactly once for a live, matching secret.
|
||||
pub(crate) fn consume(&self, handle: &str, secret: &str, now: DateTime<Utc>) -> bool {
|
||||
let mut pending = self.pending.lock().expect("auth guard");
|
||||
if !pending
|
||||
.get(handle)
|
||||
.is_some_and(|attempt| attempt.expires_at > now && attempt.secret_hash == secret_hash(secret))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
pending.remove(handle);
|
||||
true
|
||||
}
|
||||
|
||||
/// Counts one request from `client`; false once it has used its window.
|
||||
pub(crate) fn allow(&self, client: &str, now: DateTime<Utc>) -> bool {
|
||||
let window = now.timestamp().div_euclid(WINDOW_SECONDS);
|
||||
let mut windows = self.windows.lock().expect("auth guard");
|
||||
if windows.len() >= MAX_CLIENTS {
|
||||
windows.retain(|_, (started, _)| *started == window);
|
||||
if windows.len() >= MAX_CLIENTS && !windows.contains_key(client) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
let entry = windows.entry(client.to_owned()).or_insert((window, 0));
|
||||
if entry.0 != window {
|
||||
*entry = (window, 0);
|
||||
}
|
||||
entry.1 += 1;
|
||||
entry.1 <= MAX_PER_WINDOW
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use chrono::Duration;
|
||||
|
||||
#[test]
|
||||
fn a_binding_is_spent_once_and_only_by_its_own_secret_and_handle() {
|
||||
let guard = AuthGuard::default();
|
||||
let now = Utc::now();
|
||||
let secret = guard.start("handle-a", now + Duration::minutes(5), now).unwrap();
|
||||
let other = guard.start("handle-b", now + Duration::minutes(5), now).unwrap();
|
||||
assert_ne!(secret, other);
|
||||
assert_eq!(secret.len(), 64);
|
||||
assert!(guard.matches("handle-a", &secret, now));
|
||||
assert!(!guard.matches("handle-a", &other, now), "another begin's secret");
|
||||
assert!(!guard.matches("handle-a", "", now));
|
||||
assert!(!guard.matches("handle-unknown", &secret, now));
|
||||
assert!(!guard.consume("handle-a", &other, now));
|
||||
assert!(guard.matches("handle-a", &secret, now), "a refused spend keeps the binding");
|
||||
assert!(guard.consume("handle-a", &secret, now));
|
||||
assert!(!guard.consume("handle-a", &secret, now), "single use");
|
||||
assert!(!guard.matches("handle-a", &secret, now));
|
||||
assert!(guard.consume("handle-b", &other, now), "the other binding is untouched");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_binding_expires() {
|
||||
let guard = AuthGuard::default();
|
||||
let now = Utc::now();
|
||||
let expiry = now + Duration::minutes(5);
|
||||
let secret = guard.start("h", expiry, now).unwrap();
|
||||
assert!(guard.matches("h", &secret, expiry - Duration::seconds(1)));
|
||||
assert!(!guard.matches("h", &secret, expiry));
|
||||
assert!(!guard.consume("h", &secret, expiry));
|
||||
assert!(!guard.consume("h", &secret, expiry + Duration::hours(1)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn expired_bindings_are_dropped_and_the_open_set_is_bounded() {
|
||||
let guard = AuthGuard::default();
|
||||
let now = Utc::now();
|
||||
for index in 0..MAX_PENDING {
|
||||
assert!(guard.start(&format!("h{index}"), now + Duration::minutes(1), now).is_some());
|
||||
}
|
||||
assert!(guard.start("one-too-many", now + Duration::minutes(1), now).is_none());
|
||||
let later = now + Duration::minutes(2);
|
||||
assert!(guard.start("after-expiry", later + Duration::minutes(1), later).is_some());
|
||||
assert_eq!(guard.pending.lock().unwrap().len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_client_gets_a_fixed_window_and_clients_are_counted_apart() {
|
||||
let guard = AuthGuard::default();
|
||||
let start = DateTime::<Utc>::from_timestamp(1_000_020, 0).unwrap();
|
||||
assert_eq!(start.timestamp() % WINDOW_SECONDS, 0);
|
||||
for _ in 0..MAX_PER_WINDOW {
|
||||
assert!(guard.allow("203.0.113.9", start));
|
||||
}
|
||||
assert!(!guard.allow("203.0.113.9", start + Duration::seconds(59)));
|
||||
assert!(guard.allow("203.0.113.10", start + Duration::seconds(59)), "another client");
|
||||
assert!(guard.allow("203.0.113.9", start + Duration::seconds(60)), "the next window");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_full_client_table_forgets_old_windows_and_refuses_strangers_not_counts() {
|
||||
let guard = AuthGuard::default();
|
||||
let start = DateTime::<Utc>::from_timestamp(1_000_020, 0).unwrap();
|
||||
for index in 0..MAX_CLIENTS {
|
||||
guard.allow(&format!("old{index}"), start);
|
||||
}
|
||||
let later = start + Duration::seconds(WINDOW_SECONDS);
|
||||
for _ in 0..MAX_PER_WINDOW {
|
||||
assert!(guard.allow("busy", later));
|
||||
}
|
||||
for index in 0..MAX_CLIENTS {
|
||||
guard.allow(&format!("fresh{index}"), later);
|
||||
}
|
||||
assert!(!guard.allow("busy", later), "pruning keeps the current window's counts");
|
||||
assert!(guard.windows.lock().unwrap().len() <= MAX_CLIENTS);
|
||||
assert!(!guard.allow("brand-new", later), "a full table refuses a stranger rather than forget everyone");
|
||||
}
|
||||
}
|
||||
|
|
@ -260,6 +260,17 @@ impl Catalog {
|
|||
Ok(Ok(identity.to_owned()))
|
||||
}
|
||||
|
||||
/// Links a second external identity to the account `principal` names.
|
||||
/// Test-only until a second-identity link is a designed feature.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn link_identity(&mut self, principal: &str, identity: &str) -> anyhow::Result<()> {
|
||||
let account_id = self.state.identities[principal].clone();
|
||||
let mut next = self.state.clone();
|
||||
next.identities.insert(identity.to_owned(), account_id.clone());
|
||||
next.accounts.get_mut(&account_id).unwrap().identities.push(identity.to_owned());
|
||||
self.commit(next)
|
||||
}
|
||||
|
||||
pub(crate) fn timeline(&self, id: &str) -> Option<&Timeline> {
|
||||
self.state.timelines.get(id)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -135,13 +135,145 @@ impl SessionRefresher for HeimdallClient {
|
|||
}
|
||||
}
|
||||
|
||||
/// A sign-in provider Heimdall may be asked to authenticate with. The Dungeon
|
||||
/// owns which of them it offers; Heimdall's app profile owns which it accepts.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum AuthProvider {
|
||||
Google,
|
||||
Discord,
|
||||
Twitch,
|
||||
}
|
||||
|
||||
impl AuthProvider {
|
||||
pub(crate) fn parse(name: &str) -> Option<Self> {
|
||||
match name {
|
||||
"google" => Some(Self::Google),
|
||||
"discord" => Some(Self::Discord),
|
||||
"twitch" => Some(Self::Twitch),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::Google => "google",
|
||||
Self::Discord => "discord",
|
||||
Self::Twitch => "twitch",
|
||||
}
|
||||
}
|
||||
|
||||
/// The offered set from `GHOSTLIGHT_AUTH_PROVIDERS`, a comma list. An
|
||||
/// unnamed provider is a startup error, not a silent drop.
|
||||
fn set_from(value: &str) -> anyhow::Result<Vec<Self>> {
|
||||
let mut set = Vec::new();
|
||||
for name in value.split(',').map(str::trim).filter(|name| !name.is_empty()) {
|
||||
let provider = Self::parse(name)
|
||||
.with_context(|| format!("GHOSTLIGHT_AUTH_PROVIDERS names an unknown provider {name:?}"))?;
|
||||
if !set.contains(&provider) {
|
||||
set.push(provider);
|
||||
}
|
||||
}
|
||||
anyhow::ensure!(!set.is_empty(), "GHOSTLIGHT_AUTH_PROVIDERS names no provider");
|
||||
Ok(set)
|
||||
}
|
||||
}
|
||||
|
||||
/// The sign-in half of Heimdall the HTTP handlers use, as a port so a scripted
|
||||
/// Heimdall can stand in for the real one. The refresh loop's half is the
|
||||
/// supertrait.
|
||||
#[async_trait::async_trait]
|
||||
pub(crate) trait HeimdallPort: SessionRefresher + Send + Sync {
|
||||
/// The provider named, if the Dungeon offers it.
|
||||
fn offered(&self, name: &str) -> Option<AuthProvider>;
|
||||
|
||||
async fn begin(
|
||||
&self,
|
||||
provider: AuthProvider,
|
||||
idempotency_key: &str,
|
||||
) -> anyhow::Result<AuthBeginReceipt>;
|
||||
|
||||
async fn complete(
|
||||
&self,
|
||||
handle: &str,
|
||||
idempotency_key: &str,
|
||||
) -> anyhow::Result<AuthCompletionReceipt>;
|
||||
|
||||
async fn verify_completion(
|
||||
&self,
|
||||
completion: AuthCompletionReceipt,
|
||||
) -> anyhow::Result<VerifiedSessionAdmission>;
|
||||
|
||||
async fn logout(
|
||||
&self,
|
||||
refresh_token: &str,
|
||||
idempotency_key: &str,
|
||||
) -> anyhow::Result<AuthLogoutReceipt>;
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl HeimdallPort for HeimdallClient {
|
||||
fn offered(&self, name: &str) -> Option<AuthProvider> {
|
||||
AuthProvider::parse(name).filter(|provider| self.providers.contains(provider))
|
||||
}
|
||||
|
||||
async fn begin(
|
||||
&self,
|
||||
provider: AuthProvider,
|
||||
idempotency_key: &str,
|
||||
) -> anyhow::Result<AuthBeginReceipt> {
|
||||
HeimdallClient::begin(self, provider, idempotency_key).await
|
||||
}
|
||||
|
||||
async fn complete(
|
||||
&self,
|
||||
handle: &str,
|
||||
idempotency_key: &str,
|
||||
) -> anyhow::Result<AuthCompletionReceipt> {
|
||||
HeimdallClient::complete(self, handle, idempotency_key).await
|
||||
}
|
||||
|
||||
async fn verify_completion(
|
||||
&self,
|
||||
completion: AuthCompletionReceipt,
|
||||
) -> anyhow::Result<VerifiedSessionAdmission> {
|
||||
HeimdallClient::verify_completion(self, completion).await
|
||||
}
|
||||
|
||||
async fn logout(
|
||||
&self,
|
||||
refresh_token: &str,
|
||||
idempotency_key: &str,
|
||||
) -> anyhow::Result<AuthLogoutReceipt> {
|
||||
HeimdallClient::logout(self, refresh_token, idempotency_key).await
|
||||
}
|
||||
}
|
||||
#[derive(Clone)]
|
||||
struct DiscordGate {
|
||||
guild_id: String,
|
||||
role_id: String,
|
||||
}
|
||||
|
||||
impl DiscordGate {
|
||||
fn policy(&self) -> DiscordRolePolicy<'_> {
|
||||
DiscordRolePolicy {
|
||||
kind: "discord_role_access",
|
||||
guild_id: &self.guild_id,
|
||||
allowed_role_ids: [&self.role_id],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct HeimdallClient {
|
||||
http: Client,
|
||||
issuer: String,
|
||||
public_app_url: String,
|
||||
discord_guild_id: String,
|
||||
discord_role_id: String,
|
||||
providers: Vec<AuthProvider>,
|
||||
/// The Discord guild-role policy Heimdall's ghostlight profile demands with a
|
||||
/// Discord sign-in. It gates Discord only; the Dungeon's invite and account
|
||||
/// gate every other provider.
|
||||
discord: Option<DiscordGate>,
|
||||
boundary_locator: HeimdallBoundaryLocator,
|
||||
runtime_id: String,
|
||||
shared_secret: String,
|
||||
|
|
@ -248,7 +380,8 @@ struct BeginCommand<'a> {
|
|||
provider: &'a str,
|
||||
mode: &'a str,
|
||||
return_to: &'a str,
|
||||
entitlement_policy: DiscordRolePolicy<'a>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
entitlement_policy: Option<DiscordRolePolicy<'a>>,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
|
|
@ -256,7 +389,8 @@ struct BeginCommand<'a> {
|
|||
struct RefreshCommand<'a> {
|
||||
schema: &'static str,
|
||||
refresh_token: &'a str,
|
||||
entitlement_policy: DiscordRolePolicy<'a>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
entitlement_policy: Option<DiscordRolePolicy<'a>>,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
|
|
@ -472,6 +606,26 @@ impl HeimdallClient {
|
|||
if shared_secret.is_empty() {
|
||||
bail!("Ghostlight's Heimdall app secret is empty");
|
||||
}
|
||||
let providers = AuthProvider::set_from(
|
||||
&std::env::var("GHOSTLIGHT_AUTH_PROVIDERS").unwrap_or_else(|_| "discord".into()),
|
||||
)?;
|
||||
// Heimdall's ghostlight profile demands the Discord role policy on
|
||||
// every begin and refresh, so it is required when Discord is offered
|
||||
// and still carried on refresh when it is configured without it.
|
||||
let discord = if providers.contains(&AuthProvider::Discord) {
|
||||
Some(DiscordGate {
|
||||
guild_id: required_env("GHOSTLIGHT_DISCORD_GUILD_ID")?,
|
||||
role_id: required_env("GHOSTLIGHT_DISCORD_ROLE_ID")?,
|
||||
})
|
||||
} else {
|
||||
match (
|
||||
required_env("GHOSTLIGHT_DISCORD_GUILD_ID"),
|
||||
required_env("GHOSTLIGHT_DISCORD_ROLE_ID"),
|
||||
) {
|
||||
(Ok(guild_id), Ok(role_id)) => Some(DiscordGate { guild_id, role_id }),
|
||||
_ => None,
|
||||
}
|
||||
};
|
||||
Ok(Self {
|
||||
http: Client::builder().timeout(Duration::from_secs(10)).build()?,
|
||||
issuer: std::env::var("GHOSTLIGHT_HEIMDALL_BASE_URL")
|
||||
|
|
@ -480,8 +634,8 @@ impl HeimdallClient {
|
|||
.into(),
|
||||
public_app_url: std::env::var("GHOSTLIGHT_PUBLIC_APP_URL")
|
||||
.unwrap_or_else(|_| "https://yggdrasil.gamecult.org/ghostlight/".into()),
|
||||
discord_guild_id: required_env("GHOSTLIGHT_DISCORD_GUILD_ID")?,
|
||||
discord_role_id: required_env("GHOSTLIGHT_DISCORD_ROLE_ID")?,
|
||||
providers,
|
||||
discord,
|
||||
boundary_locator: HeimdallBoundaryLocator::Odin {
|
||||
endpoint: odin_endpoint,
|
||||
expected,
|
||||
|
|
@ -498,8 +652,11 @@ impl HeimdallClient {
|
|||
http: Client::new(),
|
||||
issuer: "https://heimdall.invalid".into(),
|
||||
public_app_url: "https://ghostlight.invalid/".into(),
|
||||
discord_guild_id: "guild-kltst".into(),
|
||||
discord_role_id: "role-kltst".into(),
|
||||
providers: vec![AuthProvider::Google, AuthProvider::Discord, AuthProvider::Twitch],
|
||||
discord: Some(DiscordGate {
|
||||
guild_id: "guild-kltst".into(),
|
||||
role_id: "role-kltst".into(),
|
||||
}),
|
||||
boundary_locator: HeimdallBoundaryLocator::Fixed(ResolvedHeimdallBoundary {
|
||||
endpoint: "127.0.0.1:9".parse().unwrap(),
|
||||
daemon_id: "yggdrasil-heimdall".into(),
|
||||
|
|
@ -523,17 +680,26 @@ impl HeimdallClient {
|
|||
self
|
||||
}
|
||||
|
||||
pub async fn begin(&self, idempotency_key: &str) -> anyhow::Result<AuthBeginReceipt> {
|
||||
let payload = BeginCommand {
|
||||
provider: "discord",
|
||||
fn begin_command(&self, provider: AuthProvider) -> BeginCommand<'_> {
|
||||
BeginCommand {
|
||||
provider: provider.as_str(),
|
||||
mode: "sign_in",
|
||||
return_to: &self.public_app_url,
|
||||
entitlement_policy: DiscordRolePolicy {
|
||||
kind: "discord_role_access",
|
||||
guild_id: &self.discord_guild_id,
|
||||
allowed_role_ids: [&self.discord_role_id],
|
||||
},
|
||||
};
|
||||
// The Discord role gate rides the Discord sign-in only.
|
||||
entitlement_policy: self
|
||||
.discord
|
||||
.as_ref()
|
||||
.filter(|_| provider == AuthProvider::Discord)
|
||||
.map(DiscordGate::policy),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn begin(
|
||||
&self,
|
||||
provider: AuthProvider,
|
||||
idempotency_key: &str,
|
||||
) -> anyhow::Result<AuthBeginReceipt> {
|
||||
let payload = self.begin_command(provider);
|
||||
self.invoke(
|
||||
"heimdall.auth.begin",
|
||||
"heimdall.auth_begin_command.v1",
|
||||
|
|
@ -567,11 +733,7 @@ impl HeimdallClient {
|
|||
let payload = RefreshCommand {
|
||||
schema: "heimdall.auth_refresh_command.v1",
|
||||
refresh_token,
|
||||
entitlement_policy: DiscordRolePolicy {
|
||||
kind: "discord_role_access",
|
||||
guild_id: &self.discord_guild_id,
|
||||
allowed_role_ids: [&self.discord_role_id],
|
||||
},
|
||||
entitlement_policy: self.discord.as_ref().map(DiscordGate::policy),
|
||||
};
|
||||
self.invoke(
|
||||
"heimdall.auth.refresh",
|
||||
|
|
@ -1676,3 +1838,65 @@ mod tests {
|
|||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod provider_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_discord_role_policy_rides_the_discord_begin_alone() {
|
||||
let client = HeimdallClient::fixture();
|
||||
let discord = serde_json::to_value(client.begin_command(AuthProvider::Discord)).unwrap();
|
||||
assert_eq!(
|
||||
discord,
|
||||
serde_json::json!({
|
||||
"provider": "discord",
|
||||
"mode": "sign_in",
|
||||
"returnTo": "https://ghostlight.invalid/",
|
||||
"entitlementPolicy": {
|
||||
"kind": "discord_role_access",
|
||||
"guildId": "guild-kltst",
|
||||
"allowedRoleIds": ["role-kltst"],
|
||||
},
|
||||
})
|
||||
);
|
||||
for (provider, name) in [(AuthProvider::Google, "google"), (AuthProvider::Twitch, "twitch")] {
|
||||
let command = serde_json::to_value(client.begin_command(provider)).unwrap();
|
||||
assert_eq!(
|
||||
command,
|
||||
serde_json::json!({
|
||||
"provider": name,
|
||||
"mode": "sign_in",
|
||||
"returnTo": "https://ghostlight.invalid/",
|
||||
}),
|
||||
"the Discord role gate must not gate {name}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_offered_set_is_the_configured_set() {
|
||||
let mut client = HeimdallClient::fixture();
|
||||
client.providers = vec![AuthProvider::Discord, AuthProvider::Google];
|
||||
assert_eq!(client.offered("google"), Some(AuthProvider::Google));
|
||||
assert_eq!(client.offered("discord"), Some(AuthProvider::Discord));
|
||||
assert_eq!(client.offered("twitch"), None);
|
||||
assert_eq!(client.offered("Google"), None);
|
||||
assert_eq!(client.offered("patreon"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_provider_list_names_only_known_providers_and_at_least_one() {
|
||||
assert_eq!(
|
||||
AuthProvider::set_from("google, discord,google").unwrap(),
|
||||
vec![AuthProvider::Google, AuthProvider::Discord]
|
||||
);
|
||||
assert_eq!(AuthProvider::set_from("twitch").unwrap(), vec![AuthProvider::Twitch]);
|
||||
for bad in ["", " , ", "github", "discord,patreon"] {
|
||||
assert!(AuthProvider::set_from(bad).is_err(), "{bad:?}");
|
||||
}
|
||||
for provider in [AuthProvider::Google, AuthProvider::Discord, AuthProvider::Twitch] {
|
||||
assert_eq!(AuthProvider::parse(provider.as_str()), Some(provider));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
mod api;
|
||||
mod app_session;
|
||||
mod auth_guard;
|
||||
mod begin;
|
||||
mod catalog;
|
||||
mod heimdall;
|
||||
|
|
|
|||
|
|
@ -4,9 +4,10 @@
|
|||
use crate::{
|
||||
api,
|
||||
app_session::AppSessionOwner,
|
||||
auth_guard::AuthGuard,
|
||||
begin::{NoVaults, Vaults},
|
||||
catalog::Catalog,
|
||||
heimdall::HeimdallClient,
|
||||
heimdall::{HeimdallClient, HeimdallPort},
|
||||
idunn_health::{
|
||||
IDUNN_RUNTIME_CANDIDATE_BIND_ENVIRONMENT, ProcessWriteLeaseGuard, RuntimePresencePublisher,
|
||||
TARGET as GHOSTLIGHT_TARGET,
|
||||
|
|
@ -60,7 +61,8 @@ pub(crate) struct AppState {
|
|||
pub(crate) timelines: Arc<Timelines>,
|
||||
pub(crate) vaults: Arc<dyn Vaults>,
|
||||
pub(crate) sessions: Arc<Mutex<AppSessionOwner>>,
|
||||
pub(crate) heimdall: Arc<HeimdallClient>,
|
||||
pub(crate) heimdall: Arc<dyn HeimdallPort>,
|
||||
pub(crate) auth: Arc<AuthGuard>,
|
||||
pub(crate) runtime_id: String,
|
||||
pub(crate) runtime_health: Option<RuntimeHealthOwner>,
|
||||
pub(crate) fatal: mpsc::UnboundedSender<String>,
|
||||
|
|
@ -208,6 +210,7 @@ pub(crate) async fn run(state_root_binding: Option<PathBuf>) -> anyhow::Result<(
|
|||
vaults: Arc::new(NoVaults),
|
||||
sessions: Arc::new(Mutex::new(sessions)),
|
||||
heimdall,
|
||||
auth: Arc::default(),
|
||||
runtime_id,
|
||||
runtime_health: None,
|
||||
fatal,
|
||||
|
|
|
|||
|
|
@ -17,7 +17,7 @@ const SESSION_REFRESH_PERIOD: Duration = Duration::from_secs(60);
|
|||
/// spent upstream whose verification could not yet be judged.
|
||||
pub(crate) async fn run_refresh_loop(
|
||||
sessions: &Mutex<AppSessionOwner>,
|
||||
heimdall: &impl SessionRefresher,
|
||||
heimdall: &(impl SessionRefresher + ?Sized),
|
||||
) -> anyhow::Result<()> {
|
||||
let mut interval = tokio::time::interval(SESSION_REFRESH_PERIOD);
|
||||
interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
|
||||
|
|
@ -34,7 +34,7 @@ pub(crate) async fn run_refresh_loop(
|
|||
/// fetched: the next pass verifies it instead of refreshing again.
|
||||
async fn refresh_due_sessions(
|
||||
sessions: &Mutex<AppSessionOwner>,
|
||||
heimdall: &impl SessionRefresher,
|
||||
heimdall: &(impl SessionRefresher + ?Sized),
|
||||
unverified: &mut HashMap<String, heimdall::AuthCompletionReceipt>,
|
||||
) -> anyhow::Result<()> {
|
||||
let candidates = sessions
|
||||
|
|
|
|||
Loading…
Reference in a new issue