forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.010.9 MiBd75b65dTahinli28 minutes ago340 commits

snippet_raw.rs126 lines, 3.9 KiBHistoryRawDownload
1use forge_core::raw_token::verify_raw;
2use forge_core::store::snippets::{Snippet, SnippetVisibility};
3use sha2::{Digest, Sha256};
4use topcoat::context::{Cx, context};
5use topcoat::router::request::{headers, method};
6use topcoat::router::response::Response;
7use topcoat::router::{
8 Body, Method, RouteFuture, StatusCode, header, parse_query_params, path_param_segment,
9 path_param_segments,
10};
11
12use crate::raw::{
13 CACHE_NONE, CACHE_PRIVATE, CACHE_PUBLIC, Meta, TEXT, TokenQuery, encode_path, finish, now_unix,
14 plain, signed_url,
15};
16use crate::state::AppState;
17
18const MARKDOWN: &str = "text/markdown; charset=utf-8";
19const JSON: &str = "application/json; charset=utf-8";
20
21pub fn snippet_raw_url(state: &AppState, snippet: &Snippet, file: &str) -> String {
22 let encoded = format!(
23 "-/snippets/{}/{}",
24 encode_path(&snippet.id),
25 encode_path(file)
26 );
27 signed_url(
28 state,
29 &encoded,
30 &snippet.id,
31 snippet.visibility == SnippetVisibility::Private,
32 )
33}
34
35pub fn snippet_file(cx: &Cx, _body: Body) -> RouteFuture<'_> {
36 Box::pin(async move { Ok(serve(cx).await) })
37}
38
39fn content_type(file_name: &str) -> &'static str {
40 match file_name
41 .rsplit_once('.')
42 .map(|(_, ext)| ext.to_ascii_lowercase())
43 .as_deref()
44 {
45 Some("md" | "markdown") => MARKDOWN,
46 Some("json") => JSON,
47 _ => TEXT,
48 }
49}
50
51async fn serve(cx: &Cx) -> Response {
52 let state = context::<AppState>(cx).clone();
53 let id = path_param_segment(cx, "id").to_owned();
54 let segments: Vec<&str> = path_param_segments(cx, "rest").collect();
55 let [name] = segments.as_slice() else {
56 return plain(StatusCode::NOT_FOUND, CACHE_NONE, None);
57 };
58 let name = (*name).to_owned();
59 let is_head = method(cx) == Method::HEAD;
60 let token = parse_query_params::<TokenQuery>(cx)
61 .ok()
62 .and_then(|query| query.token);
63 let if_none_match = headers(cx)
64 .get(header::IF_NONE_MATCH)
65 .and_then(|v| v.to_str().ok())
66 .map(str::to_owned);
67
68 let snippet = match state.store.get_snippet(&id).await {
69 Ok(Some(snippet)) => snippet,
70 Ok(None) => return plain(StatusCode::NOT_FOUND, CACHE_NONE, None),
71 Err(e) => {
72 tracing::error!(error = %e, "snippet raw: lookup failed");
73 return plain(StatusCode::INTERNAL_SERVER_ERROR, CACHE_NONE, None);
74 }
75 };
76 let cache = match snippet.visibility {
77 SnippetVisibility::Public => CACHE_PUBLIC,
78 SnippetVisibility::Unlisted => CACHE_PRIVATE,
79 SnippetVisibility::Private => {
80 let valid = token
81 .as_deref()
82 .is_some_and(|t| verify_raw(&state.key, t, &snippet.id, now_unix()));
83 if !valid {
84 return plain(StatusCode::NOT_FOUND, CACHE_NONE, None);
85 }
86 CACHE_PRIVATE
87 }
88 };
89
90 let Some(file) = snippet.file(&name) else {
91 return plain(StatusCode::NOT_FOUND, CACHE_NONE, None);
92 };
93 let etag = hex::encode(Sha256::digest(file.content.as_bytes()));
94 let quoted = format!("\"{etag}\"");
95 if if_none_match
96 .as_deref()
97 .is_some_and(|value| super::etag_matches(value, &quoted))
98 {
99 return finish(StatusCode::NOT_MODIFIED, Body::empty(), &etag, cache, None);
100 }
101
102 let meta = Meta {
103 content_type: content_type(&name),
104 attachment: false,
105 len: file.content.len() as u64,
106 };
107 let body = if is_head {
108 Body::empty()
109 } else {
110 Body::from(bytes::Bytes::from(file.content.clone().into_bytes()))
111 };
112 finish(StatusCode::OK, body, &etag, cache, Some(meta))
113}
114
115#[cfg(test)]
116mod tests {
117 use super::*;
118
119 #[test]
120 fn content_types_follow_extensions() {
121 assert_eq!(content_type("notes.md"), MARKDOWN);
122 assert_eq!(content_type("data.JSON"), JSON);
123 assert_eq!(content_type("main.rs"), TEXT);
124 assert_eq!(content_type("README"), TEXT);
125 }
126}