steid

@jamesgill /

Rust18.7 KBCode·Blame·History·Raw
1//! Request-scoped helpers.
2//!
3//! Functions taking `cx: &Cx`, not middleware or extractors — Topcoat's guidance, and
4//! the safer shape: a page that forgets to call `current_actor` gets no actor, whereas
5//! a route added without its middleware silently gets someone else's.
6
7use std::{sync::Arc, time::SystemTime};
8
9use sqlx::SqlitePool;
10use topcoat::{
11 Result,
12 context::{Cx, app_context},
13 router::{
14 HeaderName, HeaderValue,
15 error::{internal_server_error, not_found},
16 header::{HOST, LOCATION},
17 headers,
18 },
19 session,
20};
21
22use crate::{
23 application::{
24 AppConfig, Error, Identity, PublicProfile, RepoView, describe_identity, is_claimed,
25 resolve_actor,
26 },
27 domain::{Actor, DomainError, PrivateTargets, SessionTokenHash},
28 infrastructure::{
29 cat_file::CatFilePool,
30 disk::WalkingDiskUsage,
31 git::{DiskGitArchive, DiskGitMerge, DiskGitStorage, GitFeatures, GitHttpBackend},
32 git_query::DiskGitQuery,
33 highlight::HighlightCache,
34 mail::LettreMailer,
35 merge_cache::MergeCache,
36 repository::{
37 SqliteInstanceSettingsRepo, SqliteIssueRepo, SqliteLabelRepo, SqliteMembershipRepo,
38 SqliteOrgRepo, SqlitePasswordResetRepo, SqlitePullRequestRepo, SqlitePushEventRepo,
39 SqliteRepoRepo, SqliteSessionRepo, SqliteTokenRepo, SqliteUserRepo,
40 SqliteWebhookDeliveryRepo, SqliteWebhookRepo,
41 },
42 webhook::UreqWebhookSender,
43 },
44};
45
46/// The one-time token that authorises claiming an unclaimed instance.
47///
48/// Present in app context only while the installation is unclaimed.
49pub struct SetupState(pub crate::domain::SetupToken);
50
51pub fn pool(cx: &Cx) -> &SqlitePool {
52 app_context::<SqlitePool>(cx)
53}
54
55/// Anything below the web layer failing is a 500 — the visitor can't act on it, and
56/// the detail belongs in the log rather than the page.
57pub fn server_error<E>(error: E) -> topcoat::Error
58where
59 E: std::error::Error + Send + Sync + 'static,
60{
61 eprintln!("steid: {error}");
62 internal_server_error(error).into()
63}
64
65/// Whether a use case failed because git was too slow rather than because git broke.
66///
67/// A timeout is the one read failure that is not a fault: the repository is fine and the
68/// request asked more of it than one page's budget allows. A page that can say so
69/// renders a state of its own — in its own words, offering whatever costs less — rather
70/// than a 500 that claims the instance is broken.
71///
72/// Four pages wanted this within one wave (`refs`, `commit`, `blame`, and `search`
73/// before it moved), which is what it took to earn a home here. `search_repo` is the
74/// exception and stays as it is: it answers `Searched::TimedOut` in the application
75/// layer, because there the timeout is one of several results the same form re-renders
76/// rather than an error to be caught.
77pub fn timed_out(error: &Error) -> bool {
78 matches!(error, Error::GitQuery(query) if query.is_timeout())
79}
80
81pub fn orgs(cx: &Cx) -> SqliteOrgRepo {
82 SqliteOrgRepo::new(pool(cx).clone())
83}
84
85/// The instance's own settings — one row, which says where the root URL lands.
86pub fn instance_settings(cx: &Cx) -> SqliteInstanceSettingsRepo {
87 SqliteInstanceSettingsRepo::new(pool(cx).clone())
88}
89
90pub fn memberships(cx: &Cx) -> SqliteMembershipRepo {
91 SqliteMembershipRepo::new(pool(cx).clone())
92}
93
94pub fn repos(cx: &Cx) -> SqliteRepoRepo {
95 SqliteRepoRepo::new(pool(cx).clone())
96}
97
98/// How much disk the instance is using.
99///
100/// A borrow, not a clone, and the one accessor here that is: it holds the cache, and a
101/// per-request copy would share the `Arc` but there is nothing to be gained by building
102/// the wrapper again. Absent from the context is not a state Steid builds, so this
103/// panics like every other `app_context` reader.
104pub fn disk_usage(cx: &Cx) -> &WalkingDiskUsage {
105 app_context::<WalkingDiskUsage>(cx)
106}
107
108/// Bare repositories on disk, rooted at the configured data directory.
109pub fn storage(cx: &Cx) -> DiskGitStorage {
110 DiskGitStorage::new(app_context::<AppConfig>(cx).data_dir.clone())
111}
112
113pub fn users(cx: &Cx) -> SqliteUserRepo {
114 SqliteUserRepo::new(pool(cx).clone())
115}
116
117pub fn tokens(cx: &Cx) -> SqliteTokenRepo {
118 SqliteTokenRepo::new(pool(cx).clone())
119}
120
121/// Session records, for the pages that end them rather than merely read one.
122///
123/// [`current_actor`] builds its own; this is for the password paths, which sign other
124/// devices out and so need the repository itself rather than the actor behind it.
125pub fn sessions(cx: &Cx) -> SqliteSessionRepo {
126 SqliteSessionRepo::new(pool(cx).clone())
127}
128
129/// One-shot password reset links.
130pub fn resets(cx: &Cx) -> SqlitePasswordResetRepo {
131 SqlitePasswordResetRepo::new(pool(cx).clone())
132}
133
134/// Outgoing mail.
135///
136/// Constructed per request like every repository here. It cannot fail at this point:
137/// `main` builds one at boot from the same configuration and refuses to start if the
138/// configuration is unusable, so anything that gets this far parses — and an
139/// unconfigured instance yields a mailer that says `configured()` is false, which is a
140/// state and not a fault.
141pub fn mailer(cx: &Cx) -> LettreMailer {
142 LettreMailer::from_config(app_context::<AppConfig>(cx)).unwrap_or_else(|error| {
143 // Unreachable in a process that booted. Said out loud rather than silently
144 // becoming an instance that cannot mail, because that is the failure that would
145 // otherwise look like configuration nobody set.
146 eprintln!("steid: the mail configuration stopped being usable: {error}");
147 LettreMailer::unusable()
148 })
149}
150
151pub fn issues(cx: &Cx) -> SqliteIssueRepo {
152 SqliteIssueRepo::new(pool(cx).clone())
153}
154
155/// Labels, and which issues carry them.
156pub fn labels(cx: &Cx) -> SqliteLabelRepo {
157 SqliteLabelRepo::new(pool(cx).clone())
158}
159
160/// Pull requests, and their comments.
161pub fn pulls(cx: &Cx) -> SqlitePullRequestRepo {
162 SqlitePullRequestRepo::new(pool(cx).clone())
163}
164
165/// Writing a merge into a bare repository, rooted at the same data directory as
166/// [`storage`].
167///
168/// Separate from [`storage`] because merging is a different git family — see
169/// [`GitMerge`](crate::application::port::GitMerge).
170pub fn merges(cx: &Cx) -> DiskGitMerge {
171 DiskGitMerge::new(app_context::<AppConfig>(cx).data_dir.clone())
172}
173
174/// What this server's `git` can do, read once at boot.
175///
176/// Out of app context rather than detected per request: it is one `git --version` per
177/// process, and asking on every page that draws a merge box would be a subprocess spent
178/// re-learning something that cannot change while the process runs.
179///
180/// Absent only in a context built without it, which is no context Steid builds — the
181/// default reports no capabilities, so a merge box would say the server cannot merge
182/// rather than offering a button that fails.
183pub fn git_features(cx: &Cx) -> GitFeatures {
184 topcoat::context::try_app_context::<GitFeatures>(cx)
185 .copied()
186 .unwrap_or_default()
187}
188
189/// Push events — one row per ref an authorized push moved.
190pub fn push_events(cx: &Cx) -> SqlitePushEventRepo {
191 SqlitePushEventRepo::new(pool(cx).clone())
192}
193
194pub fn webhooks(cx: &Cx) -> SqliteWebhookRepo {
195 SqliteWebhookRepo::new(pool(cx).clone())
196}
197
198pub fn deliveries(cx: &Cx) -> SqliteWebhookDeliveryRepo {
199 SqliteWebhookDeliveryRepo::new(pool(cx).clone())
200}
201
202/// Outbound webhook delivery.
203///
204/// Stateless apart from the one policy it carries, so it is constructed per request like
205/// every repository here rather than living in app context.
206pub fn webhook_sender(cx: &Cx) -> UreqWebhookSender {
207 UreqWebhookSender::new(private_targets(cx))
208}
209
210/// Whether this instance will deliver to its own network.
211///
212/// Read here rather than in each caller so that the two halves of the SSRF rule — the
213/// check when a hook is saved and the check on the resolved address before it is dialled
214/// — cannot end up reading different configuration. `Refused` unless
215/// `STEID_ALLOW_PRIVATE_WEBHOOKS` says otherwise; see
216/// [`AppConfig::allow_private_webhooks`].
217pub fn private_targets(cx: &Cx) -> PrivateTargets {
218 if app_context::<AppConfig>(cx).allow_private_webhooks {
219 PrivateTargets::Allowed
220 } else {
221 PrivateTargets::Refused
222 }
223}
224
225/// Repository contents, read from the same data directory as [`storage`].
226///
227/// Constructed per request like every adapter here, but handed the process pool out of
228/// app context rather than making one: the pool owns live `git cat-file` processes, and
229/// one built per request would spawn and kill a pair per request. See
230/// [`cat_file`](crate::infrastructure::cat_file).
231pub fn queries(cx: &Cx) -> DiskGitQuery {
232 DiskGitQuery::new(
233 app_context::<AppConfig>(cx).data_dir.clone(),
234 app_context::<Arc<CatFilePool>>(cx).clone(),
235 app_context::<Arc<MergeCache>>(cx).clone(),
236 )
237}
238
239/// Highlighted markup, remembered across requests.
240///
241/// Out of app context rather than constructed here, and the one adapter on this page
242/// that is: a cache built per request remembers nothing, which is the same reason the
243/// `cat-file` pool lives there. See [`highlight`](crate::infrastructure::highlight).
244pub fn highlights(cx: &Cx) -> &Arc<HighlightCache> {
245 app_context::<Arc<HighlightCache>>(cx)
246}
247
248/// `git archive`, rooted at the same data directory as [`storage`].
249pub fn archives(cx: &Cx) -> DiskGitArchive {
250 DiskGitArchive::new(app_context::<AppConfig>(cx).data_dir.clone())
251}
252
253/// The git smart-HTTP protocol, rooted at the same data directory as [`storage`].
254pub fn protocol(cx: &Cx) -> GitHttpBackend {
255 GitHttpBackend::new(app_context::<AppConfig>(cx).data_dir.clone())
256}
257
258/// Who is making this request.
259///
260/// Resolves to [`Actor::Anonymous`] when there is no session, the session is unknown,
261/// or it has expired.
262pub async fn current_actor(cx: &Cx) -> Result<Actor> {
263 let presented = session::token_hash(cx)
264 .await?
265 .map(|hash| SessionTokenHash::from_trusted(hex(&hash)));
266
267 let sessions = SqliteSessionRepo::new(pool(cx).clone());
268
269 resolve_actor(presented.as_ref(), SystemTime::now(), &sessions)
270 .await
271 .map_err(server_error)
272}
273
274/// Who the current actor actually is, resolved for display.
275///
276/// `None` when anonymous, or when the session outlived the user it names.
277pub async fn identity(cx: &Cx) -> Result<Option<Identity>> {
278 let actor = current_actor(cx).await?;
279 let pool = pool(cx).clone();
280
281 describe_identity(
282 &actor,
283 &SqliteUserRepo::new(pool.clone()),
284 &SqliteOrgRepo::new(pool),
285 )
286 .await
287 .map_err(server_error)
288}
289
290/// Whether this installation has an owner yet.
291pub async fn claimed(cx: &Cx) -> Result<bool> {
292 let users = SqliteUserRepo::new(pool(cx).clone());
293
294 is_claimed(&users).await.map_err(server_error)
295}
296
297/// The setup token, when the instance is still unclaimed.
298pub fn setup_token(cx: &Cx) -> Option<&crate::domain::SetupToken> {
299 topcoat::context::try_app_context::<SetupState>(cx).map(|state| &state.0)
300}
301
302/// The `Location` header for a post-redirect-get reply.
303///
304/// Pair it with `StatusCode::SEE_OTHER` inside a `view!` to redirect from a page that
305/// otherwise renders a view:
306///
307/// ```ignore
308/// view! { (StatusCode::SEE_OTHER) (location("/somewhere")?) }
309/// ```
310///
311/// The awkward-looking route to a 303: `redirect()` is a **307**, which preserves the
312/// method, so a browser re-POSTs the form to its target instead of fetching it.
313/// `see_other()` is the right status but is a response type, and `#[page]` handlers
314/// must return a view so the layout can wrap the failure re-render. Setting the status
315/// and header inside `view!` is the documented way to get both from one handler.
316pub fn location(uri: &str) -> Result<(HeaderName, HeaderValue)> {
317 Ok((LOCATION, HeaderValue::try_from(uri).map_err(server_error)?))
318}
319
320/// The origin this instance is being reached on, e.g. `https://steid.example`.
321///
322/// Derived from the request rather than configured, so an instance is deployable
323/// anywhere without being told its own address — behind a proxy, on a platform
324/// subdomain, or on localhost, all with no configuration.
325///
326/// The scheme comes from `X-Forwarded-Proto` when a proxy sets it, since TLS is
327/// terminated in front of us and the request that arrives here is plain HTTP. Falling
328/// back to `http` is right for local development and wrong nowhere that matters: a
329/// deployment without a terminating proxy has no TLS to advertise anyway.
330pub fn public_origin(cx: &Cx) -> String {
331 let headers = headers(cx);
332 let value = |name: &str| headers.get(name).and_then(|value| value.to_str().ok());
333
334 let scheme = value("x-forwarded-proto").unwrap_or("http");
335 let host = headers
336 .get(HOST)
337 .and_then(|value| value.to_str().ok())
338 .unwrap_or("localhost");
339
340 format!("{scheme}://{host}")
341}
342
343/// Renders a `TokenHash` as lowercase hex for storage.
344pub fn hex(hash: &session::TokenHash) -> String {
345 hash.iter().map(|byte| format!("{byte:02x}")).collect()
346}
347
348/// The repository in the path, refused for anyone who does not own it.
349///
350/// [`repo_for`](super::repo::repo_for) already 404s a repository the viewer may not
351/// see; this adds the stronger half, and answers **404 rather than 403** — a 403 on a
352/// repository somebody cannot see would confirm it exists, and an owner-only page that
353/// answered differently to a stranger than to a passer-by would leak the same fact by
354/// its status code alone.
355///
356/// The use cases decide this too. The guard only keeps a page from rendering for
357/// someone whose submission would be refused a moment later; it is not the
358/// authorization.
359///
360/// Written out identically in five page modules before it landed here, with three more
361/// inline copies on profiles — see [`owned_profile`].
362pub async fn owned_repo(cx: &Cx) -> Result<RepoView> {
363 let repo = super::repo::repo_for(cx).await?;
364
365 if !repo.viewer_is_owner {
366 return Err(not_found().into());
367 }
368
369 Ok(repo)
370}
371
372/// Whether the viewer owns the **instance**, as opposed to the thing in the path.
373///
374/// [`owned_repo`]'s question two levels up, and the only way a page asks it. The rule
375/// itself is [`application::instance_owner`](crate::application::instance_owner) — what
376/// "the instance's owner" means is a milestone 7 decision, and a page that compared
377/// against the sole user itself would have to be found and changed when it moves.
378///
379/// A `bool` rather than a guard, because the two callers want different things from the
380/// same answer: `/{handle}/settings` draws or omits its Backup section, and
381/// `/{handle}/settings/backup.tar.gz` turns a `false` into a 404. Neither is *the*
382/// authorization — `back_up_for` re-checks before it writes a byte, and it is that
383/// answer which counts. This one keeps a page from offering something whose submission
384/// would be refused a moment later.
385pub async fn instance_owner(cx: &Cx) -> Result<bool> {
386 crate::application::instance_owner(&current_actor(cx).await?, &users(cx))
387 .await
388 .map_err(server_error)
389}
390
391/// The profile in the path, refused for anyone but its owner.
392///
393/// [`owned_repo`]'s rule one level up, for `/{handle}/settings` and the pages under it.
394/// The same 404: whether a handle has settings is not a stranger's business, and the
395/// profile pages used to answer 403 here while every repository page answered 404.
396pub async fn owned_profile(cx: &Cx) -> Result<PublicProfile> {
397 let profile = super::profile::profile_for(cx).await?;
398
399 if !profile.viewer_is_owner {
400 return Err(not_found().into());
401 }
402
403 Ok(profile)
404}
405
406/// Turns a use case failure into either a message to re-render with, or a response.
407///
408/// The shape every form in Steid wants: validation is the visitor's to fix, so it is
409/// shown beside what they typed; anything about authorization is a page they should
410/// not have reached, so it is a status code.
411///
412/// `Forbidden` reaching here means the actor lost ownership between the guard and the
413/// write, and `NotFound` that the thing being edited went away. Both answer **404**,
414/// the same answer [`owned_repo`] gives, because by this point the two are
415/// indistinguishable to whoever is asking and a 403 would confirm the target exists.
416/// Three near-copies of this lived in `issues`, `labels` and `pulls` and disagreed on
417/// exactly that arm; a fourth in `webhook` was spelled `explain`.
418///
419/// A page with more to say layers its own arms *before* calling this — see
420/// `pulls::merge_failure`, which turns an archived repository and a stale merge into
421/// sentences rather than statuses.
422pub fn write_failure(error: Error) -> std::result::Result<String, topcoat::Error> {
423 match error {
424 Error::Domain(DomainError::Validation { field, reason }) => {
425 Ok(format!("That {field} is no good: {reason}."))
426 }
427 Error::Domain(DomainError::Forbidden | DomainError::NotFound { .. }) => {
428 Err(not_found().into())
429 }
430 // Ours, so it is logged and answered generically.
431 other => Err(server_error(std::io::Error::other(other.to_string()))),
432 }
433}
434
435#[cfg(test)]
436mod tests {
437 use topcoat::router::error::{InternalServerError, NotFoundError};
438
439 use super::*;
440
441 /// The status a `topcoat::Error` will answer with.
442 ///
443 /// Asserted by downcasting rather than by rendering: `into_response` wants a `Cx`,
444 /// and a request context is not something a unit test has.
445 fn is_not_found(error: topcoat::Error) -> bool {
446 error.downcast::<NotFoundError>().is_ok()
447 }
448
449 #[test]
450 fn a_validation_failure_becomes_a_sentence_the_form_can_show() {
451 let message = write_failure(Error::Domain(DomainError::Validation {
452 field: "title".to_owned(),
453 reason: "it is empty".to_owned(),
454 }));
455
456 assert_eq!(
457 message.expect("a message"),
458 "That title is no good: it is empty."
459 );
460 }
461
462 #[test]
463 fn losing_ownership_mid_write_is_a_404_rather_than_a_403() {
464 // The 403 three of the four copies used to give would confirm that the thing
465 // being written to exists, which the guard's 404 was careful not to.
466 let error = write_failure(Error::Domain(DomainError::Forbidden)).expect_err("a response");
467
468 assert!(is_not_found(error));
469 }
470
471 #[test]
472 fn a_target_that_went_away_is_the_same_404() {
473 let error = write_failure(Error::Domain(DomainError::NotFound { entity: "issue" }))
474 .expect_err("a response");
475
476 assert!(is_not_found(error));
477 }
478
479 #[test]
480 fn anything_else_is_ours_and_is_a_500() {
481 // Archived is a sentence on the pull request pages, which layer that arm before
482 // calling this. Anywhere else it is a case nobody handled, and a 500 says so.
483 let error = write_failure(Error::Domain(DomainError::Archived)).expect_err("a response");
484
485 assert!(error.downcast::<InternalServerError>().is_ok());
486 }
487}