| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | |
| 15 | |
| 16 | |
| 17 | |
| 18 | |
| 19 | |
| 20 | use std::net::SocketAddr; |
| 21 | |
| 22 | use steid::{ |
| 23 | application::AppConfig, |
| 24 | domain::SetupToken, |
| 25 | infrastructure::{app, database}, |
| 26 | }; |
| 27 | use tempfile::TempDir; |
| 28 | use tokio::{net::TcpListener, sync::oneshot, task::JoinHandle}; |
| 29 | use topcoat::asset::AssetBundle; |
| 30 | |
| 31 | |
| 32 | |
| 33 | struct Instance { |
| 34 | base: String, |
| 35 | |
| 36 | setup_token: String, |
| 37 | |
| 38 | _dir: TempDir, |
| 39 | stop: Option<oneshot::Sender<()>>, |
| 40 | serving: Option<JoinHandle<()>>, |
| 41 | } |
| 42 | |
| 43 | impl Instance { |
| 44 | |
| 45 | fn url(&self, path: &str) -> String { |
| 46 | format!("{}{path}", self.base) |
| 47 | } |
| 48 | } |
| 49 | |
| 50 | impl Drop for Instance { |
| 51 | fn drop(&mut self) { |
| 52 | |
| 53 | |
| 54 | |
| 55 | if let Some(stop) = self.stop.take() { |
| 56 | let _ = stop.send(()); |
| 57 | } |
| 58 | if let Some(serving) = self.serving.take() { |
| 59 | serving.abort(); |
| 60 | } |
| 61 | } |
| 62 | } |
| 63 | |
| 64 | |
| 65 | async fn boot() -> Instance { |
| 66 | let dir = tempfile::tempdir().expect("a temp dir"); |
| 67 | let data_dir = dir.path().join("data"); |
| 68 | std::fs::create_dir_all(&data_dir).expect("mkdir"); |
| 69 | |
| 70 | let config = AppConfig { |
| 71 | database_url: format!("sqlite:{}?mode=rwc", dir.path().join("steid.db").display()), |
| 72 | data_dir, |
| 73 | |
| 74 | |
| 75 | |
| 76 | insecure_cookies: false, |
| 77 | allow_private_webhooks: false, |
| 78 | trusted_proxy: false, |
| 79 | |
| 80 | |
| 81 | operator_token: None, |
| 82 | setup_token: None, |
| 83 | backup_marker: None, |
| 84 | smtp_url: None, |
| 85 | mail_from: None, |
| 86 | public_url: None, |
| 87 | }; |
| 88 | |
| 89 | let pool = database::connect(&config.database_url) |
| 90 | .await |
| 91 | .expect("the database opens"); |
| 92 | |
| 93 | let token = SetupToken::generate(); |
| 94 | let setup_token = token.reveal().to_owned(); |
| 95 | |
| 96 | let router = app::build(config, pool, assets(), Some(token)) |
| 97 | .await |
| 98 | .build(); |
| 99 | |
| 100 | |
| 101 | |
| 102 | let listener = TcpListener::bind("127.0.0.1:0").await.expect("a port"); |
| 103 | let addr: SocketAddr = listener.local_addr().expect("the address it got"); |
| 104 | |
| 105 | let (stop, stopped) = oneshot::channel(); |
| 106 | let serving = tokio::spawn(async move { |
| 107 | let _ = topcoat::serve_until(listener, router, async { |
| 108 | let _ = stopped.await; |
| 109 | }) |
| 110 | .await; |
| 111 | }); |
| 112 | |
| 113 | Instance { |
| 114 | base: format!("http://{addr}"), |
| 115 | setup_token, |
| 116 | _dir: dir, |
| 117 | stop: Some(stop), |
| 118 | serving: Some(serving), |
| 119 | } |
| 120 | } |
| 121 | |
| 122 | |
| 123 | |
| 124 | |
| 125 | |
| 126 | |
| 127 | |
| 128 | |
| 129 | |
| 130 | fn assets() -> AssetBundle { |
| 131 | |
| 132 | |
| 133 | let dir = Box::leak(Box::new(tempfile::tempdir().expect("a temp dir"))); |
| 134 | std::fs::write( |
| 135 | dir.path().join("manifest.toml"), |
| 136 | "version = 1\nassets = []\n", |
| 137 | ) |
| 138 | .expect("the manifest is written"); |
| 139 | |
| 140 | AssetBundle::load_dir(dir.path()).expect("an empty bundle loads") |
| 141 | } |
| 142 | |
| 143 | |
| 144 | struct Answer { |
| 145 | status: u16, |
| 146 | headers: Vec<(String, String)>, |
| 147 | body: String, |
| 148 | } |
| 149 | |
| 150 | impl Answer { |
| 151 | |
| 152 | fn header(&self, name: &str) -> Option<&str> { |
| 153 | self.headers |
| 154 | .iter() |
| 155 | .find(|(key, _)| key.eq_ignore_ascii_case(name)) |
| 156 | .map(|(_, value)| value.as_str()) |
| 157 | } |
| 158 | } |
| 159 | |
| 160 | |
| 161 | |
| 162 | |
| 163 | |
| 164 | |
| 165 | |
| 166 | |
| 167 | |
| 168 | async fn request(url: String, body: Option<(&str, String)>) -> Answer { |
| 169 | let body = body.map(|(content_type, body)| (content_type.to_owned(), body)); |
| 170 | |
| 171 | tokio::task::spawn_blocking(move || { |
| 172 | let agent = ureq::Agent::config_builder() |
| 173 | |
| 174 | |
| 175 | |
| 176 | .http_status_as_error(false) |
| 177 | .max_redirects(0) |
| 178 | .build() |
| 179 | .new_agent(); |
| 180 | |
| 181 | let mut response = match body { |
| 182 | Some((content_type, body)) => agent |
| 183 | .post(&url) |
| 184 | .header("content-type", &content_type) |
| 185 | .send(&body) |
| 186 | .expect("the request completes"), |
| 187 | None => agent.get(&url).call().expect("the request completes"), |
| 188 | }; |
| 189 | |
| 190 | let status = response.status().as_u16(); |
| 191 | let headers = response |
| 192 | .headers() |
| 193 | .iter() |
| 194 | .map(|(name, value)| { |
| 195 | ( |
| 196 | name.as_str().to_owned(), |
| 197 | String::from_utf8_lossy(value.as_bytes()).into_owned(), |
| 198 | ) |
| 199 | }) |
| 200 | .collect(); |
| 201 | let body = response.body_mut().read_to_string().unwrap_or_default(); |
| 202 | |
| 203 | Answer { |
| 204 | status, |
| 205 | headers, |
| 206 | body, |
| 207 | } |
| 208 | }) |
| 209 | .await |
| 210 | .expect("the blocking thread finishes") |
| 211 | } |
| 212 | |
| 213 | async fn get(instance: &Instance, path: &str) -> Answer { |
| 214 | request(instance.url(path), None).await |
| 215 | } |
| 216 | |
| 217 | async fn post_form(instance: &Instance, path: &str, body: &str) -> Answer { |
| 218 | request( |
| 219 | instance.url(path), |
| 220 | Some(("application/x-www-form-urlencoded", body.to_owned())), |
| 221 | ) |
| 222 | .await |
| 223 | } |
| 224 | |
| 225 | async fn post_json(instance: &Instance, path: &str, body: String) -> Answer { |
| 226 | request(instance.url(path), Some(("application/json", body))).await |
| 227 | } |
| 228 | |
| 229 | |
| 230 | |
| 231 | |
| 232 | |
| 233 | |
| 234 | async fn claim(instance: &Instance) { |
| 235 | let body = format!( |
| 236 | r#"{{"setup_token":"{}","email":"ada@example.com","handle":"ada","password":"a-long-enough-password"}}"#, |
| 237 | instance.setup_token |
| 238 | ); |
| 239 | |
| 240 | let answer = post_json(instance, "/api/setup", body).await; |
| 241 | |
| 242 | assert_eq!(answer.status, 201, "the claim was refused: {}", answer.body); |
| 243 | assert!( |
| 244 | answer.body.contains("\"handle\":\"ada\""), |
| 245 | "{}", |
| 246 | answer.body |
| 247 | ); |
| 248 | } |
| 249 | |
| 250 | #[tokio::test] |
| 251 | async fn an_instance_boots_and_can_be_claimed_without_a_browser() { |
| 252 | let instance = boot().await; |
| 253 | |
| 254 | let before = get(&instance, "/api/instance").await; |
| 255 | assert_eq!(before.status, 200); |
| 256 | assert_eq!(before.body.trim(), r#"{"claimed":false}"#); |
| 257 | |
| 258 | claim(&instance).await; |
| 259 | |
| 260 | let after = get(&instance, "/api/instance").await; |
| 261 | assert_eq!(after.status, 200); |
| 262 | assert_eq!(after.body.trim(), r#"{"claimed":true}"#); |
| 263 | } |
| 264 | |
| 265 | #[tokio::test] |
| 266 | async fn every_response_carries_the_security_headers_including_a_404() { |
| 267 | let instance = boot().await; |
| 268 | |
| 269 | |
| 270 | |
| 271 | |
| 272 | for path in ["/api/instance", "/nothing-is-here"] { |
| 273 | let answer = get(&instance, path).await; |
| 274 | |
| 275 | assert!( |
| 276 | answer.status == 200 || answer.status == 404, |
| 277 | "{path} answered {}", |
| 278 | answer.status |
| 279 | ); |
| 280 | |
| 281 | let policy = answer |
| 282 | .header("content-security-policy") |
| 283 | .unwrap_or_else(|| panic!("{path} carries no CSP")); |
| 284 | assert!( |
| 285 | policy.contains("default-src 'none'"), |
| 286 | "{path}'s CSP is {policy}" |
| 287 | ); |
| 288 | assert!( |
| 289 | policy.contains("frame-ancestors 'none'"), |
| 290 | "{path}'s CSP is {policy}" |
| 291 | ); |
| 292 | |
| 293 | assert_eq!( |
| 294 | answer.header("x-content-type-options"), |
| 295 | Some("nosniff"), |
| 296 | "{path}" |
| 297 | ); |
| 298 | assert_eq!(answer.header("x-frame-options"), Some("DENY"), "{path}"); |
| 299 | |
| 300 | |
| 301 | assert_eq!( |
| 302 | answer.header("referrer-policy"), |
| 303 | Some("no-referrer"), |
| 304 | "{path}" |
| 305 | ); |
| 306 | assert_eq!( |
| 307 | answer.header("cache-control"), |
| 308 | Some("private, no-cache"), |
| 309 | "{path}" |
| 310 | ); |
| 311 | } |
| 312 | } |
| 313 | |
| 314 | #[tokio::test] |
| 315 | async fn a_post_without_a_csrf_token_is_refused_with_a_403() { |
| 316 | let instance = boot().await; |
| 317 | |
| 318 | |
| 319 | |
| 320 | |
| 321 | |
| 322 | let empty = post_form(&instance, "/auth/logout", "").await; |
| 323 | assert_eq!(empty.status, 403, "{}", empty.body); |
| 324 | assert!( |
| 325 | empty.body.contains("submitted from somewhere else"), |
| 326 | "{}", |
| 327 | empty.body |
| 328 | ); |
| 329 | |
| 330 | let wrong = post_form(&instance, "/auth/logout", "csrf_token=not-a-token").await; |
| 331 | assert_eq!(wrong.status, 403, "{}", wrong.body); |
| 332 | |
| 333 | |
| 334 | |
| 335 | assert_eq!(empty.header("x-frame-options"), Some("DENY")); |
| 336 | } |
| 337 | |
| 338 | #[tokio::test] |
| 339 | async fn metrics_without_the_bearer_does_not_exist() { |
| 340 | let instance = boot().await; |
| 341 | |
| 342 | |
| 343 | |
| 344 | |
| 345 | let metrics = get(&instance, "/metrics").await; |
| 346 | let unrouted = get(&instance, "/definitely-not-a-route").await; |
| 347 | |
| 348 | assert_eq!(metrics.status, 404); |
| 349 | assert_eq!(metrics.status, unrouted.status); |
| 350 | assert_eq!(metrics.body, unrouted.body); |
| 351 | |
| 352 | assert!( |
| 353 | !metrics.body.contains("steid_http_requests_total"), |
| 354 | "the counters leaked into the refusal: {}", |
| 355 | metrics.body |
| 356 | ); |
| 357 | } |