authoravatarclover caruso<git@paperclover.net>2026-10-12 21:54:12-07:00
committeravatarclover caruso<git@paperclover.net>2026-10-21 02:52:29-07:00
loga2f8bb12305846efcb74fa7657ccbcc07c7aceb7
tree0fe135d303be4ab14fc8c9299bde9eb711191a25
parente026ca3b39513d4b8c9911a4cbe43d60fa13d3b1
signature Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU

Keep sign-in forms usable across tabs and idle time

Reuse a dedicated browser CSRF cookie without a form timeout, while retaining exact-origin and cookie/token checks. Keep Files handoff cookies separate and cover tab reuse, expired pending state, browser binding, and restart behavior. Assisted-by: gpt-6

3 files changed, 33 insertions(+), 17 deletions(-)

dashboard/src/auth.rs+17-14
......@@ -10,6 +10,7 @@ use webauthn_rs::prelude::*;
1010
1111const COOKIE: &str = "__Host-snow-session";
1212const FLOW_COOKIE: &str = "__Host-snow-flow";
13const CSRF_COOKIE: &str = "__Host-snow-csrf";
1314const SESSION_TTL: i64 = 30 * 86400;
1415const GROUPS: &[&str] = &["infra-admin", "media", "media-manage", "metrics", "vm", "ai"];
1516
......@@ -32,8 +33,12 @@ pub fn cookie(headers: &HeaderMap, name: &str) -> Option<String> {
3233 (key == name).then(|| value.to_owned())
3334 })
3435}
35pub(crate) fn set_cookie(name: &str, value: &str, ttl: i64) -> String {
36 format!("{name}={value}; Path=/; Secure; HttpOnly; SameSite=Lax; Max-Age={ttl}")
36pub(crate) fn set_cookie(name: &str, value: &str, ttl: Option<i64>) -> String {
37 let mut cookie = format!("{name}={value}; Path=/; Secure; HttpOnly; SameSite=Lax");
38 if let Some(ttl) = ttl {
39 cookie.push_str(&format!("; Max-Age={ttl}"));
40 }
41 cookie
3742}
3843fn row(db: &Connection, statement: &str, key: &str) -> Result<Value> {
3944 let value: Option<String> = db.query_row(statement, [key], |r| r.get(0)).optional()?;
......@@ -430,7 +435,7 @@ impl Store {
430435 now() as i64
431436 ],
432437 )?;
433 Ok(set_cookie(COOKIE, &token, SESSION_TTL))
438 Ok(set_cookie(COOKIE, &token, Some(SESSION_TTL)))
434439 }
435440 pub(crate) fn limit(&self, headers: &HeaderMap, name: &str) -> Result<()> {
436441 let ip = headers
......@@ -476,15 +481,11 @@ impl Store {
476481 {
477482 return Err(Error::new(403, "Open sign-in on Snowglobe and try again."));
478483 }
479 let cookie = cookie(headers, FLOW_COOKIE).unwrap_or_default();
484 let cookie = cookie(headers, CSRF_COOKIE).unwrap_or_default();
480485 if cookie.is_empty()
481486 || !bool::from(cookie.as_bytes().ct_eq(string(&body["csrf"]).as_bytes()))
482 || pending(&self.db.lock().unwrap(), &cookie, "csrf", false)?.is_null()
483487 {
484 return Err(Error::new(
485 403,
486 "Sign-in expired. Reload the page and try again.",
487 ));
488 return Err(Error::new(403, "Reload the page to sign in."));
488489 }
489490 Ok(())
490491 }
......@@ -635,7 +636,7 @@ pub async fn route(State(app): State<Arc<App>>, request: Request) -> Result<Resp
635636 "location",
636637 format!("{}auth/continue?flow={flow}", auth.origin),
637638 ),
638 ("set-cookie", set_cookie(FLOW_COOKIE, &flow, 300)),
639 ("set-cookie", set_cookie(FLOW_COOKIE, &flow, Some(300))),
639640 ],
640641 )
641642 .into_response());
......@@ -693,7 +694,9 @@ pub async fn route(State(app): State<Arc<App>>, request: Request) -> Result<Resp
693694 .into_response());
694695 }
695696 if path == "/auth/status" && method == Method::GET {
696 let csrf = issue(&auth.db.lock().unwrap(), "csrf", json!({}), 900)?;
697 let csrf = cookie(&headers, CSRF_COOKIE)
698 .filter(|token| !token.is_empty())
699 .unwrap_or_else(mcp::secret);
697700 let mut value = json!({"csrf":csrf,"account":auth.session(&headers,"dashboard")?});
698701 value["service"] = json!("snow globe");
699702 if let Some(flow) = query.get("flow") {
......@@ -754,7 +757,7 @@ pub async fn route(State(app): State<Arc<App>>, request: Request) -> Result<Resp
754757 }
755758 return Ok((
756759 [
757 ("set-cookie", set_cookie(FLOW_COOKIE, &csrf, 900)),
760 ("set-cookie", set_cookie(CSRF_COOKIE, &csrf, None)),
758761 ("cache-control", "no-store".into()),
759762 ],
760763 axum::Json(value),
......@@ -807,7 +810,7 @@ pub async fn route(State(app): State<Arc<App>>, request: Request) -> Result<Resp
807810 return Ok((
808811 StatusCode::SEE_OTHER,
809812 [
810 ("set-cookie", set_cookie(COOKIE, "", 0)),
813 ("set-cookie", set_cookie(COOKIE, "", Some(0))),
811814 (
812815 "location",
813816 if shale_logout {
......@@ -821,7 +824,7 @@ pub async fn route(State(app): State<Arc<App>>, request: Request) -> Result<Resp
821824 .into_response());
822825 }
823826 return Ok((
824 [("set-cookie", set_cookie(COOKIE, "", 0))],
827 [("set-cookie", set_cookie(COOKIE, "", Some(0)))],
825828 axum::Json(json!({"next":"/sign-in"})),
826829 )
827830 .into_response());
dashboard/src/guest.rs+3-3
......@@ -575,7 +575,7 @@ async fn handle(app: &App, request: Request) -> Result<Response> {
575575 StatusCode::FOUND,
576576 [
577577 ("location", target.to_string()),
578 ("set-cookie", auth::set_cookie(COOKIE, &state, 300)),
578 ("set-cookie", auth::set_cookie(COOKIE, &state, Some(300))),
579579 ],
580580 )
581581 .into_response());
......@@ -633,7 +633,7 @@ async fn handle(app: &App, request: Request) -> Result<Response> {
633633 Ok(session) => Ok((
634634 StatusCode::FOUND,
635635 [("location", next), ("set-cookie", session)],
636 axum::response::AppendHeaders([("set-cookie", auth::set_cookie(COOKIE, "", 0))]),
636 axum::response::AppendHeaders([("set-cookie", auth::set_cookie(COOKIE, "", Some(0)))]),
637637 )
638638 .into_response()),
639639 Err(error) => {
......@@ -648,7 +648,7 @@ async fn handle(app: &App, request: Request) -> Result<Response> {
648648 "location",
649649 format!("/sign-in?next={}&guest_error=1", encoded(&next)),
650650 ),
651 ("set-cookie", auth::set_cookie(COOKIE, "", 0)),
651 ("set-cookie", auth::set_cookie(COOKIE, "", Some(0))),
652652 ],
653653 )
654654 .into_response())
tools/dashboard-auth-test.py+13
......@@ -121,8 +121,18 @@ def main():
121121 request('/api/me', status=401, extra={'User-Name': name, 'User-Groups': 'infra-admin'})
122122 request('/auth/status', status=403, extra={'Studio-Proxy-Token': 'wrong'})
123123 csrf = request('/auth/status', cookies=cookies)['csrf']
124 csrf_headers = request('/auth/status', cookies=cookies, include_headers=True)
125 assert csrf_headers['set-cookie'].startswith('__Host-snow-csrf=')
126 assert 'Max-Age=' not in csrf_headers['set-cookie'] and 'Expires=' not in csrf_headers['set-cookie']
127 assert request('/auth/status', cookies=cookies)['csrf'] == csrf
128 with sqlite3.connect(data / 'accounts.sqlite') as db:
129 db.execute("UPDATE pending SET expires=0 WHERE kind='csrf'")
124130 login = {'csrf': csrf, 'username': name, 'password': password, 'next': '/users'}
125131 request('/auth/password', 'POST', login, cookies, 403, {'Origin': 'https://evil.example'})
132 request('/auth/password', 'POST', login, cookies, 403, {'Origin': 'https://shale.paperclover.net'})
133 request('/auth/password', 'POST', login, cookies, 403, {'Origin': ''})
134 request('/auth/password', 'POST', login, {}, 403)
135 request('/auth/password', 'POST', {**login, 'csrf': ''}, cookies, 403)
126136 request('/auth/password', 'POST', {**login, 'csrf': 'wrong'}, cookies, 403)
127137 request('/auth/password', 'POST', {**login, 'password': 'wrong'}, cookies, 401)
128138 assert request('/auth/password', 'POST', login, cookies)['next'] == '/users'
......@@ -138,6 +148,8 @@ def main():
138148 phc = json.loads(db.execute("SELECT data FROM credentials WHERE kind='password'").fetchone()[0])['phc']
139149 assert '$m=7168,t=5,p=1$' in phc
140150 other = {}; csrf2 = request('/auth/status', cookies=other)['csrf']
151 assert csrf2 != csrf
152 request('/auth/password', 'POST', login, other, 403)
141153 begun = request('/auth/passkey/start', 'POST', {'csrf': csrf2, 'username': name}, other)
142154 assert begun['options']['publicKey']['rpId'] == rp
143155
......@@ -260,6 +272,7 @@ def main():
260272 request('/api/users/' + invitation['id'], 'PATCH', {'enabled': False}, cookies, 204)
261273 request('/api/me', cookies=newcomer, status=401)
262274 stop(); start()
275 assert request('/auth/password', 'POST', login, cookies)['next'] == '/users'
263276 request('/api/me', cookies=cookies)
264277 request('/auth/file/check', cookies=file_cookies, status=204, host=file)
265278 shale_session = {}; shale_csrf = request('/auth/status', cookies=shale_session)['csrf']