This commit is contained in:
nora 2025-07-12 21:38:06 +02:00
commit 1772e21364
13 changed files with 2961 additions and 0 deletions

21
idp/Cargo.toml Normal file
View file

@ -0,0 +1,21 @@
[package]
name = "idp"
version = "0.1.0"
edition = "2024"
[dependencies]
argon2 = "0.5.3"
askama = "0.14.0"
axum = { version = "0.8.4", features = ["macros"] }
axum-extra = { version = "0.10.1", features = ["cookie"] }
color-eyre = "0.6.5"
hex = "0.4.3"
jiff = "0.2.15"
password-hash = { version = "0.5.0" }
rand_core = { version = "0.6.0", features = ["getrandom"] }
serde = { version = "1.0.219", features = ["derive"] }
sqlx = { version = "0.8.6", features = ["runtime-tokio", "migrate", "macros", "sqlite"] }
time = "0.3.41"
tokio = { version = "1.46.1", features = ["full"] }
tracing = { version = "0.1.41", features = ["attributes"] }
tracing-subscriber = { version = "0.3.19", features = ["env-filter"] }

View file

@ -0,0 +1,7 @@
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT, -- ensure no IDs are reused
username TEXT NOT NULL UNIQUE,
password TEXT NOT NULL
);
CREATE INDEX users_username ON users(username);

View file

@ -0,0 +1,7 @@
CREATE TABLE IF NOT EXISTS sessions (
session_id TEXT NOT NULL PRIMARY KEY,
user_id INTEGER NOT NULL,
created INTEGER NOT NULL,
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
) STRICT;

202
idp/src/main.rs Normal file
View file

@ -0,0 +1,202 @@
mod session;
mod users;
use std::str::FromStr;
use askama::Template;
use axum::{
Form, Router,
extract::State,
http::StatusCode,
response::{Html, IntoResponse, Redirect, Response},
routing::get,
};
use axum_extra::extract::{
CookieJar,
cookie::{Cookie, SameSite},
};
use color_eyre::Result;
use color_eyre::eyre::Context;
use serde::Deserialize;
use session::UserSession;
use sqlx::{SqlitePool, sqlite::SqliteConnectOptions};
use tracing::{error, info, level_filters::LevelFilter};
use tracing_subscriber::EnvFilter;
const SESSION_ID_COOKIE_NAME: &str = "IDP_SESSION_ID";
#[derive(Clone)]
struct Db {
pool: sqlx::Pool<sqlx::Sqlite>,
}
#[tokio::main]
async fn main() -> Result<()> {
tracing_subscriber::fmt()
.with_env_filter(
EnvFilter::builder()
.with_default_directive(LevelFilter::INFO.into())
.from_env_lossy(),
)
.init();
let opts = SqliteConnectOptions::from_str("db.sqlite")
.unwrap()
.create_if_missing(true);
let pool = SqlitePool::connect_with(opts)
.await
.wrap_err("connecting to db")?;
sqlx::migrate!()
.run(&pool)
.await
.wrap_err("running migrations")?;
let app = Router::<Db>::new()
.route("/", get::<_, _, Db>(root))
.route("/signup", get(signup).post(signup_post))
.route("/login", get(login).post(login_post))
.route("/users", get(users))
.with_state(Db { pool });
let addr = "0.0.0.0:3000";
let listener = tokio::net::TcpListener::bind(addr)
.await
.wrap_err("binding listener")?;
info!(?addr, "Starting server");
axum::serve(listener, app).await.wrap_err("serving app")
}
async fn root(session: UserSession) -> impl IntoResponse {
#[derive(askama::Template)]
#[template(path = "index.html")]
struct Data {
username: Option<String>,
}
Html(
Data {
username: session.0.map(|user| user.username),
}
.render()
.unwrap(),
)
}
#[derive(askama::Template)]
#[template(path = "signup.html")]
struct SignupTemplate {
already_exists: bool,
}
#[axum::debug_handler]
async fn signup() -> impl IntoResponse {
Html(
SignupTemplate {
already_exists: false,
}
.render()
.unwrap(),
)
}
#[derive(askama::Template)]
#[template(path = "login.html")]
struct LoginTemplate {
error: bool,
}
#[axum::debug_handler]
async fn login() -> impl IntoResponse {
Html(LoginTemplate { error: false }.render().unwrap())
}
#[axum::debug_handler]
async fn users(State(db): State<Db>) -> Result<impl IntoResponse, Response> {
let users = users::all_user_names(&db).await.map_err(|err| {
error!(?err, "Failed to fetch users");
StatusCode::INTERNAL_SERVER_ERROR.into_response()
})?;
#[derive(askama::Template)]
#[template(path = "users.html")]
struct Data {
users: Vec<String>,
}
Ok(Html(Data { users }.render().unwrap()))
}
#[derive(Deserialize)]
struct UsernamePasswordForm {
username: String,
password: String,
}
async fn make_session_cookie_for_user(db: &Db, user_id: i64) -> Result<Cookie<'static>, Response> {
let session = session::create_session(&db, user_id).await.map_err(|err| {
error!(?err, "Failed to create session for user");
StatusCode::INTERNAL_SERVER_ERROR.into_response()
})?;
Ok(Cookie::build((SESSION_ID_COOKIE_NAME, session.0))
.secure(true)
.http_only(true)
.same_site(SameSite::Lax)
.expires(axum_extra::extract::cookie::Expiration::DateTime(
time::OffsetDateTime::now_utc()
.checked_add(time::Duration::days(30))
.unwrap(),
))
.build())
}
async fn signup_post(
State(db): State<Db>,
jar: CookieJar,
Form(signup): Form<UsernamePasswordForm>,
) -> Result<impl IntoResponse, Response> {
let user = users::create_user(&db, signup.username, signup.password)
.await
.map_err(|err| {
error!(?err, "Failed to create user");
StatusCode::INTERNAL_SERVER_ERROR.into_response()
})?;
let Some(user) = user else {
return Err(Html(
SignupTemplate {
already_exists: true,
}
.render()
.unwrap(),
)
.into_response());
};
let session_id = make_session_cookie_for_user(&db, user.id).await?;
Ok((jar.add(session_id), Redirect::to("/")))
}
async fn login_post(
State(db): State<Db>,
jar: CookieJar,
Form(login): Form<UsernamePasswordForm>,
) -> Result<impl IntoResponse, Response> {
let user = users::authenticate_user(&db, login.username, login.password)
.await
.map_err(|err| {
error!(?err, "Failed to create user");
StatusCode::INTERNAL_SERVER_ERROR.into_response()
})?;
let Some(user) = user else {
return Err(Html(LoginTemplate { error: true }.render().unwrap()).into_response());
};
let session_id = make_session_cookie_for_user(&db, user.id).await?;
Ok((jar.add(session_id), Redirect::to("/")))
}

80
idp/src/session.rs Normal file
View file

@ -0,0 +1,80 @@
use axum::extract::FromRequestParts;
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
use axum_extra::extract::CookieJar;
use color_eyre::Result;
use color_eyre::eyre::Context;
use rand_core::RngCore;
use tracing::error;
use crate::Db;
#[derive(Debug, sqlx::FromRow)]
pub struct SessionWithUser {
#[expect(dead_code)]
pub user_id: i32,
/// unix ms
#[expect(dead_code)]
pub created: i64,
pub username: String,
}
pub struct SessionId(pub String);
pub async fn find_session(db: &Db, session_id: &str) -> Result<Option<SessionWithUser>> {
let result = sqlx::query_as::<_, SessionWithUser>(
"select user_id, created, username from sessions left join users on sessions.user_id = users.id where session_id = ?",
)
.bind(session_id)
.fetch_one(&db.pool)
.await;
match result {
Ok(session) => Ok(Some(session)),
Err(sqlx::Error::RowNotFound) => Ok(None),
Err(e) => Err(e).wrap_err("failed to fetch session"),
}
}
pub async fn create_session(db: &Db, user_id: i64) -> Result<SessionId> {
let mut session_id = [0_u8; 32];
rand_core::OsRng.fill_bytes(&mut session_id);
let session_id = format!("idpsess_{}", hex::encode(session_id));
sqlx::query("insert into sessions (session_id, user_id, created) values (?, ?, ?)")
.bind(&session_id)
.bind(user_id)
.bind(jiff::Timestamp::now().as_millisecond())
.execute(&db.pool)
.await
.wrap_err("inserting new session")?;
Ok(SessionId(session_id))
}
#[derive(Debug)]
pub struct UserSession(pub Option<SessionWithUser>);
impl FromRequestParts<Db> for UserSession {
type Rejection = Response;
async fn from_request_parts(
parts: &mut axum::http::request::Parts,
db: &Db,
) -> Result<Self, Self::Rejection> {
let jar = CookieJar::from_headers(&parts.headers);
match jar.get(crate::SESSION_ID_COOKIE_NAME) {
None => Err(StatusCode::FORBIDDEN.into_response()),
Some(cookie) => {
let sess = find_session(&db, cookie.value()).await;
match sess {
Ok(user) => Ok(UserSession(user)),
Err(err) => {
error!(?err, "Error fetching session");
Err(StatusCode::INTERNAL_SERVER_ERROR.into_response())
}
}
}
}
}
}

104
idp/src/users.rs Normal file
View file

@ -0,0 +1,104 @@
use color_eyre::{Result, eyre::Context};
use crate::Db;
#[derive(sqlx::FromRow)]
pub struct User {
pub id: i64,
#[expect(dead_code)]
pub username: String,
}
#[derive(sqlx::FromRow)]
pub struct UserWithPassword {
pub id: i64,
pub username: String,
pub password: String,
}
fn hash_password(password: &str) -> String {
use password_hash::PasswordHasher;
let salt = password_hash::SaltString::generate(&mut rand_core::OsRng);
let argon2 = argon2::Argon2::default();
argon2
.hash_password(password.as_bytes(), &salt)
.unwrap()
.to_string()
}
fn verify_password(password: &str, stored_hash: &str) -> bool {
let Ok(hash) = password_hash::PasswordHash::parse(stored_hash, password_hash::Encoding::B64)
else {
return false;
};
hash.verify_password(&[&argon2::Argon2::default()], password)
.is_ok()
}
pub async fn create_user(db: &Db, username: String, password: String) -> Result<Option<User>> {
let password = tokio::task::spawn_blocking(move || hash_password(&password)).await?;
let result = sqlx::query_as::<_, User>(
"insert into users (username, password) values (?, ?) RETURNING *",
)
.bind(username)
.bind(password)
.fetch_one(&db.pool)
.await;
match result {
Ok(user) => Ok(Some(user)),
Err(sqlx::Error::Database(db)) if db.kind() == sqlx::error::ErrorKind::UniqueViolation => {
Ok(None)
}
Err(err) => Err(err).wrap_err("creating user"),
}
}
pub async fn authenticate_user(
db: &Db,
username: String,
password: String,
) -> Result<Option<User>> {
let user_result = sqlx::query_as::<_, UserWithPassword>(
"select id, username, password from users where username = ?",
)
.bind(username)
.fetch_one(&db.pool)
.await;
let user = match user_result {
Ok(user) => user,
Err(sqlx::Error::RowNotFound) => return Ok(None),
Err(e) => return Err(e).wrap_err("failed to fetch user"),
};
let is_ok =
tokio::task::spawn_blocking(move || verify_password(&password, &user.password)).await?;
if !is_ok {
return Ok(None);
}
Ok(Some(User {
id: user.id,
username: user.username,
}))
}
pub async fn all_user_names(db: &Db) -> Result<Vec<String>> {
#[derive(sqlx::FromRow)]
struct User {
username: String,
}
Ok(sqlx::query_as::<_, User>("select username from users")
.fetch_all(&db.pool)
.await
.wrap_err("fetching users")?
.into_iter()
.map(|user| user.username)
.collect())
}

24
idp/templates/index.html Normal file
View file

@ -0,0 +1,24 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>IDP</title>
</head>
<body>
<h1>Your favorite identity provider</h1>
<a href="/">home</a>
{% if let Some(username) = username %}
<p>Hello, {{username}}!</p>
{% endif %}
<div>
<a href="/signup">Create an account</a>
</div>
<div>
<a href="/login">Login</a>
</div>
<div>
<a href="/users">List all users</a>
</div>
</body>
</html>

29
idp/templates/login.html Normal file
View file

@ -0,0 +1,29 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Login - IDP</title>
</head>
<body>
<h1>Log into your beautiful account</h1>
<a href="/">home</a>
<form method="post" action="/login">
<div>
<label for="username">Username</label>
<input id="username" name="username" />
</div>
<div>
<label for="password">Password</label>
<input id="password" name="password" />
</div>
<button type="submit">Login</button>
{% if error %}
<p>Invalid username or password.</p>
{% endif %}
</form>
</body>
</html>

29
idp/templates/signup.html Normal file
View file

@ -0,0 +1,29 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Signup - IDP</title>
</head>
<body>
<h1>Create a new account</h1>
<a href="/">home</a>
<form method="post" action="/signup">
<div>
<label for="username">Username</label>
<input id="username" name="username" />
</div>
<div>
<label for="password">Password</label>
<input id="password" name="password" />
</div>
<button type="submit">Create Account</button>
{% if already_exists %}
<p>Username is already taken</p>
{% endif %}
</form>
</body>
</html>

17
idp/templates/users.html Normal file
View file

@ -0,0 +1,17 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Users - IDP</title>
</head>
<body>
<h1>Your favorite identity provider</h1>
<a href="/">home</a>
<ul>
{% for user in users %}
<li>{{user}}</li>
{% endfor %}
</ul>
</body>
</html>