3a0944ebff
ci / check (pull_request) Has been cancelled
The relay stores files (id, upload and fetch token hashes, chunk count, uploaded hour) and chunks (file id, index, ciphertext): every chunk is 256 000 bytes, so it learns the size rounded up to 250 KiB and nothing finer, and it keeps no fetch count. Only the uploader's token puts or deletes, only the fetch token gets, a chunk never changes; per-file and relay-wide quotas answer 507; files go after 30 days, incomplete ones after 24 hours. The client pads a file to whole chunks and seals each with ChaCha20-Poly1305 in the aead crate's STREAM, under a key made for that file; the key, name, type, size and thumbnail travel only in the new `file` payload, which shares `seq` with text. Also: every route now answers a bare 413 (axum's own carried a text). PROTOCOL.md §1, §4, §5, §7, §8.
421 lines
15 KiB
Rust
421 lines
15 KiB
Rust
//! Two clients through the real relay over loopback TCP, then a byte search of the relay's
|
|
//! database file: the canary in a message, and both names, must not be in it (`PROTOCOL.md` §7).
|
|
//! The relay is a dev-dependency only; the client library never depends on it.
|
|
|
|
use std::io::{Read, Write};
|
|
use std::net::{SocketAddr, TcpStream};
|
|
use std::sync::Arc;
|
|
use tabellarius_client::*;
|
|
use tabellarius_protocol::*;
|
|
use tabellarius_relay::http::{router, AppState, Clock};
|
|
use tabellarius_relay::store::Store;
|
|
|
|
/// A deliberately small blocking HTTP/1.1 transport for the test: one connection per request.
|
|
#[derive(Clone)]
|
|
struct Http(SocketAddr);
|
|
|
|
impl Http {
|
|
fn call(
|
|
&self,
|
|
method: &str,
|
|
path: &str,
|
|
auth: Option<&Token>,
|
|
body: &[u8],
|
|
json: bool,
|
|
) -> Result<Vec<u8>, TransportError> {
|
|
let mut s = TcpStream::connect(self.0).map_err(|_| TransportError::Failed)?;
|
|
let auth = auth
|
|
.map(|t| format!("Authorization: {}\r\n", t.to_bearer()))
|
|
.unwrap_or_default();
|
|
let ctype = if json {
|
|
"Content-Type: application/json\r\n"
|
|
} else {
|
|
""
|
|
};
|
|
let head = format!(
|
|
"{method} {path} HTTP/1.1\r\nHost: relay\r\n{auth}{ctype}Content-Length: {}\r\nConnection: close\r\n\r\n",
|
|
body.len()
|
|
);
|
|
s.write_all(head.as_bytes())
|
|
.map_err(|_| TransportError::Failed)?;
|
|
s.write_all(body).map_err(|_| TransportError::Failed)?;
|
|
let mut resp = Vec::new();
|
|
s.read_to_end(&mut resp)
|
|
.map_err(|_| TransportError::Failed)?;
|
|
let split = resp
|
|
.windows(4)
|
|
.position(|w| w == b"\r\n\r\n")
|
|
.ok_or(TransportError::Failed)?;
|
|
let status = std::str::from_utf8(&resp[9..12]).map_err(|_| TransportError::Failed)?;
|
|
match status {
|
|
"200" | "201" | "204" => Ok(resp[split + 4..].to_vec()),
|
|
"404" => Err(TransportError::NotFound),
|
|
"409" => Err(TransportError::Conflict),
|
|
"507" => Err(TransportError::Full),
|
|
_ => Err(TransportError::Failed),
|
|
}
|
|
}
|
|
}
|
|
|
|
impl Transport for Http {
|
|
fn create_mailbox(&self, req: &CreateMailbox) -> Result<(), TransportError> {
|
|
let body = serde_json::to_vec(req).map_err(|_| TransportError::Failed)?;
|
|
self.call("POST", "/v0/mailboxes", None, &body, true)
|
|
.map(|_| ())
|
|
}
|
|
fn post(&self, id: &MailboxId, post: &Token, blob: &[u8]) -> Result<(), TransportError> {
|
|
self.call(
|
|
"POST",
|
|
&format!("/v0/mailboxes/{}/blobs", id.to_wire()),
|
|
Some(post),
|
|
blob,
|
|
false,
|
|
)
|
|
.map(|_| ())
|
|
}
|
|
fn fetch(&self, id: &MailboxId, fetch: &Token) -> Result<Vec<Vec<u8>>, TransportError> {
|
|
let body = self.call(
|
|
"GET",
|
|
&format!("/v0/mailboxes/{}/blobs", id.to_wire()),
|
|
Some(fetch),
|
|
&[],
|
|
false,
|
|
)?;
|
|
let blobs: FetchedBlobs =
|
|
serde_json::from_slice(&body).map_err(|_| TransportError::Failed)?;
|
|
Ok(blobs
|
|
.blobs
|
|
.into_iter()
|
|
.map(|b| b.blob.bytes().to_vec())
|
|
.collect())
|
|
}
|
|
fn acknowledge(
|
|
&self,
|
|
id: &MailboxId,
|
|
fetch: &Token,
|
|
hash: &Sha256Hash,
|
|
) -> Result<(), TransportError> {
|
|
let path = format!("/v0/mailboxes/{}/blobs/{}", id.to_wire(), hash.to_wire());
|
|
self.call("DELETE", &path, Some(fetch), &[], false)
|
|
.map(|_| ())
|
|
}
|
|
fn rotate_post_token(
|
|
&self,
|
|
id: &MailboxId,
|
|
fetch: &Token,
|
|
new_hash: &Sha256Hash,
|
|
) -> Result<(), TransportError> {
|
|
let body = serde_json::to_vec(&RotatePostToken {
|
|
post_token_hash: *new_hash,
|
|
})
|
|
.map_err(|_| TransportError::Failed)?;
|
|
let path = format!("/v0/mailboxes/{}/post-token", id.to_wire());
|
|
self.call("PUT", &path, Some(fetch), &body, true)
|
|
.map(|_| ())
|
|
}
|
|
fn create_invite(&self, req: &CreateInvite) -> Result<(), TransportError> {
|
|
let body = serde_json::to_vec(req).map_err(|_| TransportError::Failed)?;
|
|
self.call("POST", "/v0/invites", None, &body, true)
|
|
.map(|_| ())
|
|
}
|
|
fn claim_invite(&self, id: &InviteId, secret: &Token) -> Result<Vec<u8>, TransportError> {
|
|
let body = self.call(
|
|
"GET",
|
|
&format!("/v0/invites/{}", id.to_wire()),
|
|
Some(secret),
|
|
&[],
|
|
false,
|
|
)?;
|
|
let claimed: ClaimedInvite =
|
|
serde_json::from_slice(&body).map_err(|_| TransportError::Failed)?;
|
|
Ok(claimed.key_package.bytes().to_vec())
|
|
}
|
|
fn set_push(
|
|
&self,
|
|
id: &MailboxId,
|
|
fetch: &Token,
|
|
endpoint: Option<&PushEndpoint>,
|
|
) -> Result<(), TransportError> {
|
|
let path = format!("/v0/mailboxes/{}/push", id.to_wire());
|
|
match endpoint {
|
|
Some(e) => {
|
|
let body = serde_json::to_vec(&SetPush {
|
|
endpoint: e.clone(),
|
|
})
|
|
.map_err(|_| TransportError::Failed)?;
|
|
self.call("PUT", &path, Some(fetch), &body, true)
|
|
}
|
|
None => self.call("DELETE", &path, Some(fetch), &[], false),
|
|
}
|
|
.map(|_| ())
|
|
}
|
|
fn create_file(&self, req: &CreateFile) -> Result<(), TransportError> {
|
|
let body = serde_json::to_vec(req).map_err(|_| TransportError::Failed)?;
|
|
self.call("POST", "/v0/files", None, &body, true)
|
|
.map(|_| ())
|
|
}
|
|
fn put_chunk(
|
|
&self,
|
|
id: &FileId,
|
|
upload: &Token,
|
|
index: u32,
|
|
chunk: &[u8],
|
|
) -> Result<(), TransportError> {
|
|
let path = format!("/v0/files/{}/chunks/{index}", id.to_wire());
|
|
self.call("PUT", &path, Some(upload), chunk, false)
|
|
.map(|_| ())
|
|
}
|
|
fn get_chunk(&self, id: &FileId, fetch: &Token, index: u32) -> Result<Vec<u8>, TransportError> {
|
|
let path = format!("/v0/files/{}/chunks/{index}", id.to_wire());
|
|
self.call("GET", &path, Some(fetch), &[], false)
|
|
}
|
|
fn delete_file(&self, id: &FileId, upload: &Token) -> Result<(), TransportError> {
|
|
let path = format!("/v0/files/{}", id.to_wire());
|
|
self.call("DELETE", &path, Some(upload), &[], false)
|
|
.map(|_| ())
|
|
}
|
|
}
|
|
|
|
/// Starts the real relay on 127.0.0.1:<free port> with its database in `db`.
|
|
fn start_relay(db: &std::path::Path) -> SocketAddr {
|
|
let store = Arc::new(Store::open(db).expect("store"));
|
|
let clock: Clock = Arc::new(|| 1_794_000_000);
|
|
let app = router(AppState::new(store, clock));
|
|
let (tx, rx) = std::sync::mpsc::channel();
|
|
std::thread::spawn(move || {
|
|
let rt = tokio::runtime::Builder::new_current_thread()
|
|
.enable_all()
|
|
.build()
|
|
.expect("runtime");
|
|
rt.block_on(async move {
|
|
let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
|
|
.await
|
|
.expect("bind");
|
|
tx.send(listener.local_addr().expect("addr"))
|
|
.expect("send addr");
|
|
let _ = axum::serve(listener, app).await;
|
|
});
|
|
});
|
|
rx.recv().expect("relay address")
|
|
}
|
|
|
|
fn contains(haystack: &[u8], needle: &[u8]) -> bool {
|
|
!needle.is_empty() && haystack.windows(needle.len()).any(|w| w == needle)
|
|
}
|
|
|
|
#[test]
|
|
fn pair_and_talk_through_a_real_relay_which_never_sees_a_name_or_a_word() {
|
|
let dir = tempfile::tempdir().expect("tempdir");
|
|
let db = dir.path().join("relay.db");
|
|
let relay = Http(start_relay(&db));
|
|
|
|
let mut eva = Client::new("Eva Nováková", relay.clone()).expect("eva");
|
|
let mut jan = Client::new("Jan Dvořák", relay.clone()).expect("jan");
|
|
eva.set_receipts(false);
|
|
jan.set_receipts(false);
|
|
let invite = eva.create_invite().expect("invite");
|
|
// While the invite waits, the relay holds Eva's KeyPackage: it must not carry her name.
|
|
let invited = std::fs::read(&db).expect("db");
|
|
let jan_side = jan.accept_invite(&invite).expect("accept");
|
|
let events = eva.poll().expect("poll");
|
|
let Some(Event::Joined {
|
|
contact: eva_side,
|
|
name,
|
|
..
|
|
}) = events.first().cloned()
|
|
else {
|
|
panic!("no join: {events:?}");
|
|
};
|
|
assert_eq!(name, "Jan Dvořák");
|
|
assert_eq!(jan.poll().expect("poll").len(), 1);
|
|
|
|
let canary = "CANARY-relay-test-4b2e-never-in-the-database";
|
|
eva.send(eva_side, canary).expect("send");
|
|
jan.send(jan_side, &format!("re: {canary}")).expect("send");
|
|
// A reaction (F27) waits with them: its emoji must not be readable either.
|
|
let emoji = "🦜CANARY🦜";
|
|
let mine = MessageRef {
|
|
author: jan.author(),
|
|
seq: 1,
|
|
};
|
|
let out = jan.react(jan_side, mine, Some(emoji)).expect("react");
|
|
jan.deliver(&out).expect("deliver");
|
|
// And a poll (F28): its question and options neither.
|
|
let question = "POLL-QUESTION-CANARY";
|
|
let options = vec!["OPTION-CANARY-A".to_string(), "OPTION-CANARY-B".to_string()];
|
|
let out = jan
|
|
.compose_poll(jan_side, question, &options, false)
|
|
.expect("poll");
|
|
jan.deliver(&out).expect("deliver");
|
|
|
|
// Snapshot the database while both messages wait, before anyone fetches.
|
|
let waiting = std::fs::read(&db).expect("db");
|
|
assert_eq!(
|
|
jan.poll().expect("poll"),
|
|
vec![Event::Message {
|
|
contact: jan_side,
|
|
text: canary.into(),
|
|
seq: 1,
|
|
reply_to: None,
|
|
}]
|
|
);
|
|
assert_eq!(
|
|
eva.poll().expect("poll"),
|
|
vec![
|
|
Event::Message {
|
|
contact: eva_side,
|
|
text: format!("re: {canary}"),
|
|
seq: 1,
|
|
reply_to: None,
|
|
},
|
|
Event::Reaction {
|
|
contact: eva_side,
|
|
to: mine,
|
|
emoji: Some(emoji.into()),
|
|
},
|
|
Event::Poll {
|
|
contact: eva_side,
|
|
seq: 2,
|
|
question: question.into(),
|
|
options: options.clone(),
|
|
multiple: false,
|
|
},
|
|
]
|
|
);
|
|
let after = std::fs::read(&db).expect("db");
|
|
|
|
for snapshot in [&invited, &waiting, &after] {
|
|
for (what, needle) in [
|
|
("canary", canary.as_bytes()),
|
|
("reaction", emoji.as_bytes()),
|
|
("poll question", question.as_bytes()),
|
|
("poll option", options[0].as_bytes()),
|
|
("poll option", options[1].as_bytes()),
|
|
("inviter's name", "Eva Nováková".as_bytes()),
|
|
("invitee's name", "Jan Dvořák".as_bytes()),
|
|
("invite secret", invite.secret.as_bytes().as_slice()),
|
|
] {
|
|
assert!(
|
|
!contains(snapshot, needle),
|
|
"{what} is readable in the relay's database"
|
|
);
|
|
}
|
|
}
|
|
// The messages were there, as ciphertext: the database grew while they waited.
|
|
assert!(waiting.len() >= 4096, "the relay stored something");
|
|
}
|
|
|
|
/// Files (`.agents/features/files.md` §5): a photo through the real relay. Its name, type,
|
|
/// thumbnail and content are in no byte of the relay's database, before or after the download, and
|
|
/// every chunk the relay holds is the same size.
|
|
#[test]
|
|
fn a_file_goes_through_the_real_relay_which_never_sees_its_name_type_or_content() {
|
|
let dir = tempfile::tempdir().expect("tempdir");
|
|
let db = dir.path().join("relay.db");
|
|
let relay = Http(start_relay(&db));
|
|
let mut eva = Client::new("Eva", relay.clone()).expect("eva");
|
|
let mut jan = Client::new("Jan", relay.clone()).expect("jan");
|
|
eva.set_receipts(false);
|
|
jan.set_receipts(false);
|
|
let invite = eva.create_invite().expect("invite");
|
|
let jan_side = jan.accept_invite(&invite).expect("accept");
|
|
eva.poll().expect("poll");
|
|
jan.poll().expect("poll");
|
|
|
|
// Two chunks and a bit, every one of them full of canaries, so any plaintext would be found.
|
|
let line = b"FILE-CONTENT-CANARY-7f3a ";
|
|
let content: Vec<u8> = line
|
|
.iter()
|
|
.copied()
|
|
.cycle()
|
|
.take(2 * FILE_CHUNK_PLAIN + 999)
|
|
.collect();
|
|
let name = "FILENAME-CANARY-Menu.jpg";
|
|
let mime = "image/x-mime-canary";
|
|
let mut thumb = vec![0xFF, 0xD8, 0xFF, 0xE0];
|
|
thumb.extend_from_slice(b"THUMBNAIL-CANARY");
|
|
let up = jan.start_upload(content.len() as u64).expect("start");
|
|
jan.upload(&up, &content).expect("upload");
|
|
let out = jan
|
|
.compose_file(jan_side, &up, name, mime, Some(&thumb))
|
|
.expect("compose");
|
|
jan.deliver(&out).expect("deliver");
|
|
let waiting = std::fs::read(&db).expect("db");
|
|
|
|
let events = eva.poll().expect("poll");
|
|
let Some(Event::File {
|
|
file,
|
|
name: got_name,
|
|
mime: got_mime,
|
|
thumb: got_thumb,
|
|
seq,
|
|
..
|
|
}) = events.first().cloned()
|
|
else {
|
|
panic!("no file: {events:?}");
|
|
};
|
|
assert_eq!((got_name.as_str(), got_mime.as_str(), seq), (name, mime, 1));
|
|
assert_eq!(got_thumb.as_deref(), Some(thumb.as_slice()));
|
|
assert_eq!(file.chunks(), 3);
|
|
assert_eq!(eva.download(&file).expect("download"), content);
|
|
let after = std::fs::read(&db).expect("db");
|
|
|
|
for snapshot in [&waiting, &after] {
|
|
for (what, needle) in [
|
|
("file content", &line[..]),
|
|
("file name", name.as_bytes()),
|
|
("media type", mime.as_bytes()),
|
|
("thumbnail", b"THUMBNAIL-CANARY".as_slice()),
|
|
] {
|
|
assert!(
|
|
!contains(snapshot, needle),
|
|
"{what} is readable in the relay's database"
|
|
);
|
|
}
|
|
}
|
|
assert!(
|
|
waiting.len() >= 3 * FILE_CHUNK_BYTES,
|
|
"the three chunks were stored"
|
|
);
|
|
// The sender deletes it early; the relay answers 404 from then on.
|
|
jan.delete_file(&up).expect("delete");
|
|
assert_eq!(
|
|
eva.get_chunk(&file, 0),
|
|
Err(ClientError::Transport(TransportError::NotFound))
|
|
);
|
|
}
|
|
|
|
// Wake-up (`.agents/features/wake-up.md` §2.4): an endpoint per mailbox, set and cleared through the
|
|
// real relay with the mailbox's fetch token.
|
|
#[test]
|
|
fn each_inbox_takes_its_own_push_endpoint_through_the_real_relay() {
|
|
let dir = tempfile::tempdir().expect("tempdir");
|
|
let db = dir.path().join("relay.db");
|
|
let relay = Http(start_relay(&db));
|
|
let mut eva = Client::new("Eva", relay.clone()).expect("eva");
|
|
let mut jan = Client::new("Jan", relay.clone()).expect("jan");
|
|
let invite = eva.create_invite().expect("invite");
|
|
jan.accept_invite(&invite).expect("accept");
|
|
eva.poll().expect("poll");
|
|
let (eva_boxes, jan_boxes) = (eva.inboxes(), jan.inboxes());
|
|
assert_eq!((eva_boxes.len(), jan_boxes.len()), (1, 1));
|
|
let endpoint = |path: &str| PushEndpoint::parse(&format!("https://push.invalid/{path}"));
|
|
let a = endpoint("upEvaOnly1").expect("endpoint");
|
|
eva.set_push(&eva_boxes[0], Some(&a)).expect("set");
|
|
jan.set_push(
|
|
&jan_boxes[0],
|
|
Some(&endpoint("upJanOnly2").expect("endpoint")),
|
|
)
|
|
.expect("set");
|
|
let stored = std::fs::read(&db).expect("db");
|
|
assert!(contains(&stored, b"upEvaOnly1") && contains(&stored, b"upJanOnly2"));
|
|
// Not Jan's mailbox: Eva cannot set it.
|
|
assert_eq!(
|
|
eva.set_push(&jan_boxes[0], Some(&a)),
|
|
Err(ClientError::UnknownContact)
|
|
);
|
|
eva.set_push(&eva_boxes[0], None).expect("clear");
|
|
// Nothing is posted after this: a post would make the relay try to wake `push.invalid`, and no
|
|
// test reaches for the network.
|
|
}
|