feat: add account avatars and a deployable image

Accounts get a profile page with an uploaded picture, shown in the
sidebar, the room bar, and every human message. Pictures live in the
SQLite database and are served through an authenticated route.

Hardening from the security audit: preview hosts expire after 24 hours
and carry no-referrer; removing a member or archiving a room ends their
event feed, presence socket, and terminal within seconds; previews and
the terminal pin the SSH host key; invites are claimed atomically;
missing accounts spend the same argon2 time as wrong passwords;
registration is closed by default; WebSockets check the origin; and the
master key is created with mode 0600.

The Dockerfile builds one image with the static client and the server.
The Helm chart runs a single replica with a SQLite volume, a wildcard
preview ingress, and the proxy settings the event feed and uploads
need. It refuses more than one replica because state is in process.
This commit is contained in:
vhaudiquet committed 2026-11-28 02:07:26 +01:00
1 parent 7e7a1d2bb6
commit 3b82719d56
38 files changed
+1307 -106

No files matched your search

+20 -3
View File
@@ -8,7 +8,8 @@ use serde::Deserialize;
use serde_json::{Value, json};
use crate::auth::{
self, AuthUser, clean_display_name, hash_password, valid_handle, verify_password,
self, AuthUser, clean_display_name, dummy_password_hash, hash_password, valid_handle,
verify_password,
};
use crate::error::{AppError, AppResult};
use crate::models::User;
@@ -109,6 +110,7 @@ pub async fn setup(
handle,
display_name,
kind: "user".into(),
avatar_updated_at: None,
}),
))
}
@@ -176,6 +178,7 @@ pub async fn register(
handle,
display_name,
kind: "user".into(),
avatar_updated_at: None,
}),
))
}
@@ -196,7 +199,9 @@ pub async fn login(
.db
.conn()
.query_row(
"SELECT id, handle, display_name, kind, password_hash FROM accounts
"SELECT id, handle, display_name, kind, password_hash,
(SELECT updated_at FROM avatars WHERE account_id = accounts.id)
FROM accounts
WHERE handle = ?1 OR (email IS NOT NULL AND email = ?1)
LIMIT 1",
rusqlite::params![identifier],
@@ -207,11 +212,22 @@ pub async fn login(
row.get::<_, String>(2)?,
row.get::<_, String>(3)?,
row.get::<_, Option<String>>(4)?,
row.get::<_, Option<i64>>(5)?,
))
},
)
.ok();
let Some((id, handle, display_name, kind, Some(password_hash))) = row else {
let (id, handle, display_name, kind, password_hash, avatar_updated_at) = match row {
Some(row) => row,
None => {
// Spend the same argon2 work as a real check so the response
// time does not reveal whether the handle exists.
let _ = verify_password(dummy_password_hash(), &body.password);
return Err(AppError::unauthorized("wrong handle or password"));
}
};
let Some(password_hash) = password_hash else {
let _ = verify_password(dummy_password_hash(), &body.password);
return Err(AppError::unauthorized("wrong handle or password"));
};
if !verify_password(&password_hash, &body.password) {
@@ -227,6 +243,7 @@ pub async fn login(
handle,
display_name,
kind,
avatar_updated_at,
}),
))
}
+9 -1
View File
@@ -6,6 +6,7 @@ use std::time::Duration;
use axum::Json;
use axum::extract::ws::WebSocketUpgrade;
use axum::extract::{Path, Query, State};
use axum::http::HeaderMap;
use axum::response::Response;
use rhema_sandbox::Sandbox;
use rhema_sandbox::exec_util::shquote;
@@ -233,9 +234,16 @@ pub async fn terminal(
user: AuthUser,
State(state): State<Shared>,
Path(room): Path<String>,
headers: HeaderMap,
ws: WebSocketUpgrade,
) -> AppResult<Response> {
if !super::websocket_origin_ok(&state.config, &headers) {
return Err(AppError::forbidden("websocket origin does not match"));
}
member_of(&state, &room, &user.user.id)?;
let (workspace, target) = room_workspace(&state, &room)?;
Ok(ws.on_upgrade(move |socket| crate::ssh::terminal(socket, state, workspace, target)))
let account = user.user.id.clone();
Ok(ws.on_upgrade(move |socket| {
crate::ssh::terminal(socket, state, room, account, workspace, target)
}))
}
+59 -14
View File
@@ -7,6 +7,7 @@ use std::time::Duration;
use axum::Json;
use axum::extract::ws::{Message as WsMessage, WebSocket, WebSocketUpgrade};
use axum::extract::{Path, Query, State};
use axum::http::HeaderMap;
use axum::response::Response;
use axum::response::sse::{Event as SseEvent, KeepAlive, KeepAliveStream, Sse};
use futures::{SinkExt, Stream, StreamExt};
@@ -130,7 +131,15 @@ pub async fn events(
Query(query): Query<Since>,
) -> AppResult<Sse<KeepAliveStream<EventStream>>> {
member_of(&state, &room, &user.user.id)?;
let since = query.since.unwrap_or(0) as i64;
let requested = query.since.unwrap_or(0).min(i64::MAX as u64) as i64;
let max_seq: i64 = state.db.scalar(
"SELECT COALESCE(MAX(seq), 0) FROM events WHERE room_id = ?1",
rusqlite::params![room],
)?;
// A client asking for a future sequence must not skip everything
// that arrives after it.
let since = requested.min(max_seq);
let user_id = user.user.id.clone();
// Subscribe before reading the backlog: an event that lands between
// the two is then either in the backlog or on the feed, never lost.
let mut rx = state.hub.subscribe(&state.db, &room);
@@ -161,21 +170,37 @@ pub async fn events(
let data = serde_json::to_string(&envelope).unwrap_or_else(|_| "{}".into());
yield Ok(SseEvent::default().id(envelope.seq.to_string()).data(data));
}
let mut access = tokio::time::interval(Duration::from_secs(2));
loop {
match rx.recv().await {
Ok(envelope) => {
if envelope.seq <= last {
continue;
tokio::select! {
_ = access.tick() => {
if member_of(&state, &room, &user_id).is_err() {
break;
}
last = envelope.seq;
let data = serde_json::to_string(&envelope).unwrap_or_else(|_| "{}".into());
yield Ok(SseEvent::default().id(envelope.seq.to_string()).data(data));
}
Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => {
let data = json!({ "seq": last, "kind": "lag", "data": {} }).to_string();
yield Ok(SseEvent::default().event("lag").data(data));
message = rx.recv() => {
match message {
Ok(envelope) => {
if member_of(&state, &room, &user_id).is_err() {
break;
}
if envelope.seq <= last {
continue;
}
last = envelope.seq;
let data = serde_json::to_string(&envelope).unwrap_or_else(|_| "{}".into());
yield Ok(SseEvent::default().id(envelope.seq.to_string()).data(data));
}
Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => {
if member_of(&state, &room, &user_id).is_err() {
break;
}
let data = json!({ "seq": last, "kind": "lag", "data": {} }).to_string();
yield Ok(SseEvent::default().event("lag").data(data));
}
Err(tokio::sync::broadcast::error::RecvError::Closed) => break,
}
}
Err(tokio::sync::broadcast::error::RecvError::Closed) => break,
}
}
};
@@ -192,13 +217,24 @@ pub async fn presence(
user: AuthUser,
State(state): State<Shared>,
Path(room): Path<String>,
headers: HeaderMap,
ws: WebSocketUpgrade,
) -> AppResult<Response> {
if !super::websocket_origin_ok(&state.config, &headers) {
return Err(AppError::forbidden("websocket origin does not match"));
}
let member = member_of(&state, &room, &user.user.id)?;
Ok(ws.on_upgrade(move |socket| presence_loop(socket, state, room, member)))
let account = user.user.id.clone();
Ok(ws.on_upgrade(move |socket| presence_loop(socket, state, room, account, member)))
}
async fn presence_loop(socket: WebSocket, state: Shared, room: String, member: Membership) {
async fn presence_loop(
socket: WebSocket,
state: Shared,
room: String,
account: String,
member: Membership,
) {
let (mut sink, mut source) = socket.split();
let peer = Peer {
member_id: member.id.clone(),
@@ -209,8 +245,14 @@ async fn presence_loop(socket: WebSocket, state: Shared, room: String, member: M
let (id, snapshot, mut updates) = state.presence.join(&room, peer);
let _ = send_presence(&mut sink, &snapshot).await;
let mut ping = tokio::time::interval(Duration::from_secs(25));
let mut access = tokio::time::interval(Duration::from_secs(2));
loop {
tokio::select! {
_ = access.tick() => {
if member_of(&state, &room, &account).is_err() {
break;
}
}
message = source.next() => {
match message {
Some(Ok(WsMessage::Text(text))) => {
@@ -230,6 +272,9 @@ async fn presence_loop(socket: WebSocket, state: Shared, room: String, member: M
}
}
_ = ping.tick() => {
if member_of(&state, &room, &account).is_err() {
break;
}
if sink.send(WsMessage::Ping(Vec::new().into())).await.is_err() {
break;
}
+37 -2
View File
@@ -4,13 +4,14 @@
pub mod auth;
pub mod files;
pub mod messages;
pub mod profile;
pub mod rooms;
pub mod settings;
use axum::Router;
use axum::body::Body;
use axum::extract::{Request, State};
use axum::http::{HeaderValue, StatusCode, Uri, header};
use axum::extract::{DefaultBodyLimit, Request, State};
use axum::http::{HeaderMap, HeaderValue, StatusCode, Uri, header};
use axum::middleware::{self, Next};
use axum::response::{Html, IntoResponse, Response};
use axum::routing::{delete, get, post};
@@ -28,6 +29,13 @@ pub fn router(state: Shared) -> Router {
.route("/register", post(auth::register))
.route("/login", post(auth::login))
.route("/logout", post(auth::logout))
.route(
"/profile/avatar",
post(profile::upload_avatar)
.delete(profile::delete_avatar)
.layer(DefaultBodyLimit::max(profile::MAX_AVATAR_BYTES + 64 * 1024)),
)
.route("/avatars/{account}", get(profile::get_avatar))
.route(
"/provider-configs",
get(settings::list_providers).post(settings::create_provider),
@@ -72,6 +80,27 @@ pub fn router(state: Shared) -> Router {
.with_state(state)
}
/// Whether a browser WebSocket handshake came from the app's origin.
/// A client that sends no `Origin` is not a browser page and is left to
/// the cookie check.
pub(crate) fn websocket_origin_ok(config: &crate::config::Config, headers: &HeaderMap) -> bool {
let Some(origin) = headers
.get(header::ORIGIN)
.and_then(|value| value.to_str().ok())
else {
return true;
};
let origin = origin.trim_end_matches('/');
let public = config.public_url.trim_end_matches('/');
if origin == public {
return true;
}
// The Nuxt dev server proxies the sockets from port 3000 while the
// API keeps its own port. Both are loopback, so accept that pair.
let loopback = public.starts_with("http://localhost") || public.starts_with("http://127.0.0.1");
loopback && (origin.starts_with("http://localhost:") || origin.starts_with("http://127.0.0.1:"))
}
/// Rejects a mutating API request without the matching CSRF header.
/// Setup, login, registration, and joining with an invite happen before
/// the client has a CSRF cookie.
@@ -122,6 +151,12 @@ async fn headers(State(state): State<Shared>, request: Request, next: Next) -> R
HeaderValue::from_static("strict-origin-when-cross-origin"),
);
h.insert(header::X_FRAME_OPTIONS, HeaderValue::from_static("DENY"));
if state.config.secure_cookies() {
h.insert(
header::STRICT_TRANSPORT_SECURITY,
HeaderValue::from_static("max-age=31536000"),
);
}
let frame_src = match state.config.preview_frame_source() {
Some(source) => format!("'self' {source}"),
None => "'self'".to_owned(),
+142
View File
@@ -0,0 +1,142 @@
//! The account's picture: a small image served back to rooms and the
//! sidebar. The client resizes before upload; the server checks the
//! magic bytes and the size so a crafted request cannot store markup.
use axum::Json;
use axum::body::Bytes;
use axum::extract::{Path, State};
use axum::http::{HeaderValue, StatusCode, header};
use axum::response::{IntoResponse, Response};
use crate::auth::AuthUser;
use crate::error::{AppError, AppResult};
use crate::models::User;
use crate::state::Shared;
use crate::util::now_ms;
/// Two megabytes fits a 512px JPEG many times over.
pub const MAX_AVATAR_BYTES: usize = 2 * 1024 * 1024;
/// The image type named by the file's first bytes. SVG is deliberately
/// absent: it can carry script when opened as a document.
fn image_mime(bytes: &[u8]) -> Option<&'static str> {
if bytes.starts_with(b"\x89PNG\r\n\x1a\n") {
Some("image/png")
} else if bytes.starts_with(&[0xFF, 0xD8, 0xFF]) {
Some("image/jpeg")
} else if bytes.starts_with(b"GIF87a") || bytes.starts_with(b"GIF89a") {
Some("image/gif")
} else if bytes.len() >= 12 && bytes.starts_with(b"RIFF") && &bytes[8..12] == b"WEBP" {
Some("image/webp")
} else {
None
}
}
/// The stored picture. Any signed-in account may read one.
pub async fn get_avatar(
_user: AuthUser,
State(state): State<Shared>,
Path(account): Path<String>,
) -> AppResult<Response> {
let row = state
.db
.conn()
.query_row(
"SELECT mime, bytes FROM avatars WHERE account_id = ?1",
rusqlite::params![account],
|row| Ok((row.get::<_, String>(0)?, row.get::<_, Vec<u8>>(1)?)),
)
.ok();
let Some((mime, bytes)) = row else {
return Err(AppError::not_found("no picture for this account"));
};
let mut response = bytes.into_response();
let headers = response.headers_mut();
headers.insert(
header::CONTENT_TYPE,
HeaderValue::from_static(match mime.as_str() {
"image/png" => "image/png",
"image/jpeg" => "image/jpeg",
"image/gif" => "image/gif",
"image/webp" => "image/webp",
_ => "application/octet-stream",
}),
);
headers.insert(
header::CACHE_CONTROL,
HeaderValue::from_static("private, max-age=300"),
);
headers.insert(
header::X_CONTENT_TYPE_OPTIONS,
HeaderValue::from_static("nosniff"),
);
Ok(response)
}
/// Replaces the caller's picture with the raw request body.
pub async fn upload_avatar(
user: AuthUser,
State(state): State<Shared>,
body: Bytes,
) -> AppResult<Json<User>> {
if body.is_empty() {
return Err(AppError::bad_request("the picture is empty"));
}
if body.len() > MAX_AVATAR_BYTES {
return Err(AppError::new(
StatusCode::PAYLOAD_TOO_LARGE,
"the picture must be 2 MB or smaller",
));
}
let mime = image_mime(&body).ok_or_else(|| {
AppError::bad_request("the picture must be a PNG, JPEG, GIF, or WebP image")
})?;
let mut account = user.user;
let now = now_ms();
state.db.conn().execute(
"INSERT INTO avatars (account_id, mime, bytes, updated_at)
VALUES (?1, ?2, ?3, ?4)
ON CONFLICT(account_id) DO UPDATE SET
mime = excluded.mime,
bytes = excluded.bytes,
updated_at = excluded.updated_at",
rusqlite::params![&account.id, mime, body.as_ref(), now],
)?;
account.avatar_updated_at = Some(now);
Ok(Json(account))
}
/// Removes the caller's picture and falls the avatar back to initials.
pub async fn delete_avatar(user: AuthUser, State(state): State<Shared>) -> AppResult<Json<User>> {
let mut account = user.user;
state.db.conn().execute(
"DELETE FROM avatars WHERE account_id = ?1",
rusqlite::params![&account.id],
)?;
account.avatar_updated_at = None;
Ok(Json(account))
}
#[cfg(test)]
mod tests {
use super::image_mime;
#[test]
fn recognizes_the_four_image_types() {
assert_eq!(image_mime(b"\x89PNG\r\n\x1a\nrest"), Some("image/png"));
assert_eq!(image_mime(&[0xFF, 0xD8, 0xFF, 0xE0]), Some("image/jpeg"));
assert_eq!(image_mime(b"GIF89a..."), Some("image/gif"));
assert_eq!(image_mime(b"RIFF\0\0\0\0WEBPVP8 "), Some("image/webp"));
}
#[test]
fn rejects_markup_and_unknown_bytes() {
assert_eq!(
image_mime(b"<svg xmlns=\"http://www.w3.org/2000/svg\">"),
None
);
assert_eq!(image_mime(b"RIFF\0\0\0\0WAVEfmt "), None);
assert_eq!(image_mime(b""), None);
}
}
+20 -4
View File
@@ -88,8 +88,10 @@ fn load_members(state: &Shared, room: &str) -> AppResult<Vec<Member>> {
let online = state.presence.online(room);
let conn = state.db.conn();
let mut stmt = conn.prepare(
"SELECT id, account_id, display_name, role, color FROM members
WHERE room_id = ?1 ORDER BY created_at ASC",
"SELECT m.id, m.account_id, m.display_name, m.role, m.color,
(SELECT updated_at FROM avatars WHERE account_id = m.account_id)
FROM members m
WHERE m.room_id = ?1 ORDER BY m.created_at ASC",
)?;
let rows = stmt.query_map(rusqlite::params![room], |row| {
Ok(Member {
@@ -98,6 +100,7 @@ fn load_members(state: &Shared, room: &str) -> AppResult<Vec<Member>> {
display_name: row.get(2)?,
role: row.get(3)?,
color: row.get(4)?,
avatar_updated_at: row.get(5)?,
online: false,
})
})?;
@@ -504,6 +507,18 @@ pub async fn join(
return Err(AppError::gone("this invite has expired"));
}
let display_name = clean_display_name(&body.display_name)?;
// Claim the invite before creating an account or a member. The
// conditional update is atomic, so two requests racing with the
// same link cannot both redeem it.
let token_hash = sha256_hex(token.as_bytes());
let claimed = state.db.conn().execute(
"UPDATE invites SET used_at = ?1
WHERE token_hash = ?2 AND used_at IS NULL AND expires_at >= ?1",
rusqlite::params![now_ms(), &token_hash],
)?;
if claimed == 0 {
return Err(AppError::gone("this invite was already used"));
}
let existing = auth::user_from_headers(&state, &headers);
let mut new_session = false;
let account = match existing {
@@ -522,6 +537,7 @@ pub async fn join(
handle,
display_name,
kind: "guest".into(),
avatar_updated_at: None,
}
}
};
@@ -559,8 +575,8 @@ pub async fn join(
}
};
state.db.conn().execute(
"UPDATE invites SET used_at = ?1, used_by = ?2 WHERE token_hash = ?3",
rusqlite::params![now_ms(), account.id, sha256_hex(token.as_bytes())],
"UPDATE invites SET used_by = ?1 WHERE token_hash = ?2",
rusqlite::params![account.id, token_hash],
)?;
let cookies = if new_session {
let raw = auth::create_session(&state, &account.id)?;
+1
View File
@@ -257,6 +257,7 @@ pub async fn delete_target(
"DELETE FROM sandbox_targets WHERE id = ?1 AND account_id = ?2",
rusqlite::params![id, user.user.id],
)?;
state.previews.forget(&id);
Ok(Json(json!({ "ok": true })))
}
+10 -1
View File
@@ -58,7 +58,8 @@ pub fn user_from_token(state: &Shared, token_hash: &str) -> Option<User> {
.db
.conn()
.query_row(
"SELECT a.id, a.handle, a.display_name, a.kind, s.expires_at
"SELECT a.id, a.handle, a.display_name, a.kind, s.expires_at,
(SELECT updated_at FROM avatars WHERE account_id = a.id)
FROM auth_sessions s JOIN accounts a ON a.id = s.account_id
WHERE s.token_hash = ?1",
rusqlite::params![token_hash],
@@ -69,6 +70,7 @@ pub fn user_from_token(state: &Shared, token_hash: &str) -> Option<User> {
handle: row.get(1)?,
display_name: row.get(2)?,
kind: row.get(3)?,
avatar_updated_at: row.get(5)?,
},
row.get::<_, i64>(4)?,
))
@@ -105,6 +107,13 @@ pub fn hash_password(password: &str) -> AppResult<String> {
.map_err(|_| AppError::internal("could not hash the password"))
}
/// A valid hash used to keep a missing account's login time close to a
/// wrong password's. Generated once, then reused.
pub(crate) fn dummy_password_hash() -> &'static str {
static HASH: std::sync::OnceLock<String> = std::sync::OnceLock::new();
HASH.get_or_init(|| hash_password("rhema-together-login-timing").unwrap_or_default())
}
/// Verifies a password against a stored argon2 hash.
pub fn verify_password(stored: &str, password: &str) -> bool {
let Ok(hash) = PasswordHash::new(stored) else {
+2 -6
View File
@@ -31,7 +31,7 @@ pub struct Config {
pub allowed_frame_ancestors: Vec<String>,
/// Whether anyone may create an account. Off leaves setup and
/// invites as the only doors.
#[serde(default = "default_true")]
#[serde(default)]
pub allow_registration: bool,
}
@@ -39,10 +39,6 @@ fn default_steps() -> u32 {
48
}
fn default_true() -> bool {
true
}
impl Default for Config {
fn default() -> Self {
Self {
@@ -54,7 +50,7 @@ impl Default for Config {
web_dir: PathBuf::from("web/.output/public"),
max_turn_steps: default_steps(),
allowed_frame_ancestors: Vec::new(),
allow_registration: true,
allow_registration: false,
}
}
}
+12 -3
View File
@@ -1,6 +1,7 @@
//! Symmetric protection for the credentials the server stores: provider
//! API keys and ssh private keys. The key comes from a 0600 file.
use std::io::Write;
use std::path::Path;
use base64::Engine;
@@ -22,6 +23,11 @@ impl Secrets {
/// bytes nor base64 for 32 bytes is refused.
pub fn load_or_create(path: &Path) -> anyhow::Result<Self> {
let key = if path.exists() {
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600));
}
let raw = std::fs::read(path)?;
decode_key(&raw)?
} else {
@@ -31,12 +37,15 @@ impl Secrets {
use rand::RngCore;
let mut key = [0u8; 32];
rand::rngs::OsRng.fill_bytes(&mut key);
std::fs::write(path, key)?;
let mut options = std::fs::OpenOptions::new();
options.write(true).create_new(true);
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600))?;
use std::os::unix::fs::OpenOptionsExt;
options.mode(0o600);
}
let mut file = options.open(path)?;
file.write_all(&key)?;
key
};
use sha2::{Digest, Sha256};
+7
View File
@@ -63,6 +63,13 @@ CREATE TABLE IF NOT EXISTS accounts (
created_at INTEGER NOT NULL
) STRICT;
CREATE TABLE IF NOT EXISTS avatars (
account_id TEXT PRIMARY KEY REFERENCES accounts(id) ON DELETE CASCADE,
mime TEXT NOT NULL,
bytes BLOB NOT NULL,
updated_at INTEGER NOT NULL
) STRICT;
CREATE TABLE IF NOT EXISTS auth_sessions (
token_hash TEXT PRIMARY KEY,
account_id TEXT NOT NULL REFERENCES accounts(id) ON DELETE CASCADE,
+3
View File
@@ -52,6 +52,7 @@ pub struct Member {
pub display_name: String,
pub role: String,
pub color: String,
pub avatar_updated_at: Option<i64>,
pub online: bool,
}
@@ -62,6 +63,8 @@ pub struct User {
pub handle: String,
pub display_name: String,
pub kind: String,
/// When the account last replaced its picture, or `None`.
pub avatar_updated_at: Option<i64>,
}
/// One server-sent event. Durable events are also rows in `events`;
+111 -22
View File
@@ -43,7 +43,7 @@ impl PreviewTunnels {
.insert(target.to_owned(), handle);
}
fn forget(&self, target: &str) {
pub(crate) fn forget(&self, target: &str) {
self.handles
.lock()
.unwrap_or_else(|err| err.into_inner())
@@ -75,6 +75,10 @@ pub fn is_preview_host(config: &Config, host: &str) -> bool {
name.ends_with(&format!(".{domain}"))
}
/// How long a preview host stays valid. The browser keeps using the
/// host it was given; a reload of the room mints a fresh one.
const PREVIEW_TTL_SECONDS: i64 = 24 * 60 * 60;
/// The signed URL for one room and port.
pub fn url(config: &Config, secrets: &Secrets, room: &str, port: u16) -> AppResult<String> {
let Some((scheme, domain)) = domain(config) else {
@@ -82,7 +86,8 @@ pub fn url(config: &Config, secrets: &Secrets, room: &str, port: u16) -> AppResu
"the preview proxy is not configured",
));
};
let signature = secrets.sign(&format!("{room}:{port}"));
let expires = crate::util::now_ms() / 1000 + PREVIEW_TTL_SECONDS;
let signature = secrets.sign(&format!("{room}:{port}:{expires}"));
let port_part = config
.preview_origin
.split_once("://")
@@ -93,23 +98,44 @@ pub fn url(config: &Config, secrets: &Secrets, room: &str, port: u16) -> AppResu
.map(|(_, value)| format!(":{value}"))
.unwrap_or_default();
Ok(format!(
"{scheme}://r{room}-p{port}-{signature}.{domain}{port_part}/"
"{scheme}://r{room}-p{port}-{expires}-{signature}.{domain}{port_part}/"
))
}
/// Splits `r<room>-p<port>-<sig>` from the Host header.
fn target_of_host(config: &Config, host: &str) -> Option<(String, u16, String)> {
/// Splits `r<room>-p<port>-<expiry>-<sig>` from the Host header.
fn target_of_host(config: &Config, host: &str) -> Option<(String, u16, i64, String)> {
let (_, domain) = domain(config)?;
let name = host.split(':').next().unwrap_or(host);
let label = name.strip_suffix(&format!(".{domain}"))?;
let rest = label.strip_prefix('r')?;
let (room, port) = rest.rsplit_once("-p")?;
let (port, signature) = port.rsplit_once('-')?;
if room.is_empty() || signature.is_empty() {
let (room, rest) = rest.rsplit_once("-p")?;
let mut fields = rest.split('-');
let port: u16 = fields.next()?.parse().ok()?;
let expires: i64 = fields.next()?.parse().ok()?;
let signature = fields.next()?;
if room.is_empty() || signature.is_empty() || fields.next().is_some() {
return None;
}
let port: u16 = port.parse().ok()?;
Some((room.to_owned(), port, signature.to_owned()))
Some((room.to_owned(), port, expires, signature.to_owned()))
}
fn signatures_match(a: &str, b: &str) -> bool {
if a.len() != b.len() {
return false;
}
let mut diff = 0u8;
for (left, right) in a.as_bytes().iter().zip(b.as_bytes()) {
diff |= left ^ right;
}
diff == 0
}
fn no_referrer(mut response: Response) -> Response {
response.headers_mut().insert(
header::REFERRER_POLICY,
HeaderValue::from_static("no-referrer"),
);
response
}
/// Verifies the signature in the Host header against the room and port
@@ -121,20 +147,25 @@ pub async fn proxy(state: Shared, request: Request<Body>) -> Response {
.and_then(|value| value.to_str().ok())
.unwrap_or("")
.to_owned();
let Some((room, port, signature)) = target_of_host(&state.config, &host) else {
let Some((room, port, expires, signature)) = target_of_host(&state.config, &host) else {
return (StatusCode::NOT_FOUND, "not a preview host").into_response();
};
let expected = state.secrets.sign(&format!("{room}:{port}"));
if signature != expected {
if expires < crate::util::now_ms() / 1000 {
return (StatusCode::NOT_FOUND, "this preview link has expired").into_response();
}
let expected = state.secrets.sign(&format!("{room}:{port}:{expires}"));
if !signatures_match(&signature, &expected) {
return (StatusCode::NOT_FOUND, "not a preview host").into_response();
}
match try_proxy(&state, &room, port, request).await {
Ok(response) => response,
Err(message) => (
StatusCode::BAD_GATEWAY,
format!("the preview did not answer: {message}"),
)
.into_response(),
Ok(response) => no_referrer(response),
Err(message) => no_referrer(
(
StatusCode::BAD_GATEWAY,
format!("the preview did not answer: {message}"),
)
.into_response(),
),
}
}
@@ -153,7 +184,9 @@ async fn try_proxy(
let handle = match state.previews.get(&target.id) {
Some(handle) => handle,
None => {
let handle = Arc::new(crate::ssh::connect_handle(&target, &key).await?);
let (handle, learned) = crate::ssh::connect_handle(&target, &key).await?;
crate::ssh::remember_host_key(state, &target, learned);
let handle = Arc::new(handle);
state.previews.put(&target.id, handle.clone());
handle
}
@@ -165,7 +198,9 @@ async fn try_proxy(
Ok(channel) => channel,
Err(_) => {
state.previews.forget(&target.id);
let handle = Arc::new(crate::ssh::connect_handle(&target, &key).await?);
let (handle, learned) = crate::ssh::connect_handle(&target, &key).await?;
crate::ssh::remember_host_key(state, &target, learned);
let handle = Arc::new(handle);
state.previews.put(&target.id, handle.clone());
handle
.channel_open_direct_tcpip("127.0.0.1", port as u32, "127.0.0.1", 0)
@@ -208,7 +243,7 @@ async fn try_proxy(
*out.status_mut() = parts.status;
*out.headers_mut() = parts.headers;
strip_hop_by_hop(out.headers_mut());
Ok(out)
Ok(no_referrer(out))
}
fn strip_hop_by_hop(headers: &mut HeaderMap) {
@@ -225,3 +260,57 @@ fn strip_hop_by_hop(headers: &mut HeaderMap) {
headers.remove(name);
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::config::Config;
fn secrets() -> (Secrets, std::path::PathBuf) {
let path = std::env::temp_dir().join(format!(
"rhema-together-preview-test-{}.key",
crate::util::random_id(10)
));
let secrets = Secrets::load_or_create(&path).expect("test key");
(secrets, path)
}
#[test]
fn a_preview_host_carries_room_port_expiry_and_signature() {
let mut config = Config::default();
config.preview_origin = "https://preview.example.com".into();
let (secrets, path) = secrets();
let url = url(&config, &secrets, "room123", 5173).expect("url");
let host = url
.trim_start_matches("https://")
.split('/')
.next()
.expect("host");
let (room, port, expires, signature) = target_of_host(&config, host).expect("parsed host");
assert_eq!(room, "room123");
assert_eq!(port, 5173);
assert!(expires >= crate::util::now_ms() / 1000);
assert_eq!(signature, secrets.sign(&format!("room123:5173:{expires}")));
let _ = std::fs::remove_file(path);
}
#[test]
fn the_old_host_shape_is_not_accepted() {
let mut config = Config::default();
config.preview_origin = "https://preview.example.com".into();
assert!(
target_of_host(
&config,
"rroom123-p5173-0123456789abcdef01234567.preview.example.com"
)
.is_none()
);
}
#[test]
fn signatures_compare_by_value() {
assert!(signatures_match("abcd", "abcd"));
assert!(!signatures_match("abcd", "abce"));
assert!(!signatures_match("abcd", "abc"));
}
}
+32 -13
View File
@@ -46,13 +46,26 @@ impl client::Handler for HostKey {
}
}
/// Opens a connection for the preview proxy.
/// Opens a connection for the preview proxy, returning the host-key
/// fingerprint when this was the first contact.
pub(crate) async fn connect_handle(
target: &TargetRow,
private_key: &str,
) -> Result<Handle<HostKey>, String> {
let (handle, _fingerprint) = connect(target, private_key).await?;
Ok(handle)
) -> Result<(Handle<HostKey>, Option<String>), String> {
connect(target, private_key).await
}
/// Pins a learned host key after a successful login. A later connection
/// then refuses a different key.
pub(crate) fn remember_host_key(state: &Shared, target: &TargetRow, learned: Option<String>) {
if target.host_fingerprint.is_none()
&& let Some(fingerprint) = learned
{
let _ = state.db.conn().execute(
"UPDATE sandbox_targets SET host_fingerprint = ?1 WHERE id = ?2",
rusqlite::params![fingerprint, target.id],
);
}
}
async fn connect(
@@ -95,7 +108,14 @@ async fn connect(
/// Attaches a browser socket to an interactive shell in the room's
/// sandbox.
pub async fn terminal(socket: WebSocket, state: Shared, workspace: String, target: TargetRow) {
pub async fn terminal(
socket: WebSocket,
state: Shared,
room: String,
account: String,
workspace: String,
target: TargetRow,
) {
let (mut sink, mut source) = socket.split();
let key = match state.secrets.open_str(&target.private_key_ciphertext) {
Ok(key) => key,
@@ -125,14 +145,7 @@ pub async fn terminal(socket: WebSocket, state: Shared, workspace: String, targe
};
// Learn the host key once the login succeeded, not before: a
// server that refuses us should not become known.
if target.host_fingerprint.is_none()
&& let Some(fingerprint) = learned
{
let _ = state.db.conn().execute(
"UPDATE sandbox_targets SET host_fingerprint = ?1 WHERE id = ?2",
rusqlite::params![fingerprint, target.id],
);
}
remember_host_key(&state, &target, learned);
let mut channel = match connection.channel_open_session().await {
Ok(channel) => channel,
Err(err) => {
@@ -160,8 +173,14 @@ pub async fn terminal(socket: WebSocket, state: Shared, workspace: String, targe
json!({ "type": "ready" }).to_string().into(),
))
.await;
let mut access = tokio::time::interval(std::time::Duration::from_secs(2));
loop {
tokio::select! {
_ = access.tick() => {
if crate::api::rooms::member_of(&state, &room, &account).is_err() {
break;
}
}
message = channel.wait() => {
match message {
Some(ChannelMsg::Data { data }) => {