Phase 1: app, Kanidm login, people, passports, addresses, audit log
visa.buildfor.life keeps the immigration records of the foreigners B4L looks after. This first phase is the base the deadlines and extension packs build on (docs/PLAN.md, phases 2 to 7). - One Rust binary (axum 0.8, minijinja, sqlx on PostgreSQL) with its templates, static files and migrations compiled in. - Login through Kanidm (OpenID Connect with PKCE and a nonce, ES256), client visa-web, group visa; sessions in PostgreSQL keyed by the SHA-256 of the cookie. VISA_INSECURE_NO_LOGIN=1 for loopback development only. - Same-site check and form token on every POST; a CSP without inline script or style; security headers. - People: list with filter, page, create, edit, archive, restore. - Passports from the machine-readable zone with check digits (ICAO 9303 TD3); expiry warnings at 12 and 6 months. - Addresses in Thailand in the order Thai forms use, with the house master and the TM.30 receipt. - Append-only audit log of every view and change, with the names of the changed fields but never their values (PDPA); the Activity page. - Invented demo people (visa seed-demo, refused when login is on). - 40 tests: unit tests, pages with demo data, the forms, the audit log and the whole login against a fake OpenID provider. - CI: gitleaks over the history, fmt, clippy and the tests against PostgreSQL 18; the pre-commit secret scan.
This commit is contained in:
commit
2e009700a9
56 files changed
+11193
No files matched your search
+252
@@ -0,0 +1,252 @@
|
||||
//! Signing in through Kanidm and out again.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
use axum::Extension;
|
||||
use axum::extract::{Query, State};
|
||||
use axum::http::{HeaderMap, HeaderValue, StatusCode, header};
|
||||
use axum::response::{IntoResponse, Redirect, Response};
|
||||
use tracing::{info, warn};
|
||||
|
||||
use super::{AppError, AppState, message, safe_next};
|
||||
use crate::audit::{self, Action, Entity, Entry};
|
||||
use crate::config::Auth;
|
||||
use crate::oidc;
|
||||
use crate::session::{self, FLOW_COOKIE, SESSION_COOKIE, User};
|
||||
|
||||
fn cookie_header(value: &str) -> HeaderValue {
|
||||
HeaderValue::from_str(value).expect("cookie values are base64url")
|
||||
}
|
||||
|
||||
fn now() -> f64 {
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map(|d| d.as_secs_f64())
|
||||
.unwrap_or(0.0)
|
||||
}
|
||||
|
||||
pub async fn login(
|
||||
State(st): State<Arc<AppState>>,
|
||||
Query(q): Query<HashMap<String, String>>,
|
||||
) -> Response {
|
||||
let Auth::Oidc(oc) = &st.cfg.auth else {
|
||||
return Redirect::to("/").into_response();
|
||||
};
|
||||
let Some(provider) = st.provider() else {
|
||||
return message(
|
||||
&st,
|
||||
StatusCode::SERVICE_UNAVAILABLE,
|
||||
"The login service is not reachable yet",
|
||||
"visa.buildfor.life fetches id.cnx.network's settings when it starts and keeps \
|
||||
trying. Try again in a minute.",
|
||||
("/", "Try again"),
|
||||
);
|
||||
};
|
||||
let Some(flow) = st.flows.start(safe_next(q.get("next"))) else {
|
||||
return message(
|
||||
&st,
|
||||
StatusCode::TOO_MANY_REQUESTS,
|
||||
"Too many logins at once",
|
||||
"Wait a few minutes and try again.",
|
||||
("/", "Try again"),
|
||||
);
|
||||
};
|
||||
let url = match provider.authorize_url(
|
||||
&oc.client_id,
|
||||
&st.cfg.redirect_uri(),
|
||||
&flow.state,
|
||||
&flow.nonce,
|
||||
&flow.verifier,
|
||||
) {
|
||||
Ok(u) => u,
|
||||
Err(e) => {
|
||||
warn!("login: {e:#}");
|
||||
return message(
|
||||
&st,
|
||||
StatusCode::BAD_GATEWAY,
|
||||
"The login service sent unusable settings",
|
||||
"The server log has the details.",
|
||||
("/", "Try again"),
|
||||
);
|
||||
}
|
||||
};
|
||||
let mut resp = Redirect::to(&url).into_response();
|
||||
resp.headers_mut().append(
|
||||
header::SET_COOKIE,
|
||||
cookie_header(&session::set_cookie(
|
||||
FLOW_COOKIE,
|
||||
&flow.state,
|
||||
session::FLOW_TTL,
|
||||
)),
|
||||
);
|
||||
resp
|
||||
}
|
||||
|
||||
pub async fn callback(
|
||||
State(st): State<Arc<AppState>>,
|
||||
headers: HeaderMap,
|
||||
Query(q): Query<HashMap<String, String>>,
|
||||
) -> Result<Response, AppError> {
|
||||
let Auth::Oidc(oc) = &st.cfg.auth else {
|
||||
return Ok(Redirect::to("/").into_response());
|
||||
};
|
||||
if let Some(err) = q.get("error") {
|
||||
let detail = q.get("error_description").cloned().unwrap_or_default();
|
||||
warn!("login refused by the provider: {err} {detail}");
|
||||
return Ok(message(
|
||||
&st,
|
||||
StatusCode::FORBIDDEN,
|
||||
"id.cnx.network did not sign you in",
|
||||
&format!(
|
||||
"It answered \u{201c}{err}\u{201d}{}. Only members of the group {} may open \
|
||||
this site.",
|
||||
if detail.is_empty() {
|
||||
String::new()
|
||||
} else {
|
||||
format!(": {detail}")
|
||||
},
|
||||
oc.group
|
||||
),
|
||||
("/", "Try again"),
|
||||
));
|
||||
}
|
||||
let (Some(code), Some(state)) = (q.get("code"), q.get("state")) else {
|
||||
return Ok(message(
|
||||
&st,
|
||||
StatusCode::BAD_REQUEST,
|
||||
"Incomplete login answer",
|
||||
"The address lacks the code or the state. Start again.",
|
||||
("/", "Start again"),
|
||||
));
|
||||
};
|
||||
if session::cookie_value(&headers, FLOW_COOKIE).as_deref() != Some(state.as_str()) {
|
||||
return Ok(message(
|
||||
&st,
|
||||
StatusCode::BAD_REQUEST,
|
||||
"This login was started elsewhere",
|
||||
"The login answer does not belong to this browser. Start again.",
|
||||
("/", "Start again"),
|
||||
));
|
||||
}
|
||||
let (Some(flow), Some(provider)) = (st.flows.take(state), st.provider()) else {
|
||||
return Ok(message(
|
||||
&st,
|
||||
StatusCode::BAD_REQUEST,
|
||||
"The login took too long",
|
||||
"Logins must finish within ten minutes. Start again.",
|
||||
("/", "Start again"),
|
||||
));
|
||||
};
|
||||
let redirect_uri = st.cfg.redirect_uri();
|
||||
let exchange = oidc::Exchange {
|
||||
client_id: &oc.client_id,
|
||||
client_secret: &oc.client_secret,
|
||||
redirect_uri: &redirect_uri,
|
||||
code,
|
||||
verifier: &flow.verifier,
|
||||
nonce: &flow.nonce,
|
||||
};
|
||||
let identity = match oidc::finish(&st.http, &provider, &exchange, now()).await {
|
||||
Ok(i) => i,
|
||||
Err(e) => {
|
||||
warn!("login failed: {e:#}");
|
||||
return Ok(message(
|
||||
&st,
|
||||
StatusCode::BAD_GATEWAY,
|
||||
"The login could not be finished",
|
||||
"id.cnx.network's answer did not check out. The server log says why.",
|
||||
("/", "Start again"),
|
||||
));
|
||||
}
|
||||
};
|
||||
if !identity.in_group(&oc.group) {
|
||||
warn!(
|
||||
"{} signed in but is not in group {}",
|
||||
identity.login, oc.group
|
||||
);
|
||||
return Ok(message(
|
||||
&st,
|
||||
StatusCode::FORBIDDEN,
|
||||
"No access",
|
||||
&format!(
|
||||
"You are signed in as {}, who is not in the group {}. Members are set in \
|
||||
identity/people.nix of the fleet repository.",
|
||||
identity.login, oc.group
|
||||
),
|
||||
("/signed-out", "OK"),
|
||||
));
|
||||
}
|
||||
info!("{} signed in", identity.login);
|
||||
let id = session::create(&st.db, &identity.login, &identity.name).await?;
|
||||
audit::record(
|
||||
&st.db,
|
||||
&Entry {
|
||||
actor: &identity.login,
|
||||
action: Action::SignIn,
|
||||
entity: Entity::Session,
|
||||
entity_id: None,
|
||||
person_id: None,
|
||||
fields: &[],
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
let mut resp = Redirect::to(&flow.next).into_response();
|
||||
let h = resp.headers_mut();
|
||||
h.append(
|
||||
header::SET_COOKIE,
|
||||
cookie_header(&session::set_cookie(
|
||||
SESSION_COOKIE,
|
||||
&id,
|
||||
session::SESSION_TTL,
|
||||
)),
|
||||
);
|
||||
h.append(
|
||||
header::SET_COOKIE,
|
||||
cookie_header(&session::clear_cookie(FLOW_COOKIE)),
|
||||
);
|
||||
Ok(resp)
|
||||
}
|
||||
|
||||
/// POST only; the forms guard has checked the site and the token.
|
||||
pub async fn logout(
|
||||
State(st): State<Arc<AppState>>,
|
||||
Extension(user): Extension<User>,
|
||||
headers: HeaderMap,
|
||||
) -> Result<Response, AppError> {
|
||||
if user.local {
|
||||
return Ok(Redirect::to("/").into_response());
|
||||
}
|
||||
if let Some(id) = session::cookie_value(&headers, SESSION_COOKIE) {
|
||||
session::remove(&st.db, &id).await?;
|
||||
}
|
||||
audit::record(
|
||||
&st.db,
|
||||
&Entry {
|
||||
actor: &user.login,
|
||||
action: Action::SignOut,
|
||||
entity: Entity::Session,
|
||||
entity_id: None,
|
||||
person_id: None,
|
||||
fields: &[],
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
let mut resp = Redirect::to("/signed-out").into_response();
|
||||
resp.headers_mut().append(
|
||||
header::SET_COOKIE,
|
||||
cookie_header(&session::clear_cookie(SESSION_COOKIE)),
|
||||
);
|
||||
Ok(resp)
|
||||
}
|
||||
|
||||
pub async fn signed_out(State(st): State<Arc<AppState>>) -> Response {
|
||||
message(
|
||||
&st,
|
||||
StatusCode::OK,
|
||||
"Signed out",
|
||||
"You are signed out of visa.buildfor.life. Your session at id.cnx.network stays open \
|
||||
until you sign out there.",
|
||||
("/", "Sign in again"),
|
||||
)
|
||||
}
|
||||
Reference in new issue
Block a user