1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
use crate::axum::{
body::Body,
extract::{Request, State},
middleware::{from_fn, from_fn_with_state, Next},
response::Response,
Router,
};
use crate::config::CorsConfig;
use http::{header, HeaderValue, Method, StatusCode};
use std::sync::Arc;
use tower_http::{
catch_panic::CatchPanicLayer,
cors::{Any, CorsLayer},
};
/// A router transformation registered by the app to insert its own middleware
/// relative to doido's always-on stack (Rails `config.middleware.insert_*`).
type RouterTransform = Box<dyn FnOnce(Router) -> Router + Send>;
pub struct MiddlewareStack {
cors: bool,
cors_config: Option<CorsConfig>,
allowed_hosts: Vec<String>,
csrf: bool,
force_ssl: bool,
api_only: bool,
before: Vec<RouterTransform>,
after: Vec<RouterTransform>,
}
impl MiddlewareStack {
pub fn new() -> Self {
Self {
cors: false,
cors_config: None,
allowed_hosts: Vec::new(),
csrf: false,
force_ssl: false,
api_only: false,
before: Vec::new(),
after: Vec::new(),
}
}
/// Mark the stack as serving a JSON-only API (`doido new --api`). HTML-only
/// middleware that makes no difference for `application/json` clients is
/// skipped even if requested: CSRF (form double-submit) is a no-op here, and
/// future session/flash/static-file layers must honor this flag too. Security
/// layers relevant to any content type (CORS, force-SSL, host allowlist,
/// logging, panic recovery) are unaffected.
pub fn with_api_only(mut self, api_only: bool) -> Self {
self.api_only = api_only;
self
}
/// Enable CSRF protection (double-submit cookie): state-changing requests
/// must send an `X-CSRF-Token` header matching the `csrf_token` cookie.
pub fn with_csrf(mut self) -> Self {
self.csrf = true;
self
}
/// Redirect insecure requests to HTTPS (Rails `force_ssl`). A request is
/// considered secure when its `X-Forwarded-Proto` is `https` (or the URI
/// scheme is `https`); otherwise it gets a 301 to the `https://` URL.
pub fn with_force_ssl(mut self) -> Self {
self.force_ssl = true;
self
}
/// Insert custom middleware **inside** the always-on layers (closer to the
/// router), i.e. it runs after logging/panic-recovery on the way in. The
/// closure receives the router and returns it with its `.layer(...)` added.
pub fn insert_before(
mut self,
transform: impl FnOnce(Router) -> Router + Send + 'static,
) -> Self {
self.before.push(Box::new(transform));
self
}
/// Insert custom middleware **outside** the always-on layers (outermost), so
/// it wraps the whole stack.
pub fn insert_after(
mut self,
transform: impl FnOnce(Router) -> Router + Send + 'static,
) -> Self {
self.after.push(Box::new(transform));
self
}
/// Enable permissive CORS (any origin/method/header). For fine-grained,
/// config-driven CORS use [`with_cors_config`](Self::with_cors_config).
pub fn with_cors(mut self) -> Self {
self.cors = true;
self
}
/// Enable CORS from parsed [`CorsConfig`] (spec 07 `[middleware.cors]`). A
/// config with `enabled: false` is ignored, keeping CORS opt-in.
pub fn with_cors_config(mut self, config: CorsConfig) -> Self {
self.cors_config = Some(config);
self
}
/// Restrict requests to an allowlist of `Host` header values (Rails
/// `config.hosts` / `ActionDispatch::HostAuthorization`). An empty list
/// permits any host; a request whose host is not listed gets a `403`.
pub fn with_allowed_hosts(mut self, hosts: Vec<String>) -> Self {
self.allowed_hosts = hosts;
self
}
pub fn apply(self, router: Router) -> Router {
// App-registered "before" middleware sits innermost (closest to routes).
let mut r = router;
for transform in self.before {
r = transform(r);
}
// Log every request and its response (method, path, status, latency)
// through doido's centralized logger. Added after `CatchPanicLayer` so
// it sits outermost and logs panic-recovered `500`s too.
r = r
.layer(CatchPanicLayer::new())
.layer(from_fn(crate::logging::log_requests));
match &self.cors_config {
Some(config) if config.enabled => r = r.layer(build_cors(config)),
_ if self.cors => r = r.layer(CorsLayer::permissive()),
_ => {}
}
if !self.allowed_hosts.is_empty() {
r = r.layer(from_fn_with_state(Arc::new(self.allowed_hosts), host_guard));
}
// CSRF is a form/cookie defense; a JSON API authenticates with tokens and
// is protected by CORS, so the guard is skipped entirely in API mode.
if self.csrf && !self.api_only {
r = r.layer(from_fn(csrf_guard));
}
if self.force_ssl {
r = r.layer(from_fn(force_ssl_guard));
}
// App-registered "after" middleware wraps everything (outermost).
for transform in self.after {
r = transform(r);
}
r
}
}
/// Redirect insecure requests to their `https://` equivalent with a 301.
async fn force_ssl_guard(request: Request, next: Next) -> Response {
let forwarded_https = request
.headers()
.get("x-forwarded-proto")
.and_then(|v| v.to_str().ok())
.map(|p| p.eq_ignore_ascii_case("https"))
.unwrap_or(false);
let scheme_https = request.uri().scheme_str() == Some("https");
if forwarded_https || scheme_https {
return next.run(request).await;
}
let host = request
.headers()
.get(header::HOST)
.and_then(|v| v.to_str().ok())
.unwrap_or("");
let path = request
.uri()
.path_and_query()
.map(|pq| pq.as_str())
.unwrap_or("/");
let location = format!("https://{host}{path}");
match HeaderValue::from_str(&location) {
Ok(value) => {
let mut response = Response::builder()
.status(StatusCode::MOVED_PERMANENTLY)
.body(Body::empty())
.expect("valid 301 response");
response.headers_mut().insert(header::LOCATION, value);
response
}
Err(_) => Response::builder()
.status(StatusCode::BAD_REQUEST)
.body(Body::empty())
.expect("valid 400 response"),
}
}
/// Enforce the double-submit CSRF check on state-changing methods. Safe methods
/// (GET/HEAD/OPTIONS/TRACE) always pass; others require the `csrf_token` cookie
/// and the `X-CSRF-Token` header to be present and equal.
async fn csrf_guard(request: Request, next: Next) -> Response {
let method = request.method();
let is_safe = matches!(
*method,
Method::GET | Method::HEAD | Method::OPTIONS | Method::TRACE
);
if is_safe {
return next.run(request).await;
}
let cookie_token = request
.headers()
.get(header::COOKIE)
.and_then(|c| c.to_str().ok())
.and_then(crate::csrf::token_from_cookie_header);
let header_token = request
.headers()
.get("x-csrf-token")
.and_then(|h| h.to_str().ok())
.map(str::to_string);
match (cookie_token, header_token) {
(Some(cookie), Some(header)) if crate::csrf::tokens_match(&cookie, &header) => {
next.run(request).await
}
_ => Response::builder()
.status(StatusCode::FORBIDDEN)
.body(Body::from("CSRF token mismatch"))
.expect("valid 403 response"),
}
}
/// Reject requests whose `Host` header (port stripped) is not in the allowlist.
async fn host_guard(
State(allowed): State<Arc<Vec<String>>>,
request: Request,
next: Next,
) -> Response {
let host = request
.headers()
.get(header::HOST)
.and_then(|h| h.to_str().ok())
.map(|h| h.split(':').next().unwrap_or(h).to_string());
match host {
Some(h) if allowed.iter().any(|a| a == &h) => next.run(request).await,
_ => Response::builder()
.status(StatusCode::FORBIDDEN)
.body(Body::from("Forbidden host"))
.expect("valid 403 response"),
}
}
/// Build a [`CorsLayer`] from configuration. `"*"` in `allowed_origins` maps to
/// "any origin"; otherwise each origin/method is parsed and unparseable entries
/// are skipped.
fn build_cors(config: &CorsConfig) -> CorsLayer {
let mut layer = CorsLayer::new();
if config.allowed_origins.iter().any(|o| o == "*") {
layer = layer.allow_origin(Any);
} else {
let origins: Vec<HeaderValue> = config
.allowed_origins
.iter()
.filter_map(|o| o.parse().ok())
.collect();
if !origins.is_empty() {
layer = layer.allow_origin(origins);
}
}
let methods: Vec<Method> = config
.allowed_methods
.iter()
.filter_map(|m| Method::from_bytes(m.as_bytes()).ok())
.collect();
if !methods.is_empty() {
layer = layer.allow_methods(methods);
}
layer
}
impl Default for MiddlewareStack {
fn default() -> Self {
Self::new()
}
}