steid

@jamesgill /

Rust8.0 KBCode·Blame·History·Raw
1//! Archive download — `/{handle}/repos/{name}/archive/{rev}.tar.gz` and `.zip`.
2//!
3//! A route rather than a page: the response is a file, and one that may be as large as
4//! the repository, so it streams out of `git archive` the same way pack data streams out
5//! of the protocol backend — see [`GitBody`].
6//!
7//! The extension is part of the last segment rather than a segment of its own, because
8//! it is part of the *filename* a browser saves: `steid-main.tar.gz` is what the URL
9//! promises and what the download is called. A revision containing a slash is
10//! percent-encoded whole, exactly as the tree routes encode it, so `release%2F2.0.zip`
11//! arrives here as one parameter.
12
13use topcoat::{
14 Result,
15 context::Cx,
16 router::{
17 Response, StatusCode,
18 error::{RouterErrorExt, not_found},
19 header::{CONTENT_DISPOSITION, CONTENT_TYPE, ETAG, IF_NONE_MATCH},
20 headers, path_param, route,
21 },
22};
23
24use crate::{
25 application::{Stores, archive_repo, open_archive, port::ArchiveFormat},
26 domain::RefName,
27};
28
29use super::{
30 context::{archives, current_actor, memberships, orgs, queries, repos, server_error},
31 git::{GitBody, too_many_requests},
32 rate_limit::archive_throttled,
33 repo::repo_for,
34};
35
36/// `{file}` from the path: the revision and its extension, e.g. `main.tar.gz`.
37#[path_param]
38struct File(str);
39
40/// Every extension served, longest first.
41///
42/// Order matters only in that `.tar.gz` must be tried before anything that is a suffix
43/// of it; today nothing is, and the list is written so that stays true by construction
44/// rather than by luck.
45const FORMATS: [(&str, ArchiveFormat); 2] = [
46 (".tar.gz", ArchiveFormat::TarGz),
47 (".zip", ArchiveFormat::Zip),
48];
49
50/// Splits `main.tar.gz` into the revision and the format it is asked for.
51///
52/// An unknown extension is a 404 rather than a bad request: `/archive/main.rar` is a
53/// URL Steid does not have, not a malformed one.
54fn requested(cx: &Cx) -> Result<(RefName, ArchiveFormat)> {
55 let file = path_param::<File>(cx);
56
57 let (rev, format) = FORMATS
58 .iter()
59 .find_map(|(extension, format)| Some((file.strip_suffix(extension)?, *format)))
60 .ok_or_else(not_found)?;
61
62 Ok((RefName::new(rev).map_err(|_| not_found())?, format))
63}
64
65/// A repository at a revision, as a `.tar.gz` or a `.zip`.
66///
67/// **Two `git` processes** — one resolving the revision, one packing — and the second is
68/// skipped entirely when the client already has this commit: the `ETag` *is* the
69/// resolved commit id, so `If-None-Match` can be answered before anything is spawned.
70/// That is what the use case's two-step shape buys.
71///
72/// Visibility is [`archive_repo`]'s answer, which is [`view_repo`]'s answer, which is
73/// the browse pages' answer: a private repository 404s for a stranger exactly as its
74/// page does. No `WWW-Authenticate` challenge here — this is a link on a page, reached
75/// with a session cookie, not a git client that can offer a credential.
76#[route(GET "/{handle}/repos/{name}/archive/{file}")]
77async fn archive_download(cx: &Cx) -> Result<Response<GitBody>> {
78 // Counted before any work, including the 404s: an archive is a whole pack of the
79 // repository per request, and a crawler walking the tags page asks for one per tag.
80 if let Some(retry_after) = archive_throttled(cx) {
81 return too_many_requests(retry_after);
82 }
83
84 let (rev, format) = requested(cx)?;
85 let repo = repo_for(cx).await?;
86
87 let target = archive_repo(
88 &repo.handle,
89 &repo.name,
90 &rev,
91 format,
92 &current_actor(cx).await?,
93 &Stores::new(&orgs(cx), &memberships(cx), &repos(cx)),
94 &queries(cx),
95 )
96 .await
97 .map_err(server_error)?
98 .ok_or_not_found()?;
99
100 let etag = format!("\"{}\"", target.commit().as_str());
101
102 if presented_etag(cx).is_some_and(|presented| presented == etag) {
103 return not_modified(&etag);
104 }
105
106 let filename = target.filename().to_owned();
107 let body = open_archive(target, &archives(cx))
108 .await
109 .map_err(server_error)?;
110
111 Response::builder()
112 .header(CONTENT_TYPE, format.content_type())
113 // A tar.gz and a zip are both archives a browser saves rather than renders, so
114 // unlike the raw endpoint the honest type costs nothing. `nosniff` stays: the
115 // policy that the origin never lets a browser reconsider a type it was given is
116 // worth keeping uniform.
117 .header(NOSNIFF.0, NOSNIFF.1)
118 .header(CONTENT_DISPOSITION, disposition(&filename))
119 // The commit, so a repeat download of a tag is a 304 and a repeat download of a
120 // moving branch is not. Nothing weaker would do: `main` is a different archive
121 // every push.
122 .header(ETAG, etag)
123 .body(GitBody::new(body))
124 .map_err(server_error)
125}
126
127/// The header that stops a browser second-guessing a `Content-Type`.
128///
129/// The same pair [`browse`](super::browse) uses, written again rather than shared
130/// because it is two words and importing it would couple two modules over nothing.
131const NOSNIFF: (&str, &str) = ("x-content-type-options", "nosniff");
132
133/// The `If-None-Match` a client presented, if any.
134///
135/// Only the simple single-tag form is honoured. A list, or a `W/` weak tag, is treated
136/// as no match and the archive is packed — the cost of being wrong here is a download
137/// that was already going to happen.
138fn presented_etag(cx: &Cx) -> Option<String> {
139 Some(
140 headers(cx)
141 .get(IF_NONE_MATCH)?
142 .to_str()
143 .ok()?
144 .trim()
145 .to_owned(),
146 )
147}
148
149/// "You already have this one."
150///
151/// The `ETag` is repeated, per RFC 9110: a 304 must carry what the cached entry would
152/// have been validated against.
153fn not_modified(etag: &str) -> Result<Response<GitBody>> {
154 Response::builder()
155 .status(StatusCode::NOT_MODIFIED)
156 .header(ETAG, etag)
157 .body(GitBody::new(Box::pin(tokio::io::empty())))
158 .map_err(server_error)
159}
160
161/// The `Content-Disposition` for the download.
162///
163/// Simpler than [`browse`](super::browse)'s, and deliberately: that one carries a
164/// filename out of a repository, which is arbitrary bytes somebody else chose. This one
165/// is built by the use case from a repository name and a sanitised revision, both of
166/// which are already restricted to characters that cannot end the quoted string. The
167/// filter is kept anyway, because "the caller already validated it" is how header
168/// injection arrives later.
169fn disposition(filename: &str) -> String {
170 let safe: String = filename
171 .chars()
172 .map(|char| match char {
173 'A'..='Z' | 'a'..='z' | '0'..='9' | '.' | '-' | '_' => char,
174 _ => '_',
175 })
176 .collect();
177
178 format!("attachment; filename=\"{safe}\"")
179}
180
181/// The URL an archive of a revision downloads from.
182///
183/// The revision is encoded whole, slashes included, so `release/2.0` stays one segment —
184/// the same rule [`tree_url`](super::urls::tree_url) follows, and the reason the
185/// extension can be part of that segment at all.
186pub(super) fn archive_url(handle: &str, name: &str, rev: &str, format: ArchiveFormat) -> String {
187 format!(
188 "/{handle}/repos/{name}/archive/{}.{}",
189 super::urls::encode(rev, false),
190 format.as_str()
191 )
192}
193
194#[cfg(test)]
195mod tests {
196 use super::*;
197
198 #[test]
199 fn an_archive_url_keeps_the_revision_in_one_segment() {
200 assert_eq!(
201 archive_url("ada", "steid", "main", ArchiveFormat::TarGz),
202 "/ada/repos/steid/archive/main.tar.gz"
203 );
204 assert_eq!(
205 archive_url("ada", "steid", "release/2.0", ArchiveFormat::Zip),
206 "/ada/repos/steid/archive/release%2F2.0.zip"
207 );
208 }
209
210 #[test]
211 fn a_filename_is_reduced_to_what_a_header_can_carry() {
212 assert_eq!(
213 disposition("steid-main.tar.gz"),
214 "attachment; filename=\"steid-main.tar.gz\""
215 );
216 assert_eq!(
217 disposition("a\"b\r\nc.zip"),
218 "attachment; filename=\"a_b__c.zip\""
219 );
220 }
221}