steid

@jamesgill /

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