oxedyne/fe2o3/fe2o3_steel/tests/console_session_renewal.rs
9.7 KiB, 1 run
created by r939070283:78512, which is this file's identity for as long as the history lasts, whatever it is later renamed to
download · who wrote it · its history
| 1 | //! The console's passphrase session over the real gate: renewed while in use, ended by its idle and |
| 2 | //! absolute limits, its CSRF token stable across renewal, and a lapsed session told to a fetch as a |
| 3 | //! 401 it can read while a browser's form is still redirected. |
| 4 | //! |
| 5 | //! The fault this guards (15 Nov 2026): a manage session lasted a fixed 30 minutes, nothing renewed |
| 6 | //! it, and every save after that was answered by a 303 to the home page that the editor read as |
| 7 | //! "The server did not answer." |
| 8 | |
| 9 | use oxedyne_fe2o3_steel::srv::{ |
| 10 | admin::{ |
| 11 | guard, |
| 12 | host_sampler::HostSampler, |
| 13 | session::now_secs, |
| 14 | state::AdminState, |
| 15 | traffic::TrafficRecorder, |
| 16 | }, |
| 17 | console::{ |
| 18 | self, |
| 19 | PATH_LOGIN, |
| 20 | PATH_STATUS, |
| 21 | NET_JS, |
| 22 | publish::{ |
| 23 | PATH_AI_FIX, |
| 24 | PATH_RENDER, |
| 25 | }, |
| 26 | session::{ |
| 27 | self, |
| 28 | MANAGE_COOKIE_NAME, |
| 29 | ManageSession, |
| 30 | ManageTtl, |
| 31 | }, |
| 32 | }, |
| 33 | id::{ |
| 34 | UID_LEN, |
| 35 | Uid, |
| 36 | }, |
| 37 | publish::send::MailSender, |
| 38 | }; |
| 39 | |
| 40 | use oxedyne_fe2o3_core::prelude::*; |
| 41 | use oxedyne_fe2o3_crypto::{ |
| 42 | enc::EncryptionScheme, |
| 43 | keystore::Wallet, |
| 44 | }; |
| 45 | use oxedyne_fe2o3_hash::{ |
| 46 | csum::ChecksumScheme, |
| 47 | hash::HashScheme, |
| 48 | }; |
| 49 | use oxedyne_fe2o3_net::http::{ |
| 50 | fields::{ |
| 51 | Cookie, |
| 52 | HeaderFieldValue, |
| 53 | HeaderFields, |
| 54 | HeaderName, |
| 55 | }, |
| 56 | header::HttpHeadline, |
| 57 | msg::HttpMessage, |
| 58 | status::HttpStatus, |
| 59 | }; |
| 60 | |
| 61 | use tokio_rustls::rustls::ClientConfig; |
| 62 | |
| 63 | use std::{ |
| 64 | net::SocketAddr, |
| 65 | path::PathBuf, |
| 66 | sync::{ |
| 67 | Arc, |
| 68 | RwLock, |
| 69 | }, |
| 70 | }; |
| 71 | |
| 72 | type TestDb = oxedyne_fe2o3_o3db_sync::O3db< |
| 73 | { UID_LEN }, |
| 74 | Uid, |
| 75 | EncryptionScheme, |
| 76 | HashScheme, |
| 77 | HashScheme, |
| 78 | ChecksumScheme, |
| 79 | >; |
| 80 | |
| 81 | const TTL: ManageTtl = ManageTtl { |
| 82 | idle_secs: 7_200, |
| 83 | absolute_secs: 86_400, |
| 84 | touch_secs: 60, |
| 85 | }; |
| 86 | |
| 87 | fn state() -> Outcome<AdminState> { |
| 88 | Ok(res!(AdminState::new( |
| 89 | Arc::new(RwLock::new(Wallet::default())), |
| 90 | PathBuf::from("./wallet.jdat"), |
| 91 | Some([0u8; 32].to_vec()), |
| 92 | 1, |
| 93 | None, |
| 94 | TrafficRecorder::new_shared(0), |
| 95 | HostSampler::new_shared(), |
| 96 | res!(guard::new_shared()), |
| 97 | res!(guard::new_auth_shared()), |
| 98 | Vec::new(), |
| 99 | None, |
| 100 | )).with_manage_ttl(TTL)) |
| 101 | } |
| 102 | |
| 103 | /// A sealed session for "jason", signed in `ago` seconds back and last renewed `seen_ago` back. |
| 104 | fn cookie(st: &AdminState, ago: u64, seen_ago: u64) -> Outcome<(ManageSession, String)> { |
| 105 | let now = now_secs(); |
| 106 | let mut s = ManageSession::new("jason", now - ago); |
| 107 | s.seen = now - seen_ago; |
| 108 | let v = res!(session::seal(st, &s)); |
| 109 | Ok((s, v)) |
| 110 | } |
| 111 | |
| 112 | fn headers(manage: Option<&str>, json: bool) -> Arc<HeaderFields> { |
| 113 | let mut h = HeaderFields::default(); |
| 114 | if json { |
| 115 | h.insert(HeaderName::Accept, HeaderFieldValue::Generic("application/json".to_string()), None); |
| 116 | } |
| 117 | if let Some(v) = manage { |
| 118 | h.insert( |
| 119 | HeaderName::Cookie, |
| 120 | HeaderFieldValue::Cookie(vec![Cookie { |
| 121 | key: MANAGE_COOKIE_NAME.to_string(), |
| 122 | val: v.to_string(), |
| 123 | attrs: None, |
| 124 | }]), |
| 125 | None, |
| 126 | ); |
| 127 | } |
| 128 | Arc::new(h) |
| 129 | } |
| 130 | |
| 131 | async fn get(st: &AdminState, path: &str, h: &Arc<HeaderFields>) -> Outcome<HttpMessage> { |
| 132 | console::handle_get::<{ UID_LEN }, Uid, EncryptionScheme, HashScheme, TestDb>( |
| 133 | &[], Some(st), None, None, path, "", h, "t", |
| 134 | ).await |
| 135 | } |
| 136 | |
| 137 | async fn post(st: &AdminState, path: &str, h: &Arc<HeaderFields>, body: &str) -> Outcome<HttpMessage> { |
| 138 | let tls: Option<Arc<ClientConfig>> = None; |
| 139 | let mail: Option<Arc<MailSender>> = None; |
| 140 | let resp = res!(console::handle_post::<{ UID_LEN }, Uid, EncryptionScheme, HashScheme, TestDb>( |
| 141 | &[], Some(st), None, None, &tls, &mail, path, h, body.as_bytes(), |
| 142 | SocketAddr::from(([127, 0, 0, 1], 0)), "t", |
| 143 | ).await); |
| 144 | resp.ok_or_else(|| err!("The console did not answer a POST to '{}'.", path; Missing)) |
| 145 | } |
| 146 | |
| 147 | fn status_of(r: &HttpMessage) -> Option<HttpStatus> { |
| 148 | match &r.header.headline { |
| 149 | HttpHeadline::Response { status } => Some(*status), |
| 150 | _ => None, |
| 151 | } |
| 152 | } |
| 153 | |
| 154 | fn set_cookie_of(r: &HttpMessage) -> Option<String> { |
| 155 | match r.header.fields.get_one(&HeaderName::SetCookie) { |
| 156 | Some(HeaderFieldValue::SetCookie(c)) => Some(c.val.clone()), |
| 157 | _ => None, |
| 158 | } |
| 159 | } |
| 160 | |
| 161 | /// The CSRF token a status answer hands out. |
| 162 | fn csrf_of(r: &HttpMessage) -> Outcome<String> { |
| 163 | let body = r.body_as_string().into_owned(); |
| 164 | let at = res!(body.find("\"csrf\":\"").ok_or_else(|| err!("No csrf in '{}'.", body; Missing))); |
| 165 | let rest = &body[at + 8..]; |
| 166 | let end = res!(rest.find('"').ok_or_else(|| err!("Unterminated csrf in '{}'.", body; Invalid))); |
| 167 | Ok(rest[..end].to_string()) |
| 168 | } |
| 169 | |
| 170 | /// A session used after its touch gap is answered with a fresh cookie: same id and sign-in time, |
| 171 | /// renewed now, so it outlives the one it replaces. |
| 172 | #[tokio::test] |
| 173 | async fn test_a_session_in_use_is_renewed_00() -> Outcome<()> { |
| 174 | let st = res!(state()); |
| 175 | let (old, value) = res!(cookie(&st, 3_600, 3_000)); |
| 176 | let resp = res!(get(&st, PATH_STATUS, &headers(Some(&value), true)).await); |
| 177 | let fresh = res!(set_cookie_of(&resp).ok_or_else(|| err!("No renewal cookie."; Missing))); |
| 178 | let s = res!(session::decode(&st, &fresh)); |
| 179 | assert_eq!(s.sid, old.sid); |
| 180 | assert_eq!(s.issued, old.issued); |
| 181 | assert!(s.seen >= now_secs() - 1, "renewal did not move the last-seen time"); |
| 182 | // The old cookie lapses 4,200 s from now; the renewed one is good well past that. |
| 183 | let later = now_secs() + 5_000; |
| 184 | assert!(session::decode_at(&st, &value, later).is_err()); |
| 185 | assert!(session::decode_at(&st, &fresh, later).is_ok()); |
| 186 | Ok(()) |
| 187 | } |
| 188 | |
| 189 | /// Within the touch gap nothing is re-issued, so not every request carries a Set-Cookie. |
| 190 | #[tokio::test] |
| 191 | async fn test_no_renewal_within_the_touch_gap_01() -> Outcome<()> { |
| 192 | let st = res!(state()); |
| 193 | let (_, value) = res!(cookie(&st, 10, 10)); |
| 194 | let resp = res!(get(&st, PATH_STATUS, &headers(Some(&value), true)).await); |
| 195 | assert!(resp.body_as_string().contains("\"admin\":true")); |
| 196 | assert!(set_cookie_of(&resp).is_none()); |
| 197 | Ok(()) |
| 198 | } |
| 199 | |
| 200 | /// However busily used, a session ends at its absolute limit, and a fetch is told so in JSON. |
| 201 | #[tokio::test] |
| 202 | async fn test_the_absolute_limit_ends_a_busy_session_02() -> Outcome<()> { |
| 203 | let st = res!(state()); |
| 204 | let (_, value) = res!(cookie(&st, TTL.absolute_secs + 1, 10)); |
| 205 | let resp = res!(post(&st, PATH_AI_FIX, &headers(Some(&value), true), "csrf=x&source=hi").await); |
| 206 | assert_eq!(status_of(&resp), Some(HttpStatus::Unauthorized)); |
| 207 | assert!(set_cookie_of(&resp).is_none(), "an ended session was renewed"); |
| 208 | Ok(()) |
| 209 | } |
| 210 | |
| 211 | /// An unused session ends after its idle time. |
| 212 | #[tokio::test] |
| 213 | async fn test_an_idle_session_ends_03() -> Outcome<()> { |
| 214 | let st = res!(state()); |
| 215 | let (_, value) = res!(cookie(&st, TTL.idle_secs + 10, TTL.idle_secs + 1)); |
| 216 | let resp = res!(post(&st, PATH_AI_FIX, &headers(Some(&value), true), "csrf=x&source=hi").await); |
| 217 | assert_eq!(status_of(&resp), Some(HttpStatus::Unauthorized)); |
| 218 | Ok(()) |
| 219 | } |
| 220 | |
| 221 | /// A signed-out fetch, write or read, gets 401 JSON that names where to sign in. |
| 222 | #[tokio::test] |
| 223 | async fn test_a_signed_out_fetch_gets_401_json_04() -> Outcome<()> { |
| 224 | let st = res!(state()); |
| 225 | let h = headers(None, true); |
| 226 | for resp in [ |
| 227 | res!(post(&st, PATH_AI_FIX, &h, "csrf=x&source=probe").await), |
| 228 | res!(get(&st, console::PATH_ROOT, &h).await), |
| 229 | ] { |
| 230 | assert_eq!(status_of(&resp), Some(HttpStatus::Unauthorized)); |
| 231 | match resp.header.fields.get_one(&HeaderName::ContentType) { |
| 232 | Some(HeaderFieldValue::Generic(t)) => assert!(t.contains("application/json")), |
| 233 | other => panic!("content type {:?}", other), |
| 234 | } |
| 235 | let body = resp.body_as_string(); |
| 236 | assert!(body.contains("\"error\":\"signed out; sign in again\""), "{}", body); |
| 237 | assert!(body.contains(&fmt!("\"signin\":\"{}\"", PATH_LOGIN)), "{}", body); |
| 238 | } |
| 239 | Ok(()) |
| 240 | } |
| 241 | |
| 242 | /// A browser's form post and page visit are unchanged: a redirect, and the sign-in form. |
| 243 | #[tokio::test] |
| 244 | async fn test_a_signed_out_navigation_is_redirected_05() -> Outcome<()> { |
| 245 | let st = res!(state()); |
| 246 | let h = headers(None, false); |
| 247 | let resp = res!(post(&st, PATH_AI_FIX, &h, "csrf=x&source=probe").await); |
| 248 | assert_eq!(status_of(&resp), Some(HttpStatus::SeeOther)); |
| 249 | let page = res!(get(&st, console::PATH_ROOT, &h).await); |
| 250 | assert_eq!(status_of(&page), Some(HttpStatus::OK)); |
| 251 | assert!(page.body_as_string().contains("type=\"password\"")); |
| 252 | Ok(()) |
| 253 | } |
| 254 | |
| 255 | /// The token a page was rendered with still passes after the cookie under it was renewed. |
| 256 | #[tokio::test] |
| 257 | async fn test_the_csrf_token_holds_across_renewal_06() -> Outcome<()> { |
| 258 | let st = res!(state()); |
| 259 | let (_, value) = res!(cookie(&st, 3_600, 3_000)); |
| 260 | let first = res!(get(&st, PATH_STATUS, &headers(Some(&value), true)).await); |
| 261 | let token = res!(csrf_of(&first)); |
| 262 | let fresh = res!(set_cookie_of(&first).ok_or_else(|| err!("No renewal cookie."; Missing))); |
| 263 | assert_ne!(fresh, value); |
| 264 | |
| 265 | let again = res!(get(&st, PATH_STATUS, &headers(Some(&fresh), true)).await); |
| 266 | assert_eq!(res!(csrf_of(&again)), token); |
| 267 | |
| 268 | let body = fmt!("csrf={}&markup=markdown&source=hello", token); |
| 269 | let resp = res!(post(&st, PATH_RENDER, &headers(Some(&fresh), true), &body).await); |
| 270 | assert_eq!(status_of(&resp), Some(HttpStatus::OK)); |
| 271 | assert!(resp.body_as_string().contains("\"html\""), "{}", resp.body_as_string()); |
| 272 | Ok(()) |
| 273 | } |
| 274 | |
| 275 | /// A live session with another session's token is refused as stale, flagged so the page can take |
| 276 | /// the current token and try again. |
| 277 | #[tokio::test] |
| 278 | async fn test_a_stale_token_is_flagged_07() -> Outcome<()> { |
| 279 | let st = res!(state()); |
| 280 | let (_, value) = res!(cookie(&st, 10, 10)); |
| 281 | let resp = res!(post(&st, PATH_RENDER, &headers(Some(&value), true), "csrf=other&source=hi").await); |
| 282 | assert_eq!(status_of(&resp), Some(HttpStatus::Forbidden)); |
| 283 | assert!(resp.body_as_string().contains("\"stale\":true")); |
| 284 | Ok(()) |
| 285 | } |
| 286 | |
| 287 | /// A lifetime that would let a session in use lapse between renewals, or never end, is refused. |
| 288 | #[test] |
| 289 | fn test_an_unsafe_lifetime_is_refused_08() { |
| 290 | assert!(TTL.check().is_ok()); |
| 291 | assert!(ManageTtl::default().check().is_ok()); |
| 292 | assert!(ManageTtl { touch_secs: TTL.idle_secs, ..TTL }.check().is_err()); |
| 293 | assert!(ManageTtl { idle_secs: 0, ..TTL }.check().is_err()); |
| 294 | assert!(ManageTtl { absolute_secs: 0, ..TTL }.check().is_err()); |
| 295 | } |
| 296 | |
| 297 | /// The page's fetch helper asks the status path this crate serves for a fresh token. |
| 298 | #[test] |
| 299 | fn test_the_fetch_helper_names_the_status_path_09() { |
| 300 | assert!(NET_JS.contains(&fmt!("'{}'", PATH_STATUS))); |
| 301 | } |