Skip to main content

cosmic_applet_avestruz/nostr/
blossom.rs

1// SPDX-License-Identifier: MIT
2
3//! Media servers (Blossom): the account's list of them, and sending a
4//! file to them so that a note can link to it.
5//!
6//! A media server keeps files by what they are: each is known by the
7//! SHA-256 of its bytes, and is at that address on every server that has
8//! it. So a file that is on several servers is still to be found when one
9//! of them is gone, by anyone who knows where else its owner keeps files:
10//! which is what the account's server list says (BUD-03, kind 10063), one
11//! `server` tag for each, the one to try first at the top.
12//!
13//! A file is sent to the first server of the list that takes it (BUD-02),
14//! and the others are then asked to fetch it from there (BUD-04), so that
15//! it is on all of them:
16//!
17//! ```mermaid
18//! sequenceDiagram
19//!     participant A as Avestruz
20//!     participant F as The first server
21//!     participant O as Each other server
22//!     Note over A: The file is hashed, and an authorization signed for that hash
23//!     A->>F: HEAD /upload: would you take this? Its hash, size and type
24//!     F-->>A: Yes. Or no, and why: the next server is tried
25//!     A->>F: PUT /upload: the file
26//!     F-->>A: Where it is now: its address, hash, size and type
27//!     A->>O: PUT /mirror: fetch it from that address
28//!     O-->>A: Done, or not: the file is attached either way
29//! ```
30//!
31//! Every request carries the same authorization (BUD-11): an event of
32//! kind 24242 that the account signs, which says what may be done
33//! (`t`: `upload`), to which file (`x`: its hash) and until when
34//! (`expiration`). It goes in the `Authorization` header, as base64. The
35//! specification says base64 for addresses, without padding; servers
36//! written before it said so read only the plain kind, padded, and answer
37//! the other with 400 or 401. Such an answer has the request made once
38//! more, the other way.
39//!
40//! The server is asked first whether it would take the file (BUD-06),
41//! which costs nothing; a server that says no is not sent the file to say
42//! no again, and one that doesn't know the question is sent it.
43//!
44//! What the note then carries is the file's address, in its text, and an
45//! `imeta` tag (NIP-92) that says of that address what whoever shows the
46//! note would otherwise have to fetch the file to know: what kind of file
47//! it is, how large, its hash, and for a picture its width and height.
48//!
49//! No server is built in, and no list is written that the account did not
50//! ask for: where its files go is for the account to say.
51
52use std::sync::Arc;
53use std::sync::atomic::{AtomicUsize, Ordering};
54use std::time::Duration;
55
56use base64::Engine;
57use base64::engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD};
58use futures_util::StreamExt;
59use futures_util::future::join_all;
60use nostr_sdk::prelude::{Event, EventBuilder, Kind, Tag, Timestamp, Url};
61use reqwest::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE};
62use reqwest::{Method, Response, StatusCode};
63use serde::Deserialize;
64use sha2::{Digest, Sha256};
65
66use crate::media::Media;
67
68/// The name of the tag that names a media server in a server list
69/// (BUD-03).
70const SERVER_TAG: &str = "server";
71
72/// The name of the tag that says of a link in a note what is at it
73/// (NIP-92).
74const IMETA_TAG: &str = "imeta";
75
76/// How long an authorization holds: long enough for a large file on a slow
77/// line, and not much use to whoever comes by it later.
78const AUTH_SECONDS: u64 = 60 * 60;
79
80/// How long a server gets to take a file, and how long to fetch one from
81/// another server.
82const UPLOAD_TIMEOUT: Duration = Duration::from_secs(AUTH_SECONDS);
83const MIRROR_TIMEOUT: Duration = Duration::from_secs(120);
84
85/// How much of a file is handed over at a time: how finely it is known
86/// how much of it has gone.
87const PIECE: usize = 64 * 1024;
88
89/// How much is read of what a server answers: where the file is, or why
90/// it was not taken.
91const MAX_ANSWER: usize = 64 * 1024;
92
93/// How much of a server's reason is shown, in characters.
94const MAX_REASON: usize = 300;
95
96/// What a server answers a question it doesn't know with, where the
97/// question is whether it would take a file (BUD-06): the file is sent
98/// without asking.
99const NOT_ASKED_THAT: [StatusCode; 3] = [StatusCode::NOT_FOUND, StatusCode::METHOD_NOT_ALLOWED, StatusCode::NOT_IMPLEMENTED];
100
101/// What a server that doesn't read the authorization as it was written
102/// answers with: it is written the other way and sent once more.
103const NOT_READ: [StatusCode; 2] = [StatusCode::BAD_REQUEST, StatusCode::UNAUTHORIZED];
104
105/// How much of a file has been handed over to be sent, in bytes: counted
106/// by what sends it, and read by what shows how far it has got.
107pub type Sent = Arc<AtomicUsize>;
108
109/// The media server typed as `typed`, with or without `https://`. `None`
110/// if it is no address, or not an `https` one: nothing else is sent to.
111/// A server is where its endpoints are, which is at the root of its
112/// domain (BUD-01), so whatever path was typed after it is not part of it.
113pub fn typed_server(typed: &str) -> Option<Url> {
114    let typed = typed.trim();
115    if typed.is_empty() || typed.contains(char::is_whitespace) {
116        return None;
117    }
118    let url = if typed.contains("://") { Url::parse(typed) } else { Url::parse(&format!("https://{typed}")) }.ok()?;
119    server_of(&url)
120}
121
122/// The server that `url` is the address of, or is an address on.
123fn server_of(url: &Url) -> Option<Url> {
124    if url.scheme() != "https" || url.host_str().is_none_or(|host| !host.contains('.')) {
125        return None;
126    }
127    Url::parse(&url.origin().ascii_serialization()).ok()
128}
129
130/// What a server is called on a page: its address without the scheme.
131pub fn server_name(server: &Url) -> String {
132    let name = server.as_str().trim_end_matches('/');
133    name.strip_prefix("https://").unwrap_or(name).to_string()
134}
135
136/// The address of `path` on `server`.
137fn endpoint(server: &Url, path: &str) -> String {
138    format!("{}/{path}", server.origin().ascii_serialization())
139}
140
141/// Whether `tag` names a media server.
142fn names_server(tag: &Tag) -> bool {
143    tag.as_slice().first().is_some_and(|name| name == SERVER_TAG)
144}
145
146/// The media servers the server list `list` names, in its order, each
147/// once. None with no list.
148pub fn servers(list: Option<&Event>) -> Vec<Url> {
149    let mut servers = Vec::new();
150    let named = list.into_iter().flat_map(|list| list.tags.iter()).filter(|tag| names_server(tag));
151    for server in named.filter_map(|tag| Url::parse(tag.as_slice().get(1)?).ok()).filter_map(|url| server_of(&url)) {
152        if !servers.contains(&server) {
153            servers.push(server);
154        }
155    }
156    servers
157}
158
159/// The server list (BUD-03) that replaces `earlier`, if there is one to
160/// replace: with `servers` for its servers, in that order, and whatever
161/// else `earlier` had in it as it was.
162///
163/// `None` when `earlier` names the same servers in the same order: there
164/// is nothing to write.
165pub fn server_list(earlier: Option<&Event>, servers_now: &[Url], now: Timestamp) -> Option<EventBuilder> {
166    if earlier.is_some() && servers(earlier) == servers_now {
167        return None;
168    }
169    let kept = earlier.into_iter().flat_map(|earlier| earlier.tags.iter()).filter(|tag| !names_server(tag)).cloned();
170    let named = servers_now.iter().filter_map(|server| Tag::parse([SERVER_TAG, server.as_str().trim_end_matches('/')]).ok());
171    let tags: Vec<Tag> = named.chain(kept).collect();
172    let content = earlier.map(|earlier| earlier.content.clone()).unwrap_or_default();
173    // Claimed to be from after the one it replaces: it has to be the newer.
174    let after = earlier.map_or(now, |earlier| now.max(Timestamp::from_secs(earlier.created_at.as_secs() + 1)));
175    Some(EventBuilder::new(Kind::BlossomServerList, content).tags(tags).custom_created_at(after))
176}
177
178/// What a file is known by on a media server: the SHA-256 of `bytes`, in
179/// lowercase hex.
180pub fn hash_of(bytes: &[u8]) -> String {
181    Sha256::digest(bytes).iter().map(|byte| format!("{byte:02x}")).collect()
182}
183
184/// The authorization (BUD-11) to send the file called `name`, whose hash
185/// is `hash`, to media servers, from `now` for [`AUTH_SECONDS`]: for the
186/// account to sign.
187pub fn upload_auth(name: &str, hash: &str, now: Timestamp) -> EventBuilder {
188    let tags = [Tag::parse(["t", "upload"]).ok(), Tag::parse(["x", hash]).ok(), Some(Tag::expiration(now + AUTH_SECONDS))];
189    EventBuilder::new(Kind::BlossomAuth, format!("Upload {name}")).tags(tags.into_iter().flatten()).custom_created_at(now)
190}
191
192/// What the `Authorization` header says for the authorization `auth`:
193/// the event as base64, for addresses and unpadded as the specification
194/// has it, or plain and `padded` as servers older than that read it.
195fn authorization(auth: &Event, padded: bool) -> String {
196    let json = auth.as_json();
197    let encoded = if padded { STANDARD.encode(json) } else { URL_SAFE_NO_PAD.encode(json) };
198    format!("Nostr {encoded}")
199}
200
201/// Why a server did not take a file, or did not fetch it.
202#[derive(Debug, Clone, PartialEq, Eq)]
203pub enum UploadError {
204    /// It could not be reached, or the line broke.
205    Unreachable(String),
206    /// It said no: with this status, and for this reason, if it gave one.
207    Refused { status: u16, reason: String },
208    /// It said yes, and what it said of where the file is could not be
209    /// read.
210    Unreadable(String),
211}
212
213/// A file as a server says it has it (BUD-02).
214#[derive(Debug, Clone, PartialEq, Eq)]
215pub struct Blob {
216    /// Where it is.
217    pub url: String,
218    /// The hash of what is there.
219    pub hash: String,
220}
221
222/// What a server answers when it has taken a file: a blob descriptor.
223#[derive(Deserialize)]
224struct Descriptor {
225    url: String,
226    sha256: Option<String>,
227}
228
229/// What `response` says, as far as [`MAX_ANSWER`].
230async fn answer(mut response: Response) -> Vec<u8> {
231    let mut bytes = Vec::new();
232    while let Ok(Some(chunk)) = response.chunk().await {
233        let room = MAX_ANSWER.saturating_sub(bytes.len());
234        bytes.extend_from_slice(chunk.get(..chunk.len().min(room)).unwrap_or_default());
235        if bytes.len() >= MAX_ANSWER {
236            break;
237        }
238    }
239    bytes
240}
241
242/// Why `response`, which is no success, says the request was refused: the
243/// reason the server gives in its `X-Reason` header, or failing that in
244/// what it answers, or failing that what the status means.
245async fn refusal(response: Response) -> UploadError {
246    let status = response.status();
247    let header = response.headers().get("x-reason").and_then(|reason| reason.to_str().ok()).map(str::to_string);
248    let reason = match header.filter(|reason| !reason.trim().is_empty()) {
249        Some(reason) => reason,
250        None => {
251            let said = String::from_utf8_lossy(&answer(response).await).trim().to_string();
252            let message = serde_json::from_str::<serde_json::Value>(&said)
253                .ok()
254                .and_then(|json| json.get("message").and_then(|message| message.as_str().map(str::to_string)));
255            // A page of HTML is no reason.
256            message.or_else(|| (!said.is_empty() && !said.starts_with('<')).then_some(said)).unwrap_or_default()
257        }
258    };
259    let reason = if reason.trim().is_empty() { status.canonical_reason().unwrap_or_default().to_string() } else { reason };
260    UploadError::Refused { status: status.as_u16(), reason: reason.trim().chars().take(MAX_REASON).collect() }
261}
262
263/// Why `error` came about, down to what was behind it: a request that
264/// failed says no more of itself than that it did.
265fn why(error: &dyn std::error::Error) -> String {
266    let mut said = error.to_string();
267    let mut behind = error.source();
268    while let Some(cause) = behind {
269        let cause_said = cause.to_string();
270        if !said.contains(&cause_said) {
271            said = format!("{said}: {cause_said}");
272        }
273        behind = cause.source();
274    }
275    said
276}
277
278/// Requests to one server, each with the authorization: written as the
279/// specification has it until the server doesn't read it, and the other
280/// way from then on.
281struct Asking<'a> {
282    http: &'a reqwest::Client,
283    auth: &'a Event,
284    padded: bool,
285}
286
287impl Asking<'_> {
288    /// Send what `request` makes, with the authorization.
289    async fn send(&mut self, request: impl Fn(&reqwest::Client) -> reqwest::RequestBuilder) -> Result<Response, UploadError> {
290        let unreachable = |e: reqwest::Error| UploadError::Unreachable(why(&e.without_url()));
291        let sent = |padded: bool| request(self.http).header(AUTHORIZATION, authorization(self.auth, padded)).send();
292        let response = sent(self.padded).await.map_err(unreachable)?;
293        if self.padded || !NOT_READ.contains(&response.status()) {
294            return Ok(response);
295        }
296        self.padded = true;
297        sent(true).await.map_err(unreachable)
298    }
299}
300
301/// `bytes` as what a request sends, a piece at a time, with `sent` kept
302/// at how much of it was handed over.
303fn counted(bytes: &Arc<Vec<u8>>, sent: &Sent) -> reqwest::Body {
304    let (bytes, sent) = (bytes.clone(), sent.clone());
305    sent.store(0, Ordering::Relaxed);
306    let pieces = futures_util::stream::iter((0..bytes.len()).step_by(PIECE)).map(move |start| {
307        let end = (start + PIECE).min(bytes.len());
308        sent.store(end, Ordering::Relaxed);
309        Ok::<_, std::io::Error>(bytes.get(start..end).unwrap_or_default().to_vec())
310    });
311    reqwest::Body::wrap_stream(pieces)
312}
313
314/// Send the file `bytes`, whose hash is `hash` and which is a `mime`, to
315/// `server` (BUD-02), after asking whether it would take it (BUD-06),
316/// with `sent` kept at how much of it has gone. Returns the file as the
317/// server has it.
318pub async fn upload(
319    http: &reqwest::Client,
320    server: &Url,
321    auth: &Event,
322    bytes: &Arc<Vec<u8>>,
323    hash: &str,
324    mime: &str,
325    sent: &Sent,
326) -> Result<Blob, UploadError> {
327    let address = endpoint(server, "upload");
328    let mut asking = Asking { http, auth, padded: false };
329
330    let asked = asking
331        .send(|http| {
332            http.request(Method::HEAD, &address)
333                .header("X-SHA-256", hash)
334                .header("X-Content-Length", bytes.len())
335                .header("X-Content-Type", mime)
336        })
337        .await?;
338    if !asked.status().is_success() && !NOT_ASKED_THAT.contains(&asked.status()) {
339        return Err(refusal(asked).await);
340    }
341
342    let taken = asking
343        .send(|http| {
344            http.put(&address)
345                .timeout(UPLOAD_TIMEOUT)
346                .header(CONTENT_TYPE, mime)
347                // Said, since what is sent a piece at a time doesn't say
348                // how much there is of it, and servers ask.
349                .header(CONTENT_LENGTH, bytes.len())
350                .header("X-SHA-256", hash)
351                .body(counted(bytes, sent))
352        })
353        .await?;
354    if !taken.status().is_success() {
355        return Err(refusal(taken).await);
356    }
357    let said = answer(taken).await;
358    let descriptor: Descriptor = serde_json::from_slice(&said).map_err(|e| UploadError::Unreadable(e.to_string()))?;
359    let url = Url::parse(&descriptor.url).ok().filter(|url| matches!(url.scheme(), "https" | "http"));
360    let url = url.ok_or_else(|| UploadError::Unreadable(format!("no address: {}", descriptor.url)))?;
361    // A server is to keep a file as it was sent. One that didn't says
362    // which file it has instead.
363    let is_hash = |hash: &String| hash.len() == 64 && hash.bytes().all(|byte| byte.is_ascii_hexdigit());
364    let kept = descriptor.sha256.map(|hash| hash.to_ascii_lowercase()).filter(is_hash).unwrap_or_else(|| hash.to_string());
365    Ok(Blob { url: url.to_string(), hash: kept })
366}
367
368/// Ask `server` to fetch the file at `url`, which the authorization `auth`
369/// is for, and keep it as well (BUD-04).
370pub async fn mirror(http: &reqwest::Client, server: &Url, auth: &Event, url: &str) -> Result<(), UploadError> {
371    let address = endpoint(server, "mirror");
372    let body = serde_json::json!({ "url": url }).to_string();
373    let mut asking = Asking { http, auth, padded: false };
374    let fetched = asking
375        .send(|http| http.put(&address).timeout(MIRROR_TIMEOUT).header(CONTENT_TYPE, "application/json").body(body.clone()))
376        .await?;
377    if fetched.status().is_success() { Ok(()) } else { Err(refusal(fetched).await) }
378}
379
380/// A file that is on a media server, for a note to link to.
381#[derive(Debug, Clone, PartialEq, Eq)]
382pub struct Attachment {
383    /// Where it is: what goes in the note's text.
384    pub url: String,
385    /// What the note says of that address (NIP-92).
386    pub imeta: Tag,
387    /// The server that took it.
388    pub server: Url,
389    /// The servers that fetched it from there.
390    pub mirrored: Vec<Url>,
391}
392
393/// What a note says of the link `url` (NIP-92): that it is to `media`,
394/// whose hash there is `hash`. Its kind, its hash, its size, and for a
395/// picture that was measured its width and height.
396pub fn imeta(url: &str, media: &Media, hash: &str) -> Tag {
397    let mut fields =
398        vec![format!("url {url}"), format!("m {}", media.mime), format!("x {hash}"), format!("size {}", media.bytes.len())];
399    fields.extend(media.dim.map(|(width, height)| format!("dim {width}x{height}")));
400    Tag::custom(IMETA_TAG, fields)
401}
402
403/// The link that `tag` says something of, if it is an `imeta` tag.
404pub fn imeta_url(tag: &Tag) -> Option<&str> {
405    let fields = tag.as_slice();
406    if fields.first()? != IMETA_TAG {
407        return None;
408    }
409    fields.iter().skip(1).find_map(|field| field.strip_prefix("url ")).map(str::trim)
410}
411
412/// Send `media`, whose hash is `hash` and which `auth` authorizes sending,
413/// to the first of `servers` that takes it, and have the others fetch it
414/// from there; with `sent` kept at how much of it has gone. Returns where
415/// it is, or why each server did not take it.
416///
417/// A server that refused is not asked to fetch what it refused; and a
418/// server that did not fetch it is no reason for the file not to be
419/// attached. If the server that took the file changed it, which it is
420/// not to, it is a different file that it has, and no other is asked for
421/// that one.
422pub async fn send(
423    http: &reqwest::Client,
424    servers: &[Url],
425    auth: &Event,
426    media: Media,
427    hash: &str,
428    sent: &Sent,
429) -> Result<Attachment, Vec<(Url, UploadError)>> {
430    let bytes = Arc::new(media.bytes);
431    let mut refused = Vec::new();
432    let mut taken = None;
433    for server in servers {
434        match upload(http, server, auth, &bytes, hash, media.mime, sent).await {
435            Ok(blob) => {
436                taken = Some((server.clone(), blob));
437                break;
438            }
439            Err(e) => {
440                tracing::warn!("{server} did not take {}: {e:?}", media.name);
441                refused.push((server.clone(), e));
442            }
443        }
444    }
445    let Some((server, blob)) = taken else {
446        return Err(refused);
447    };
448    sent.store(bytes.len(), Ordering::Relaxed);
449
450    let others: Vec<&Url> =
451        servers.iter().filter(|other| **other != server && !refused.iter().any(|(tried, _)| tried == *other)).collect();
452    let mut mirrored = Vec::new();
453    if blob.hash == hash {
454        let fetched = join_all(others.iter().map(|other| mirror(http, other, auth, &blob.url))).await;
455        for (other, result) in others.into_iter().zip(fetched) {
456            match result {
457                Ok(()) => mirrored.push(other.clone()),
458                Err(e) => tracing::warn!("{other} did not fetch {}: {e:?}", blob.url),
459            }
460        }
461    } else {
462        tracing::warn!("{server} keeps {} as another file than was sent: {} for {hash}", media.name, blob.hash);
463    }
464    let media = Media { bytes: Arc::unwrap_or_clone(bytes), ..media };
465    Ok(Attachment { imeta: imeta(&blob.url, &media, &blob.hash), url: blob.url, server, mirrored })
466}
467
468#[cfg(test)]
469mod tests {
470    use super::{
471        Attachment, Sent, UploadError, authorization, hash_of, imeta, imeta_url, send, server_list, server_name, servers,
472        typed_server, upload_auth,
473    };
474    use crate::media::Media;
475    use base64::Engine;
476    use base64::engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD};
477    use nostr_sdk::prelude::{Event, EventBuilder, FinalizeEvent, Keys, Kind, Tag, Timestamp, Url};
478    use std::collections::HashMap;
479    use std::sync::atomic::Ordering;
480    use std::sync::{Arc, Mutex};
481    use std::time::Duration;
482    use tokio::io::{AsyncReadExt, AsyncWriteExt};
483    use tokio::net::{TcpListener, TcpStream};
484
485    fn url(server: &str) -> Url {
486        Url::parse(server).unwrap()
487    }
488
489    fn fields(event: &Event) -> Vec<Vec<&str>> {
490        event.tags.iter().map(|tag| tag.as_slice().iter().map(String::as_str).collect()).collect()
491    }
492
493    #[test]
494    fn a_server_is_typed_with_or_without_its_scheme_and_is_the_root_of_its_domain() {
495        let server = url("https://cdn.example.com/");
496        assert_eq!(typed_server("cdn.example.com"), Some(server.clone()));
497        assert_eq!(typed_server("  https://cdn.example.com/  "), Some(server.clone()));
498        assert_eq!(typed_server("https://CDN.example.com/upload?x=1"), Some(server.clone()), "its endpoints are at the root");
499        assert_eq!(typed_server("cdn.example.com:8443"), Some(url("https://cdn.example.com:8443/")));
500        assert_eq!(server_name(&server), "cdn.example.com");
501
502        assert_eq!(typed_server("http://cdn.example.com"), None, "nothing is sent in the clear");
503        assert_eq!(typed_server("wss://relay.example.com"), None);
504        for typed in ["", "   ", "two words", "nodots", "https://"] {
505            assert_eq!(typed_server(typed), None, "{typed:?} is no server");
506        }
507    }
508
509    #[test]
510    fn a_server_list_is_written_with_its_servers_in_order_and_the_rest_as_it_was() {
511        let me = Keys::generate();
512        let (first, second, third) =
513            (url("https://one.example.com/"), url("https://two.example.com/"), url("https://three.example.com/"));
514        let now = Timestamp::from_secs(2_000);
515        assert!(servers(None).is_empty());
516
517        // A first list.
518        let list = server_list(None, std::slice::from_ref(&first), now).unwrap().finalize(&me).unwrap();
519        assert_eq!(list.kind, Kind::BlossomServerList);
520        assert_eq!(fields(&list), [vec!["server", "https://one.example.com"]]);
521        assert_eq!(servers(Some(&list)), [first.clone()]);
522        // An empty one is still a list to write, where there is none.
523        assert!(server_list(None, &[], now).is_some());
524
525        // One another client wrote, at a later time than now, with a
526        // server twice, something that is no server, and a tag of its own.
527        let theirs = [
528            Tag::parse(["server", "https://one.example.com/"]).unwrap(),
529            Tag::parse(["client", "another"]).unwrap(),
530            Tag::parse(["server", "https://two.example.com"]).unwrap(),
531            Tag::parse(["server", "https://one.example.com"]).unwrap(),
532            Tag::parse(["server", "http://clear.example.com"]).unwrap(),
533            Tag::parse(["server", "not an address"]).unwrap(),
534        ];
535        let earlier =
536            EventBuilder::new(Kind::BlossomServerList, "kept").tags(theirs).custom_created_at(Timestamp::from_secs(5_000));
537        let earlier = earlier.finalize(&me).unwrap();
538        assert_eq!(servers(Some(&earlier)), [first.clone(), second.clone()]);
539        assert!(server_list(Some(&earlier), &[first.clone(), second.clone()], now).is_none(), "it says so already");
540
541        let changed = server_list(Some(&earlier), &[third, second, first], now).unwrap().finalize(&me).unwrap();
542        assert_eq!(
543            fields(&changed),
544            [
545                vec!["server", "https://three.example.com"],
546                vec!["server", "https://two.example.com"],
547                vec!["server", "https://one.example.com"],
548                vec!["client", "another"],
549            ]
550        );
551        assert_eq!(changed.content, "kept");
552        assert_eq!(changed.created_at.as_secs(), 5_001, "it is the newer of the two");
553    }
554
555    #[test]
556    fn an_upload_is_authorized_for_one_file_and_for_a_while() {
557        let me = Keys::generate();
558        let hash = hash_of(b"a file");
559        assert_eq!(hash.len(), 64);
560        assert_eq!(hash_of(b""), "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855");
561
562        let auth = upload_auth("holiday.jpg", &hash, Timestamp::from_secs(1_000)).finalize(&me).unwrap();
563        assert_eq!(auth.kind, Kind::BlossomAuth);
564        assert_eq!(auth.content, "Upload holiday.jpg");
565        assert_eq!(auth.created_at.as_secs(), 1_000);
566        assert_eq!(fields(&auth), [vec!["t", "upload"], vec!["x", hash.as_str()], vec!["expiration", "4600"]]);
567
568        // In the header it is the event, as base64 of one kind or the other.
569        let said = authorization(&auth, false);
570        let token = said.strip_prefix("Nostr ").unwrap();
571        assert!(!token.contains(['+', '/', '=']));
572        assert_eq!(Event::from_json(URL_SAFE_NO_PAD.decode(token).unwrap()).unwrap(), auth);
573        let said = authorization(&auth, true);
574        assert_eq!(Event::from_json(STANDARD.decode(said.strip_prefix("Nostr ").unwrap()).unwrap()).unwrap(), auth);
575    }
576
577    /// A picture large enough to be sent in several pieces.
578    fn picture() -> Media {
579        let bytes = (0..200_000u32).map(|nth| (nth % 251) as u8).collect();
580        Media { name: "holiday.png".into(), bytes, mime: "image/png", dim: Some((640, 480)) }
581    }
582
583    #[test]
584    fn a_note_says_of_a_link_what_is_at_it() {
585        let tag = imeta("https://cdn.example.com/abc.png", &picture(), "abc");
586        assert_eq!(
587            tag.as_slice(),
588            ["imeta", "url https://cdn.example.com/abc.png", "m image/png", "x abc", "size 200000", "dim 640x480"]
589        );
590        assert_eq!(imeta_url(&tag), Some("https://cdn.example.com/abc.png"));
591
592        let unmeasured = imeta("https://cdn.example.com/abc.mp4", &Media { mime: "video/mp4", dim: None, ..picture() }, "abc");
593        assert_eq!(unmeasured.as_slice().len(), 5, "what was not measured is not said");
594        assert_eq!(imeta_url(&Tag::parse(["t", "url https://cdn.example.com/abc.png"]).unwrap()), None);
595        assert_eq!(imeta_url(&Tag::parse(["imeta", "m image/png"]).unwrap()), None);
596    }
597
598    /// What a media server was asked.
599    #[derive(Debug, Clone)]
600    struct Asked {
601        method: String,
602        path: String,
603        headers: HashMap<String, String>,
604        body: Vec<u8>,
605    }
606
607    /// How a media server of the tests behaves.
608    #[derive(Debug, Clone, Copy, Default)]
609    struct Manner {
610        /// It takes no file, and says why with this status.
611        refuses: Option<u16>,
612        /// It doesn't know the question of whether it would take a file.
613        asked_nothing: bool,
614        /// It reads the authorization only as plain base64, padded, and
615        /// not as the specification writes it.
616        reads_the_old_way: bool,
617        /// It keeps another file than it was sent.
618        changes: bool,
619    }
620
621    /// A media server of the tests: where it is, and what it was asked.
622    struct Server {
623        url: Url,
624        asked: Arc<Mutex<Vec<Asked>>>,
625    }
626
627    impl Server {
628        fn asked(&self) -> Vec<Asked> {
629            self.asked.lock().unwrap().clone()
630        }
631
632        /// What it was asked, each as its method and path.
633        fn requests(&self) -> Vec<String> {
634            self.asked().iter().map(|asked| format!("{} {}", asked.method, asked.path)).collect()
635        }
636    }
637
638    /// Read one request from `stream`.
639    async fn read_request(stream: &mut TcpStream) -> Option<Asked> {
640        let mut buffer = Vec::new();
641        let head_end = loop {
642            if let Some(end) = buffer.windows(4).position(|window| window == b"\r\n\r\n") {
643                break end;
644            }
645            let mut chunk = [0; 16_384];
646            let read = stream.read(&mut chunk).await.ok()?;
647            if read == 0 {
648                return None;
649            }
650            buffer.extend_from_slice(&chunk[..read]);
651        };
652        let head = String::from_utf8_lossy(&buffer[..head_end]).to_string();
653        let mut lines = head.lines();
654        let mut first = lines.next()?.split(' ');
655        let (method, path) = (first.next()?.to_string(), first.next()?.to_string());
656        let headers: HashMap<String, String> = lines
657            .filter_map(|line| line.split_once(':'))
658            .map(|(name, value)| (name.to_ascii_lowercase(), value.trim().to_string()))
659            .collect();
660        let length: usize = headers.get("content-length").and_then(|length| length.parse().ok()).unwrap_or(0);
661        let mut body = buffer[head_end + 4..].to_vec();
662        while body.len() < length {
663            let mut chunk = [0; 16_384];
664            let read = stream.read(&mut chunk).await.ok()?;
665            if read == 0 {
666                break;
667            }
668            body.extend_from_slice(&chunk[..read]);
669        }
670        Some(Asked { method, path, headers, body })
671    }
672
673    /// What a server that behaves as `manner` answers `asked` with: a status, a reason for its header, and a body.
674    fn answer_to(manner: Manner, base: &Url, asked: &Asked) -> (u16, Option<&'static str>, String) {
675        let Some(token) = asked.headers.get("authorization").and_then(|said| said.strip_prefix("Nostr ")) else {
676            return (401, Some("no authorization"), String::new());
677        };
678        if manner.reads_the_old_way && STANDARD.decode(token).is_err() {
679            return (401, Some("the authorization could not be read"), String::new());
680        }
681        let descriptor =
682            |hash: &str| format!(r#"{{"url":"{base}{hash}.png","sha256":"{hash}","size":1,"type":"image/png","uploaded":1}}"#);
683        match (asked.method.as_str(), asked.path.as_str(), manner.refuses) {
684            ("HEAD", "/upload", _) if manner.asked_nothing => (404, None, String::new()),
685            ("HEAD", "/upload", Some(status)) => (status, Some("it is too large"), String::new()),
686            ("HEAD", "/upload", None) => (200, None, String::new()),
687            // Said in what it answers, and not in a header.
688            ("PUT", "/upload", Some(status)) => (status, None, r#"{"message":"it is too large, said again"}"#.to_string()),
689            ("PUT", "/upload", None) if asked.headers.contains_key("transfer-encoding") => {
690                (411, Some("no length"), String::new())
691            }
692            ("PUT", "/upload", None) if manner.changes => (201, None, descriptor(&hash_of(b"another file"))),
693            ("PUT", "/upload", None) => (201, None, descriptor(&hash_of(&asked.body))),
694            ("PUT", "/mirror", Some(status)) => (status, Some("it is too large"), String::new()),
695            ("PUT", "/mirror", None) => (200, None, descriptor("mirrored")),
696            _ => (404, None, String::new()),
697        }
698    }
699
700    /// Start a media server that behaves as `manner`.
701    async fn serve(manner: Manner) -> Server {
702        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
703        let url = url(&format!("http://{}/", listener.local_addr().unwrap()));
704        let asked: Arc<Mutex<Vec<Asked>>> = Arc::default();
705        let (base, log) = (url.clone(), asked.clone());
706        tokio::spawn(async move {
707            while let Ok((mut stream, _)) = listener.accept().await {
708                let Some(request) = read_request(&mut stream).await else {
709                    continue;
710                };
711                let (status, reason, body) = answer_to(manner, &base, &request);
712                let body = if request.method == "HEAD" { String::new() } else { body };
713                log.lock().unwrap().push(request);
714                let reason = reason.map(|reason| format!("x-reason: {reason}\r\n")).unwrap_or_default();
715                let head =
716                    format!("HTTP/1.1 {status} Said\r\n{reason}content-length: {}\r\nconnection: close\r\n\r\n", body.len());
717                let _ = stream.write_all(format!("{head}{body}").as_bytes()).await;
718                let _ = stream.shutdown().await;
719            }
720        });
721        Server { url, asked }
722    }
723
724    /// An HTTP client that speaks to servers that are not behind TLS, as
725    /// those of the tests, which are on this machine, are not.
726    fn plain_http() -> reqwest::Client {
727        let _ = rustls::crypto::ring::default_provider().install_default();
728        reqwest::Client::new()
729    }
730
731    /// Send `media` to servers that behave as `manners`, in that order.
732    /// Returns what came of it, the servers, the authorization, and how
733    /// much was counted as sent.
734    fn sending(media: &Media, manners: &[Manner]) -> (Result<Attachment, Vec<(Url, UploadError)>>, Vec<Server>, Event, usize) {
735        let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
736        runtime.block_on(async {
737            let mut started = Vec::new();
738            for manner in manners {
739                started.push(serve(*manner).await);
740            }
741            let hash = hash_of(&media.bytes);
742            let keys = Keys::generate();
743            let authorizing = |name: &str| upload_auth(name, &hash, Timestamp::now()).finalize(&keys).unwrap();
744            // One that is not the same written both ways: base64 is only
745            // padded where what it encodes is no multiple of three long.
746            let auth = Some(authorizing(&media.name)).filter(|auth| auth.as_json().len() % 3 != 0);
747            let auth = auth.unwrap_or_else(|| authorizing(&format!("{}.", media.name)));
748            let addresses: Vec<Url> = started.iter().map(|server| server.url.clone()).collect();
749            let http = plain_http();
750            let sent = Sent::default();
751            let sending = send(&http, &addresses, &auth, media.clone(), &hash, &sent);
752            let result = tokio::time::timeout(Duration::from_secs(30), sending).await.unwrap();
753            (result, started, auth, sent.load(Ordering::Relaxed))
754        })
755    }
756
757    #[test]
758    fn a_file_goes_to_the_first_server_and_the_others_fetch_it_from_there() {
759        let media = picture();
760        let hash = hash_of(&media.bytes);
761        let (result, servers, auth, sent) = sending(&media, &[Manner::default(); 3]);
762
763        let attachment = result.unwrap();
764        let address = format!("{}{hash}.png", servers[0].url);
765        assert_eq!(attachment.url, address);
766        assert_eq!(attachment.server, servers[0].url);
767        assert_eq!(attachment.mirrored, [servers[1].url.clone(), servers[2].url.clone()]);
768        assert_eq!(attachment.imeta, imeta(&address, &media, &hash));
769        assert_eq!(sent, media.bytes.len(), "all of it was counted as it went");
770
771        // The first was asked whether it would take it, and then sent it.
772        assert_eq!(servers[0].requests(), ["HEAD /upload", "PUT /upload"]);
773        let asked = servers[0].asked();
774        let said = |request: &super::tests::Asked, name: &str| request.headers.get(name).cloned().unwrap_or_default();
775        assert_eq!(said(&asked[0], "x-sha-256"), hash);
776        assert_eq!(said(&asked[0], "x-content-length"), "200000");
777        assert_eq!(said(&asked[0], "x-content-type"), "image/png");
778        assert!(asked[0].body.is_empty());
779        assert_eq!(asked[1].body, media.bytes, "the file arrived as it was");
780        assert_eq!(said(&asked[1], "content-length"), "200000");
781        assert_eq!(said(&asked[1], "content-type"), "image/png");
782        assert_eq!(said(&asked[1], "x-sha-256"), hash);
783        assert!(!asked[1].headers.contains_key("transfer-encoding"));
784        // Both with the authorization, as the specification writes it.
785        for request in &asked {
786            assert_eq!(said(request, "authorization"), authorization(&auth, false));
787        }
788
789        // The others were asked to fetch it, with the same authorization.
790        for other in &servers[1..] {
791            let asked = other.asked();
792            assert_eq!(other.requests(), ["PUT /mirror"]);
793            assert_eq!(String::from_utf8_lossy(&asked[0].body), format!(r#"{{"url":"{address}"}}"#));
794            assert_eq!(said(&asked[0], "content-type"), "application/json");
795            assert_eq!(said(&asked[0], "authorization"), authorization(&auth, false));
796        }
797    }
798
799    #[test]
800    fn a_server_that_would_not_take_a_file_is_not_sent_it_and_the_next_one_is() {
801        let refusing = Manner { refuses: Some(413), ..Manner::default() };
802        let (result, servers, _, _) = sending(&picture(), &[refusing, Manner::default(), Manner::default()]);
803
804        let attachment = result.unwrap();
805        assert_eq!(attachment.server, servers[1].url);
806        assert_eq!(attachment.mirrored, [servers[2].url.clone()]);
807        assert_eq!(servers[0].requests(), ["HEAD /upload"], "it said no to the question, and was asked no more");
808        assert_eq!(servers[1].requests(), ["HEAD /upload", "PUT /upload"]);
809        assert_eq!(servers[2].requests(), ["PUT /mirror"]);
810    }
811
812    #[test]
813    fn a_server_that_does_not_know_the_question_is_sent_the_file() {
814        let unasked = Manner { asked_nothing: true, ..Manner::default() };
815        let (result, servers, _, _) = sending(&picture(), &[unasked]);
816        assert_eq!(result.unwrap().server, servers[0].url);
817        assert_eq!(servers[0].requests(), ["HEAD /upload", "PUT /upload"]);
818
819        // And says why it did not take it in what it answers.
820        let (result, servers, _, _) = sending(&picture(), &[Manner { refuses: Some(402), ..unasked }]);
821        let why = UploadError::Refused { status: 402, reason: "it is too large, said again".into() };
822        assert_eq!(result, Err(vec![(servers[0].url.clone(), why)]));
823    }
824
825    #[test]
826    fn a_server_that_reads_the_authorization_the_old_way_is_asked_again_that_way() {
827        let old = Manner { reads_the_old_way: true, ..Manner::default() };
828        let (result, servers, auth, _) = sending(&picture(), &[old, old]);
829
830        let attachment = result.unwrap();
831        assert_eq!(attachment.mirrored, [servers[1].url.clone()]);
832        // The question twice; then the file, the way that was read.
833        assert_eq!(servers[0].requests(), ["HEAD /upload", "HEAD /upload", "PUT /upload"]);
834        let written: Vec<String> = servers[0].asked().iter().map(|asked| asked.headers["authorization"].clone()).collect();
835        assert_eq!(written, [authorization(&auth, false), authorization(&auth, true), authorization(&auth, true)]);
836        assert_eq!(servers[1].requests(), ["PUT /mirror", "PUT /mirror"]);
837        assert_eq!(servers[1].asked()[1].headers["authorization"], authorization(&auth, true));
838    }
839
840    #[test]
841    fn when_no_server_takes_a_file_each_says_why() {
842        let refusing = Manner { refuses: Some(413), ..Manner::default() };
843        // A server that is not there: nothing listens where it was.
844        let gone = {
845            let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
846            url(&format!("http://{}/", listener.local_addr().unwrap()))
847        };
848        let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
849        let (result, there) = runtime.block_on(async {
850            let there = serve(refusing).await;
851            let media = picture();
852            let hash = hash_of(&media.bytes);
853            let auth = upload_auth(&media.name, &hash, Timestamp::now()).finalize(&Keys::generate()).unwrap();
854            let servers = [gone.clone(), there.url.clone()];
855            (send(&plain_http(), &servers, &auth, media, &hash, &Sent::default()).await, there)
856        });
857
858        let refused = result.unwrap_err();
859        assert_eq!(refused.len(), 2);
860        assert!(matches!(&refused[0], (server, UploadError::Unreachable(_)) if *server == gone), "{refused:?}");
861        assert_eq!(refused[1], (there.url.clone(), UploadError::Refused { status: 413, reason: "it is too large".into() }));
862    }
863
864    #[test]
865    fn a_file_the_server_changed_is_another_file_and_no_other_server_is_asked_for_it() {
866        let changing = Manner { changes: true, ..Manner::default() };
867        let media = picture();
868        let (result, servers, _, _) = sending(&media, &[changing, Manner::default()]);
869
870        let attachment = result.unwrap();
871        let kept = hash_of(b"another file");
872        assert_eq!(attachment.imeta, imeta(&attachment.url, &media, &kept), "the note says which file is there");
873        assert!(attachment.mirrored.is_empty());
874        assert!(servers[1].requests().is_empty());
875    }
876}