Expand description
Request checks that protect the dashboard from cross-site requests (CSRF) and oversized request bodies.
A web page the operator visits can make the browser send requests to the dashboard, and the browser attaches cached Basic credentials to them. Two independent checks stop that:
same_origin_writesrefuses state-changing requests (every method exceptGET,HEADandOPTIONS) that a browser sent from another origin, judged by theSec-Fetch-Siteheader or, without it, by comparingOriginwith theHostthe request was sent to.same_originapplies the same rule to every method, for the WebSocket handshake. Requests without either header (curl, scripts) are not from a browser page and pass. Origins listed inAllowedOriginspass as well.json_bodyonly accepts bodies sent asContent-Type: application/json, which a page on another origin cannot send without a CORS preflight, and at mostMAX_JSON_BODY_BYTESof them.
use hammerwork_web::security::{AllowedOrigins, normalize_origin};
assert_eq!(
normalize_origin("https://Ops.Example.com/").as_deref(),
Some("https://ops.example.com")
);
assert!(normalize_origin("https://ops.example.com/path").is_none());
let allowed = AllowedOrigins::new(["https://ops.example.com"]).unwrap();
assert!(allowed.contains("https://ops.example.com"));
assert!(!allowed.contains("https://evil.example"));Structs§
- Allowed
Origins - Origins other than the dashboard’s own that may send state-changing requests (and, with CORS enabled, read API responses).
Enums§
- Request
Refused - Why a request was refused before reaching its handler.
Constants§
- MAX_
JSON_ BODY_ BYTES - The largest JSON request body the API accepts, in bytes.
Functions§
- json_
body - A JSON request body: requires
Content-Type: application/jsonand aContent-Lengthof at mostMAX_JSON_BODY_BYTES, then deserializes the body. - normalize_
origin - The canonical form of a web origin (
scheme://host[:port], lowercase, without a trailing slash), orNoneiforiginis not one: the scheme must behttporhttps, the host must be present, a port must be a number, and there must be no path, query or user info. - request_
allowed - Whether a request with these headers may proceed.
- same_
origin - Refuses every request a browser sent from another origin, whatever its method. Used for
the WebSocket handshake, which is a
GET. - same_
origin_ writes - Refuses state-changing requests (any method but
GET,HEADandOPTIONS) that a browser sent from another origin. Seerequest_allowed.