389 lines
14 KiB
Rust
389 lines
14 KiB
Rust
//! Every rule of the relay, over SQLite, with the clock passed in.
|
|
//!
|
|
//! The database holds exactly `docs/PROTOCOL.md` §5: three tables, and nothing about who connected.
|
|
//! A wrong token and an unknown id give the same [`Refused::NotFound`], so nobody can probe which
|
|
//! mailboxes or invites exist.
|
|
|
|
use rusqlite::{params, Connection, OptionalExtension};
|
|
use std::path::Path;
|
|
use std::sync::Mutex;
|
|
use subtle::ConstantTimeEq;
|
|
use tabellarius_protocol::{
|
|
blob_hash, day_of, hour_of, BlobBytes, ClaimedInvite, CreateInvite, CreateMailbox, FetchedBlob,
|
|
InviteId, KeyPackageBytes, MailboxId, Sha256Hash, Token, BLOB_TTL_SECS, INVITE_TTL_SECS,
|
|
MAX_BLOBS_PER_FETCH, MAX_BLOB_BYTES,
|
|
};
|
|
|
|
/// The schema, and nothing else (`PROTOCOL.md` §5). A column added here is a protocol change.
|
|
pub const SCHEMA: &str = "
|
|
CREATE TABLE IF NOT EXISTS mailboxes (
|
|
id BLOB PRIMARY KEY NOT NULL,
|
|
post_hash BLOB NOT NULL,
|
|
fetch_hash BLOB NOT NULL,
|
|
created_day INTEGER NOT NULL
|
|
);
|
|
CREATE TABLE IF NOT EXISTS blobs (
|
|
mailbox_id BLOB NOT NULL,
|
|
ciphertext BLOB NOT NULL,
|
|
size INTEGER NOT NULL,
|
|
received_hour INTEGER NOT NULL
|
|
);
|
|
CREATE INDEX IF NOT EXISTS blobs_by_mailbox ON blobs (mailbox_id);
|
|
CREATE TABLE IF NOT EXISTS invites (
|
|
id BLOB PRIMARY KEY NOT NULL,
|
|
secret_hash BLOB NOT NULL,
|
|
key_package BLOB NOT NULL,
|
|
expiry INTEGER NOT NULL
|
|
);
|
|
";
|
|
|
|
/// Why a request was refused. Deliberately coarse: it says nothing about which part was wrong.
|
|
#[derive(Debug, PartialEq, Eq)]
|
|
pub enum Refused {
|
|
/// Unknown id, wrong token, or an expired invite: indistinguishable on purpose.
|
|
NotFound,
|
|
/// The id is already taken.
|
|
Exists,
|
|
/// Over a protocol limit.
|
|
TooLarge,
|
|
/// The database failed; nothing about the request is in the error.
|
|
Storage,
|
|
/// A quota is reached (`PROTOCOL.md` §8, 507): the mailbox's, after its token, or the relay's.
|
|
Full,
|
|
}
|
|
|
|
/// How much the relay holds before it answers [`Refused::Full`]. The per-mailbox caps are the
|
|
/// protocol's; the relay-wide ones are the operator's (`.agents/features/home-relay.md` §2).
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
pub struct Limits {
|
|
pub mailbox_blobs: i64,
|
|
pub mailbox_bytes: i64,
|
|
pub total_bytes: i64,
|
|
pub mailboxes: i64,
|
|
pub invites: i64,
|
|
}
|
|
|
|
/// Waiting blobs in one mailbox (`PROTOCOL.md` §8).
|
|
pub const MAILBOX_BLOBS: i64 = 1_000;
|
|
/// Waiting bytes in one mailbox (`PROTOCOL.md` §8).
|
|
pub const MAILBOX_BYTES: i64 = 32 * 1024 * 1024;
|
|
|
|
impl Default for Limits {
|
|
fn default() -> Self {
|
|
Limits {
|
|
mailbox_blobs: MAILBOX_BLOBS,
|
|
mailbox_bytes: MAILBOX_BYTES,
|
|
total_bytes: 1024 * 1024 * 1024,
|
|
mailboxes: 100_000,
|
|
invites: 10_000,
|
|
}
|
|
}
|
|
}
|
|
|
|
impl From<rusqlite::Error> for Refused {
|
|
fn from(_: rusqlite::Error) -> Self {
|
|
Refused::Storage
|
|
}
|
|
}
|
|
|
|
pub struct Store {
|
|
conn: Mutex<Connection>,
|
|
limits: Limits,
|
|
}
|
|
|
|
/// What a purge removed.
|
|
#[derive(Debug, PartialEq, Eq, Default)]
|
|
pub struct Purged {
|
|
pub blobs: usize,
|
|
pub invites: usize,
|
|
}
|
|
|
|
fn same_hash(stored: &[u8], presented: &Sha256Hash) -> bool {
|
|
stored.len() == 32 && bool::from(stored.ct_eq(presented.as_bytes()))
|
|
}
|
|
|
|
impl Store {
|
|
pub fn open(path: &Path) -> Result<Self, rusqlite::Error> {
|
|
Self::init(Connection::open(path)?, Limits::default())
|
|
}
|
|
|
|
pub fn open_with(path: &Path, limits: Limits) -> Result<Self, rusqlite::Error> {
|
|
Self::init(Connection::open(path)?, limits)
|
|
}
|
|
|
|
pub fn open_in_memory() -> Result<Self, rusqlite::Error> {
|
|
Self::init(Connection::open_in_memory()?, Limits::default())
|
|
}
|
|
|
|
pub fn open_in_memory_with(limits: Limits) -> Result<Self, rusqlite::Error> {
|
|
Self::init(Connection::open_in_memory()?, limits)
|
|
}
|
|
|
|
fn init(conn: Connection, limits: Limits) -> Result<Self, rusqlite::Error> {
|
|
// Deleted rows are overwritten in the file, and there is no -wal copy of anything.
|
|
conn.pragma_update(None, "secure_delete", "ON")?;
|
|
conn.pragma_update(None, "journal_mode", "DELETE")?;
|
|
conn.execute_batch(SCHEMA)?;
|
|
Ok(Self {
|
|
conn: Mutex::new(conn),
|
|
limits,
|
|
})
|
|
}
|
|
|
|
/// One number from the database: a count or a sum, 0 for none.
|
|
fn number(conn: &Connection, sql: &str, args: impl rusqlite::Params) -> Result<i64, Refused> {
|
|
Ok(conn
|
|
.query_row(sql, args, |r| r.get::<_, Option<i64>>(0))?
|
|
.unwrap_or(0))
|
|
}
|
|
|
|
fn conn(&self) -> std::sync::MutexGuard<'_, Connection> {
|
|
// A panic while holding the lock leaves SQLite consistent (every write is one statement or
|
|
// one transaction), so a poisoned lock is still safe to use.
|
|
self.conn.lock().unwrap_or_else(|p| p.into_inner())
|
|
}
|
|
|
|
pub fn create_mailbox(&self, req: &CreateMailbox, now: i64) -> Result<(), Refused> {
|
|
let conn = self.conn();
|
|
if Self::number(&conn, "SELECT count(*) FROM mailboxes", [])? >= self.limits.mailboxes {
|
|
return Err(Refused::Full);
|
|
}
|
|
let changed = conn.execute(
|
|
"INSERT OR IGNORE INTO mailboxes (id, post_hash, fetch_hash, created_day)
|
|
VALUES (?1, ?2, ?3, ?4)",
|
|
params![
|
|
&req.id.as_bytes()[..],
|
|
&req.post_token_hash.as_bytes()[..],
|
|
&req.fetch_token_hash.as_bytes()[..],
|
|
day_of(now)
|
|
],
|
|
)?;
|
|
if changed == 0 {
|
|
return Err(Refused::Exists);
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
/// Checks a token against the mailbox's stored hash (`post_hash` or `fetch_hash`).
|
|
fn authorize(
|
|
conn: &Connection,
|
|
id: &MailboxId,
|
|
token: &Token,
|
|
column: Column,
|
|
) -> Result<(), Refused> {
|
|
let sql = match column {
|
|
Column::Post => "SELECT post_hash FROM mailboxes WHERE id = ?1",
|
|
Column::Fetch => "SELECT fetch_hash FROM mailboxes WHERE id = ?1",
|
|
};
|
|
let stored: Option<Vec<u8>> = conn
|
|
.query_row(sql, [&id.as_bytes()[..]], |r| r.get(0))
|
|
.optional()?;
|
|
let presented = token.hash();
|
|
// Compare against something even when the mailbox is unknown, so both cases take the same path.
|
|
let stored = stored.unwrap_or_else(|| vec![0; 32]);
|
|
let known = !stored.iter().all(|b| *b == 0);
|
|
if known & same_hash(&stored, &presented) {
|
|
Ok(())
|
|
} else {
|
|
Err(Refused::NotFound)
|
|
}
|
|
}
|
|
|
|
pub fn post(
|
|
&self,
|
|
id: &MailboxId,
|
|
token: &Token,
|
|
blob: &[u8],
|
|
now: i64,
|
|
) -> Result<(), Refused> {
|
|
if blob.len() > MAX_BLOB_BYTES {
|
|
return Err(Refused::TooLarge);
|
|
}
|
|
let conn = self.conn();
|
|
Self::authorize(&conn, id, token, Column::Post)?;
|
|
// After the token: a stranger learns nothing about this mailbox from a 507.
|
|
let size = blob.len() as i64;
|
|
let (count, bytes): (i64, Option<i64>) = conn.query_row(
|
|
"SELECT count(*), sum(size) FROM blobs WHERE mailbox_id = ?1",
|
|
[&id.as_bytes()[..]],
|
|
|r| Ok((r.get(0)?, r.get(1)?)),
|
|
)?;
|
|
let total = Self::number(&conn, "SELECT sum(size) FROM blobs", [])?;
|
|
if count >= self.limits.mailbox_blobs
|
|
|| bytes.unwrap_or(0) + size > self.limits.mailbox_bytes
|
|
|| total + size > self.limits.total_bytes
|
|
{
|
|
return Err(Refused::Full);
|
|
}
|
|
conn.execute(
|
|
"INSERT INTO blobs (mailbox_id, ciphertext, size, received_hour) VALUES (?1, ?2, ?3, ?4)",
|
|
params![&id.as_bytes()[..], blob, blob.len() as i64, hour_of(now)],
|
|
)?;
|
|
Ok(())
|
|
}
|
|
|
|
/// The waiting blobs, oldest first, at most [`MAX_BLOBS_PER_FETCH`]. Fetching deletes nothing:
|
|
/// a blob goes only when it is acknowledged, or at the TTL.
|
|
pub fn fetch(&self, id: &MailboxId, token: &Token) -> Result<Vec<FetchedBlob>, Refused> {
|
|
let conn = self.conn();
|
|
Self::authorize(&conn, id, token, Column::Fetch)?;
|
|
let mut stmt = conn.prepare(
|
|
"SELECT ciphertext, received_hour FROM blobs WHERE mailbox_id = ?1
|
|
ORDER BY received_hour, rowid LIMIT ?2",
|
|
)?;
|
|
let rows = stmt.query_map(
|
|
params![&id.as_bytes()[..], MAX_BLOBS_PER_FETCH as i64],
|
|
|r| Ok((r.get::<_, Vec<u8>>(0)?, r.get::<_, i64>(1)?)),
|
|
)?;
|
|
let mut out = Vec::new();
|
|
for row in rows {
|
|
let (bytes, received_hour) = row?;
|
|
let blob = BlobBytes::new(bytes).map_err(|_| Refused::Storage)?;
|
|
out.push(FetchedBlob {
|
|
blob,
|
|
received_hour,
|
|
});
|
|
}
|
|
Ok(out)
|
|
}
|
|
|
|
/// Deletes this mailbox's blob whose SHA-256 is `hash`. Unknown hash = [`Refused::NotFound`].
|
|
pub fn acknowledge(
|
|
&self,
|
|
id: &MailboxId,
|
|
token: &Token,
|
|
hash: &Sha256Hash,
|
|
) -> Result<(), Refused> {
|
|
let mut conn = self.conn();
|
|
Self::authorize(&conn, id, token, Column::Fetch)?;
|
|
let tx = conn.transaction()?;
|
|
let rowid: Option<i64> = {
|
|
let mut stmt =
|
|
tx.prepare("SELECT rowid, ciphertext FROM blobs WHERE mailbox_id = ?1")?;
|
|
let mut rows = stmt.query([&id.as_bytes()[..]])?;
|
|
let mut found = None;
|
|
while let Some(row) = rows.next()? {
|
|
let bytes: Vec<u8> = row.get(1)?;
|
|
if blob_hash(&bytes) == *hash {
|
|
found = Some(row.get(0)?);
|
|
break;
|
|
}
|
|
}
|
|
found
|
|
};
|
|
let rowid = rowid.ok_or(Refused::NotFound)?;
|
|
tx.execute("DELETE FROM blobs WHERE rowid = ?1", [rowid])?;
|
|
tx.commit()?;
|
|
Ok(())
|
|
}
|
|
|
|
/// Blocking: the owner (fetch token) gives the mailbox a new post token hash.
|
|
pub fn rotate_post_token(
|
|
&self,
|
|
id: &MailboxId,
|
|
fetch: &Token,
|
|
new_hash: &Sha256Hash,
|
|
) -> Result<(), Refused> {
|
|
let conn = self.conn();
|
|
Self::authorize(&conn, id, fetch, Column::Fetch)?;
|
|
conn.execute(
|
|
"UPDATE mailboxes SET post_hash = ?2 WHERE id = ?1",
|
|
params![&id.as_bytes()[..], &new_hash.as_bytes()[..]],
|
|
)?;
|
|
Ok(())
|
|
}
|
|
|
|
pub fn create_invite(&self, req: &CreateInvite, now: i64) -> Result<(), Refused> {
|
|
// Expiry rounded up to the hour: the exact second the invite was made is not kept.
|
|
let expiry = (hour_of(now + INVITE_TTL_SECS) + 1) * 3600;
|
|
let conn = self.conn();
|
|
// Expired invites wait for the hourly purge; they do not count against new ones.
|
|
let waiting = Self::number(
|
|
&conn,
|
|
"SELECT count(*) FROM invites WHERE expiry > ?1",
|
|
[now],
|
|
)?;
|
|
if waiting >= self.limits.invites {
|
|
return Err(Refused::Full);
|
|
}
|
|
let changed = conn.execute(
|
|
"INSERT OR IGNORE INTO invites (id, secret_hash, key_package, expiry) VALUES (?1, ?2, ?3, ?4)",
|
|
params![
|
|
&req.id.as_bytes()[..],
|
|
&req.secret_hash.as_bytes()[..],
|
|
req.key_package.bytes(),
|
|
expiry
|
|
],
|
|
)?;
|
|
if changed == 0 {
|
|
return Err(Refused::Exists);
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
/// Hands the KeyPackage out once and deletes the invite. Expired = not found.
|
|
pub fn claim_invite(
|
|
&self,
|
|
id: &InviteId,
|
|
secret: &Token,
|
|
now: i64,
|
|
) -> Result<ClaimedInvite, Refused> {
|
|
let mut conn = self.conn();
|
|
let tx = conn.transaction()?;
|
|
let row: Option<(Vec<u8>, Vec<u8>, i64)> = tx
|
|
.query_row(
|
|
"SELECT secret_hash, key_package, expiry FROM invites WHERE id = ?1",
|
|
[&id.as_bytes()[..]],
|
|
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
|
|
)
|
|
.optional()?;
|
|
let (stored, key_package, expiry) =
|
|
row.unwrap_or_else(|| (vec![0; 32], Vec::new(), i64::MIN));
|
|
let ok =
|
|
same_hash(&stored, &secret.hash()) & (now < expiry) & !stored.iter().all(|b| *b == 0);
|
|
if !ok {
|
|
return Err(Refused::NotFound);
|
|
}
|
|
tx.execute("DELETE FROM invites WHERE id = ?1", [&id.as_bytes()[..]])?;
|
|
tx.commit()?;
|
|
Ok(ClaimedInvite {
|
|
key_package: KeyPackageBytes::new(key_package).map_err(|_| Refused::Storage)?,
|
|
})
|
|
}
|
|
|
|
/// Deletes blobs older than 30 days and invites past their expiry.
|
|
pub fn purge(&self, now: i64) -> Result<Purged, Refused> {
|
|
let conn = self.conn();
|
|
// A blob that arrived in hour h is gone once h is more than 30 days before now's hour.
|
|
let oldest_kept = hour_of(now - BLOB_TTL_SECS);
|
|
let blobs = conn.execute("DELETE FROM blobs WHERE received_hour < ?1", [oldest_kept])?;
|
|
let invites = conn.execute("DELETE FROM invites WHERE expiry <= ?1", [now])?;
|
|
Ok(Purged { blobs, invites })
|
|
}
|
|
|
|
/// The live schema: (table, columns) for every table, in name order. For the §5 test.
|
|
pub fn live_schema(&self) -> Result<Vec<(String, Vec<String>)>, rusqlite::Error> {
|
|
let conn = self.conn();
|
|
let mut stmt =
|
|
conn.prepare("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name")?;
|
|
let tables: Vec<String> = stmt
|
|
.query_map([], |r| r.get(0))?
|
|
.collect::<Result<_, _>>()?;
|
|
let mut out = Vec::new();
|
|
for table in tables {
|
|
let mut cols = conn.prepare(&format!("PRAGMA table_info(\"{table}\")"))?;
|
|
let names: Vec<String> = cols
|
|
.query_map([], |r| r.get(1))?
|
|
.collect::<Result<_, _>>()?;
|
|
out.push((table, names));
|
|
}
|
|
Ok(out)
|
|
}
|
|
}
|
|
|
|
#[derive(Clone, Copy)]
|
|
enum Column {
|
|
Post,
|
|
Fetch,
|
|
}
|