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::*;...@@ -10,6 +10,7 @@ use webauthn_rs::prelude::*;
1010
11const COOKIE: &str = "__Host-snow-session";11const COOKIE: &str = "__Host-snow-session";
12const FLOW_COOKIE: &str = "__Host-snow-flow";12const FLOW_COOKIE: &str = "__Host-snow-flow";
13const CSRF_COOKIE: &str = "__Host-snow-csrf";
13const SESSION_TTL: i64 = 30 * 86400;14const SESSION_TTL: i64 = 30 * 86400;
14const GROUPS: &[&str] = &["infra-admin", "media", "media-manage", "metrics", "vm", "ai"];15const GROUPS: &[&str] = &["infra-admin", "media", "media-manage", "metrics", "vm", "ai"];
1516
...@@ -32,8 +33,12 @@ pub fn cookie(headers: &HeaderMap, name: &str) -> Option<String> {...@@ -32,8 +33,12 @@ pub fn cookie(headers: &HeaderMap, name: &str) -> Option<String> {
32 (key == name).then(|| value.to_owned())33 (key == name).then(|| value.to_owned())
33 })34 })
34}35}
35pub(crate) fn set_cookie(name: &str, value: &str, ttl: i64) -> String {36pub(crate) fn set_cookie(name: &str, value: &str, ttl: Option<i64>) -> String {
36 format!("{name}={value}; Path=/; Secure; HttpOnly; SameSite=Lax; Max-Age={ttl}")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
37}42}
38fn row(db: &Connection, statement: &str, key: &str) -> Result<Value> {43fn row(db: &Connection, statement: &str, key: &str) -> Result<Value> {
39 let value: Option<String> = db.query_row(statement, [key], |r| r.get(0)).optional()?;44 let value: Option<String> = db.query_row(statement, [key], |r| r.get(0)).optional()?;
...@@ -430,7 +435,7 @@ impl Store {...@@ -430,7 +435,7 @@ impl Store {
430 now() as i64435 now() as i64
431 ],436 ],
432 )?;437 )?;
433 Ok(set_cookie(COOKIE, &token, SESSION_TTL))438 Ok(set_cookie(COOKIE, &token, Some(SESSION_TTL)))
434 }439 }
435 pub(crate) fn limit(&self, headers: &HeaderMap, name: &str) -> Result<()> {440 pub(crate) fn limit(&self, headers: &HeaderMap, name: &str) -> Result<()> {
436 let ip = headers441 let ip = headers
...@@ -476,15 +481,11 @@ impl Store {...@@ -476,15 +481,11 @@ impl Store {
476 {481 {
477 return Err(Error::new(403, "Open sign-in on Snowglobe and try again."));482 return Err(Error::new(403, "Open sign-in on Snowglobe and try again."));
478 }483 }
479 let cookie = cookie(headers, FLOW_COOKIE).unwrap_or_default();484 let cookie = cookie(headers, CSRF_COOKIE).unwrap_or_default();
480 if cookie.is_empty()485 if cookie.is_empty()
481 || !bool::from(cookie.as_bytes().ct_eq(string(&body["csrf"]).as_bytes()))486 || !bool::from(cookie.as_bytes().ct_eq(string(&body["csrf"]).as_bytes()))
482 || pending(&self.db.lock().unwrap(), &cookie, "csrf", false)?.is_null()
483 {487 {
484 return Err(Error::new(488 return Err(Error::new(403, "Reload the page to sign in."));
485 403,
486 "Sign-in expired. Reload the page and try again.",
487 ));
488 }489 }
489 Ok(())490 Ok(())
490 }491 }
...@@ -635,7 +636,7 @@ pub async fn route(State(app): State<Arc<App>>, request: Request) -> Result<Resp...@@ -635,7 +636,7 @@ pub async fn route(State(app): State<Arc<App>>, request: Request) -> Result<Resp
635 "location",636 "location",
636 format!("{}auth/continue?flow={flow}", auth.origin),637 format!("{}auth/continue?flow={flow}", auth.origin),
637 ),638 ),
638 ("set-cookie", set_cookie(FLOW_COOKIE, &flow, 300)),639 ("set-cookie", set_cookie(FLOW_COOKIE, &flow, Some(300))),
639 ],640 ],
640 )641 )
641 .into_response());642 .into_response());
...@@ -693,7 +694,9 @@ pub async fn route(State(app): State<Arc<App>>, request: Request) -> Result<Resp...@@ -693,7 +694,9 @@ pub async fn route(State(app): State<Arc<App>>, request: Request) -> Result<Resp
693 .into_response());694 .into_response());
694 }695 }
695 if path == "/auth/status" && method == Method::GET {696 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);
697 let mut value = json!({"csrf":csrf,"account":auth.session(&headers,"dashboard")?});700 let mut value = json!({"csrf":csrf,"account":auth.session(&headers,"dashboard")?});
698 value["service"] = json!("snow globe");701 value["service"] = json!("snow globe");
699 if let Some(flow) = query.get("flow") {702 if let Some(flow) = query.get("flow") {
...@@ -754,7 +757,7 @@ pub async fn route(State(app): State<Arc<App>>, request: Request) -> Result<Resp...@@ -754,7 +757,7 @@ pub async fn route(State(app): State<Arc<App>>, request: Request) -> Result<Resp
754 }757 }
755 return Ok((758 return Ok((
756 [759 [
757 ("set-cookie", set_cookie(FLOW_COOKIE, &csrf, 900)),760 ("set-cookie", set_cookie(CSRF_COOKIE, &csrf, None)),
758 ("cache-control", "no-store".into()),761 ("cache-control", "no-store".into()),
759 ],762 ],
760 axum::Json(value),763 axum::Json(value),
...@@ -807,7 +810,7 @@ pub async fn route(State(app): State<Arc<App>>, request: Request) -> Result<Resp...@@ -807,7 +810,7 @@ pub async fn route(State(app): State<Arc<App>>, request: Request) -> Result<Resp
807 return Ok((810 return Ok((
808 StatusCode::SEE_OTHER,811 StatusCode::SEE_OTHER,
809 [812 [
810 ("set-cookie", set_cookie(COOKIE, "", 0)),813 ("set-cookie", set_cookie(COOKIE, "", Some(0))),
811 (814 (
812 "location",815 "location",
813 if shale_logout {816 if shale_logout {
...@@ -821,7 +824,7 @@ pub async fn route(State(app): State<Arc<App>>, request: Request) -> Result<Resp...@@ -821,7 +824,7 @@ pub async fn route(State(app): State<Arc<App>>, request: Request) -> Result<Resp
821 .into_response());824 .into_response());
822 }825 }
823 return Ok((826 return Ok((
824 [("set-cookie", set_cookie(COOKIE, "", 0))],827 [("set-cookie", set_cookie(COOKIE, "", Some(0)))],
825 axum::Json(json!({"next":"/sign-in"})),828 axum::Json(json!({"next":"/sign-in"})),
826 )829 )
827 .into_response());830 .into_response());
dashboard/src/guest.rs+3-3
...@@ -575,7 +575,7 @@ async fn handle(app: &App, request: Request) -> Result<Response> {...@@ -575,7 +575,7 @@ async fn handle(app: &App, request: Request) -> Result<Response> {
575 StatusCode::FOUND,575 StatusCode::FOUND,
576 [576 [
577 ("location", target.to_string()),577 ("location", target.to_string()),
578 ("set-cookie", auth::set_cookie(COOKIE, &state, 300)),578 ("set-cookie", auth::set_cookie(COOKIE, &state, Some(300))),
579 ],579 ],
580 )580 )
581 .into_response());581 .into_response());
...@@ -633,7 +633,7 @@ async fn handle(app: &App, request: Request) -> Result<Response> {...@@ -633,7 +633,7 @@ async fn handle(app: &App, request: Request) -> Result<Response> {
633 Ok(session) => Ok((633 Ok(session) => Ok((
634 StatusCode::FOUND,634 StatusCode::FOUND,
635 [("location", next), ("set-cookie", session)],635 [("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)))]),
637 )637 )
638 .into_response()),638 .into_response()),
639 Err(error) => {639 Err(error) => {
...@@ -648,7 +648,7 @@ async fn handle(app: &App, request: Request) -> Result<Response> {...@@ -648,7 +648,7 @@ async fn handle(app: &App, request: Request) -> Result<Response> {
648 "location",648 "location",
649 format!("/sign-in?next={}&guest_error=1", encoded(&next)),649 format!("/sign-in?next={}&guest_error=1", encoded(&next)),
650 ),650 ),
651 ("set-cookie", auth::set_cookie(COOKIE, "", 0)),651 ("set-cookie", auth::set_cookie(COOKIE, "", Some(0))),
652 ],652 ],
653 )653 )
654 .into_response())654 .into_response())
tools/dashboard-auth-test.py+13
...@@ -121,8 +121,18 @@ def main():...@@ -121,8 +121,18 @@ def main():
121 request('/api/me', status=401, extra={'User-Name': name, 'User-Groups': 'infra-admin'})121 request('/api/me', status=401, extra={'User-Name': name, 'User-Groups': 'infra-admin'})
122 request('/auth/status', status=403, extra={'Studio-Proxy-Token': 'wrong'})122 request('/auth/status', status=403, extra={'Studio-Proxy-Token': 'wrong'})
123 csrf = request('/auth/status', cookies=cookies)['csrf']123 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'")
124 login = {'csrf': csrf, 'username': name, 'password': password, 'next': '/users'}130 login = {'csrf': csrf, 'username': name, 'password': password, 'next': '/users'}
125 request('/auth/password', 'POST', login, cookies, 403, {'Origin': 'https://evil.example'})131 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)
126 request('/auth/password', 'POST', {**login, 'csrf': 'wrong'}, cookies, 403)136 request('/auth/password', 'POST', {**login, 'csrf': 'wrong'}, cookies, 403)
127 request('/auth/password', 'POST', {**login, 'password': 'wrong'}, cookies, 401)137 request('/auth/password', 'POST', {**login, 'password': 'wrong'}, cookies, 401)
128 assert request('/auth/password', 'POST', login, cookies)['next'] == '/users'138 assert request('/auth/password', 'POST', login, cookies)['next'] == '/users'
...@@ -138,6 +148,8 @@ def main():...@@ -138,6 +148,8 @@ def main():
138 phc = json.loads(db.execute("SELECT data FROM credentials WHERE kind='password'").fetchone()[0])['phc']148 phc = json.loads(db.execute("SELECT data FROM credentials WHERE kind='password'").fetchone()[0])['phc']
139 assert '$m=7168,t=5,p=1$' in phc149 assert '$m=7168,t=5,p=1$' in phc
140 other = {}; csrf2 = request('/auth/status', cookies=other)['csrf']150 other = {}; csrf2 = request('/auth/status', cookies=other)['csrf']
151 assert csrf2 != csrf
152 request('/auth/password', 'POST', login, other, 403)
141 begun = request('/auth/passkey/start', 'POST', {'csrf': csrf2, 'username': name}, other)153 begun = request('/auth/passkey/start', 'POST', {'csrf': csrf2, 'username': name}, other)
142 assert begun['options']['publicKey']['rpId'] == rp154 assert begun['options']['publicKey']['rpId'] == rp
143155
...@@ -260,6 +272,7 @@ def main():...@@ -260,6 +272,7 @@ def main():
260 request('/api/users/' + invitation['id'], 'PATCH', {'enabled': False}, cookies, 204)272 request('/api/users/' + invitation['id'], 'PATCH', {'enabled': False}, cookies, 204)
261 request('/api/me', cookies=newcomer, status=401)273 request('/api/me', cookies=newcomer, status=401)
262 stop(); start()274 stop(); start()
275 assert request('/auth/password', 'POST', login, cookies)['next'] == '/users'
263 request('/api/me', cookies=cookies)276 request('/api/me', cookies=cookies)
264 request('/auth/file/check', cookies=file_cookies, status=204, host=file)277 request('/auth/file/check', cookies=file_cookies, status=204, host=file)
265 shale_session = {}; shale_csrf = request('/auth/status', cookies=shale_session)['csrf']278 shale_session = {}; shale_csrf = request('/auth/status', cookies=shale_session)['csrf']