steid

@jamesgill /

steid/src/application/archive.rs
Rust10.4 KBCode·Blame·History·Raw
1//! Packing a repository at a revision into a downloadable archive.
2//!
3//! Two steps rather than one, and the split is the point: [`archive_repo`] decides
4//! *whether* — visibility, and whether the revision exists — and [`open_archive`] then
5//! runs git. Nothing but [`archive_repo`] can build an [`ArchiveTarget`], so the
6//! expensive half cannot be reached without the authorized half having happened. It
7//! also lets a caller answer a conditional request from the resolved commit without
8//! spawning anything, which is what the `ETag` is for.
9//!
10//! Authorization is not re-implemented here: like everything in [`browse`](super::browse)
11//! it goes through [`visible_repo`](super::access::visible_repo), so a repository invisible on
12//! its page has no archive either.
13
14use crate::domain::{
15 Actor, ObjectId, OrgName, RefName, RepoName,
16 repository::{MembershipRepository, OrgRepository, RepoRepository},
17};
18
19use super::{
20 access::{Stores, visible_repo},
21 error::Result,
22 port::{ArchiveFormat, ArchiveRequest, ByteStream, GitArchive, GitQuery},
23};
24
25/// An archive that may be produced: authorized, and resolved to a commit.
26///
27/// Fields are private and there is no constructor, so the only way to hold one is to
28/// have been through [`archive_repo`].
29#[derive(Debug, Clone, PartialEq, Eq)]
30pub struct ArchiveTarget {
31 handle: OrgName,
32 name: RepoName,
33 format: ArchiveFormat,
34 commit: ObjectId,
35 prefix: String,
36 filename: String,
37}
38
39impl ArchiveTarget {
40 /// The commit the revision resolved to.
41 ///
42 /// What the response's `ETag` is: two requests for `main` a week apart are
43 /// different archives, and two requests for a tag are the same one forever.
44 pub fn commit(&self) -> &ObjectId {
45 &self.commit
46 }
47
48 /// What the download is called, e.g. `steid-v0.2.0.tar.gz`.
49 pub fn filename(&self) -> &str {
50 &self.filename
51 }
52
53 pub fn format(&self) -> ArchiveFormat {
54 self.format
55 }
56}
57
58/// Settles whether this actor may download this revision of this repository, and what
59/// the archive would be called.
60///
61/// **One `git` process** — resolving the revision — and no packing. `Ok(None)` covers
62/// an invisible repository, an absent one, an unknown revision, and a repository with
63/// no commits: all of them are one answer for the reason
64/// [`visible_repo`](super::access::visible_repo) gives, and none of them is a thing to download.
65pub async fn archive_repo(
66 handle: &OrgName,
67 name: &RepoName,
68 rev: &RefName,
69 format: ArchiveFormat,
70 actor: &Actor,
71 stores: &Stores<'_, impl OrgRepository, impl MembershipRepository, impl RepoRepository>,
72 queries: &impl GitQuery,
73) -> Result<Option<ArchiveTarget>> {
74 if visible_repo(actor, handle, name, stores).await?.is_none() {
75 return Ok(None);
76 }
77
78 // Resolved before anything is packed, for the module rule `git_query` sets out: a
79 // revision that is not there must be a 404 rather than a fatal `git archive`.
80 let Some(commit) = queries.resolve(handle, name, rev).await? else {
81 return Ok(None);
82 };
83
84 let stem = format!("{}-{}", name.as_str(), safe_component(rev.as_str()));
85
86 Ok(Some(ArchiveTarget {
87 handle: handle.clone(),
88 name: name.clone(),
89 format,
90 commit,
91 prefix: format!("{stem}/"),
92 filename: format!("{stem}.{}", format.as_str()),
93 }))
94}
95
96/// Runs the pack, handing back its bytes as they arrive.
97///
98/// Takes the target by value: an archive is a side effect large enough that producing
99/// one twice from the same decision should be a deliberate act, not an accident.
100pub async fn open_archive(target: ArchiveTarget, archives: &impl GitArchive) -> Result<ByteStream> {
101 Ok(archives
102 .archive(ArchiveRequest {
103 handle: target.handle,
104 name: target.name,
105 format: target.format,
106 commit: target.commit,
107 prefix: target.prefix,
108 })
109 .await?)
110}
111
112/// A revision reduced to something that can be a filename and a directory name.
113///
114/// A revision may contain slashes — `release/2.0` is an ordinary branch — and a
115/// `Content-Disposition` naming `steid-release/2.0.zip` is at best ignored and at worst
116/// a path. Everything outside the unreserved set becomes a hyphen, which is what every
117/// forge does and what people expect a downloaded branch archive to look like.
118///
119/// A leading dot is dropped as well: a hidden archive in the downloads folder is not a
120/// security problem, just a file nobody can find.
121fn safe_component(rev: &str) -> String {
122 let mut safe: String = rev
123 .chars()
124 .map(|char| match char {
125 'A'..='Z' | 'a'..='z' | '0'..='9' | '.' | '-' | '_' => char,
126 _ => '-',
127 })
128 .collect();
129
130 while safe.starts_with('.') {
131 safe.remove(0);
132 }
133
134 // A revision written entirely in a script this cannot carry reduces to a row of
135 // hyphens, which is a worse filename than saying nothing — the same rule
136 // `browse::disposition` applies to a file's own name. The commit is in the `ETag`;
137 // the name only has to be usable.
138 if !safe.chars().any(|char| char.is_ascii_alphanumeric()) {
139 safe = "archive".to_owned();
140 }
141
142 safe
143}
144
145#[cfg(test)]
146mod tests {
147 use std::time::SystemTime;
148
149 use super::*;
150 use crate::{
151 domain::{
152 Membership, MembershipId, OrgId, Organization, RepoId, Repository, UserId, Visibility,
153 },
154 infrastructure::{
155 git::{InMemoryGitArchive, InMemoryGitQuery},
156 repository::{InMemoryMembershipRepo, InMemoryOrgRepo, InMemoryRepoRepo},
157 },
158 };
159
160 struct Fixture {
161 orgs: InMemoryOrgRepo,
162 memberships: InMemoryMembershipRepo,
163 repos: InMemoryRepoRepo,
164 handle: OrgName,
165 owner: Actor,
166 stranger: Actor,
167 }
168
169 async fn fixture(visibility: Visibility) -> Fixture {
170 let orgs = InMemoryOrgRepo::new();
171 let memberships = InMemoryMembershipRepo::new();
172 let repos = InMemoryRepoRepo::new();
173
174 let org = Organization::new(OrgId::generate(), "acme", None).expect("valid org");
175 orgs.save(&org).await.expect("save org");
176
177 let owner = UserId::generate();
178 memberships
179 .save(&Membership::new(
180 MembershipId::generate(),
181 org.id.clone(),
182 owner.clone(),
183 crate::domain::Role::Owner,
184 ))
185 .await
186 .expect("save membership");
187
188 repos
189 .save(
190 &Repository::new(
191 RepoId::generate(),
192 org.id.clone(),
193 "steid",
194 None,
195 visibility,
196 SystemTime::now(),
197 )
198 .expect("valid repository"),
199 )
200 .await
201 .expect("save repo");
202
203 Fixture {
204 orgs,
205 memberships,
206 repos,
207 handle: org.name,
208 owner: Actor::User(owner),
209 stranger: Actor::Anonymous,
210 }
211 }
212
213 fn repo_name() -> RepoName {
214 RepoName::new("steid").expect("valid repository name")
215 }
216
217 fn rev(value: &str) -> RefName {
218 RefName::new(value).expect("valid revision")
219 }
220
221 impl Fixture {
222 async fn target(
223 &self,
224 actor: &Actor,
225 rev: &RefName,
226 queries: &InMemoryGitQuery,
227 ) -> Result<Option<ArchiveTarget>> {
228 archive_repo(
229 &self.handle,
230 &repo_name(),
231 rev,
232 ArchiveFormat::TarGz,
233 actor,
234 &Stores::new(&self.orgs, &self.memberships, &self.repos),
235 queries,
236 )
237 .await
238 }
239 }
240
241 #[tokio::test]
242 async fn a_public_repository_archives_under_its_own_name() {
243 let f = fixture(Visibility::Public).await;
244
245 let target = f
246 .target(&f.stranger, &rev("main"), &InMemoryGitQuery::new())
247 .await
248 .expect("should read")
249 .expect("archivable");
250
251 assert_eq!(target.filename(), "steid-main.tar.gz");
252 assert_eq!(target.prefix, "steid-main/");
253 }
254
255 #[tokio::test]
256 async fn a_private_repository_has_no_archive_for_a_stranger() {
257 // The same answer the page gives: absent and invisible are one thing.
258 let f = fixture(Visibility::Private).await;
259 let queries = InMemoryGitQuery::new();
260
261 assert!(
262 f.target(&f.stranger, &rev("main"), &queries)
263 .await
264 .expect("should read")
265 .is_none()
266 );
267 assert!(
268 f.target(&f.owner, &rev("main"), &queries)
269 .await
270 .expect("should read")
271 .is_some()
272 );
273 }
274
275 #[tokio::test]
276 async fn a_revision_that_does_not_resolve_has_nothing_to_pack() {
277 // An empty repository resolves nothing, which is the same non-answer as a
278 // branch that was never pushed.
279 let f = fixture(Visibility::Public).await;
280
281 assert!(
282 f.target(&f.owner, &rev("main"), &InMemoryGitQuery::empty())
283 .await
284 .expect("should read")
285 .is_none()
286 );
287 }
288
289 #[tokio::test]
290 async fn the_pack_is_asked_for_exactly_what_was_resolved() {
291 let f = fixture(Visibility::Public).await;
292 let archives = InMemoryGitArchive::new();
293
294 let target = f
295 .target(&f.owner, &rev("release/2.0"), &InMemoryGitQuery::new())
296 .await
297 .expect("should read")
298 .expect("archivable");
299 let commit = target.commit().clone();
300
301 open_archive(target, &archives).await.expect("should pack");
302
303 let requested = archives.requests().pop().expect("one request");
304 assert_eq!(requested.commit, commit);
305 // A slash in a branch name is not a directory in the archive.
306 assert_eq!(requested.prefix, "steid-release-2.0/");
307 }
308
309 #[test]
310 fn a_revision_becomes_something_a_filesystem_will_take() {
311 assert_eq!(safe_component("main"), "main");
312 assert_eq!(safe_component("v0.2.0"), "v0.2.0");
313 assert_eq!(safe_component("release/2.0"), "release-2.0");
314 assert_eq!(safe_component("../etc/passwd"), "-etc-passwd");
315 assert_eq!(safe_component("..."), "archive");
316 assert_eq!(safe_component("日本語"), "archive");
317 }
318}