forge
Explore
Log in

Don't you dare go Hollow

Sessions record their IP and open a detail page

Browse files at this commit

f579eed04e984fea98ac1c0dfbac4bd5f4e5afdcAhmet Kaan GümüşParent: aec2066
  • feat
    • sessions record their IP and open a detail page
Show full message
✨ feat: sessions record their IP and open a detail page
crates/forge-core/migrations/0066_session_ip.sqladded+6 -0
@@ -0,0 +1,6 @@
1+-- Sessions record the client IP. `ip` is the address the session signed in from, `last_ip` the one
2+-- of the most recent request. Both are NULL for sessions made before this migration. Applied by
3+-- store/migrate.rs.
4+
5+ALTER TABLE sessions ADD COLUMN ip TEXT;
6+ALTER TABLE sessions ADD COLUMN last_ip TEXT;
crates/forge-core/src/model.rsmodified+8 -0
@@ -120,6 +120,10 @@ pub struct Session {
120 pub expires_at: String,120 pub expires_at: String,
121 pub last_seen: String,121 pub last_seen: String,
122 pub user_agent: Option<String>,122 pub user_agent: Option<String>,
123+ /// The address the session signed in from.
124+ pub ip: Option<String>,
125+ /// The address of the most recent request.
126+ pub last_ip: Option<String>,
123 }127 }
124 128
125 const REDACTED: &str = "<redacted>";129 const REDACTED: &str = "<redacted>";
@@ -158,6 +162,8 @@ impl std::fmt::Debug for Session {
158 .field("expires_at", &self.expires_at)162 .field("expires_at", &self.expires_at)
159 .field("last_seen", &self.last_seen)163 .field("last_seen", &self.last_seen)
160 .field("user_agent", &self.user_agent)164 .field("user_agent", &self.user_agent)
165+ .field("ip", &self.ip)
166+ .field("last_ip", &self.last_ip)
161 .finish()167 .finish()
162 }168 }
163 }169 }
@@ -247,6 +253,8 @@ mod tests {
247 expires_at: "later".into(),253 expires_at: "later".into(),
248 last_seen: "now".into(),254 last_seen: "now".into(),
249 user_agent: None,255 user_agent: None,
256+ ip: None,
257+ last_ip: None,
250 };258 };
251 let dbg = format!("{user:?} {session:?}");259 let dbg = format!("{user:?} {session:?}");
252 assert!(dbg.contains("\"<redacted>\""));260 assert!(dbg.contains("\"<redacted>\""));
crates/forge-core/src/store/migrate.rsmodified+1 -0
@@ -105,6 +105,7 @@ pub const MIGRATIONS: &[(u32, &str)] = &[
105 (63, include_str!("../../migrations/0063_web_push.sql")),105 (63, include_str!("../../migrations/0063_web_push.sql")),
106 (64, include_str!("../../migrations/0064_merge_queue.sql")),106 (64, include_str!("../../migrations/0064_merge_queue.sql")),
107 (65, include_str!("../../migrations/0065_hue_colours.sql")),107 (65, include_str!("../../migrations/0065_hue_colours.sql")),
108+ (66, include_str!("../../migrations/0066_session_ip.sql")),
108 ];109 ];
109 110
110 /// The highest migration version this binary knows about.111 /// The highest migration version this binary knows about.
crates/forge-core/src/store/mod.rsmodified+18 -9
@@ -126,7 +126,8 @@ struct Inner {
126 const USER_COLS: &str = "id, username, email, password_hash, is_admin, created_at, about, timezone, \126 const USER_COLS: &str = "id, username, email, password_hash, is_admin, created_at, about, timezone, \
127 (SELECT hash FROM avatars WHERE avatars.user_id = users.id) AS avatar_hash, \127 (SELECT hash FROM avatars WHERE avatars.user_id = users.id) AS avatar_hash, \
128 theme, language, kind, email_notifications, display_name, accent, accent_dark, base_light, base_dark, sidebar_side";128 theme, language, kind, email_notifications, display_name, accent, accent_dark, base_light, base_dark, sidebar_side";
129-const SESSION_COLS: &str = "id, user_id, csrf_token, created_at, expires_at, last_seen, user_agent";129+const SESSION_COLS: &str =
130+ "id, user_id, csrf_token, created_at, expires_at, last_seen, user_agent, ip, last_ip";
130 const SSH_KEY_COLS: &str =131 const SSH_KEY_COLS: &str =
131 "id, user_id, title, algorithm, key_blob, fingerprint, created_at, last_used_at";132 "id, user_id, title, algorithm, key_blob, fingerprint, created_at, last_used_at";
132 const TOKEN_COLS: &str = "id, user_id, name, scopes, expires_at, created_at, last_used_at";133 const TOKEN_COLS: &str = "id, user_id, name, scopes, expires_at, created_at, last_used_at";
@@ -350,6 +351,7 @@ impl Store {
350 csrf_token: &str,351 csrf_token: &str,
351 expires_at: &str,352 expires_at: &str,
352 user_agent: Option<&str>,353 user_agent: Option<&str>,
354+ ip: Option<&str>,
353 ) -> Result<Session> {355 ) -> Result<Session> {
354 let now = now_stamp();356 let now = now_stamp();
355 let session = Session {357 let session = Session {
@@ -360,11 +362,13 @@ impl Store {
360 expires_at: expires_at.to_string(),362 expires_at: expires_at.to_string(),
361 last_seen: now.clone(),363 last_seen: now.clone(),
362 user_agent: user_agent.map(str::to_owned),364 user_agent: user_agent.map(str::to_owned),
365+ ip: ip.map(str::to_owned),
366+ last_ip: ip.map(str::to_owned),
363 };367 };
364 let conn = self.inner.conn.lock().await;368 let conn = self.inner.conn.lock().await;
365 conn.execute(369 conn.execute(
366- "INSERT INTO sessions (id, user_id, token_hash, csrf_token, created_at, expires_at, last_seen, user_agent) \370+ "INSERT INTO sessions (id, user_id, token_hash, csrf_token, created_at, expires_at, last_seen, user_agent, ip, last_ip) \
367- VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",371+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)",
368 (372 (
369 session.id.clone(),373 session.id.clone(),
370 session.user_id.clone(),374 session.user_id.clone(),
@@ -374,6 +378,8 @@ impl Store {
374 session.expires_at.clone(),378 session.expires_at.clone(),
375 now,379 now,
376 session.user_agent.clone(),380 session.user_agent.clone(),
381+ session.ip.clone(),
382+ session.last_ip.clone(),
377 ),383 ),
378 )384 )
379 .await385 .await
@@ -396,11 +402,12 @@ impl Store {
396 .await402 .await
397 }403 }
398 404
399- pub async fn touch_session(&self, id: &str) -> Result<()> {405+ /// Records a request: bumps `last_seen`, and `last_ip` when the request's address is known.
406+ pub async fn touch_session(&self, id: &str, ip: Option<&str>) -> Result<()> {
400 let conn = self.inner.conn.lock().await;407 let conn = self.inner.conn.lock().await;
401 conn.execute(408 conn.execute(
402- "UPDATE sessions SET last_seen = ?2 WHERE id = ?1",409+ "UPDATE sessions SET last_seen = ?2, last_ip = COALESCE(?3, last_ip) WHERE id = ?1",
403- (id.to_string(), now_stamp()),410+ (id.to_string(), now_stamp(), ip.map(str::to_owned)),
404 )411 )
405 .await412 .await
406 .map_err(db_err)?;413 .map_err(db_err)?;
@@ -1093,6 +1100,8 @@ fn map_session(row: &Row) -> Result<Session> {
1093 expires_at: col_text(row, 4)?,1100 expires_at: col_text(row, 4)?,
1094 last_seen: col_text(row, 5)?,1101 last_seen: col_text(row, 5)?,
1095 user_agent: col_opt_text(row, 6)?,1102 user_agent: col_opt_text(row, 6)?,
1103+ ip: col_opt_text(row, 7)?,
1104+ last_ip: col_opt_text(row, 8)?,
1096 })1105 })
1097 }1106 }
1098 1107
@@ -2580,15 +2589,15 @@ mod security_tests {
2580 // Scenario: deleting sessions except one keeps only the named session.2589 // Scenario: deleting sessions except one keeps only the named session.
2581 let expiry = crate::time::stamp_after(std::time::Duration::from_secs(3600));2590 let expiry = crate::time::stamp_after(std::time::Duration::from_secs(3600));
2582 let keep = store2591 let keep = store
2583- .create_session(&user.id, "h1", "c1", &expiry, None)2592+ .create_session(&user.id, "h1", "c1", &expiry, None, None)
2584 .await2593 .await
2585 .unwrap();2594 .unwrap();
2586 store2595 store
2587- .create_session(&user.id, "h2", "c2", &expiry, None)2596+ .create_session(&user.id, "h2", "c2", &expiry, None, None)
2588 .await2597 .await
2589 .unwrap();2598 .unwrap();
2590 store2599 store
2591- .create_session(&user.id, "h3", "c3", &expiry, None)2600+ .create_session(&user.id, "h3", "c3", &expiry, None, None)
2592 .await2601 .await
2593 .unwrap();2602 .unwrap();
2594 assert_eq!(2603 assert_eq!(
crates/forge-core/src/store/suspension.rsmodified+1 -1
@@ -213,7 +213,7 @@ mod tests {
213 213
214 // Scenario: suspending ends the user's sessions until it is lifted.214 // Scenario: suspending ends the user's sessions until it is lifted.
215 store215 store
216- .create_session(&other.id, "th", "csrf", "2999-01-01T00:00:00Z", None)216+ .create_session(&other.id, "th", "csrf", "2999-01-01T00:00:00Z", None, None)
217 .await217 .await
218 .unwrap();218 .unwrap();
219 assert!(store.session_by_token_hash("th").await.unwrap().is_some());219 assert!(store.session_by_token_hash("th").await.unwrap().is_some());
crates/forge-core/src/store/user_delete.rsmodified+1 -1
@@ -582,7 +582,7 @@ mod tests {
582 let fx = fixture().await;582 let fx = fixture().await;
583 let expiry = crate::time::stamp_after(std::time::Duration::from_secs(3600));583 let expiry = crate::time::stamp_after(std::time::Duration::from_secs(3600));
584 fx.store584 fx.store
585- .create_session(&fx.tahinli.id, "sess-hash", "csrf", &expiry, None)585+ .create_session(&fx.tahinli.id, "sess-hash", "csrf", &expiry, None, None)
586 .await586 .await
587 .unwrap();587 .unwrap();
588 fx.store588 fx.store
crates/forge-core/tests/integration/store_basic.rsmodified+4 -1
@@ -108,6 +108,7 @@ async fn sessions_respect_expiry() {
108 "csrf-live",108 "csrf-live",
109 &stamp_after(Duration::from_secs(3600)),109 &stamp_after(Duration::from_secs(3600)),
110 Some("agent/1"),110 Some("agent/1"),
111+ None,
111 )112 )
112 .await113 .await
113 .unwrap();114 .unwrap();
@@ -118,6 +119,7 @@ async fn sessions_respect_expiry() {
118 "csrf-dead",119 "csrf-dead",
119 &stamp_after(Duration::from_secs(0)),120 &stamp_after(Duration::from_secs(0)),
120 None,121 None,
122+ None,
121 )123 )
122 .await124 .await
123 .unwrap();125 .unwrap();
@@ -147,7 +149,7 @@ async fn sessions_respect_expiry() {
147 .is_none()149 .is_none()
148 );150 );
149 151
150- store.touch_session(&live.id).await.unwrap();152+ store.touch_session(&live.id, None).await.unwrap();
151 let sessions = store.list_sessions(&user.id).await.unwrap();153 let sessions = store.list_sessions(&user.id).await.unwrap();
152 assert_eq!(sessions.len(), 1, "expired sessions are not listed");154 assert_eq!(sessions.len(), 1, "expired sessions are not listed");
153 155
@@ -167,6 +169,7 @@ async fn sessions_respect_expiry() {
167 "c2",169 "c2",
168 &stamp_after(Duration::from_secs(60)),170 &stamp_after(Duration::from_secs(60)),
169 None,171 None,
172+ None,
170 )173 )
171 .await174 .await
172 .unwrap();175 .unwrap();
crates/forge-web/src/admin_cli.rsmodified+2 -2
@@ -662,11 +662,11 @@ mod tests {
662 .unwrap();662 .unwrap();
663 let expiry = forge_core::time::stamp_after(std::time::Duration::from_secs(3600));663 let expiry = forge_core::time::stamp_after(std::time::Duration::from_secs(3600));
664 store664 store
665- .create_session(&user.id, "h1", "c1", &expiry, None)665+ .create_session(&user.id, "h1", "c1", &expiry, None, None)
666 .await666 .await
667 .unwrap();667 .unwrap();
668 store668 store
669- .create_session(&user.id, "h2", "c2", &expiry, None)669+ .create_session(&user.id, "h2", "c2", &expiry, None, None)
670 .await670 .await
671 .unwrap();671 .unwrap();
672 672
crates/forge-web/src/auth.rsmodified+7 -1
@@ -16,6 +16,7 @@ use topcoat::cookie::{Cookie, Cookies, SameSite, cookies, time};
16 use topcoat::router::error::{forbidden, see_other};16 use topcoat::router::error::{forbidden, see_other};
17 use topcoat::router::request::{headers, uri};17 use topcoat::router::request::{headers, uri};
18 18
19+use crate::client_ip::client_addr;
19 use crate::state::AppState;20 use crate::state::AppState;
20 21
21 /// Logical cookie name. `override_prefix_host()` stores it as `__Host-forge_session`.22 /// Logical cookie name. `override_prefix_host()` stores it as `__Host-forge_session`.
@@ -66,7 +67,8 @@ pub async fn current_user(cx: &Cx) -> forge_core::Result<Option<(User, Session)>
66 else {67 else {
67 return Ok(None);68 return Ok(None);
68 };69 };
69- store.touch_session(&session.id).await?;70+ let addr = client_addr(cx).to_string();
71+ store.touch_session(&session.id, Some(&addr)).await?;
70 Ok(Some((user, session)))72 Ok(Some((user, session)))
71 }73 }
72 74
@@ -74,6 +76,7 @@ pub async fn current_user(cx: &Cx) -> forge_core::Result<Option<(User, Session)>
74 pub async fn login(cx: &Cx, user: &User) -> forge_core::Result<Session> {76 pub async fn login(cx: &Cx, user: &User) -> forge_core::Result<Session> {
75 let store = &app_context::<AppState>(cx).store;77 let store = &app_context::<AppState>(cx).store;
76 let token = new_session_token();78 let token = new_session_token();
79+ let addr = client_addr(cx).to_string();
77 let session = store80 let session = store
78 .create_session(81 .create_session(
79 &user.id,82 &user.id,
@@ -81,6 +84,7 @@ pub async fn login(cx: &Cx, user: &User) -> forge_core::Result<Session> {
81 &new_csrf_token(),84 &new_csrf_token(),
82 &stamp_after(SESSION_TTL),85 &stamp_after(SESSION_TTL),
83 user_agent(cx).as_deref(),86 user_agent(cx).as_deref(),
87+ Some(&addr),
84 )88 )
85 .await?;89 .await?;
86 // A new sign-in shows up in the user's session list in their other open tabs.90 // A new sign-in shows up in the user's session list in their other open tabs.
@@ -356,6 +360,8 @@ mod tests {
356 expires_at: String::new(),360 expires_at: String::new(),
357 last_seen: String::new(),361 last_seen: String::new(),
358 user_agent: None,362 user_agent: None,
363+ ip: None,
364+ last_ip: None,
359 }365 }
360 }366 }
361 367
crates/forge-web/src/client_ip.rsmodified+19 -6
@@ -18,6 +18,12 @@ const FORWARDED_FOR: &str = "x-forwarded-for";
18 /// The client IP for this request, bucketed for throttling. Unix-socket requests have no peer and18 /// The client IP for this request, bucketed for throttling. Unix-socket requests have no peer and
19 /// map to the unspecified address.19 /// map to the unspecified address.
20 pub fn client_ip(cx: &Cx) -> IpAddr {20 pub fn client_ip(cx: &Cx) -> IpAddr {
21+ bucket(client_addr(cx))
22+}
23+
24+/// The exact client address for this request, normalized but not bucketed, for display and audit.
25+/// Unix-socket requests map to the unspecified address.
26+pub fn client_addr(cx: &Cx) -> IpAddr {
21 let live = app_context::<AppState>(cx).live();27 let live = app_context::<AppState>(cx).live();
22 let trusted = &live.trusted_proxies;28 let trusted = &live.trusted_proxies;
23 let peer = remote_addr(cx).map(|addr| addr.ip());29 let peer = remote_addr(cx).map(|addr| addr.ip());
@@ -27,27 +33,34 @@ pub fn client_ip(cx: &Cx) -> IpAddr {
27 .filter_map(|value| value.to_str().ok())33 .filter_map(|value| value.to_str().ok())
28 .collect::<Vec<_>>()34 .collect::<Vec<_>>()
29 .join(",");35 .join(",");
30- resolve(peer, &forwarded, trusted)36+ resolve_addr(peer, &forwarded, trusted)
31 }37 }
32 38
33 /// Pure form of [`client_ip`]: `forwarded` is the combined `X-Forwarded-For` value, or empty.39 /// Pure form of [`client_ip`]: `forwarded` is the combined `X-Forwarded-For` value, or empty.
40+/// Only the tests use the bucketed form; the server takes [`client_ip`], which buckets itself.
41+#[cfg(test)]
34 pub fn resolve(peer: Option<IpAddr>, forwarded: &str, trusted: &[IpNet]) -> IpAddr {42 pub fn resolve(peer: Option<IpAddr>, forwarded: &str, trusted: &[IpNet]) -> IpAddr {
43+ bucket(resolve_addr(peer, forwarded, trusted))
44+}
45+
46+/// Pure form of [`client_addr`]: the exact client address, normalized but not bucketed.
47+pub fn resolve_addr(peer: Option<IpAddr>, forwarded: &str, trusted: &[IpNet]) -> IpAddr {
35 let Some(peer) = peer.map(normalize) else {48 let Some(peer) = peer.map(normalize) else {
36- return bucket(IpAddr::V4(Ipv4Addr::UNSPECIFIED));49+ return IpAddr::V4(Ipv4Addr::UNSPECIFIED);
37 };50 };
38 if !is_trusted(peer, trusted) {51 if !is_trusted(peer, trusted) {
39- return bucket(peer);52+ return peer;
40 }53 }
41 for entry in forwarded.rsplit(',') {54 for entry in forwarded.rsplit(',') {
42 let Ok(ip) = entry.trim().parse::<IpAddr>() else {55 let Ok(ip) = entry.trim().parse::<IpAddr>() else {
43- return bucket(peer);56+ return peer;
44 };57 };
45 let ip = normalize(ip);58 let ip = normalize(ip);
46 if !is_trusted(ip, trusted) {59 if !is_trusted(ip, trusted) {
47- return bucket(ip);60+ return ip;
48 }61 }
49 }62 }
50- bucket(peer)63+ peer
51 }64 }
52 65
53 fn is_trusted(ip: IpAddr, trusted: &[IpNet]) -> bool {66 fn is_trusted(ip: IpAddr, trusted: &[IpNet]) -> bool {
crates/forge-web/src/i18n/mod.rsmodified+52 -5
@@ -260,6 +260,12 @@ pub enum Key {
260 UnknownBrowser,260 UnknownBrowser,
261 ThisSession,261 ThisSession,
262 RevokeAllOthers,262 RevokeAllOthers,
263+ UserAgent,
264+ SignInIp,
265+ LastIp,
266+ LastSeenAt,
267+ ExpiresAt,
268+ BackToSessions,
263 269
264 // Metadata lines (see the helpers below for the words in between).270 // Metadata lines (see the helpers below for the words in between).
265 Added,271 Added,
@@ -472,6 +478,12 @@ pub const ALL: &[Key] = &[
472 Key::UnknownBrowser,478 Key::UnknownBrowser,
473 Key::ThisSession,479 Key::ThisSession,
474 Key::RevokeAllOthers,480 Key::RevokeAllOthers,
481+ Key::UserAgent,
482+ Key::SignInIp,
483+ Key::LastIp,
484+ Key::LastSeenAt,
485+ Key::ExpiresAt,
486+ Key::BackToSessions,
475 Key::Added,487 Key::Added,
476 Key::LastUsed,488 Key::LastUsed,
477 Key::Created,489 Key::Created,
@@ -864,6 +876,18 @@ pub fn t(lang: Lang, key: Key) -> &'static str {
864 (UnknownBrowser, Tr) => "Bilinmeyen tarayıcı",876 (UnknownBrowser, Tr) => "Bilinmeyen tarayıcı",
865 (ThisSession, En) => "This session",877 (ThisSession, En) => "This session",
866 (ThisSession, Tr) => "Bu oturum",878 (ThisSession, Tr) => "Bu oturum",
879+ (UserAgent, En) => "User agent",
880+ (UserAgent, Tr) => "Kullanıcı aracısı",
881+ (SignInIp, En) => "Sign-in IP",
882+ (SignInIp, Tr) => "Giriş IP adresi",
883+ (LastIp, En) => "Last IP",
884+ (LastIp, Tr) => "Son IP adresi",
885+ (LastSeenAt, En) => "Last seen",
886+ (LastSeenAt, Tr) => "Son görülme",
887+ (ExpiresAt, En) => "Expires",
888+ (ExpiresAt, Tr) => "Bitiş",
889+ (BackToSessions, En) => "Back to sessions",
890+ (BackToSessions, Tr) => "Oturumlara dön",
867 (RevokeAllOthers, En) => "Revoke all other sessions",891 (RevokeAllOthers, En) => "Revoke all other sessions",
868 (RevokeAllOthers, Tr) => "Diğer tüm oturumları iptal et",892 (RevokeAllOthers, Tr) => "Diğer tüm oturumları iptal et",
869 893
@@ -1307,21 +1331,44 @@ mod tests {
1307 let cases: [(&str, Option<&str>, &str, Lang); 10] = [1331 let cases: [(&str, Option<&str>, &str, Lang); 10] = [
1308 ("stored en beats browser tr", Some("en"), "tr", Lang::En),1332 ("stored en beats browser tr", Some("en"), "tr", Lang::En),
1309 ("stored tr with no header", Some("tr"), "", Lang::Tr),1333 ("stored tr with no header", Some("tr"), "", Lang::Tr),
1310- ("auto follows browser", Some("auto"), "tr-TR,en;q=0.5", Lang::Tr),1334+ (
1335+ "auto follows browser",
1336+ Some("auto"),
1337+ "tr-TR,en;q=0.5",
1338+ Lang::Tr,
1339+ ),
1311 ("missing preference follows browser", None, "tr", Lang::Tr),1340 ("missing preference follows browser", None, "tr", Lang::Tr),
1312 ("no preference, no header", None, "", Lang::En),1341 ("no preference, no header", None, "", Lang::En),
1313- ("highest q supported wins", None, "de,en;q=0.8,tr;q=0.9", Lang::Tr),1342+ (
1343+ "highest q supported wins",
1344+ None,
1345+ "de,en;q=0.8,tr;q=0.9",
1346+ Lang::Tr,
1347+ ),
1314 ("higher q for en", None, "en;q=0.9,tr;q=0.5", Lang::En),1348 ("higher q for en", None, "en;q=0.9,tr;q=0.5", Lang::En),
1315 ("q=0 rejects tr", None, "tr;q=0,en", Lang::En),1349 ("q=0 rejects tr", None, "tr;q=0,en", Lang::En),
1316- ("unsupported tags fall back to en", None, "de,fr;q=0.9", Lang::En),1350+ (
1317- ("malformed q is ignored", None, "tr;q=oops,en;q=0.1", Lang::En),1351+ "unsupported tags fall back to en",
1352+ None,
1353+ "de,fr;q=0.9",
1354+ Lang::En,
1355+ ),
1356+ (
1357+ "malformed q is ignored",
1358+ None,
1359+ "tr;q=oops,en;q=0.1",
1360+ Lang::En,
1361+ ),
1318 ];1362 ];
1319 for (name, stored, accept, want) in cases {1363 for (name, stored, accept, want) in cases {
1320 let map = if accept.is_empty() {1364 let map = if accept.is_empty() {
1321 HeaderMap::new()1365 HeaderMap::new()
1322 } else {1366 } else {
1323 let mut map = HeaderMap::new();1367 let mut map = HeaderMap::new();
1324- map.insert(ACCEPT_LANGUAGE, HeaderValue::from_str(accept).expect("ascii"));1368+ map.insert(
1369+ ACCEPT_LANGUAGE,
1370+ HeaderValue::from_str(accept).expect("ascii"),
1371+ );
1325 map1372 map
1326 };1373 };
1327 assert_eq!(resolve(stored, &map), want, "case {name}");1374 assert_eq!(resolve(stored, &map), want, "case {name}");
crates/forge-web/src/pages/settings_security.rsmodified+10 -3
@@ -1109,7 +1109,7 @@ mod tests {
1109 .unwrap();1109 .unwrap();
1110 let expiry = stamp_after(std::time::Duration::from_secs(3600));1110 let expiry = stamp_after(std::time::Duration::from_secs(3600));
1111 store1111 store
1112- .create_session(&user.id, &hash_token(TOKEN), CSRF, &expiry, None)1112+ .create_session(&user.id, &hash_token(TOKEN), CSRF, &expiry, None, None)
1113 .await1113 .await
1114 .unwrap();1114 .unwrap();
1115 let router = Router::builder()1115 let router = Router::builder()
@@ -1234,7 +1234,10 @@ mod tests {
1234 &mismatch,1234 &mismatch,
1235 )1235 )
1236 .await;1236 .await;
1237- assert!(reply.body.contains("do not match"), "mismatched confirmation");1237+ assert!(
1238+ reply.body.contains("do not match"),
1239+ "mismatched confirmation"
1240+ );
1238 1241
1239 // An SSH key puts the user's address into the allowed-signers file. With no address1242 // An SSH key puts the user's address into the allowed-signers file. With no address
1240 // yet, the username is the principal.1243 // yet, the username is the principal.
@@ -1310,6 +1313,7 @@ mod tests {
1310 "other",1313 "other",
1311 &expiry,1314 &expiry,
1312 None,1315 None,
1316+ None,
1313 )1317 )
1314 .await1318 .await
1315 .unwrap();1319 .unwrap();
@@ -1491,7 +1495,10 @@ mod tests {
1491 1495
1492 // The enrollment page shows the secret and the URI, not the codes.1496 // The enrollment page shows the secret and the URI, not the codes.
1493 let page = send(&fx.router, "GET", "/settings/security", true, "").await;1497 let page = send(&fx.router, "GET", "/settings/security", true, "").await;
1494- assert!(page.body.contains(&totp::base32_encode(&shared)), "secret shown");1498+ assert!(
1499+ page.body.contains(&totp::base32_encode(&shared)),
1500+ "secret shown"
1501+ );
1495 assert!(1502 assert!(
1496 page.body.contains("otpauth://totp/forge:tahinli?secret="),1503 page.body.contains("otpauth://totp/forge:tahinli?secret="),
1497 "uri shown"1504 "uri shown"
crates/forge-web/src/pages/settings_sessions.rsmodified+89 -5
@@ -1,12 +1,13 @@
1-//! Page: web sessions (`/settings/sessions`). Revoke one or all other sessions.1+//! Page: web sessions (`/settings/sessions`). Revoke one or all other sessions, and a detail page
2+//! per session (`/settings/sessions/{id}`).
2 3
3 use forge_core::{AuditAction, Session};4 use forge_core::{AuditAction, Session};
4 use serde::Deserialize;5 use serde::Deserialize;
5 use topcoat::Result;6 use topcoat::Result;
6 use topcoat::context::{Cx, app_context};7 use topcoat::context::{Cx, app_context};
7 use topcoat::router::content::Form;8 use topcoat::router::content::Form;
8-use topcoat::router::error::{SeeOther, see_other};9+use topcoat::router::error::{SeeOther, not_found, see_other};
9-use topcoat::router::{page, route};10+use topcoat::router::{page, path_param_segment, route};
10 use topcoat::view::{View, component, view};11 use topcoat::view::{View, component, view};
11 12
12 use crate::audit::{self, Actor, Target};13 use crate::audit::{self, Actor, Target};
@@ -14,6 +15,7 @@ use crate::auth::{logout, require_csrf, require_user};
14 use crate::i18n::{self, Key, Lang, t};15 use crate::i18n::{self, Key, Lang, t};
15 use crate::state::AppState;16 use crate::state::AppState;
16 use crate::views::{rel_time, shell};17 use crate::views::{rel_time, shell};
18+use crate::web_push::agent_label;
17 19
18 #[derive(Deserialize)]20 #[derive(Deserialize)]
19 struct RevokeForm {21 struct RevokeForm {
@@ -29,6 +31,23 @@ struct CsrfForm {
29 csrf: String,31 csrf: String,
30 }32 }
31 33
34+/// A short title for a session: "Chrome on Linux", or the unknown-browser label.
35+fn session_label(lang: Lang, session: &Session) -> String {
36+ session
37+ .user_agent
38+ .as_deref()
39+ .map_or_else(|| t(lang, Key::UnknownBrowser).to_owned(), agent_label)
40+}
41+
42+/// " · " and the address the session was last seen at (or signed in from), for the list's meta
43+/// line. Empty when no address was recorded.
44+fn address_text(session: &Session) -> String {
45+ match session.last_ip.as_deref().or(session.ip.as_deref()) {
46+ Some(ip) => format!(" · {ip}"),
47+ None => String::new(),
48+ }
49+}
50+
32 #[component]51 #[component]
33 async fn sessions_view(52 async fn sessions_view(
34 lang: Lang,53 lang: Lang,
@@ -46,8 +65,8 @@ async fn sessions_view(
46 for session in sessions.into_iter() {65 for session in sessions.into_iter() {
47 <li class="item">66 <li class="item">
48 <div class="item-main">67 <div class="item-main">
49- <strong>(session.user_agent.clone().unwrap_or_else(|| t(lang, Key::UnknownBrowser).into()))</strong>68+ <a href=(format!("/settings/sessions/{}", session.id))><strong>(session_label(lang, &session))</strong></a>
50- <span class="muted small">(i18n::dated_label(lang, Key::SignedIn)) " " rel_time(lang: lang, stamp: session.created_at.as_str()) " · " (i18n::dated_label(lang, Key::LastSeen)) " " rel_time(lang: lang, stamp: session.last_seen.as_str()) " · " (i18n::dated_label(lang, Key::ExpiresLabel)) " " rel_time(lang: lang, stamp: session.expires_at.as_str())</span>69+ <span class="muted small">(i18n::dated_label(lang, Key::SignedIn)) " " rel_time(lang: lang, stamp: session.created_at.as_str()) " · " (i18n::dated_label(lang, Key::LastSeen)) " " rel_time(lang: lang, stamp: session.last_seen.as_str()) " · " (i18n::dated_label(lang, Key::ExpiresLabel)) " " rel_time(lang: lang, stamp: session.expires_at.as_str()) (address_text(&session))</span>
51 if session.id == current_id {70 if session.id == current_id {
52 <span class="badge public">(t(lang, Key::ThisSession))</span>71 <span class="badge public">(t(lang, Key::ThisSession))</span>
53 }72 }
@@ -74,6 +93,50 @@ async fn sessions_view(
74 })93 })
75 }94 }
76 95
96+#[component]
97+async fn session_detail_view(
98+ lang: Lang,
99+ csrf: &str,
100+ session: Session,
101+ current: bool,
102+) -> Result<impl View> {
103+ let user_agent = session
104+ .user_agent
105+ .clone()
106+ .unwrap_or_else(|| t(lang, Key::UnknownBrowser).to_owned());
107+ let sign_in_ip = session.ip.clone().unwrap_or_else(|| "-".to_owned());
108+ let last_ip = session.last_ip.clone().unwrap_or_else(|| "-".to_owned());
109+ let id = session.id.clone();
110+ Ok(view! {
111+ <section class="page-head">
112+ <h1>(session_label(lang, &session))</h1>
113+ </section>
114+ if current {
115+ <p><span class="badge public">(t(lang, Key::ThisSession))</span></p>
116+ }
117+ <section class="card">
118+ <dl class="kv-grid">
119+ <div><dt>(t(lang, Key::UserAgent))</dt><dd>(user_agent.as_str())</dd></div>
120+ <div><dt>(t(lang, Key::SignInIp))</dt><dd>(sign_in_ip.as_str())</dd></div>
121+ <div><dt>(t(lang, Key::LastIp))</dt><dd>(last_ip.as_str())</dd></div>
122+ <div><dt>(t(lang, Key::SignedIn))</dt><dd>rel_time(lang: lang, stamp: session.created_at.as_str()) " (" (session.created_at.as_str()) ")"</dd></div>
123+ <div><dt>(t(lang, Key::LastSeenAt))</dt><dd>rel_time(lang: lang, stamp: session.last_seen.as_str()) " (" (session.last_seen.as_str()) ")"</dd></div>
124+ <div><dt>(t(lang, Key::ExpiresAt))</dt><dd>rel_time(lang: lang, stamp: session.expires_at.as_str()) " (" (session.expires_at.as_str()) ")"</dd></div>
125+ </dl>
126+ </section>
127+ <section class="card">
128+ if !current {
129+ <form method="post" action="/settings/sessions/revoke">
130+ <input type="hidden" name="csrf" value=(csrf)>
131+ <input type="hidden" name="id" value=(id.as_str())>
132+ <button type="submit" class="danger">(t(lang, Key::Revoke))</button>
133+ </form>
134+ }
135+ <p><a href="/settings/sessions">(t(lang, Key::BackToSessions))</a></p>
136+ </section>
137+ })
138+}
139+
77 #[page("/settings/sessions")]140 #[page("/settings/sessions")]
78 async fn sessions_page(cx: &Cx) -> Result<impl View> {141 async fn sessions_page(cx: &Cx) -> Result<impl View> {
79 let viewer = require_user(cx).await?;142 let viewer = require_user(cx).await?;
@@ -89,6 +152,27 @@ async fn sessions_page(cx: &Cx) -> Result<impl View> {
89 })152 })
90 }153 }
91 154
155+#[page("/settings/sessions/{id}")]
156+async fn session_page(cx: &Cx) -> Result<impl View> {
157+ let viewer = require_user(cx).await?;
158+ let lang = i18n::lang(cx, Some(&viewer.0));
159+ let id = path_param_segment(cx, "id").to_owned();
160+ // Only the signed-in user's own sessions are shown; anything else is not found.
161+ let sessions = app_context::<AppState>(cx)
162+ .store
163+ .list_sessions(&viewer.0.id)
164+ .await?;
165+ let Some(session) = sessions.into_iter().find(|s| s.id == id) else {
166+ return Err(not_found().into());
167+ };
168+ let current = session.id == viewer.1.id;
169+ let csrf = viewer.1.csrf_token.clone();
170+ let title = session_label(lang, &session);
171+ Ok(view! {
172+ shell(title: title.as_str(), viewer: Some(&viewer), session_detail_view(lang: lang, csrf: csrf.as_str(), session: session, current: current))
173+ })
174+}
175+
92 #[route(POST "/settings/sessions/revoke")]176 #[route(POST "/settings/sessions/revoke")]
93 async fn sessions_revoke(cx: &Cx, Form(form): Form<RevokeForm>) -> Result<SeeOther> {177 async fn sessions_revoke(cx: &Cx, Form(form): Form<RevokeForm>) -> Result<SeeOther> {
94 let (user, current) = require_csrf(cx, &form.csrf).await?;178 let (user, current) = require_csrf(cx, &form.csrf).await?;
crates/forge-web/src/test_support.rsmodified+1 -0
@@ -126,6 +126,7 @@ pub async fn create_session(store: &Store, user_id: &str, token: &str, csrf: &st
126 csrf,126 csrf,
127 &stamp_after(Duration::from_secs(3600)),127 &stamp_after(Duration::from_secs(3600)),
128 None,128 None,
129+ None,
129 )130 )
130 .await131 .await
131 .expect("session");132 .expect("session");
crates/forge-web/tests/e2e/orgs_core_e2e.rsmodified+8 -1
@@ -106,7 +106,14 @@ async fn seed_org(_dir: PathBuf, store: Store) {
106 .unwrap();106 .unwrap();
107 let expiry = forge_core::time::stamp_after(Duration::from_secs(3600));107 let expiry = forge_core::time::stamp_after(Duration::from_secs(3600));
108 store108 store
109- .create_session(&org.id, &hash_token(ORG_SESSION), "csrf", &expiry, None)109+ .create_session(
110+ &org.id,
111+ &hash_token(ORG_SESSION),
112+ "csrf",
113+ &expiry,
114+ None,
115+ None,
116+ )
110 .await117 .await
111 .unwrap();118 .unwrap();
112 store119 store