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::{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 &orgs(cx),
94 &memberships(cx),
95 &repos(cx),
96 &queries(cx),
97 )
98 .await
99 .map_err(server_error)?
100 .ok_or_not_found()?;
101
102 let etag = format!("\"{}\"", target.commit().as_str());
103
104 if presented_etag(cx).is_some_and(|presented| presented == etag) {
105 return not_modified(&etag);
106 }
107
108 let filename = target.filename().to_owned();
109 let body = open_archive(target, &archives(cx))
110 .await
111 .map_err(server_error)?;
112
113 Response::builder()
114 .header(CONTENT_TYPE, format.content_type())
115 // A tar.gz and a zip are both archives a browser saves rather than renders, so
116 // unlike the raw endpoint the honest type costs nothing. `nosniff` stays: the
117 // policy that the origin never lets a browser reconsider a type it was given is
118 // worth keeping uniform.
119 .header(NOSNIFF.0, NOSNIFF.1)
120 .header(CONTENT_DISPOSITION, disposition(&filename))
121 // The commit, so a repeat download of a tag is a 304 and a repeat download of a
122 // moving branch is not. Nothing weaker would do: `main` is a different archive
123 // every push.
124 .header(ETAG, etag)
125 .body(GitBody::new(body))
126 .map_err(server_error)
127}
128
129/// The header that stops a browser second-guessing a `Content-Type`.
130///
131/// The same pair [`browse`](super::browse) uses, written again rather than shared
132/// because it is two words and importing it would couple two modules over nothing.
133const NOSNIFF: (&str, &str) = ("x-content-type-options", "nosniff");
134
135/// The `If-None-Match` a client presented, if any.
136///
137/// Only the simple single-tag form is honoured. A list, or a `W/` weak tag, is treated
138/// as no match and the archive is packed — the cost of being wrong here is a download
139/// that was already going to happen.
140fn presented_etag(cx: &Cx) -> Option<String> {
141 Some(
142 headers(cx)
143 .get(IF_NONE_MATCH)?
144 .to_str()
145 .ok()?
146 .trim()
147 .to_owned(),
148 )
149}
150
151/// "You already have this one."
152///
153/// The `ETag` is repeated, per RFC 9110: a 304 must carry what the cached entry would
154/// have been validated against.
155fn not_modified(etag: &str) -> Result<Response<GitBody>> {
156 Response::builder()
157 .status(StatusCode::NOT_MODIFIED)
158 .header(ETAG, etag)
159 .body(GitBody::new(Box::pin(tokio::io::empty())))
160 .map_err(server_error)
161}
162
163/// The `Content-Disposition` for the download.
164///
165/// Simpler than [`browse`](super::browse)'s, and deliberately: that one carries a
166/// filename out of a repository, which is arbitrary bytes somebody else chose. This one
167/// is built by the use case from a repository name and a sanitised revision, both of
168/// which are already restricted to characters that cannot end the quoted string. The
169/// filter is kept anyway, because "the caller already validated it" is how header
170/// injection arrives later.
171fn disposition(filename: &str) -> String {
172 let safe: String = filename
173 .chars()
174 .map(|char| match char {
175 'A'..='Z' | 'a'..='z' | '0'..='9' | '.' | '-' | '_' => char,
176 _ => '_',
177 })
178 .collect();
179
180 format!("attachment; filename=\"{safe}\"")
181}
182
183/// The URL an archive of a revision downloads from.
184///
185/// The revision is encoded whole, slashes included, so `release/2.0` stays one segment —
186/// the same rule [`tree_url`](super::browse::tree_url) follows, and the reason the
187/// extension can be part of that segment at all.
188pub(super) fn archive_url(handle: &str, name: &str, rev: &str, format: ArchiveFormat) -> String {
189 format!(
190 "/{handle}/repos/{name}/archive/{}.{}",
191 super::browse::encode(rev, false),
192 format.as_str()
193 )
194}
195
196#[cfg(test)]
197mod tests {
198 use super::*;
199
200 #[test]
201 fn an_archive_url_keeps_the_revision_in_one_segment() {
202 assert_eq!(
203 archive_url("ada", "steid", "main", ArchiveFormat::TarGz),
204 "/ada/repos/steid/archive/main.tar.gz"
205 );
206 assert_eq!(
207 archive_url("ada", "steid", "release/2.0", ArchiveFormat::Zip),
208 "/ada/repos/steid/archive/release%2F2.0.zip"
209 );
210 }
211
212 #[test]
213 fn a_filename_is_reduced_to_what_a_header_can_carry() {
214 assert_eq!(
215 disposition("steid-main.tar.gz"),
216 "attachment; filename=\"steid-main.tar.gz\""
217 );
218 assert_eq!(
219 disposition("a\"b\r\nc.zip"),
220 "attachment; filename=\"a_b__c.zip\""
221 );
222 }
223}