[relay] F20: axum + SQLite relay storing exactly PROTOCOL.md section 5, tokens as hashes, no request log
This commit is contained in:
@@ -0,0 +1,162 @@
|
||||
//! The HTTP face of the store. No logging, no connection info: a handler never sees the client's
|
||||
//! address, and nothing here writes a request anywhere.
|
||||
|
||||
use crate::store::{Refused, Store};
|
||||
use axum::body::Bytes;
|
||||
use axum::extract::{DefaultBodyLimit, Path, State};
|
||||
use axum::http::{header, HeaderMap, StatusCode};
|
||||
use axum::response::{IntoResponse, Response};
|
||||
use axum::routing::{delete, get, post, put};
|
||||
use axum::{Json, Router};
|
||||
use serde::de::DeserializeOwned;
|
||||
use std::sync::Arc;
|
||||
use tabellarius_protocol::{
|
||||
CreateInvite, CreateMailbox, FetchedBlobs, InviteId, MailboxId, RotatePostToken, Sha256Hash,
|
||||
Token, VersionInfo, MAX_BLOB_BYTES, VERSION,
|
||||
};
|
||||
|
||||
/// Unix seconds. The server passes the system clock; tests pass their own.
|
||||
pub type Clock = Arc<dyn Fn() -> i64 + Send + Sync>;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct AppState {
|
||||
pub store: Arc<Store>,
|
||||
pub clock: Clock,
|
||||
}
|
||||
|
||||
/// JSON bodies are small: the largest is an invite with a 16 KiB KeyPackage in base64url.
|
||||
const MAX_JSON_BYTES: usize = 32 * 1024;
|
||||
|
||||
pub fn router(state: AppState) -> Router {
|
||||
let blob_routes = Router::new()
|
||||
.route("/v0/mailboxes/{id}/blobs", post(post_blob).get(fetch_blobs))
|
||||
.layer(DefaultBodyLimit::max(MAX_BLOB_BYTES));
|
||||
Router::new()
|
||||
.route("/v0/mailboxes", post(create_mailbox))
|
||||
.route("/v0/mailboxes/{id}/blobs/{hash}", delete(acknowledge))
|
||||
.route("/v0/mailboxes/{id}/post-token", put(rotate_post_token))
|
||||
.route("/v0/invites", post(create_invite))
|
||||
.route("/v0/invites/{id}", get(claim_invite))
|
||||
.route("/version", get(version))
|
||||
.layer(DefaultBodyLimit::max(MAX_JSON_BYTES))
|
||||
.merge(blob_routes)
|
||||
.with_state(state)
|
||||
}
|
||||
|
||||
/// Every refusal is a bare status code: no body that could echo the request back.
|
||||
struct Status(StatusCode);
|
||||
|
||||
impl IntoResponse for Status {
|
||||
fn into_response(self) -> Response {
|
||||
self.0.into_response()
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Refused> for Status {
|
||||
fn from(r: Refused) -> Self {
|
||||
Status(match r {
|
||||
Refused::NotFound => StatusCode::NOT_FOUND,
|
||||
Refused::Exists => StatusCode::CONFLICT,
|
||||
Refused::TooLarge => StatusCode::PAYLOAD_TOO_LARGE,
|
||||
Refused::Storage => StatusCode::INTERNAL_SERVER_ERROR,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Parses a JSON body with the protocol's strict types; any failure is a plain 400.
|
||||
fn json<T: DeserializeOwned>(body: &Bytes) -> Result<T, Status> {
|
||||
serde_json::from_slice(body).map_err(|_| Status(StatusCode::BAD_REQUEST))
|
||||
}
|
||||
|
||||
/// A malformed id in the path is treated like an unknown one.
|
||||
fn mailbox(id: &str) -> Result<MailboxId, Status> {
|
||||
MailboxId::parse(id).map_err(|_| Status(StatusCode::NOT_FOUND))
|
||||
}
|
||||
|
||||
/// A missing or malformed bearer token is treated like a wrong one.
|
||||
fn bearer(headers: &HeaderMap) -> Result<Token, Status> {
|
||||
headers
|
||||
.get(header::AUTHORIZATION)
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.and_then(|v| Token::from_bearer(v).ok())
|
||||
.ok_or(Status(StatusCode::NOT_FOUND))
|
||||
}
|
||||
|
||||
async fn create_mailbox(State(s): State<AppState>, body: Bytes) -> Result<StatusCode, Status> {
|
||||
let req: CreateMailbox = json(&body)?;
|
||||
s.store.create_mailbox(&req, (s.clock)())?;
|
||||
Ok(StatusCode::CREATED)
|
||||
}
|
||||
|
||||
async fn post_blob(
|
||||
State(s): State<AppState>,
|
||||
Path(id): Path<String>,
|
||||
headers: HeaderMap,
|
||||
body: Bytes,
|
||||
) -> Result<StatusCode, Status> {
|
||||
let id = mailbox(&id)?;
|
||||
let token = bearer(&headers)?;
|
||||
s.store.post(&id, &token, &body, (s.clock)())?;
|
||||
Ok(StatusCode::CREATED)
|
||||
}
|
||||
|
||||
async fn fetch_blobs(
|
||||
State(s): State<AppState>,
|
||||
Path(id): Path<String>,
|
||||
headers: HeaderMap,
|
||||
) -> Result<Json<FetchedBlobs>, Status> {
|
||||
let id = mailbox(&id)?;
|
||||
let token = bearer(&headers)?;
|
||||
let blobs = s.store.fetch(&id, &token)?;
|
||||
Ok(Json(FetchedBlobs { blobs }))
|
||||
}
|
||||
|
||||
async fn acknowledge(
|
||||
State(s): State<AppState>,
|
||||
Path((id, hash)): Path<(String, String)>,
|
||||
headers: HeaderMap,
|
||||
) -> Result<StatusCode, Status> {
|
||||
let id = mailbox(&id)?;
|
||||
let token = bearer(&headers)?;
|
||||
let hash = Sha256Hash::parse(&hash).map_err(|_| Status(StatusCode::NOT_FOUND))?;
|
||||
s.store.acknowledge(&id, &token, &hash)?;
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
async fn rotate_post_token(
|
||||
State(s): State<AppState>,
|
||||
Path(id): Path<String>,
|
||||
headers: HeaderMap,
|
||||
body: Bytes,
|
||||
) -> Result<StatusCode, Status> {
|
||||
let id = mailbox(&id)?;
|
||||
let token = bearer(&headers)?;
|
||||
let req: RotatePostToken = json(&body)?;
|
||||
s.store
|
||||
.rotate_post_token(&id, &token, &req.post_token_hash)?;
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
async fn create_invite(State(s): State<AppState>, body: Bytes) -> Result<StatusCode, Status> {
|
||||
let req: CreateInvite = json(&body)?;
|
||||
s.store.create_invite(&req, (s.clock)())?;
|
||||
Ok(StatusCode::CREATED)
|
||||
}
|
||||
|
||||
async fn claim_invite(
|
||||
State(s): State<AppState>,
|
||||
Path(id): Path<String>,
|
||||
headers: HeaderMap,
|
||||
) -> Result<Response, Status> {
|
||||
let id = InviteId::parse(&id).map_err(|_| Status(StatusCode::NOT_FOUND))?;
|
||||
let secret = bearer(&headers)?;
|
||||
let claimed = s.store.claim_invite(&id, &secret, (s.clock)())?;
|
||||
Ok(Json(claimed).into_response())
|
||||
}
|
||||
|
||||
async fn version() -> Json<VersionInfo> {
|
||||
Json(VersionInfo {
|
||||
protocol: VERSION.to_string(),
|
||||
relay: env!("CARGO_PKG_VERSION").to_string(),
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
//! The Tabellarius relay: holds ciphertext addressed to a mailbox until its owner fetches and
|
||||
//! acknowledges it. Stores exactly `docs/PROTOCOL.md` §5 and logs no request.
|
||||
|
||||
pub mod http;
|
||||
pub mod store;
|
||||
|
||||
use std::net::SocketAddr;
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// Loopback unless told otherwise: a relay reachable from outside is a deliberate choice (F23).
|
||||
pub const DEFAULT_LISTEN: &str = "127.0.0.1:8470";
|
||||
pub const DEFAULT_DB: &str = "tabellarius-relay.db";
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub struct Args {
|
||||
pub listen: SocketAddr,
|
||||
pub db: PathBuf,
|
||||
}
|
||||
|
||||
/// `--listen <addr:port>`, `--db <path>`. Anything else is refused with a usage line.
|
||||
pub fn parse_args<I: IntoIterator<Item = String>>(args: I) -> Result<Args, String> {
|
||||
let usage = "usage: tabellarius-relay [--listen 127.0.0.1:8470] [--db tabellarius-relay.db]";
|
||||
let mut listen: SocketAddr = DEFAULT_LISTEN.parse().map_err(|_| usage.to_string())?;
|
||||
let mut db = PathBuf::from(DEFAULT_DB);
|
||||
let mut it = args.into_iter();
|
||||
while let Some(arg) = it.next() {
|
||||
match arg.as_str() {
|
||||
"--listen" => {
|
||||
listen = it
|
||||
.next()
|
||||
.and_then(|v| v.parse().ok())
|
||||
.ok_or_else(|| usage.to_string())?;
|
||||
}
|
||||
"--db" => {
|
||||
db = it
|
||||
.next()
|
||||
.map(PathBuf::from)
|
||||
.ok_or_else(|| usage.to_string())?
|
||||
}
|
||||
_ => return Err(usage.to_string()),
|
||||
}
|
||||
}
|
||||
Ok(Args { listen, db })
|
||||
}
|
||||
@@ -1,10 +1,77 @@
|
||||
//! Placeholder: prints its version and exits. Opens no socket, stores nothing.
|
||||
//! It exists so the reproducible build has an artefact to hash. The relay itself is written only
|
||||
//! after the protocol review is approved.
|
||||
//! `tabellarius-relay [--listen 127.0.0.1:8470] [--db tabellarius-relay.db]`
|
||||
//!
|
||||
//! Prints one line at start (version and address) and nothing per request.
|
||||
|
||||
fn main() {
|
||||
println!(
|
||||
"tabellarius-relay {} (no relay yet: protocol under review)",
|
||||
env!("CARGO_PKG_VERSION")
|
||||
);
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||
use tabellarius_relay::http::{router, AppState, Clock};
|
||||
use tabellarius_relay::parse_args;
|
||||
use tabellarius_relay::store::Store;
|
||||
|
||||
fn now() -> i64 {
|
||||
SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map(|d| d.as_secs() as i64)
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
let args = match parse_args(std::env::args().skip(1)) {
|
||||
Ok(a) => a,
|
||||
Err(usage) => {
|
||||
eprintln!("{usage}");
|
||||
std::process::exit(2);
|
||||
}
|
||||
};
|
||||
let store = match Store::open(&args.db) {
|
||||
Ok(s) => Arc::new(s),
|
||||
Err(_) => {
|
||||
eprintln!(
|
||||
"tabellarius-relay: cannot open the database {}",
|
||||
args.db.display()
|
||||
);
|
||||
std::process::exit(1);
|
||||
}
|
||||
};
|
||||
let listener = match tokio::net::TcpListener::bind(args.listen).await {
|
||||
Ok(l) => l,
|
||||
Err(_) => {
|
||||
eprintln!("tabellarius-relay: cannot listen on {}", args.listen);
|
||||
std::process::exit(1);
|
||||
}
|
||||
};
|
||||
let bound = listener
|
||||
.local_addr()
|
||||
.map(|a| a.to_string())
|
||||
.unwrap_or_default();
|
||||
println!(
|
||||
"tabellarius-relay {} protocol {} listening on {bound}",
|
||||
env!("CARGO_PKG_VERSION"),
|
||||
tabellarius_protocol::VERSION
|
||||
);
|
||||
|
||||
// Purge at start and every hour: blobs after 30 days, invites after their expiry.
|
||||
let purger = Arc::clone(&store);
|
||||
tokio::spawn(async move {
|
||||
let mut every_hour = tokio::time::interval(Duration::from_secs(3600));
|
||||
loop {
|
||||
every_hour.tick().await;
|
||||
let _ = purger.purge(now());
|
||||
}
|
||||
});
|
||||
|
||||
let clock: Clock = Arc::new(now);
|
||||
let app = router(AppState { store, clock });
|
||||
let shutdown = async {
|
||||
let _ = tokio::signal::ctrl_c().await;
|
||||
};
|
||||
if axum::serve(listener, app)
|
||||
.with_graceful_shutdown(shutdown)
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
eprintln!("tabellarius-relay: the server stopped with an error");
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,313 @@
|
||||
//! 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,
|
||||
}
|
||||
|
||||
impl From<rusqlite::Error> for Refused {
|
||||
fn from(_: rusqlite::Error) -> Self {
|
||||
Refused::Storage
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Store {
|
||||
conn: Mutex<Connection>,
|
||||
}
|
||||
|
||||
/// 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)?)
|
||||
}
|
||||
|
||||
pub fn open_in_memory() -> Result<Self, rusqlite::Error> {
|
||||
Self::init(Connection::open_in_memory()?)
|
||||
}
|
||||
|
||||
fn init(conn: Connection) -> 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),
|
||||
})
|
||||
}
|
||||
|
||||
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 changed = self.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)?;
|
||||
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 changed = self.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,
|
||||
}
|
||||
Reference in New Issue
Block a user