steid

@jamesgill /

1//! First-run claim and sign-in.
2
3use serde::Deserialize;
4use topcoat::{
5 Result,
6 context::Cx,
7 router::{
8 IntoResponse, Response,
9 content::Form,
10 error::{redirect, see_other},
11 page, query_params, route,
12 },
13 session,
14 view::view,
15};
16
17use crate::{
18 application::{Error, OwnerSpec, claim_instance, end_session, login, record_session},
19 components::flash::{FlashKind, flash},
20 domain::{Actor, DomainError, Password},
21 infrastructure::{
22 password::Argon2Hasher,
23 repository::{SqliteMembershipRepo, SqliteOrgRepo, SqliteSessionRepo, SqliteUserRepo},
24 },
25};
26
27use super::{
28 context::{claimed, hex, pool, setup_token},
29 csrf::{CsrfGuard, csrf_verified_response},
30 layout::narrow,
31 rate_limit::throttled,
32};
33
34#[derive(Debug, Deserialize)]
35struct ClaimForm {
36 token: String,
37 handle: String,
38 email: String,
39 password: String,
40}
41
42#[derive(Debug, Deserialize)]
43struct LoginForm {
44 email: String,
45 password: String,
46}
47
48/// Why the last claim was refused, when it was for a reason worth saying out loud.
49///
50/// Only the password rule travels back: a wrong setup token and an already-claimed
51/// instance stay silent, because saying which one it was tells a stranger something
52/// about a secret they are guessing.
53#[query_params(error = bad_request)]
54struct Refused {
55 error: Option<String>,
56}
57
58#[page("/auth/setup")]
59async fn setup_page(cx: &Cx) -> Result {
60 if claimed(cx).await? {
61 return Err(redirect("/").into());
62 }
63
64 let refused = matches!(
65 query_params::<Refused>(cx)?.error.as_deref(),
66 Some("password")
67 );
68
69 view! {
70 narrow(
71 <h1>"Claim this instance"</h1>
72 <p>"The setup token was printed to the server log at startup."</p>
73
74 if refused {
75 <div class="mb-4">flash(kind: FlashKind::Error, (Password::RULE))</div>
76 }
77
78 <form method="post" action="/auth/setup">
79 <p><label>"Setup token " <input type="text" name="token" required="true" /></label></p>
80 <p><label>"Handle " <input type="text" name="handle" required="true" /></label></p>
81 <p><label>"Email " <input type="email" name="email" required="true" /></label></p>
82 <p><label>"Password " <input type="password" name="password" required="true" /></label></p>
83 <p class="text-xs text-muted-foreground">(Password::RULE)</p>
84 <button type="submit">"Claim"</button>
85 </form>
86 )
87 }
88}
89
90/// Claims the instance.
91///
92/// Rate limited before anything else happens: the setup token is the only thing
93/// standing between a stranger and ownership of an unclaimed instance, and unlike a
94/// personal access token it may have been chosen by a person.
95#[route(POST "/auth/setup")]
96async fn claim(cx: &Cx, Form(form): Form<ClaimForm>) -> Result<Response> {
97 if let Some(response) = throttled(cx) {
98 return Ok(response);
99 }
100
101 // Absent once claimed, so a claimed instance cannot be re-claimed even if the
102 // use case were somehow reached. 303 rather than `redirect`'s 307 for the same
103 // reason as the refusal below: a 307 re-POSTs the claim, to `/` this time.
104 let Some(token) = setup_token(cx) else {
105 return see_other("/").into_response(cx);
106 };
107
108 let pool = pool(cx).clone();
109 let users = SqliteUserRepo::new(pool.clone());
110 let orgs = SqliteOrgRepo::new(pool.clone());
111 let memberships = SqliteMembershipRepo::new(pool.clone());
112 let sessions = SqliteSessionRepo::new(pool);
113
114 let claimed = claim_instance(
115 &form.token,
116 token,
117 &OwnerSpec {
118 handle: form.handle,
119 email: form.email,
120 password: form.password,
121 },
122 &users,
123 &orgs,
124 &memberships,
125 &Argon2Hasher::new(),
126 )
127 .await;
128
129 let actor = match claimed {
130 Ok(actor) => actor,
131 Err(error) => {
132 eprintln!("steid: claim rejected: {error}");
133
134 // The password rule is not a secret and a form that refuses without saying
135 // why is unusable; everything else — a wrong token, an instance already
136 // claimed — goes back to a bare form, so the refusal is not an oracle.
137 let back = if matches!(
138 error,
139 Error::Domain(DomainError::Validation { ref field, .. }) if field == "password"
140 ) {
141 "/auth/setup?error=password"
142 } else {
143 "/auth/setup"
144 };
145
146 // 303, not `redirect`'s 307: a 307 preserves the method, so the browser
147 // would re-POST the claim to the target and refuse it again, forever.
148 return see_other(back).into_response(cx);
149 }
150 };
151
152 sign_in(cx, &actor, &sessions).await?;
153
154 see_other("/").into_response(cx)
155}
156
157/// Set by a completed password reset, which ends every session and so has nowhere to
158/// send anyone but here.
159#[query_params(error = bad_request)]
160struct Reset {
161 reset: Option<String>,
162}
163
164#[page("/auth/login")]
165async fn login_page(cx: &Cx) -> Result {
166 if !claimed(cx).await? {
167 return Err(redirect("/auth/setup").into());
168 }
169
170 let after_reset = query_params::<Reset>(cx)?.reset.is_some();
171
172 view! {
173 narrow(
174 <h1>"Sign in"</h1>
175
176 if after_reset {
177 <div class="mb-4">
178 flash(kind: FlashKind::Success, "Password changed. Sign in with the new one.")
179 </div>
180 }
181
182 <form method="post" action="/auth/login">
183 <p><label>"Email " <input type="email" name="email" required="true" /></label></p>
184 <p><label>"Password " <input type="password" name="password" required="true" /></label></p>
185 <button type="submit">"Sign in"</button>
186 </form>
187 <p class="mt-4 text-xs text-muted-foreground">
188 <a href="/auth/forgot" class="hover:text-foreground">"Forgotten your password?"</a>
189 </p>
190 )
191 }
192}
193
194/// Signs in.
195///
196/// Rate limited first, before the password is hashed: a human-chosen password is the
197/// one secret here that guessing can reach, and Argon2 is deliberately expensive
198/// enough that an unlimited endpoint is also a way to burn the server's CPU.
199#[route(POST "/auth/login")]
200async fn sign_in_route(cx: &Cx, Form(form): Form<LoginForm>) -> Result<Response> {
201 if let Some(response) = throttled(cx) {
202 return Ok(response);
203 }
204
205 let pool = pool(cx).clone();
206 let users = SqliteUserRepo::new(pool.clone());
207 let sessions = SqliteSessionRepo::new(pool);
208
209 let actor = match login(&form.email, &form.password, &users, &Argon2Hasher::new()).await {
210 Ok(actor) => actor,
211 Err(error) => {
212 eprintln!("steid: login rejected: {error}");
213
214 // 303, not `redirect`'s 307, for the same reason the refused claim above
215 // is: a 307 preserves the method, so the browser re-POSTs the credentials
216 // to the login page and is refused again, forever.
217 return see_other("/auth/login").into_response(cx);
218 }
219 };
220
221 sign_in(cx, &actor, &sessions).await?;
222
223 see_other("/").into_response(cx)
224}
225
226#[route(POST "/auth/logout")]
227async fn logout(cx: &Cx, Form(guard): Form<CsrfGuard>) -> Result<Response> {
228 if let Some(response) = csrf_verified_response(cx, &guard.csrf_token).await? {
229 return Ok(response);
230 }
231
232 // Both halves: the client discards its token, and the record goes. Doing only the
233 // first leaves the session valid server-side.
234 if let Some(hash) = session::stop(cx).await? {
235 let sessions = SqliteSessionRepo::new(pool(cx).clone());
236 end_session(
237 &crate::domain::SessionTokenHash::from_trusted(hex(&hash)),
238 &sessions,
239 )
240 .await
241 .map_err(topcoat::Error::from)?;
242 }
243
244 see_other("/").into_response(cx)
245}
246
247/// Issues a session for an authenticated actor and records it.
248async fn sign_in(cx: &Cx, actor: &Actor, sessions: &SqliteSessionRepo) -> Result<()> {
249 let Some(user_id) = actor.user_id() else {
250 return Ok(());
251 };
252
253 let session = session::start(cx).await?;
254
255 record_session(
256 crate::domain::SessionTokenHash::from_trusted(hex(&session.token_hash)),
257 user_id.clone(),
258 session.expires_at,
259 sessions,
260 )
261 .await
262 .map_err(topcoat::Error::from)?;
263
264 Ok(())
265}