Dungeon sign-in: the invite is presented at begin, grants Heimdall's first login, and is redeemed at complete; the Discord role policy goes
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
986ff92d24
commit
ce90413870
6 changed files with 208 additions and 153 deletions
|
|
@ -103,7 +103,7 @@ function signInView(message) {
|
|||
|
||||
async function beginSignIn(provider, invite, out) {
|
||||
out.replaceChildren(el("p", { class: "note pulse" }, "Asking " + provider + " for a sign-in"));
|
||||
const { status, body } = await post("auth/begin", { key: uuid(), provider });
|
||||
const { status, body } = await post("auth/begin", invite ? { key: uuid(), provider, invite } : { key: uuid(), provider });
|
||||
if (status !== 200) return out.replaceChildren(errorLine(body.error || "Sign-in could not begin (" + status + ")."));
|
||||
let target = null;
|
||||
try {
|
||||
|
|
@ -111,7 +111,7 @@ async function beginSignIn(provider, invite, out) {
|
|||
if ((body.allowedOrigins || []).includes(url.origin) && url.protocol === "https:") target = url.href;
|
||||
} catch { target = null; }
|
||||
if (!target) return out.replaceChildren(errorLine("The sign-in address was not one this page will open."));
|
||||
S.signIn = { handle: body.handle, invite, target, until: Date.now() + 9 * 60 * 1000 };
|
||||
S.signIn = { handle: body.handle, target, until: Date.now() + 9 * 60 * 1000 };
|
||||
window.open(target, "_blank", "noopener");
|
||||
resumeSignIn(out);
|
||||
}
|
||||
|
|
@ -124,7 +124,7 @@ async function resumeSignIn(out) {
|
|||
while (S.signIn === attempt && Date.now() < attempt.until) {
|
||||
await new Promise((r) => setTimeout(r, 2500));
|
||||
if (S.signIn !== attempt) return;
|
||||
const { status, body } = await post("auth/complete", { handle: attempt.handle, key: uuid(), invite: attempt.invite || null });
|
||||
const { status, body } = await post("auth/complete", { handle: attempt.handle, key: uuid() });
|
||||
if (status === 202) continue;
|
||||
S.signIn = null;
|
||||
if (status === 200 && body.status === "authenticated") { history.replaceState(null, "", location.pathname); return boot(); }
|
||||
|
|
|
|||
|
|
@ -524,6 +524,10 @@ struct AuthBeginBody {
|
|||
key: String,
|
||||
/// One of the providers the daemon offers (`GHOSTLIGHT_AUTH_PROVIDERS`).
|
||||
provider: String,
|
||||
/// The invite the browser presents for a first sign-in, if any. Checked
|
||||
/// against the catalog now, bound to this attempt, spent at complete.
|
||||
#[serde(default)]
|
||||
invite: Option<String>,
|
||||
}
|
||||
|
||||
/// The throttle's key: the address nginx sets in `X-Real-IP`. Behind the proxy
|
||||
|
|
@ -567,7 +571,13 @@ async fn auth_begin(
|
|||
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 {
|
||||
let invite = body.invite.map(|token| token.trim().to_owned()).filter(|token| !token.is_empty());
|
||||
if let Some(token) = &invite
|
||||
&& !state.catalog.lock().await.invite_is_live(token, now)
|
||||
{
|
||||
return refuse(StatusCode::FORBIDDEN, "that invite is spent or expired");
|
||||
}
|
||||
let receipt = match state.heimdall.begin(provider, invite.is_some(), &body.key).await {
|
||||
Ok(receipt) => receipt,
|
||||
Err(error) => {
|
||||
tracing::warn!(%error, "Heimdall refused to begin a sign-in");
|
||||
|
|
@ -578,7 +588,7 @@ async fn auth_begin(
|
|||
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 {
|
||||
let Some(secret) = state.auth.start(&receipt.handle, invite, expiry, now) else {
|
||||
return refuse(StatusCode::SERVICE_UNAVAILABLE, "too many sign-ins are open; try again shortly");
|
||||
};
|
||||
let mut response = reply(
|
||||
|
|
@ -601,9 +611,6 @@ async fn auth_begin(
|
|||
struct AuthCompleteBody {
|
||||
handle: String,
|
||||
key: String,
|
||||
/// The invite token the sign-in link carried, if any.
|
||||
#[serde(default)]
|
||||
invite: Option<String>,
|
||||
}
|
||||
|
||||
async fn auth_complete(
|
||||
|
|
@ -635,9 +642,9 @@ async fn auth_complete(
|
|||
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) {
|
||||
let Some(invite) = state.auth.consume(&body.handle, secret, now) else {
|
||||
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
|
||||
|
|
@ -665,7 +672,7 @@ async fn auth_complete(
|
|||
.catalog
|
||||
.lock()
|
||||
.await
|
||||
.sign_in(admission.account_id(), body.invite.as_deref(), Utc::now())
|
||||
.sign_in(admission.account_id(), invite.as_deref(), Utc::now())
|
||||
{
|
||||
Ok(Ok(principal)) => principal,
|
||||
Ok(Err(refusal)) => {
|
||||
|
|
@ -788,6 +795,8 @@ mod tests {
|
|||
#[derive(Default)]
|
||||
struct FakeHeimdall {
|
||||
begun: std::sync::Mutex<Vec<AuthProvider>>,
|
||||
/// Whether each begin carried the first-login grant, in order.
|
||||
grants: std::sync::Mutex<Vec<bool>>,
|
||||
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.
|
||||
|
|
@ -835,9 +844,10 @@ mod tests {
|
|||
AuthProvider::parse(name).filter(|provider| *provider != AuthProvider::Twitch)
|
||||
}
|
||||
|
||||
async fn begin(&self, provider: AuthProvider, _: &str) -> anyhow::Result<AuthBeginReceipt> {
|
||||
async fn begin(&self, provider: AuthProvider, grant: bool, _: &str) -> anyhow::Result<AuthBeginReceipt> {
|
||||
let mut begun = self.begun.lock().unwrap();
|
||||
begun.push(provider);
|
||||
self.grants.lock().unwrap().push(grant);
|
||||
if let Some(forced) = self.begin_override.lock().unwrap().take() {
|
||||
return forced;
|
||||
}
|
||||
|
|
@ -1304,12 +1314,17 @@ mod tests {
|
|||
|
||||
/// 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) {
|
||||
begin_with_invite(app, provider, real_ip, None).await
|
||||
}
|
||||
|
||||
/// Begins a sign-in presenting `invite`, the way the page does at begin.
|
||||
async fn begin_with_invite(app: &App, provider: &str, real_ip: &str, invite: Option<&str>) -> (String, String) {
|
||||
let (status, cookies, body) = auth_call(
|
||||
app,
|
||||
"/api/auth/begin",
|
||||
&[],
|
||||
real_ip,
|
||||
json!({"key": Uuid::new_v4(), "provider": provider}),
|
||||
json!({"key": Uuid::new_v4(), "provider": provider, "invite": invite}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(status, StatusCode::OK, "{body}");
|
||||
|
|
@ -1317,13 +1332,13 @@ mod tests {
|
|||
(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) {
|
||||
async fn complete(app: &App, handle: &str, jar: &[(&str, &str)]) -> (StatusCode, Vec<String>, Value) {
|
||||
auth_call(
|
||||
app,
|
||||
"/api/auth/complete",
|
||||
jar,
|
||||
A_BROWSER,
|
||||
json!({"handle": handle, "key": Uuid::new_v4(), "invite": invite}),
|
||||
json!({"handle": handle, "key": Uuid::new_v4()}),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
|
@ -1417,7 +1432,7 @@ mod tests {
|
|||
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 (handle, victim_secret) = begin_with_invite(&app, "google", "198.51.100.1", Some(&invite)).await;
|
||||
let (_, attacker_secret) = begin_sign_in(&app, "google", "198.51.100.2").await;
|
||||
app.heimdall.finish(&handle, "authenticated", "victim");
|
||||
for jar in [
|
||||
|
|
@ -1426,13 +1441,14 @@ mod tests {
|
|||
vec![("ghostlight_auth", attacker_secret.as_str())],
|
||||
vec![("ghostlight_session", victim_secret.as_str())],
|
||||
] {
|
||||
let (status, cookies, _) = complete(&app, &handle, &jar, Some(&invite)).await;
|
||||
let (status, cookies, _) = complete(&app, &handle, &jar).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");
|
||||
assert!(app.state.catalog.lock().await.invite_is_live(&invite, Utc::now()), "a refused completion spends no invite");
|
||||
let (status, cookies, body) =
|
||||
complete(&app, &handle, &[("ghostlight_auth", &victim_secret)], Some(&invite)).await;
|
||||
complete(&app, &handle, &[("ghostlight_auth", &victim_secret)]).await;
|
||||
assert_eq!(status, StatusCode::OK, "{body}");
|
||||
assert!(cookie_named(&cookies, "ghostlight_session").is_some());
|
||||
}
|
||||
|
|
@ -1441,14 +1457,14 @@ mod tests {
|
|||
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 (handle, secret) = begin_with_invite(&app, "discord", A_BROWSER, Some(&invite)).await;
|
||||
let jar = [("ghostlight_auth", secret.as_str())];
|
||||
let (status, cookies, _) = complete(&app, &handle, &jar, Some(&invite)).await;
|
||||
let (status, cookies, _) = complete(&app, &handle, &jar).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");
|
||||
assert_eq!(complete(&app, &handle, &jar).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;
|
||||
let (status, cookies, body) = complete(&app, &handle, &jar).await;
|
||||
assert_eq!(status, StatusCode::OK, "{body}");
|
||||
let session = cookie_named(&cookies, "ghostlight_session").unwrap();
|
||||
for flag in ["HttpOnly", "Secure", "SameSite=Lax", "Path=/ghostlight/"] {
|
||||
|
|
@ -1456,7 +1472,7 @@ mod tests {
|
|||
}
|
||||
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;
|
||||
let (status, cookies, _) = complete(&app, &handle, &jar).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;
|
||||
|
|
@ -1469,13 +1485,13 @@ mod tests {
|
|||
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;
|
||||
let (status, cookies, body) = complete(&app, &handle, &jar).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");
|
||||
assert_eq!(complete(&app, &handle, &jar).await.0, StatusCode::FORBIDDEN, "spent");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
|
|
@ -1483,10 +1499,10 @@ mod tests {
|
|||
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;
|
||||
let (status, _, body) = complete(&app, &handle, &[("ghostlight_auth", &secret)]).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;
|
||||
let (status, _, _) = complete(&app, "", &[("ghostlight_auth", &secret)]).await;
|
||||
assert_eq!(status, StatusCode::BAD_REQUEST);
|
||||
}
|
||||
|
||||
|
|
@ -1495,19 +1511,90 @@ mod tests {
|
|||
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;
|
||||
let (status, cookies, body) = complete(&app, &handle, &[("ghostlight_auth", &secret)]).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;
|
||||
let (handle, secret) = begin_with_invite(&app, "google", A_BROWSER, Some(&invite)).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);
|
||||
assert_eq!(complete(&app, &handle, &jar).await.0, StatusCode::OK);
|
||||
assert!(!app.state.catalog.lock().await.invite_is_live(&invite, Utc::now()), "complete spent the invite");
|
||||
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;
|
||||
let (status, _, _) = complete(&app, &handle, &[("ghostlight_auth", &secret)]).await;
|
||||
assert_eq!(status, StatusCode::OK, "the second device needs no invite");
|
||||
assert_eq!(*app.heimdall.grants.lock().unwrap().last().unwrap(), false, "and asks for no grant");
|
||||
let catalog = app.state.catalog.lock().await;
|
||||
assert_eq!(catalog.sign_in("deru", None, Utc::now()).unwrap().unwrap(), "deru", "the same account, whichever device");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn begin_with_a_live_invite_grants_and_consumes_nothing_and_without_one_does_not() {
|
||||
let app = app(vec![], &[]).await;
|
||||
let invite = invite(&app).await;
|
||||
begin_with_invite(&app, "google", "198.51.100.1", Some(&invite)).await;
|
||||
begin_with_invite(&app, "google", "198.51.100.2", Some(&format!(" {invite} "))).await;
|
||||
begin_with_invite(&app, "discord", "198.51.100.3", Some("")).await;
|
||||
begin_sign_in(&app, "google", "198.51.100.4").await;
|
||||
assert_eq!(*app.heimdall.grants.lock().unwrap(), vec![true, true, false, false]);
|
||||
assert!(app.state.catalog.lock().await.invite_is_live(&invite, Utc::now()), "begin spends nothing");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_dead_invite_is_refused_at_begin_before_heimdall_is_asked() {
|
||||
let app = app(vec![], &[]).await;
|
||||
let spent = invite(&app).await;
|
||||
let (handle, secret) = begin_with_invite(&app, "google", A_BROWSER, Some(&spent)).await;
|
||||
app.heimdall.finish(&handle, "authenticated", "deru");
|
||||
assert_eq!(complete(&app, &handle, &[("ghostlight_auth", &secret)]).await.0, StatusCode::OK);
|
||||
let expired = app
|
||||
.state
|
||||
.catalog
|
||||
.lock()
|
||||
.await
|
||||
.mint_invite(Utc::now() - chrono::Duration::hours(2), chrono::Duration::hours(1))
|
||||
.unwrap();
|
||||
let asked = app.heimdall.begun.lock().unwrap().len();
|
||||
for dead in [spent.as_str(), expired.as_str(), "never-minted"] {
|
||||
let (status, cookies, body) = auth_call(
|
||||
&app,
|
||||
"/api/auth/begin",
|
||||
&[],
|
||||
A_BROWSER,
|
||||
json!({"key": Uuid::new_v4(), "provider": "google", "invite": dead}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(status, StatusCode::FORBIDDEN, "{dead}");
|
||||
assert_eq!(body["error"], "that invite is spent or expired");
|
||||
assert!(cookies.is_empty());
|
||||
}
|
||||
assert_eq!(app.heimdall.begun.lock().unwrap().len(), asked, "Heimdall saw no begin");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_first_google_login_with_no_live_invite_is_refused_and_a_complete_body_cannot_carry_one() {
|
||||
let app = app(vec![], &[]).await;
|
||||
let invite = invite(&app).await;
|
||||
let (handle, secret) = begin_sign_in(&app, "google", A_BROWSER).await;
|
||||
app.heimdall.finish(&handle, "authenticated", "stranger");
|
||||
let jar = [("ghostlight_auth", secret.as_str())];
|
||||
let (status, _, body) = auth_call(
|
||||
&app,
|
||||
"/api/auth/complete",
|
||||
&jar,
|
||||
A_BROWSER,
|
||||
json!({"handle": handle, "key": Uuid::new_v4(), "invite": invite}),
|
||||
)
|
||||
.await;
|
||||
assert!(status.is_client_error(), "an invite at complete is not a field: {status}");
|
||||
assert_ne!(body["status"], "authenticated");
|
||||
let (status, cookies, body) = complete(&app, &handle, &jar).await;
|
||||
assert_eq!(status, StatusCode::FORBIDDEN);
|
||||
assert_eq!(body["status"], "refused");
|
||||
assert!(cookie_named(&cookies, "ghostlight_session").is_none());
|
||||
assert!(app.state.catalog.lock().await.invite_is_live(&invite, Utc::now()), "the live invite was not redeemed by a browser that never presented it");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
|
|
@ -1521,7 +1608,7 @@ mod tests {
|
|||
}
|
||||
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;
|
||||
let (status, cookies, body) = complete(&app, &handle, &[("ghostlight_auth", &secret)]).await;
|
||||
assert_eq!(status, StatusCode::FORBIDDEN, "{body}");
|
||||
assert!(cookie_named(&cookies, "ghostlight_session").is_none());
|
||||
}
|
||||
|
|
@ -1541,7 +1628,7 @@ mod tests {
|
|||
}
|
||||
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;
|
||||
let (status, _, _) = complete(&app, "x", &[]).await;
|
||||
assert_ne!(status, StatusCode::TOO_MANY_REQUESTS, "A_BROWSER has its own count");
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -29,6 +29,9 @@ const MAX_CLIENTS: usize = 8192;
|
|||
struct Pending {
|
||||
secret_hash: String,
|
||||
expires_at: DateTime<Utc>,
|
||||
/// The invite the browser presented at begin, held in memory only and for
|
||||
/// no longer than the attempt lives. Spent by `catalog.sign_in` at complete.
|
||||
invite: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
|
|
@ -40,7 +43,13 @@ pub(crate) struct AuthGuard {
|
|||
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> {
|
||||
pub(crate) fn start(
|
||||
&self,
|
||||
handle: &str,
|
||||
invite: Option<String>,
|
||||
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 {
|
||||
|
|
@ -54,6 +63,7 @@ impl AuthGuard {
|
|||
Pending {
|
||||
secret_hash: secret_hash(&secret),
|
||||
expires_at,
|
||||
invite,
|
||||
},
|
||||
);
|
||||
Some(secret)
|
||||
|
|
@ -68,17 +78,18 @@ impl AuthGuard {
|
|||
.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 {
|
||||
/// Spends the binding: `Some` exactly once for a live, matching secret,
|
||||
/// carrying the invite bound at begin; `None` when this is not that
|
||||
/// browser's attempt.
|
||||
pub(crate) fn consume(&self, handle: &str, secret: &str, now: DateTime<Utc>) -> Option<Option<String>> {
|
||||
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;
|
||||
return None;
|
||||
}
|
||||
pending.remove(handle);
|
||||
true
|
||||
pending.remove(handle).map(|attempt| attempt.invite)
|
||||
}
|
||||
|
||||
/// Counts one request from `client`; false once it has used its window.
|
||||
|
|
@ -109,20 +120,33 @@ mod tests {
|
|||
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();
|
||||
let secret = guard.start("handle-a", None, now + Duration::minutes(5), now).unwrap();
|
||||
let other = guard.start("handle-b", None, 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.consume("handle-a", &other, now).is_none());
|
||||
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.consume("handle-a", &secret, now).is_some());
|
||||
assert!(guard.consume("handle-a", &secret, now).is_none(), "single use");
|
||||
assert!(!guard.matches("handle-a", &secret, now));
|
||||
assert!(guard.consume("handle-b", &other, now), "the other binding is untouched");
|
||||
assert!(guard.consume("handle-b", &other, now).is_some(), "the other binding is untouched");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_invite_bound_at_begin_comes_back_once_to_the_beginning_browser_alone() {
|
||||
let guard = AuthGuard::default();
|
||||
let now = Utc::now();
|
||||
let soon = now + Duration::minutes(5);
|
||||
let secret = guard.start("h", Some("tok".into()), soon, now).unwrap();
|
||||
let other = guard.start("g", None, soon, now).unwrap();
|
||||
assert_eq!(guard.consume("h", &other, now), None, "another browser gets nothing and spends nothing");
|
||||
assert_eq!(guard.consume("h", &secret, now), Some(Some("tok".into())));
|
||||
assert_eq!(guard.consume("h", &secret, now), None);
|
||||
assert_eq!(guard.consume("g", &other, now), Some(None), "no invite bound is still this browser's");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
@ -130,11 +154,11 @@ mod tests {
|
|||
let guard = AuthGuard::default();
|
||||
let now = Utc::now();
|
||||
let expiry = now + Duration::minutes(5);
|
||||
let secret = guard.start("h", expiry, now).unwrap();
|
||||
let secret = guard.start("h", None, 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)));
|
||||
assert!(guard.consume("h", &secret, expiry).is_none());
|
||||
assert!(guard.consume("h", &secret, expiry + Duration::hours(1)).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
@ -142,11 +166,11 @@ mod tests {
|
|||
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(&format!("h{index}"), None, now + Duration::minutes(1), now).is_some());
|
||||
}
|
||||
assert!(guard.start("one-too-many", now + Duration::minutes(1), now).is_none());
|
||||
assert!(guard.start("one-too-many", None, 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!(guard.start("after-expiry", None, later + Duration::minutes(1), later).is_some());
|
||||
assert_eq!(guard.pending.lock().unwrap().len(), 1);
|
||||
}
|
||||
|
||||
|
|
@ -186,9 +210,9 @@ mod tests {
|
|||
fn a_binding_is_dead_at_its_expiry_instant_and_dropped_by_the_next_start() {
|
||||
let guard = AuthGuard::default();
|
||||
let now = Utc::now();
|
||||
guard.start("old", now + Duration::minutes(1), now).unwrap();
|
||||
guard.start("old", None, now + Duration::minutes(1), now).unwrap();
|
||||
let at_expiry = now + Duration::minutes(1);
|
||||
guard.start("new", at_expiry + Duration::minutes(1), at_expiry).unwrap();
|
||||
guard.start("new", None, at_expiry + Duration::minutes(1), at_expiry).unwrap();
|
||||
assert_eq!(guard.pending.lock().unwrap().len(), 1, "expiry is exclusive");
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -220,6 +220,16 @@ impl Catalog {
|
|||
Ok(token)
|
||||
}
|
||||
|
||||
/// Whether `token` names an invite that is live at `now`. Read-only: it
|
||||
/// spends nothing, so a begin can ask it before Heimdall is.
|
||||
pub(crate) fn invite_is_live(&self, token: &str, now: DateTime<Utc>) -> bool {
|
||||
self.hash_is_live(&token_hash(token), now)
|
||||
}
|
||||
|
||||
fn hash_is_live(&self, hash: &str, now: DateTime<Utc>) -> bool {
|
||||
self.state.invites.get(hash).is_some_and(|expires| *expires > now)
|
||||
}
|
||||
|
||||
/// The account an authenticated external identity lands on. A known
|
||||
/// identity reaches its account, on any device. An unknown one needs a
|
||||
/// live invite, which is consumed in the same write that creates the
|
||||
|
|
@ -236,13 +246,9 @@ impl Catalog {
|
|||
let account = &self.state.accounts[account];
|
||||
return Ok(Ok(account.identities[0].clone()));
|
||||
}
|
||||
let Some(hash) = invite.map(token_hash) else {
|
||||
let Some(hash) = invite.map(token_hash).filter(|hash| self.hash_is_live(hash, now)) else {
|
||||
return Ok(Err(SignInRefusal::NoInvite));
|
||||
};
|
||||
match self.state.invites.get(&hash) {
|
||||
Some(expires) if *expires > now => {}
|
||||
_ => return Ok(Err(SignInRefusal::NoInvite)),
|
||||
}
|
||||
let mut next = self.state.clone();
|
||||
next.invites.remove(&hash);
|
||||
next.invites.retain(|_, expires| *expires > now);
|
||||
|
|
|
|||
|
|
@ -189,6 +189,7 @@ pub(crate) trait HeimdallPort: SessionRefresher + Send + Sync {
|
|||
async fn begin(
|
||||
&self,
|
||||
provider: AuthProvider,
|
||||
grant: bool,
|
||||
idempotency_key: &str,
|
||||
) -> anyhow::Result<AuthBeginReceipt>;
|
||||
|
||||
|
|
@ -219,9 +220,10 @@ impl HeimdallPort for HeimdallClient {
|
|||
async fn begin(
|
||||
&self,
|
||||
provider: AuthProvider,
|
||||
grant: bool,
|
||||
idempotency_key: &str,
|
||||
) -> anyhow::Result<AuthBeginReceipt> {
|
||||
HeimdallClient::begin(self, provider, idempotency_key).await
|
||||
HeimdallClient::begin(self, provider, grant, idempotency_key).await
|
||||
}
|
||||
|
||||
async fn complete(
|
||||
|
|
@ -247,33 +249,12 @@ impl HeimdallPort for HeimdallClient {
|
|||
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,
|
||||
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,
|
||||
|
|
@ -380,8 +361,11 @@ struct BeginCommand<'a> {
|
|||
provider: &'a str,
|
||||
mode: &'a str,
|
||||
return_to: &'a str,
|
||||
/// `"invite"` when the browser presented an invite the catalog holds live:
|
||||
/// it lets Heimdall mint an auth account for a first-time identity. The
|
||||
/// Dungeon's catalog, not Heimdall, decides who is admitted.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
entitlement_policy: Option<DiscordRolePolicy<'a>>,
|
||||
first_login_grant: Option<&'static str>,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
|
|
@ -389,8 +373,6 @@ struct BeginCommand<'a> {
|
|||
struct RefreshCommand<'a> {
|
||||
schema: &'static str,
|
||||
refresh_token: &'a str,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
entitlement_policy: Option<DiscordRolePolicy<'a>>,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
|
|
@ -400,14 +382,6 @@ struct LogoutCommand<'a> {
|
|||
refresh_token: &'a str,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct DiscordRolePolicy<'a> {
|
||||
kind: &'a str,
|
||||
guild_id: &'a str,
|
||||
allowed_role_ids: [&'a str; 1],
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AuthBeginReceipt {
|
||||
|
|
@ -609,23 +583,6 @@ impl HeimdallClient {
|
|||
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")
|
||||
|
|
@ -635,7 +592,6 @@ impl HeimdallClient {
|
|||
public_app_url: std::env::var("GHOSTLIGHT_PUBLIC_APP_URL")
|
||||
.unwrap_or_else(|_| "https://yggdrasil.gamecult.org/ghostlight/".into()),
|
||||
providers,
|
||||
discord,
|
||||
boundary_locator: HeimdallBoundaryLocator::Odin {
|
||||
endpoint: odin_endpoint,
|
||||
expected,
|
||||
|
|
@ -653,10 +609,6 @@ impl HeimdallClient {
|
|||
issuer: "https://heimdall.invalid".into(),
|
||||
public_app_url: "https://ghostlight.invalid/".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(),
|
||||
|
|
@ -680,26 +632,22 @@ impl HeimdallClient {
|
|||
self
|
||||
}
|
||||
|
||||
fn begin_command(&self, provider: AuthProvider) -> BeginCommand<'_> {
|
||||
fn begin_command(&self, provider: AuthProvider, grant: bool) -> BeginCommand<'_> {
|
||||
BeginCommand {
|
||||
provider: provider.as_str(),
|
||||
mode: "sign_in",
|
||||
return_to: &self.public_app_url,
|
||||
// The Discord role gate rides the Discord sign-in only.
|
||||
entitlement_policy: self
|
||||
.discord
|
||||
.as_ref()
|
||||
.filter(|_| provider == AuthProvider::Discord)
|
||||
.map(DiscordGate::policy),
|
||||
first_login_grant: grant.then_some("invite"),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn begin(
|
||||
&self,
|
||||
provider: AuthProvider,
|
||||
grant: bool,
|
||||
idempotency_key: &str,
|
||||
) -> anyhow::Result<AuthBeginReceipt> {
|
||||
let payload = self.begin_command(provider);
|
||||
let payload = self.begin_command(provider, grant);
|
||||
self.invoke(
|
||||
"heimdall.auth.begin",
|
||||
"heimdall.auth_begin_command.v1",
|
||||
|
|
@ -733,7 +681,6 @@ impl HeimdallClient {
|
|||
let payload = RefreshCommand {
|
||||
schema: "heimdall.auth_refresh_command.v1",
|
||||
refresh_token,
|
||||
entitlement_policy: self.discord.as_ref().map(DiscordGate::policy),
|
||||
};
|
||||
self.invoke(
|
||||
"heimdall.auth.refresh",
|
||||
|
|
@ -1327,15 +1274,6 @@ impl PrivateEnvelope {
|
|||
}
|
||||
}
|
||||
|
||||
fn required_env(name: &str) -> anyhow::Result<String> {
|
||||
let value = std::env::var(name).with_context(|| format!("{name} is required"))?;
|
||||
let value = value.trim();
|
||||
if value.is_empty() {
|
||||
bail!("{name} must not be empty");
|
||||
}
|
||||
Ok(value.to_owned())
|
||||
}
|
||||
|
||||
/// A local stand-in for Heimdall's issuer: it serves the key set (or a 5xx)
|
||||
/// on a loopback port and counts the requests it receives. The key is the
|
||||
/// RFC 8037 appendix A.1 Ed25519 test key.
|
||||
|
|
@ -1844,34 +1782,36 @@ mod provider_tests {
|
|||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_discord_role_policy_rides_the_discord_begin_alone() {
|
||||
fn no_begin_or_refresh_carries_an_entitlement_policy_and_the_grant_rides_only_when_asked() {
|
||||
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();
|
||||
for (provider, name) in [
|
||||
(AuthProvider::Google, "google"),
|
||||
(AuthProvider::Discord, "discord"),
|
||||
(AuthProvider::Twitch, "twitch"),
|
||||
] {
|
||||
let plain = serde_json::to_value(client.begin_command(provider, false)).unwrap();
|
||||
assert_eq!(
|
||||
command,
|
||||
plain,
|
||||
serde_json::json!({"provider": name, "mode": "sign_in", "returnTo": "https://ghostlight.invalid/"}),
|
||||
"no policy, no grant key"
|
||||
);
|
||||
let granted = serde_json::to_value(client.begin_command(provider, true)).unwrap();
|
||||
assert_eq!(
|
||||
granted,
|
||||
serde_json::json!({
|
||||
"provider": name,
|
||||
"mode": "sign_in",
|
||||
"returnTo": "https://ghostlight.invalid/",
|
||||
}),
|
||||
"the Discord role gate must not gate {name}"
|
||||
"firstLoginGrant": "invite",
|
||||
})
|
||||
);
|
||||
}
|
||||
let refresh = serde_json::to_value(RefreshCommand {
|
||||
schema: "heimdall.auth_refresh_command.v1",
|
||||
refresh_token: "r",
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(refresh, serde_json::json!({"schema": "heimdall.auth_refresh_command.v1", "refreshToken": "r"}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
|
|||
|
|
@ -44,8 +44,6 @@ required_environment = [
|
|||
"GAMECULT_IDUNN_RUNTIME_BUNDLE",
|
||||
"GHOSTLIGHT_CONNECTOR_ADDR",
|
||||
"GHOSTLIGHT_CONNECTOR_KEY_FILE",
|
||||
"GHOSTLIGHT_DISCORD_GUILD_ID",
|
||||
"GHOSTLIGHT_DISCORD_ROLE_ID",
|
||||
"GHOSTLIGHT_HEIMDALL_APP_SECRET_FILE",
|
||||
"GHOSTLIGHT_HEIMDALL_BASE_URL",
|
||||
"GHOSTLIGHT_PUBLIC_APP_URL",
|
||||
|
|
|
|||
Loading…
Reference in a new issue