//! Android sign-in (neiam-auth app-login) end to end against Postgres: the
//! methods per config, password sign-in and its refusals and limits, the
//! OIDC code exchange, and the minted token on `/api/v1/me` through the
//! real bearer middleware.
//!
//! Skipped unless `TEST_DATABASE_URL` is set:
//!
//! ```sh
//! podman run -d --rm --name recourse-al-pg -e POSTGRES_PASSWORD=pw -p 55451:5432 postgres:17
//! TEST_DATABASE_URL=postgres://postgres:pw@localhost:55451/postgres cargo test --test app_login
//! ```
//!
//! The provider round trip (`/auth/oidc/neiam/login?app=1` -> issuer ->
//! callback) is covered by neiam-auth's own fake-issuer tests; here the
//! callback's two steps run directly: the app's link policy
//! (`AppLinker::complete_app`) and the crate's `issue_code`.
use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;
use axum::Router;
use axum::body::Body;
use axum::http::{Request, StatusCode, header};
use chrono::Utc;
use migration::MigratorTrait;
use neiam_auth::app_login::{AppFlow, AppLoginConfig, Limit, s256_challenge};
use neiam_auth::axum::{Linker, LoginCtx, ProviderInfo};
use neiam_auth::{OidcConfig, OidcIdentity, OidcProviders, Provision};
use sea_orm::*;
use serde_json::{Value, json};
use tower::ServiceExt;
use uuid::Uuid;
use recourse::auth::app_login::{REDIRECT_URI, Service, service_with};
use recourse::auth::oidc::AppLinker;
use recourse::auth::{self, password};
use recourse::entities::{api_tokens, user_sessions, users};
use recourse::{AppState, Config, api};
const ISS: &str = "https://auth.neiam.org";
const VERIFIER: &str = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk";
static MIGRATED: tokio::sync::OnceCell<()> = tokio::sync::OnceCell::const_new();
async fn db() -> Option<Arc<DatabaseConnection>> {
let Ok(url) = std::env::var("TEST_DATABASE_URL") else {
eprintln!("TEST_DATABASE_URL unset: skipping the Postgres app-login tests");
return None;
};
let db = Database::connect(&url)
.await
.expect("connect to TEST_DATABASE_URL");
MIGRATED
.get_or_init(|| async {
migration::Migrator::up(&db, None).await.expect("migrate");
})
.await;
Some(Arc::new(db))
}
fn providers(vars: &[(&str, &str)]) -> OidcProviders {
let mut map: HashMap<String, String> = [
("OIDC_ENABLED", "true"),
("OIDC_ISSUER", ISS),
("OIDC_CLIENT_ID", "recourse"),
("OIDC_CLIENT_SECRET", "s3cret-s3cret-s3cret"),
("OIDC_LABEL", "Sign in with NEIAM"),
]
.into_iter()
.map(|(k, v)| (k.to_string(), v.to_string()))
.collect();
for (k, v) in vars {
map.insert((*k).into(), (*v).into());
}
OidcProviders::from_config(OidcConfig::from_lookup(
move |k| map.get(k).cloned(),
Some("https://forum.example"),
))
}
struct App {
router: Router,
service: Service,
state: AppState,
}
impl App {
fn db(&self) -> &DatabaseConnection {
self.state.db.as_ref()
}
}
/// The routes as `main.rs` merges them: the crate's sign-in routes next to
/// the bearer-only `/api/v1` (with its JSON fallback).
fn app(
db: Arc<DatabaseConnection>,
oidc: OidcProviders,
password_login: bool,
tweak: impl FnOnce(&mut AppLoginConfig),
) -> App {
let mut config = Config::from_env();
config.public_url = "https://forum.example".into();
config.mail_prism_url = None;
config.mail_prism_api_key = None;
config.oidc = oidc;
config.password_login = password_login;
let config = Arc::new(config);
let state = AppState {
env: minijinja::Environment::new(),
db: db.clone(),
mailer: recourse::mailer::build(&config, false),
config: config.clone(),
view_throttle: recourse::new_view_throttle(),
live: recourse::live::Hub::new(),
};
let mut cfg = AppLoginConfig::new(config.app_name.clone(), REDIRECT_URI);
cfg.public_url = Some("https://forum.example".into());
cfg.failure_floor = Duration::from_millis(30);
tweak(&mut cfg);
let service = service_with(state.clone(), cfg);
let router = Router::new()
.merge(neiam_auth::app_login::router(service.clone()))
.nest("/api/v1", api::router(db))
.with_state(state.clone());
App {
router,
service,
state,
}
}
fn tag() -> String {
Uuid::now_v7().simple().to_string()[20..].to_string()
}
async fn user(db: &DatabaseConnection, pw: Option<&str>, active: bool) -> users::Model {
let name = format!("al-{}", tag());
let u = auth::create_user_direct(
db,
&name,
&format!("{name}@Example.test"),
pw.unwrap_or("placeholder-pw-1"),
false,
)
.await
.unwrap();
let mut am: users::ActiveModel = u.into();
if pw.is_none() {
am.password_hash = Set(password::NO_PASSWORD.into());
}
am.is_active = Set(active);
am.update(db).await.unwrap()
}
async fn suspend(db: &DatabaseConnection, u: &users::Model) {
let mut am: users::ActiveModel = u.clone().into();
am.suspended_at = Set(Some(Utc::now().into()));
am.suspended_until = Set(Some((Utc::now() + chrono::Duration::days(3)).into()));
am.suspend_reason = Set(Some("Cooling off".into()));
am.update(db).await.unwrap();
}
async fn call(router: &Router, req: Request<Body>) -> (StatusCode, Value) {
let resp = router.clone().oneshot(req).await.unwrap();
let status = resp.status();
let body = axum::body::to_bytes(resp.into_body(), 1 << 20)
.await
.unwrap();
(status, serde_json::from_slice(&body).unwrap_or(Value::Null))
}
async fn post(router: &Router, uri: &str, body: Value, ip: &str) -> (StatusCode, Value) {
call(
router,
Request::post(uri)
.header(header::CONTENT_TYPE, "application/json")
.header("x-real-ip", ip)
.body(Body::from(body.to_string()))
.unwrap(),
)
.await
}
async fn password_login(router: &Router, login: &str, pw: &str, ip: &str) -> (StatusCode, Value) {
post(
router,
"/api/v1/auth/password",
json!({ "username_or_email": login, "password": pw, "device_name": "Pixel 8" }),
ip,
)
.await
}
/// `GET /api/v1/me` with the token: the app's smoke call.
async fn me_with(router: &Router, token: &str) -> (StatusCode, Value) {
call(
router,
Request::get("/api/v1/me")
.header(header::AUTHORIZATION, format!("Bearer {token}"))
.body(Body::empty())
.unwrap(),
)
.await
}
async fn methods(router: &Router) -> Value {
call(
router,
Request::get("/api/v1/auth/methods")
.body(Body::empty())
.unwrap(),
)
.await
.1
}
#[tokio::test]
async fn methods_follow_the_config() {
let Some(db) = db().await else { return };
let a = app(db.clone(), OidcProviders::none(), true, |_| {});
let m = methods(&a.router).await;
assert_eq!(m["scan"], true);
assert_eq!(m["password"], true);
assert_eq!(m["oidc"]["enabled"], false);
assert_eq!(m["app_name"], a.state.config.app_name.as_str());
assert_eq!(m["server"], "https://forum.example");
let m = methods(&app(db.clone(), providers(&[]), true, |_| {}).router).await;
assert_eq!(m["oidc"]["enabled"], true);
assert_eq!(m["oidc"]["label"], "Sign in with NEIAM");
assert_eq!(m["oidc"]["login_path"], "/auth/oidc/neiam/login");
// OIDC_PASSWORD_LOGIN=false.
let m = methods(&app(db.clone(), providers(&[]), false, |_| {}).router).await;
assert_eq!(m["password"], false);
// OIDC_LOGIN_MODE=sso_strict.
let m = methods(
&app(
db.clone(),
providers(&[("OIDC_LOGIN_MODE", "sso_strict")]),
true,
|_| {},
)
.router,
)
.await;
assert_eq!(m["password"], false);
assert_eq!(m["oidc"]["enabled"], true);
// OIDC_LOGIN_MODE=local: no OIDC.
let m =
methods(&app(db, providers(&[("OIDC_LOGIN_MODE", "local")]), true, |_| {}).router).await;
assert_eq!(m["oidc"]["enabled"], false);
assert_eq!(m["password"], true);
}
#[tokio::test]
async fn the_api_keeps_its_own_routes_and_json_404() {
let Some(db) = db().await else { return };
let a = app(db.clone(), OidcProviders::none(), true, |_| {});
// No token: the API's JSON 401, not swallowed by the sign-in routes.
let (status, body) = call(
&a.router,
Request::get("/api/v1/me").body(Body::empty()).unwrap(),
)
.await;
assert_eq!(status, StatusCode::UNAUTHORIZED, "{body}");
// An unknown /api/v1/auth/... path is still a 404.
let (status, _) = call(
&a.router,
Request::get("/api/v1/auth/nope")
.body(Body::empty())
.unwrap(),
)
.await;
assert_eq!(status, StatusCode::NOT_FOUND);
}
#[tokio::test]
async fn password_sign_in_mints_a_working_device_token() {
let Some(db) = db().await else { return };
let a = app(db.clone(), OidcProviders::none(), true, |_| {});
let u = user(&db, Some("correct horse"), true).await;
let (status, body) = password_login(&a.router, &u.username, "correct horse", "10.1.0.1").await;
assert_eq!(status, StatusCode::OK, "{body}");
let token = body["token"].as_str().unwrap().to_string();
assert!(token.starts_with(auth::api_tokens::TOKEN_PREFIX));
assert_eq!(body["user"]["username"], u.username.as_str());
assert_eq!(body["user"]["email"], u.email.as_str());
// An ordinary api_tokens row: only the hash, labelled with the device,
// the pairing page's 90-day sliding expiry.
let row = api_tokens::Entity::find()
.filter(api_tokens::Column::TokenHash.eq(auth::hash_api_token(&token)))
.one(a.db())
.await
.unwrap()
.unwrap();
assert_eq!(row.user_id, u.id);
assert_eq!(row.label.as_deref(), Some("Pixel 8"));
let days = (row.expires_at.unwrap().with_timezone(&Utc) - Utc::now()).num_days();
assert!((89..=90).contains(&days), "{days}");
let (status, me) = me_with(&a.router, &token).await;
assert_eq!(status, StatusCode::OK, "{me}");
assert_eq!(me["user"]["username"], u.username.as_str());
// By email too, any case.
let (status, _) = password_login(
&a.router,
&u.email.to_uppercase(),
"correct horse",
"10.1.0.2",
)
.await;
assert_eq!(status, StatusCode::OK);
// Revoking it (as /devices does) ends it.
auth::delete_api_token(a.db(), u.id, row.id).await.unwrap();
assert_eq!(me_with(&a.router, &token).await.0, StatusCode::UNAUTHORIZED);
// Password sign-in starts no web session either.
let sessions = user_sessions::Entity::find()
.filter(user_sessions::Column::UserId.eq(u.id))
.count(a.db())
.await
.unwrap();
assert_eq!(sessions, 0);
}
#[tokio::test]
async fn wrong_password_unknown_user_and_inactive_answer_alike() {
let Some(db) = db().await else { return };
let a = app(db.clone(), OidcProviders::none(), true, |_| {});
let u = user(&db, Some("correct horse"), true).await;
let gone = user(&db, Some("correct horse"), false).await;
let oidc_only = user(&db, None, true).await;
let wrong = password_login(&a.router, &u.username, "nope", "10.2.0.1").await;
let unknown = password_login(&a.router, "no-such-user", "nope", "10.2.0.2").await;
let inactive = password_login(&a.router, &gone.username, "correct horse", "10.2.0.3").await;
let no_pw = password_login(&a.router, &oidc_only.username, "!oidc", "10.2.0.4").await;
assert_eq!(wrong.0, StatusCode::UNAUTHORIZED);
assert_eq!(wrong, unknown);
assert_eq!(wrong, inactive);
assert_eq!(wrong, no_pw);
assert_eq!(wrong.1["error"], "invalid_credentials");
}
#[tokio::test]
async fn a_suspended_account_is_refused_as_on_the_web() {
let Some(db) = db().await else { return };
let a = app(db.clone(), OidcProviders::none(), true, |_| {});
let u = user(&db, Some("correct horse"), true).await;
suspend(&db, &u).await;
let (status, body) = password_login(&a.router, &u.username, "correct horse", "10.6.0.1").await;
assert_eq!(status, StatusCode::FORBIDDEN, "{body}");
assert_eq!(body["error"], "refused");
let fresh = users::Entity::find_by_id(u.id)
.one(a.db())
.await
.unwrap()
.unwrap();
let s = recourse::policy::suspension(&fresh).unwrap();
assert_eq!(body["message"], recourse::policy::suspension_message(&s));
// A wrong password is still just wrong.
let (status, _) = password_login(&a.router, &u.username, "nope", "10.6.0.1").await;
assert_eq!(status, StatusCode::UNAUTHORIZED);
}
/// A linked identity for `u` at the provider.
async fn link(db: &DatabaseConnection, u: &users::Model) {
neiam_auth::sea_orm::link(db, u.id, &identity(&format!("sub-{}", u.id)))
.await
.unwrap();
}
fn identity(sub: &str) -> OidcIdentity {
OidcIdentity {
provider: "neiam".into(),
issuer: ISS.into(),
sub: sub.into(),
username: Some(format!("n{}", &sub[sub.len() - 12..])),
email: Some(format!("{sub}@example.com")),
email_verified: true,
name: None,
groups: vec![],
auth_time: None,
amr: vec![],
}
}
#[tokio::test]
async fn login_mode_refusals() {
let Some(db) = db().await else { return };
// sso_strict: password login is off altogether.
let strict = app(
db.clone(),
providers(&[("OIDC_LOGIN_MODE", "sso_strict")]),
true,
|_| {},
);
let u = user(&db, Some("correct horse"), true).await;
let (status, body) =
password_login(&strict.router, &u.username, "correct horse", "10.3.0.1").await;
assert_eq!(status, StatusCode::FORBIDDEN);
assert_eq!(body["error"], "password_login_off");
// OIDC_PASSWORD_LOGIN=false: the same.
let off = app(db.clone(), OidcProviders::none(), false, |_| {});
let (status, body) =
password_login(&off.router, &u.username, "correct horse", "10.3.0.2").await;
assert_eq!(status, StatusCode::FORBIDDEN);
assert_eq!(body["error"], "password_login_off");
// sso + REQUIRED_FOR_LINKED: linked accounts must use NEIAM, others may not.
let sso = app(
db.clone(),
providers(&[
("OIDC_LOGIN_MODE", "sso"),
("OIDC_REQUIRED_FOR_LINKED", "true"),
]),
true,
|_| {},
);
let linked = user(&db, Some("correct horse"), true).await;
link(&db, &linked).await;
let (status, body) =
password_login(&sso.router, &linked.username, "correct horse", "10.3.0.3").await;
assert_eq!(status, StatusCode::FORBIDDEN, "{body}");
assert_eq!(body["error"], "refused");
assert_eq!(body["message"], "This account signs in with NEIAM.");
// ... but only after the password: a wrong one is just wrong.
let (status, _) = password_login(&sso.router, &linked.username, "nope", "10.3.0.3").await;
assert_eq!(status, StatusCode::UNAUTHORIZED);
let (status, _) = password_login(&sso.router, &u.username, "correct horse", "10.3.0.4").await;
assert_eq!(
status,
StatusCode::OK,
"unlinked accounts keep their password under sso"
);
}
#[tokio::test]
async fn password_is_rate_limited() {
let Some(db) = db().await else { return };
let a = app(db.clone(), OidcProviders::none(), true, |c| {
c.failure_floor = Duration::ZERO;
c.password_per_account = Limit::new(3, Duration::from_secs(900));
c.password_per_ip = Limit::new(4, Duration::from_secs(900));
});
let u = user(&db, Some("correct horse"), true).await;
// Per account, from different addresses.
for i in 0..3 {
let (s, _) = password_login(&a.router, &u.username, "nope", &format!("10.4.0.{i}")).await;
assert_eq!(s, StatusCode::UNAUTHORIZED);
}
let (s, body) = password_login(&a.router, &u.username, "correct horse", "10.4.0.9").await;
assert_eq!(s, StatusCode::TOO_MANY_REQUESTS);
assert_eq!(body["error"], "rate_limited");
// Per address, across accounts.
for i in 0..4 {
let (s, _) = password_login(&a.router, &format!("nobody{i}"), "x", "10.4.1.1").await;
assert_eq!(s, StatusCode::UNAUTHORIZED);
}
let other = user(&db, Some("correct horse"), true).await;
let (s, _) = password_login(&a.router, &other.username, "correct horse", "10.4.1.1").await;
assert_eq!(s, StatusCode::TOO_MANY_REQUESTS);
}
fn ctx(provision: Provision) -> LoginCtx {
LoginCtx {
provider: ProviderInfo {
id: "neiam".into(),
label: "Sign in with NEIAM".into(),
issuer: ISS.into(),
trust_email: true,
provision,
groups_trusted: false,
required_for_linked: false,
},
return_to: "/".into(),
link_current_session: false,
invite: None,
}
}
fn linker(a: &App) -> AppLinker {
AppLinker {
db: a.state.db.clone(),
config: a.state.config.clone(),
}
}
/// The callback's half: the web link policy, then the crate's one-time code.
async fn oidc_code(a: &App, id: OidcIdentity) -> String {
let parts = Request::get("/").body(()).unwrap().into_parts().0;
let user_id = linker(a)
.complete_app(id, ctx(Provision::Auto), &parts)
.await
.unwrap_or_else(|_| panic!("complete_app refused"));
let flow = AppFlow {
challenge: s256_challenge(VERIFIER),
device_name: "Pixel 8 (NEIAM)".into(),
};
let to = a.service.issue_code(user_id, &flow, "neiam").await.unwrap();
assert!(to.starts_with("recourse://auth?code="), "{to}");
to.split("code=").nth(1).unwrap().to_string()
}
async fn exchange(a: &App, code: &str, verifier: &str) -> (StatusCode, Value) {
post(
&a.router,
"/api/v1/auth/oidc/exchange",
json!({ "code": code, "code_verifier": verifier, "device_name": "x" }),
"10.5.0.1",
)
.await
}
#[tokio::test]
async fn oidc_exchange_happy_path_reuse_wrong_verifier_and_expiry() {
let Some(db) = db().await else { return };
let a = app(db.clone(), providers(&[]), true, |_| {});
// Provisioned exactly as a web login would (PROVISION=auto), no session.
let sub = format!("sub-{}", Uuid::now_v7());
let code = oidc_code(&a, identity(&sub)).await;
let (status, body) = exchange(&a, &code, VERIFIER).await;
assert_eq!(status, StatusCode::OK, "{body}");
let token = body["token"].as_str().unwrap().to_string();
assert_eq!(body["label"], "Pixel 8 (NEIAM)");
let (status, me) = me_with(&a.router, &token).await;
assert_eq!(status, StatusCode::OK, "{me}");
assert_eq!(me["user"]["username"], body["user"]["username"]);
let uid = Uuid::parse_str(body["user"]["id"].as_str().unwrap()).unwrap();
let sessions = user_sessions::Entity::find()
.filter(user_sessions::Column::UserId.eq(uid))
.count(db.as_ref())
.await
.unwrap();
assert_eq!(sessions, 0, "app=1 starts no web session");
// The trusted provider's verified address counts, as on the web.
let u = users::Entity::find_by_id(uid)
.one(db.as_ref())
.await
.unwrap()
.unwrap();
assert!(u.email_verified_at.is_some());
// Reuse.
let (status, body) = exchange(&a, &code, VERIFIER).await;
assert_eq!(status, StatusCode::BAD_REQUEST);
assert_eq!(body["error"], "invalid_grant");
// Wrong verifier, then the right one: the code is gone.
let code = oidc_code(&a, identity(&sub)).await;
assert_eq!(
exchange(&a, &code, &"w".repeat(43)).await.0,
StatusCode::BAD_REQUEST
);
assert_eq!(
exchange(&a, &code, VERIFIER).await.0,
StatusCode::BAD_REQUEST
);
// Expired.
let code = oidc_code(&a, identity(&sub)).await;
let hash = neiam_auth::app_login::hash_code(&code);
db.execute(Statement::from_sql_and_values(
DbBackend::Postgres,
"UPDATE app_login_codes SET expires_at = now() - interval '1 second' WHERE code_hash = $1",
[hash.into()],
))
.await
.unwrap();
let (status, body) = exchange(&a, &code, VERIFIER).await;
assert_eq!(status, StatusCode::BAD_REQUEST);
assert_eq!(body["error"], "invalid_grant");
}
#[tokio::test]
async fn suspended_or_deactivated_get_no_code_or_no_token() {
let Some(db) = db().await else { return };
let a = app(db.clone(), providers(&[]), true, |_| {});
// Suspended after the code: the exchange refuses.
let sub = format!("sub-{}", Uuid::now_v7());
let code = oidc_code(&a, identity(&sub)).await;
let uid = neiam_auth::sea_orm::find_user_id(db.as_ref(), ISS, &sub)
.await
.unwrap()
.unwrap();
let u = users::Entity::find_by_id(uid)
.one(db.as_ref())
.await
.unwrap()
.unwrap();
suspend(&db, &u).await;
let (status, body) = exchange(&a, &code, VERIFIER).await;
assert_eq!(status, StatusCode::FORBIDDEN, "{body}");
assert_eq!(body["error"], "refused");
// Suspended before: the link policy refuses at the callback.
let parts = Request::get("/").body(()).unwrap().into_parts().0;
assert!(
linker(&a)
.complete_app(identity(&sub), ctx(Provision::Auto), &parts)
.await
.is_err()
);
// Deactivated after the code.
let sub = format!("sub-{}", Uuid::now_v7());
let code = oidc_code(&a, identity(&sub)).await;
let uid = neiam_auth::sea_orm::find_user_id(db.as_ref(), ISS, &sub)
.await
.unwrap()
.unwrap();
auth::deactivate_user(db.as_ref(), uid).await.unwrap();
let (status, body) = exchange(&a, &code, VERIFIER).await;
assert_eq!(status, StatusCode::FORBIDDEN, "{body}");
}
/// The answers the Android `ContractTest` decodes: `auth_methods.json` and
/// `auth_token.json`, written with `WRITE_ANDROID_FIXTURES` (`just
/// fixtures`). Without it this still makes the calls.
#[tokio::test]
async fn android_fixtures() {
let Some(db) = db().await else { return };
let write = std::env::var_os("WRITE_ANDROID_FIXTURES").is_some();
let dir =
std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("android/app/src/test/resources/api");
let save = |name: &str, body: &Value| {
if write {
std::fs::create_dir_all(&dir).unwrap();
let pretty = serde_json::to_string_pretty(body).unwrap() + "\n";
std::fs::write(dir.join(format!("{name}.json")), pretty).unwrap();
}
};
let a = app(db.clone(), providers(&[]), true, |_| {});
save("auth_methods", &methods(&a.router).await);
let u = user(&db, Some("correct horse"), true).await;
let (status, body) = password_login(&a.router, &u.username, "correct horse", "10.7.0.1").await;
assert_eq!(status, StatusCode::OK, "{body}");
save("auth_token", &body);
let (status, body) = password_login(&a.router, &u.username, "nope", "10.7.0.1").await;
assert_eq!(status, StatusCode::UNAUTHORIZED);
save("auth_error", &body);
}
neiam
/recourse
public · Issues · Pulls · Labels · Forks · Compare · Actions queued · Badges · Packages
⭐
Log in to mark this repository.
22.7 KiB · text
History
01e509e