forge
Explore
Log in

Don't you dare go Hollow

im_old

Clone
★ 0

0 watching0 forksRustGPL-3.0755.6 KiB84318dcTahinli2 months ago77 commits

server.rs361 lines, 13.7 KiBHistoryRawDownload
1//! Shared request plumbing: the app context, the two cookies (`im_session`
2//! for a completed login, `im_pending` for the ten minutes between password
3//! and second factor), and the refusal codes a redirect carries back to the
4//! page that posted the form.
5//!
6//! Every form post answers a plain 303 whose query names the refusal, and
7//! the page reads it back on render. The soft-nav script replays posts over
8//! fetch with `accept: text/html`, so the 303's target document is what
9//! comes back — no refusal-carrying layer as in İzlek is needed.
10
11use std::collections::HashMap;
12use std::sync::{Arc, LazyLock, Mutex, PoisonError};
13use std::time::{Duration, Instant};
14
15use im_core::model::User;
16use im_core::store::Store;
17use topcoat::context::{Cx, try_app_context};
18use topcoat::cookie::{Cookie, Cookies, cookie, cookies};
19use topcoat::router::request::client_ip;
20
21use crate::config::Config;
22
23pub const SESSION_COOKIE: &str = "im_session";
24pub const PENDING_COOKIE: &str = "im_pending";
25
26/// The pending marker's lifetime: long enough to find the authenticator,
27/// short enough to not be a session.
28pub const PENDING_MINUTES: i64 = 10;
29
30/// One proxy hop in front of the process. `im` is reached through that hop,
31/// so `client_ip` reads the address it appended rather than the hop's own.
32/// A direct connection, with no hop in front, is its own address.
33pub fn trusted_proxies() -> topcoat::router::TrustedProxies {
34 topcoat::router::TrustedProxies::new().nearest(1)
35}
36
37/// A stable-enough label for the client.
38///
39/// [`client_ip`] under [`trusted_proxies`]: the address the one trusted hop
40/// reported, or the peer when the request did not come through it. `unknown`
41/// when neither is there. A client-supplied `x-forwarded-for` is not read
42/// unless that hop appended it.
43pub fn client_label(cx: &Cx) -> String {
44 client_ip(cx)
45 .map(|ip| ip.to_string())
46 .unwrap_or_else(|| "unknown".to_string())
47}
48
49pub struct App {
50 pub store: Arc<Store>,
51 pub config: Config,
52 /// The live channel: any mutation announces itself here, and every open
53 /// tab re-reads what it is showing. A `Tick` says "re-fetch", nothing
54 /// more — never a row, never a name. A `Profile` carries the full
55 /// directory row of the one member whose row changed, for the app-facing
56 /// `/directory/live` stream.
57 pub live: tokio::sync::broadcast::Sender<LiveEvent>,
58}
59
60/// What travels the live channel. `Tick` is the panel's "something moved —
61/// re-read"; `Profile` is the directory's own news: this member's row, as it
62/// now stands, serialized exactly as `/directory` would have answered it;
63/// `Revoked` is a sign-out in motion: this user's session(s) just died, the
64/// one named by hash when the revocation was session-targeted.
65#[derive(Clone, Debug)]
66pub enum LiveEvent {
67 Tick,
68 Profile(crate::directory::DirectoryMember),
69 Revoked {
70 user_id: String,
71 session_hash: Option<String>,
72 },
73}
74
75/// Announce that the panel's data moved. Sends are lossy on purpose: nobody
76/// listening is not an error, and a lagging tab gets a resync tick.
77pub fn note(cx: &Cx) {
78 let _ = app(cx).live.send(LiveEvent::Tick);
79}
80
81/// Announce that one member's row changed. Re-reads the row — the callers
82/// hold the pre-write copy — and broadcasts it as the member `/directory`
83/// would answer. A row that no longer resolves (deleted) has no member to
84/// announce; the next full pass is where a removal surfaces.
85pub async fn notify_profile(cx: &Cx, user_id: &im_core::model::UserId) {
86 let Ok(Some(user)) = im_core::accounts::user_by_id(&app(cx).store, user_id).await else {
87 return;
88 };
89 let _ = app(cx).live.send(LiveEvent::Profile(
90 crate::directory::DirectoryMember::of(&user),
91 ));
92}
93
94/// Announce that `user`'s sessions died — one of them when `session_hash`
95/// names a session, all of them when it does not. Every write path that ends
96/// sessions speaks here, so the dead sessions' open tabs hear their own
97/// eviction on the live channel and leave without waiting out the stream
98/// window. Sent right after the write commits and before the tick, so a
99/// connection that swallows the tick has already missed nothing.
100pub async fn note_revoked(cx: &Cx, user_id: &str, session_hash: Option<&str>) {
101 let _ = app(cx).live.send(LiveEvent::Revoked {
102 user_id: user_id.to_string(),
103 session_hash: session_hash.map(str::to_string),
104 });
105}
106
107/// Log the event, then tick the live channel — the two travel together so
108/// the Logs page (and any watching panel) catches up without a reload.
109pub async fn log_event(cx: &Cx, kind: &str, actor: Option<&str>, detail: Option<&str>) {
110 im_core::events::log(&app(cx).store, kind, actor, detail).await;
111 note(cx);
112}
113
114// ---------------------------------------------------------------------------
115// The show-once shelf
116// ---------------------------------------------------------------------------
117
118/// How long a stashed secret waits for its one reader.
119const SHOWN_TTL: Duration = Duration::from_secs(10 * 60);
120
121/// Where a freshly minted client secret waits between its POST and the one
122/// GET that shows it. The panel's write answers a 303 — the house idiom —
123/// but the secret itself must never ride a URL or a log line, so the query
124/// carries only a random claim ticket: the shelf holds the plaintext, the
125/// page's read takes it out (`take_shown_secret`), and a replayed or
126/// reloaded URL finds the shelf empty and renders no secret at all. A
127/// restart drops the shelf — the admin mints another, as with the CLI.
128type ShownShelf = HashMap<String, ((String, String), Instant)>;
129static SHOWN_SECRETS: LazyLock<Mutex<ShownShelf>> = LazyLock::new(|| Mutex::new(HashMap::new()));
130
131/// Parks a client's fresh pair on the shelf and returns the claim ticket
132/// for its URL. The id travels too — it is the public half of the pair and
133/// the one render shows it beside the secret.
134pub fn stash_shown_secret(client_id: String, secret: String) -> String {
135 let ticket = im_core::accounts::Token::mint().expose().to_string();
136 let mut shelf = SHOWN_SECRETS.lock().unwrap_or_else(PoisonError::into_inner);
137 shelf.retain(|_, (_, parked)| parked.elapsed() < SHOWN_TTL);
138 shelf.insert(ticket.clone(), ((client_id, secret), Instant::now()));
139 ticket
140}
141
142/// Takes a stashed pair out — exactly once; the second reader of the same
143/// ticket gets nothing.
144pub fn take_shown_secret(ticket: &str) -> Option<(String, String)> {
145 SHOWN_SECRETS
146 .lock()
147 .unwrap_or_else(PoisonError::into_inner)
148 .remove(ticket)
149 .map(|(pair, _)| pair)
150}
151
152pub fn app(cx: &Cx) -> &App {
153 try_app_context::<App>(cx).expect("the router always carries the App")
154}
155
156/// The application cookie jar, with the attributes every im cookie wants.
157fn app_cookies(cx: &Cx) -> impl Cookies {
158 cookies(cx)
159 .default_secure(app(cx).config.is_secure())
160 .default_http_only(true)
161 .default_same_site(topcoat::cookie::SameSite::Lax)
162 .default_path("/")
163}
164
165/// The session cookie value this request presented, if it presented one.
166pub fn presented_session(cx: &Cx) -> Option<String> {
167 cookies(cx)
168 .get(SESSION_COOKIE)
169 .map(|c| c.value().to_string())
170}
171
172pub fn presented_pending(cx: &Cx) -> Option<String> {
173 cookies(cx)
174 .get(PENDING_COOKIE)
175 .map(|c| c.value().to_string())
176}
177
178/// Writes the session cookie. `HttpOnly` so script cannot read it, `Secure`
179/// (on https issuers) so it never crosses plain HTTP, `SameSite=Lax` so
180/// another site's form cannot post with it — and so the top-level redirect
181/// back from `/authorize` still carries it.
182pub fn set_session_cookie(cx: &Cx, token: &str) {
183 app_cookies(cx).add(cookie! {
184 SESSION_COOKIE = token.to_owned();
185 Path = "/";
186 HttpOnly;
187 SameSite = Lax;
188 MaxAge = time::Duration::days(im_core::sessions::SESSION_DAYS)
189 });
190}
191
192pub async fn set_pending_cookie(cx: &Cx, sealed: String) {
193 let minutes = im_core::settings::pending_minutes(&app(cx).store)
194 .await
195 .unwrap_or(PENDING_MINUTES);
196 app_cookies(cx).add(cookie! {
197 PENDING_COOKIE = sealed;
198 Path = "/";
199 HttpOnly;
200 SameSite = Lax;
201 MaxAge = time::Duration::minutes(minutes)
202 });
203}
204
205/// Removes the session cookie from this browser. The server-side revocation
206/// is what actually ends the session; this only tidies the client.
207pub fn clear_session_cookie(cx: &Cx) {
208 app_cookies(cx).remove(Cookie::build((SESSION_COOKIE, "")).path("/").build());
209}
210
211pub fn clear_pending_cookie(cx: &Cx) {
212 app_cookies(cx).remove(Cookie::build((PENDING_COOKIE, "")).path("/").build());
213}
214
215/// The person behind this request, resolved through the central session.
216pub async fn current_user(cx: &Cx) -> Option<User> {
217 let token = presented_session(cx)?;
218 im_core::sessions::resolve_session(&app(cx).store, &token)
219 .await
220 .ok()
221 .flatten()
222}
223
224// ---------------------------------------------------------------------------
225// The pending marker: between password and TOTP
226// ---------------------------------------------------------------------------
227
228#[derive(Debug, serde::Serialize, serde::Deserialize, PartialEq)]
229#[serde(rename_all = "lowercase")]
230pub enum PendingPurpose {
231 /// Password verified, TOTP code still owed.
232 Login,
233}
234
235#[derive(Debug, serde::Serialize, serde::Deserialize)]
236pub struct Pending {
237 pub user: String,
238 pub purpose: PendingPurpose,
239 /// The `/authorize` URL the login is in the middle of, urlencoded as it
240 /// arrived; `/` when there is none.
241 pub back: String,
242 pub exp: i64,
243}
244
245pub async fn mint_pending(
246 cx: &Cx,
247 user: &im_core::model::UserId,
248 purpose: PendingPurpose,
249 back: String,
250) -> String {
251 let minutes = im_core::settings::pending_minutes(&app(cx).store)
252 .await
253 .unwrap_or(PENDING_MINUTES);
254 let pending = Pending {
255 user: user.to_string(),
256 purpose,
257 back,
258 exp: time::OffsetDateTime::now_utc().unix_timestamp() + minutes * 60,
259 };
260 let json = serde_json::to_string(&pending).expect("Pending is plain data");
261 app(cx).store.seal_value(json.as_bytes())
262}
263
264/// Opens the pending cookie this request presented. `None` for absent,
265/// forged, or expired — all three mean "start the login over".
266pub fn opened_pending(cx: &Cx) -> Option<Pending> {
267 let sealed = presented_pending(cx)?;
268 let bytes = app(cx).store.open_value(&sealed)?;
269 let pending: Pending = serde_json::from_slice(&bytes).ok()?;
270 if pending.exp <= time::OffsetDateTime::now_utc().unix_timestamp() {
271 return None;
272 }
273 Some(pending)
274}
275
276/// Whether this request carries a registered OIDC app's credentials: HTTP
277/// Basic over `client_id:client_secret`, checked against the client
278/// registry. Anything unparseable, unknown, or wrong is simply false — the
279/// caller answers its one refusal and never says which.
280pub async fn valid_app(cx: &Cx) -> bool {
281 app_client(cx).await.is_some()
282}
283
284/// The same check, answering *which* app it is: the routes that write on a
285/// caller's behalf (`/family/register`) need the client id the pair
286/// authenticated, and the ones that only read do not.
287pub async fn app_client(cx: &Cx) -> Option<String> {
288 use base64::Engine as _;
289 use topcoat::router::{header, request::headers as request_headers};
290 let encoded = request_headers(cx)
291 .get(header::AUTHORIZATION)
292 .and_then(|value| value.to_str().ok())
293 .and_then(|value| value.strip_prefix("Basic "))?;
294 let decoded = base64::engine::general_purpose::STANDARD
295 .decode(encoded)
296 .ok()?;
297 let pair = std::str::from_utf8(&decoded).ok()?;
298 let (client_id, secret) = pair.split_once(':')?;
299 let store = app(cx).store.clone();
300 let client = im_core::oidc::client_by_id(&store, client_id)
301 .await
302 .ok()??;
303 im_core::oidc::verify_client_secret(&client, secret).then(|| client_id.to_string())
304}
305
306#[cfg(test)]
307mod client_label_tests {
308 use std::net::SocketAddr;
309
310 use topcoat::router::response::IntoResponse;
311 use topcoat::router::{
312 Body, Method, RemoteAddr, RouteFn, RouteFuture, Router, request::Request, to_bytes,
313 };
314
315 use super::{client_label, trusted_proxies};
316
317 fn echo(cx: &topcoat::context::Cx, _body: Body) -> RouteFuture<'_> {
318 Box::pin(async move { client_label(cx).into_response(cx) })
319 }
320
321 fn router(trust_one_hop: bool) -> Router {
322 let builder = Router::builder().route(RouteFn::new(Method::GET, "/label", echo));
323 if trust_one_hop {
324 builder.trusted_proxies(trusted_proxies()).build()
325 } else {
326 builder.build()
327 }
328 }
329
330 async fn label(trust_one_hop: bool, peer: &str, forwarded: Option<&str>) -> String {
331 let mut builder = Request::builder()
332 .method(Method::GET)
333 .uri("/label")
334 .extension(RemoteAddr(peer.parse::<SocketAddr>().unwrap()));
335 if let Some(value) = forwarded {
336 builder = builder.header("x-forwarded-for", value);
337 }
338 let response = router(trust_one_hop)
339 .handle(builder.body(Body::empty()).unwrap())
340 .await;
341 String::from_utf8(to_bytes(response.into_body(), 64).await.unwrap().to_vec()).unwrap()
342 }
343
344 #[tokio::test]
345 async fn one_trusted_hop_reports_the_client_not_the_proxy() {
346 let got = label(true, "10.0.0.1:4242", Some("198.51.100.1")).await;
347 assert_eq!(got, "198.51.100.1");
348 }
349
350 #[tokio::test]
351 async fn a_missing_header_falls_back_to_the_peer() {
352 let got = label(true, "203.0.113.9:4242", None).await;
353 assert_eq!(got, "203.0.113.9");
354 }
355
356 #[tokio::test]
357 async fn an_untrusted_peer_cannot_spoof_the_forwarded_header() {
358 let got = label(false, "203.0.113.9:4242", Some("198.51.100.1")).await;
359 assert_eq!(got, "203.0.113.9");
360 }
361}