Skip to main content

Module security

Module security 

Source
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_writes refuses state-changing requests (every method except GET, HEAD and OPTIONS) that a browser sent from another origin, judged by the Sec-Fetch-Site header or, without it, by comparing Origin with the Host the request was sent to. same_origin applies 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 in AllowedOrigins pass as well.
  • json_body only accepts bodies sent as Content-Type: application/json, which a page on another origin cannot send without a CORS preflight, and at most MAX_JSON_BODY_BYTES of 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§

AllowedOrigins
Origins other than the dashboard’s own that may send state-changing requests (and, with CORS enabled, read API responses).

Enums§

RequestRefused
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/json and a Content-Length of at most MAX_JSON_BODY_BYTES, then deserializes the body.
normalize_origin
The canonical form of a web origin (scheme://host[:port], lowercase, without a trailing slash), or None if origin is not one: the scheme must be http or https, 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, HEAD and OPTIONS) that a browser sent from another origin. See request_allowed.