`[web.no_sign_in]` instead of the OIDC settings makes everyone who reaches the web app one approver, so the demo needn't run a sign-in provider and tests can use the app. It only listens on a loopback address, every page says there's no sign-in, the audit log records `<name> (web, no sign-in)`, and it can't approve requests that need a passkey. The NixOS module has it only as an internal option, for the VM test. The VM test uses it to check a finished deploy's page, the event stream, and answering a request with the session's token. Refs #28 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
257 lines
9.2 KiB
Rust
257 lines
9.2 KiB
Rust
//! Signing approvers in through an OpenID Connect provider, and confirming single answers by
|
|
//! sending the approver back to sign in again. Both ask the provider to authenticate afresh
|
|
//! (`max_age=0`), which a passkey-only provider turns into a passkey prompt.
|
|
use std::time::{Duration, Instant};
|
|
|
|
use anyhow::{Context, Result, anyhow, ensure};
|
|
use openidconnect::core::{
|
|
CoreAuthDisplay, CoreAuthPrompt, CoreAuthenticationFlow, CoreErrorResponseType, CoreGenderClaim, CoreJsonWebKey,
|
|
CoreJweContentEncryptionAlgorithm, CoreJwsSigningAlgorithm, CoreProviderMetadata, CoreRevocableToken,
|
|
CoreRevocationErrorResponse, CoreTokenIntrospectionResponse, CoreTokenType,
|
|
};
|
|
use openidconnect::{
|
|
AdditionalClaims, AuthorizationCode, ClientId, ClientSecret, CsrfToken, EmptyExtraTokenFields, EndpointMaybeSet,
|
|
EndpointNotSet, EndpointSet, IdTokenFields, IssuerUrl, Nonce, PkceCodeChallenge, PkceCodeVerifier, RedirectUrl,
|
|
Scope, StandardErrorResponse, StandardTokenResponse, reqwest,
|
|
};
|
|
use serde::{Deserialize, Serialize};
|
|
|
|
use crate::config::OidcConfig;
|
|
use crate::queue::Decision;
|
|
|
|
/// The `groups` claim, which providers such as Pocket ID add for the `groups` scope.
|
|
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
|
|
pub struct Groups {
|
|
#[serde(default)]
|
|
groups: Vec<String>,
|
|
}
|
|
|
|
impl AdditionalClaims for Groups {}
|
|
|
|
type TokenResponse = StandardTokenResponse<
|
|
IdTokenFields<
|
|
Groups,
|
|
EmptyExtraTokenFields,
|
|
CoreGenderClaim,
|
|
CoreJweContentEncryptionAlgorithm,
|
|
CoreJwsSigningAlgorithm,
|
|
>,
|
|
CoreTokenType,
|
|
>;
|
|
|
|
type Client = openidconnect::Client<
|
|
Groups,
|
|
CoreAuthDisplay,
|
|
CoreGenderClaim,
|
|
CoreJweContentEncryptionAlgorithm,
|
|
CoreJsonWebKey,
|
|
CoreAuthPrompt,
|
|
StandardErrorResponse<CoreErrorResponseType>,
|
|
TokenResponse,
|
|
CoreTokenIntrospectionResponse,
|
|
CoreRevocableToken,
|
|
CoreRevocationErrorResponse,
|
|
EndpointSet,
|
|
EndpointNotSet,
|
|
EndpointNotSet,
|
|
EndpointNotSet,
|
|
EndpointMaybeSet,
|
|
EndpointMaybeSet,
|
|
>;
|
|
|
|
/// How long the provider's metadata and keys are used before fetching them again.
|
|
const METADATA_LIFETIME: Duration = Duration::from_secs(3600);
|
|
|
|
/// How long a sign-in may take.
|
|
pub const FLOW_LIFETIME: u64 = 600;
|
|
|
|
/// Why the approver was sent to the provider.
|
|
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
|
pub enum Purpose {
|
|
SignIn {
|
|
/// Local path to return to.
|
|
next: String,
|
|
},
|
|
/// Approving one request, which needs a passkey.
|
|
Confirm {
|
|
id: String,
|
|
decision: Decision,
|
|
/// [`super::fingerprint`] of what the approver was shown.
|
|
shown: String,
|
|
},
|
|
}
|
|
|
|
/// A sign-in in progress, kept in the session until the provider sends the approver back.
|
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
|
pub struct Flow {
|
|
pub state: String,
|
|
nonce: String,
|
|
verifier: String,
|
|
/// Unix time it started; a confirmation needs a sign-in no older than this.
|
|
pub started: i64,
|
|
pub purpose: Purpose,
|
|
}
|
|
|
|
/// Who signed in, from a verified ID token.
|
|
#[derive(Debug, Clone)]
|
|
pub struct Identity {
|
|
pub subject: String,
|
|
pub name: String,
|
|
/// Unix time the approver last authenticated with the provider.
|
|
pub auth_time: Option<i64>,
|
|
}
|
|
|
|
pub struct Oidc {
|
|
config: OidcConfig,
|
|
/// The web app's URL, for the provider to send approvers back to.
|
|
url: String,
|
|
secret: String,
|
|
http: reqwest::Client,
|
|
client: tokio::sync::Mutex<Option<(Instant, Client)>>,
|
|
}
|
|
|
|
pub fn now() -> i64 {
|
|
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_secs() as i64)
|
|
}
|
|
|
|
impl Oidc {
|
|
pub fn new(config: OidcConfig, url: String, secret: String) -> Result<Oidc> {
|
|
// Following redirects would let the provider's metadata send requests anywhere.
|
|
let http = reqwest::ClientBuilder::new()
|
|
.redirect(reqwest::redirect::Policy::none())
|
|
.timeout(Duration::from_secs(10))
|
|
.build()?;
|
|
Ok(Oidc { config, url, secret, http, client: tokio::sync::Mutex::new(None) })
|
|
}
|
|
|
|
/// The client, discovering the provider when it isn't known yet or is due for a refresh. A
|
|
/// failed refresh keeps using what was fetched before.
|
|
async fn client(&self) -> Result<Client> {
|
|
let mut cached = self.client.lock().await;
|
|
if let Some((fetched, client)) = &*cached
|
|
&& fetched.elapsed() < METADATA_LIFETIME
|
|
{
|
|
return Ok(client.clone());
|
|
}
|
|
|
|
match self.discover().await {
|
|
Ok(client) => {
|
|
*cached = Some((Instant::now(), client.clone()));
|
|
Ok(client)
|
|
}
|
|
Err(error) => match &*cached {
|
|
Some((_, client)) => Ok(client.clone()),
|
|
None => Err(error.context("reaching the sign-in provider")),
|
|
},
|
|
}
|
|
}
|
|
|
|
async fn discover(&self) -> Result<Client> {
|
|
let issuer = IssuerUrl::new(self.config.issuer.clone())?;
|
|
let metadata = CoreProviderMetadata::discover_async(issuer, &self.http).await?;
|
|
let redirect = RedirectUrl::new(format!("{}/auth/callback", self.url.trim_end_matches('/')))?;
|
|
|
|
Ok(Client::from_provider_metadata(
|
|
metadata,
|
|
ClientId::new(self.config.client_id.clone()),
|
|
Some(ClientSecret::new(self.secret.clone())),
|
|
)
|
|
.set_redirect_uri(redirect))
|
|
}
|
|
|
|
/// Where to send the approver, and what to remember until they're back.
|
|
pub async fn begin(&self, purpose: Purpose) -> Result<(String, Flow)> {
|
|
let client = self.client().await?;
|
|
let (challenge, verifier) = PkceCodeChallenge::new_random_sha256();
|
|
|
|
let request = client
|
|
.authorize_url(CoreAuthenticationFlow::AuthorizationCode, CsrfToken::new_random, Nonce::new_random)
|
|
.add_scope(Scope::new("profile".into()))
|
|
.add_scope(Scope::new("groups".into()))
|
|
.set_pkce_challenge(challenge)
|
|
.set_max_age(Duration::ZERO);
|
|
let (url, state, nonce) = request.url();
|
|
|
|
let flow = Flow {
|
|
state: state.secret().clone(),
|
|
nonce: nonce.secret().clone(),
|
|
verifier: verifier.secret().clone(),
|
|
started: now(),
|
|
purpose,
|
|
};
|
|
Ok((url.to_string(), flow))
|
|
}
|
|
|
|
/// Exchanges the code the provider sent back, and checks the ID token and group.
|
|
pub async fn finish(&self, flow: &Flow, code: String) -> Result<Identity> {
|
|
let client = self.client().await?;
|
|
let response = client
|
|
.exchange_code(AuthorizationCode::new(code))?
|
|
.set_pkce_verifier(PkceCodeVerifier::new(flow.verifier.clone()))
|
|
.request_async(&self.http)
|
|
.await
|
|
.map_err(|e| anyhow!("exchanging the sign-in code: {e}"))?;
|
|
|
|
let token = openidconnect::TokenResponse::id_token(&response).context("the provider sent no ID token")?;
|
|
let claims = token.claims(&client.id_token_verifier(), &Nonce::new(flow.nonce.clone()))?;
|
|
ensure!(
|
|
claims.additional_claims().groups.contains(&self.config.group),
|
|
"this account isn't in the {} group",
|
|
self.config.group
|
|
);
|
|
|
|
let subject = claims.subject().as_str().to_owned();
|
|
let name = claims.preferred_username().map_or_else(|| subject.clone(), |n| n.as_str().to_owned());
|
|
Ok(Identity { subject, name, auth_time: claims.auth_time().map(|t| t.timestamp()) })
|
|
}
|
|
}
|
|
|
|
/// Checks that the approver authenticated after the flow started, rather than the provider
|
|
/// reusing its own session.
|
|
pub fn fresh(flow: &Flow, identity: &Identity) -> Result<()> {
|
|
ensure!(identity.auth_time.is_some_and(|t| t >= flow.started), "the sign-in provider didn't ask for the passkey");
|
|
Ok(())
|
|
}
|
|
|
|
/// Checks that a confirmation came from the signed-in approver, who authenticated after it
|
|
/// started.
|
|
pub fn confirmed(flow: &Flow, identity: &Identity, subject: &str) -> Result<()> {
|
|
ensure!(identity.subject == subject, "the passkey belongs to a different account");
|
|
fresh(flow, identity)
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
fn flow(started: i64) -> Flow {
|
|
Flow {
|
|
state: "s".into(),
|
|
nonce: "n".into(),
|
|
verifier: "v".into(),
|
|
started,
|
|
purpose: Purpose::Confirm { id: "r".into(), decision: Decision::Once, shown: "h".into() },
|
|
}
|
|
}
|
|
|
|
fn identity(subject: &str, auth_time: Option<i64>) -> Identity {
|
|
Identity { subject: subject.into(), name: "dev".into(), auth_time }
|
|
}
|
|
|
|
#[test]
|
|
fn confirmation_needs_a_fresh_sign_in_by_the_same_account() {
|
|
assert!(confirmed(&flow(100), &identity("a", Some(100)), "a").is_ok());
|
|
assert!(confirmed(&flow(100), &identity("a", Some(130)), "a").is_ok());
|
|
assert!(confirmed(&flow(100), &identity("a", Some(99)), "a").is_err());
|
|
assert!(confirmed(&flow(100), &identity("a", None), "a").is_err());
|
|
assert!(confirmed(&flow(100), &identity("b", Some(130)), "a").is_err());
|
|
}
|
|
|
|
#[test]
|
|
fn sign_in_needs_a_fresh_authentication() {
|
|
assert!(fresh(&flow(100), &identity("a", Some(100))).is_ok());
|
|
assert!(fresh(&flow(100), &identity("a", Some(99))).is_err());
|
|
assert!(fresh(&flow(100), &identity("a", None)).is_err());
|
|
}
|
|
}
|