PNRxA commited on
Commit
5f0e2ae
·
1 Parent(s): cdc7037

CORS lockdown, path traversal prevention, error redaction, password max

Browse files

length, API key log redaction, timing side-channel fix, HSTS, and poster
rate limiting

api/Cargo.toml CHANGED
@@ -15,7 +15,7 @@ ab_glyph = "0.2.32"
15
  tracing = "0.1.44"
16
  tracing-subscriber = { version = "0.3.22", features = ["env-filter"] }
17
  thiserror = "2.0.18"
18
- tower-http = { version = "0.6.8", features = ["trace", "cors", "compression-gzip", "fs"] }
19
  dashmap = "6.1.0"
20
  moka = { version = "0.12.14", features = ["future", "sync"] }
21
  dotenvy = "0.15.7"
 
15
  tracing = "0.1.44"
16
  tracing-subscriber = { version = "0.3.22", features = ["env-filter"] }
17
  thiserror = "2.0.18"
18
+ tower-http = { version = "0.6.8", features = ["trace", "cors", "compression-gzip", "fs", "set-header"] }
19
  dashmap = "6.1.0"
20
  moka = { version = "0.12.14", features = ["future", "sync"] }
21
  dotenvy = "0.15.7"
api/src/cache/mod.rs CHANGED
@@ -18,14 +18,24 @@ pub struct MemCacheEntry {
18
  pub last_checked: Instant,
19
  }
20
 
21
- pub fn cache_path(cache_dir: &str, id_type: &str, id_value: &str) -> PathBuf {
22
- Path::new(cache_dir).join(id_type).join(format!("{id_value}.jpg"))
23
  }
24
 
25
- pub fn poster_cache_path(cache_dir: &str, poster_path: &str) -> PathBuf {
 
 
 
 
 
 
 
26
  // poster_path is like "/abc123.jpg" from TMDB
27
  let filename = poster_path.trim_start_matches('/');
28
- Path::new(cache_dir).join("posters").join(filename)
 
 
 
29
  }
30
 
31
  /// Read a cached file. `stale_secs = 0` means never stale.
@@ -213,22 +223,39 @@ mod tests {
213
 
214
  #[test]
215
  fn cache_path_construction() {
216
- let p = cache_path("/tmp/cache", "imdb", "tt1234567");
217
  assert_eq!(p, PathBuf::from("/tmp/cache/imdb/tt1234567.jpg"));
218
  }
219
 
220
  #[test]
221
  fn poster_cache_path_strips_leading_slash() {
222
- let p = poster_cache_path("/tmp/cache", "/abc123.jpg");
223
  assert_eq!(p, PathBuf::from("/tmp/cache/posters/abc123.jpg"));
224
  }
225
 
226
  #[test]
227
  fn poster_cache_path_no_leading_slash() {
228
- let p = poster_cache_path("/tmp/cache", "abc123.jpg");
229
  assert_eq!(p, PathBuf::from("/tmp/cache/posters/abc123.jpg"));
230
  }
231
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
232
  #[test]
233
  fn is_leap_year_cases() {
234
  assert!(is_leap(2000)); // divisible by 400
 
18
  pub last_checked: Instant,
19
  }
20
 
21
+ fn is_safe_path_component(s: &str) -> bool {
22
+ !s.is_empty() && s != "." && s != ".." && !s.contains('/') && !s.contains('\\') && !s.contains('\0')
23
  }
24
 
25
+ pub fn cache_path(cache_dir: &str, id_type: &str, id_value: &str) -> Result<PathBuf, AppError> {
26
+ if !is_safe_path_component(id_value) {
27
+ return Err(AppError::BadRequest("invalid id value".into()));
28
+ }
29
+ Ok(Path::new(cache_dir).join(id_type).join(format!("{id_value}.jpg")))
30
+ }
31
+
32
+ pub fn poster_cache_path(cache_dir: &str, poster_path: &str) -> Result<PathBuf, AppError> {
33
  // poster_path is like "/abc123.jpg" from TMDB
34
  let filename = poster_path.trim_start_matches('/');
35
+ if !is_safe_path_component(filename) {
36
+ return Err(AppError::BadRequest("invalid poster path".into()));
37
+ }
38
+ Ok(Path::new(cache_dir).join("posters").join(filename))
39
  }
40
 
41
  /// Read a cached file. `stale_secs = 0` means never stale.
 
223
 
224
  #[test]
225
  fn cache_path_construction() {
226
+ let p = cache_path("/tmp/cache", "imdb", "tt1234567").unwrap();
227
  assert_eq!(p, PathBuf::from("/tmp/cache/imdb/tt1234567.jpg"));
228
  }
229
 
230
  #[test]
231
  fn poster_cache_path_strips_leading_slash() {
232
+ let p = poster_cache_path("/tmp/cache", "/abc123.jpg").unwrap();
233
  assert_eq!(p, PathBuf::from("/tmp/cache/posters/abc123.jpg"));
234
  }
235
 
236
  #[test]
237
  fn poster_cache_path_no_leading_slash() {
238
+ let p = poster_cache_path("/tmp/cache", "abc123.jpg").unwrap();
239
  assert_eq!(p, PathBuf::from("/tmp/cache/posters/abc123.jpg"));
240
  }
241
 
242
+ #[test]
243
+ fn cache_path_rejects_traversal() {
244
+ assert!(cache_path("/tmp/cache", "imdb", "../../etc/passwd").is_err());
245
+ assert!(cache_path("/tmp/cache", "imdb", "..").is_err());
246
+ assert!(cache_path("/tmp/cache", "imdb", ".").is_err());
247
+ assert!(cache_path("/tmp/cache", "imdb", "").is_err());
248
+ assert!(cache_path("/tmp/cache", "imdb", "foo/bar").is_err());
249
+ assert!(cache_path("/tmp/cache", "imdb", "foo\\bar").is_err());
250
+ }
251
+
252
+ #[test]
253
+ fn poster_cache_path_rejects_traversal() {
254
+ assert!(poster_cache_path("/tmp/cache", "/../etc/passwd").is_err());
255
+ assert!(poster_cache_path("/tmp/cache", "..").is_err());
256
+ assert!(poster_cache_path("/tmp/cache", "").is_err());
257
+ }
258
+
259
  #[test]
260
  fn is_leap_year_cases() {
261
  assert!(is_leap(2000)); // divisible by 400
api/src/config.rs CHANGED
@@ -13,6 +13,7 @@ pub struct Config {
13
  pub mdblist_api_key: Option<String>,
14
  pub poster_mem_cache_mb: u64,
15
  pub static_dir: Option<String>,
 
16
  }
17
 
18
  impl Config {
@@ -44,6 +45,7 @@ impl Config {
44
  .and_then(|v| v.parse().ok())
45
  .unwrap_or(512),
46
  static_dir: env::var("STATIC_DIR").ok(),
 
47
  };
48
 
49
  if config.omdb_api_key.is_none() && config.mdblist_api_key.is_none() {
 
13
  pub mdblist_api_key: Option<String>,
14
  pub poster_mem_cache_mb: u64,
15
  pub static_dir: Option<String>,
16
+ pub cors_origin: Option<String>,
17
  }
18
 
19
  impl Config {
 
45
  .and_then(|v| v.parse().ok())
46
  .unwrap_or(512),
47
  static_dir: env::var("STATIC_DIR").ok(),
48
+ cors_origin: env::var("CORS_ORIGIN").ok(),
49
  };
50
 
51
  if config.omdb_api_key.is_none() && config.mdblist_api_key.is_none() {
api/src/error.rs CHANGED
@@ -46,7 +46,7 @@ impl IntoResponse for AppError {
46
  AppError::Unauthorized => (StatusCode::UNAUTHORIZED, "Unauthorized".into()),
47
  AppError::Forbidden(msg) => (StatusCode::FORBIDDEN, msg.clone()),
48
  AppError::BadRequest(msg) => (StatusCode::BAD_REQUEST, msg.clone()),
49
- _ => (StatusCode::INTERNAL_SERVER_ERROR, self.to_string()),
50
  };
51
  tracing::error!(%status, error = %self);
52
  (status, axum::Json(json!({ "error": message }))).into_response()
@@ -58,10 +58,18 @@ mod tests {
58
  use super::*;
59
  use axum::http::StatusCode;
60
 
 
 
61
  fn status_of(err: AppError) -> StatusCode {
62
  err.into_response().status()
63
  }
64
 
 
 
 
 
 
 
65
  #[test]
66
  fn invalid_id_type_is_400() {
67
  assert_eq!(
@@ -114,4 +122,22 @@ mod tests {
114
  StatusCode::INTERNAL_SERVER_ERROR
115
  );
116
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
117
  }
 
46
  AppError::Unauthorized => (StatusCode::UNAUTHORIZED, "Unauthorized".into()),
47
  AppError::Forbidden(msg) => (StatusCode::FORBIDDEN, msg.clone()),
48
  AppError::BadRequest(msg) => (StatusCode::BAD_REQUEST, msg.clone()),
49
+ _ => (StatusCode::INTERNAL_SERVER_ERROR, "Internal server error".into()),
50
  };
51
  tracing::error!(%status, error = %self);
52
  (status, axum::Json(json!({ "error": message }))).into_response()
 
58
  use super::*;
59
  use axum::http::StatusCode;
60
 
61
+ use http_body_util::BodyExt;
62
+
63
  fn status_of(err: AppError) -> StatusCode {
64
  err.into_response().status()
65
  }
66
 
67
+ async fn body_of(err: AppError) -> serde_json::Value {
68
+ let resp = err.into_response();
69
+ let bytes = resp.into_body().collect().await.unwrap().to_bytes();
70
+ serde_json::from_slice(&bytes).unwrap()
71
+ }
72
+
73
  #[test]
74
  fn invalid_id_type_is_400() {
75
  assert_eq!(
 
122
  StatusCode::INTERNAL_SERVER_ERROR
123
  );
124
  }
125
+
126
+ #[tokio::test]
127
+ async fn internal_errors_redact_details() {
128
+ let body = body_of(AppError::DbError("connection refused to 10.0.0.5:5432".into())).await;
129
+ assert_eq!(body["error"], "Internal server error");
130
+ }
131
+
132
+ #[tokio::test]
133
+ async fn internal_error_other_redacts_details() {
134
+ let body = body_of(AppError::Other("secret internal info".into())).await;
135
+ assert_eq!(body["error"], "Internal server error");
136
+ }
137
+
138
+ #[tokio::test]
139
+ async fn client_errors_preserve_message() {
140
+ let body = body_of(AppError::BadRequest("missing field".into())).await;
141
+ assert_eq!(body["error"], "missing field");
142
+ }
143
  }
api/src/handlers/admin.rs CHANGED
@@ -104,7 +104,7 @@ pub async fn poster_image(
104
  // Validate id_type is one of the known variants (imdb, tmdb, tvdb)
105
  crate::id::IdType::parse(&id_type)?;
106
 
107
- let path = cache::cache_path(&state.config.cache_dir, &id_type, &id_value);
108
 
109
  // Canonicalize and verify the resolved path is within cache_dir to prevent traversal
110
  let canonical_path = tokio::fs::canonicalize(&path).await.map_err(|e| {
 
104
  // Validate id_type is one of the known variants (imdb, tmdb, tvdb)
105
  crate::id::IdType::parse(&id_type)?;
106
 
107
+ let path = cache::cache_path(&state.config.cache_dir, &id_type, &id_value)?;
108
 
109
  // Canonicalize and verify the resolved path is within cache_dir to prevent traversal
110
  let canonical_path = tokio::fs::canonicalize(&path).await.map_err(|e| {
api/src/handlers/auth.rs CHANGED
@@ -14,6 +14,10 @@ use crate::services::db;
14
  use crate::services::validation;
15
  use crate::AppState;
16
 
 
 
 
 
17
  const ACCESS_TOKEN_EXPIRY_MINUTES: i64 = 15;
18
  const REFRESH_TOKEN_EXPIRY_DAYS: i64 = 7;
19
  const REFRESH_TOKEN_MAX_AGE_SECS: i64 = REFRESH_TOKEN_EXPIRY_DAYS * 24 * 60 * 60;
@@ -196,6 +200,8 @@ pub async fn login(
196
  let user = match db::find_admin_user_by_username(&state.db, &req.username).await? {
197
  Some(user) => user,
198
  None => {
 
 
199
  tracing::warn!("Login failed: unknown username");
200
  return Err(AppError::Unauthorized);
201
  }
 
14
  use crate::services::validation;
15
  use crate::AppState;
16
 
17
+ static DUMMY_HASH: std::sync::LazyLock<String> = std::sync::LazyLock::new(|| {
18
+ hash_password("openposterdb-dummy-timing-pad").expect("failed to create dummy hash")
19
+ });
20
+
21
  const ACCESS_TOKEN_EXPIRY_MINUTES: i64 = 15;
22
  const REFRESH_TOKEN_EXPIRY_DAYS: i64 = 7;
23
  const REFRESH_TOKEN_MAX_AGE_SECS: i64 = REFRESH_TOKEN_EXPIRY_DAYS * 24 * 60 * 60;
 
200
  let user = match db::find_admin_user_by_username(&state.db, &req.username).await? {
201
  Some(user) => user,
202
  None => {
203
+ // Perform a dummy password verification to prevent timing side-channel
204
+ let _ = verify_password(&req.password, &DUMMY_HASH);
205
  tracing::warn!("Login failed: unknown username");
206
  return Err(AppError::Unauthorized);
207
  }
api/src/handlers/middleware.rs CHANGED
@@ -3,7 +3,7 @@ use std::sync::Arc;
3
  use axum::{
4
  body::Body,
5
  extract::State,
6
- http::{Method, Request, StatusCode},
7
  middleware::Next,
8
  response::Response,
9
  };
@@ -12,26 +12,6 @@ use jsonwebtoken::{decode, DecodingKey, Validation};
12
  use super::auth::{AuthUser, Claims};
13
  use crate::AppState;
14
 
15
- pub async fn validate_origin(req: Request<Body>, next: Next) -> Result<Response, StatusCode> {
16
- let mutating = matches!(req.method(), &Method::POST | &Method::PUT | &Method::DELETE);
17
-
18
- if mutating {
19
- if let Ok(allowed) = std::env::var("CORS_ORIGIN") {
20
- match req.headers().get("origin") {
21
- Some(origin) => {
22
- let origin_str = origin.to_str().unwrap_or("");
23
- if origin_str != allowed {
24
- return Err(StatusCode::FORBIDDEN);
25
- }
26
- }
27
- None => return Err(StatusCode::FORBIDDEN),
28
- }
29
- }
30
- }
31
-
32
- Ok(next.run(req).await)
33
- }
34
-
35
  pub async fn require_auth(
36
  State(state): State<Arc<AppState>>,
37
  mut req: Request<Body>,
 
3
  use axum::{
4
  body::Body,
5
  extract::State,
6
+ http::{Request, StatusCode},
7
  middleware::Next,
8
  response::Response,
9
  };
 
12
  use super::auth::{AuthUser, Claims};
13
  use crate::AppState;
14
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
  pub async fn require_auth(
16
  State(state): State<Arc<AppState>>,
17
  mut req: Request<Body>,
api/src/lib.rs CHANGED
@@ -11,13 +11,16 @@ pub mod services;
11
  use std::sync::Arc;
12
 
13
  use ab_glyph::FontArc;
 
 
14
  use axum::middleware;
15
  use axum::Router;
16
  use dashmap::DashMap;
17
  use sea_orm::DatabaseConnection;
18
  use tower_http::compression::CompressionLayer;
19
- use tower_http::cors::CorsLayer;
20
- use tower_http::trace::TraceLayer;
 
21
  use zeroize::Zeroizing;
22
 
23
  use cache::MemCacheEntry;
@@ -81,6 +84,83 @@ pub const SCHEMA_SQL: &[&str] = &[
81
  )",
82
  ];
83
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84
  pub fn build_app(state: Arc<AppState>) -> Router {
85
  let admin_routes = routes::api_keys::api_key_routes()
86
  .merge(routes::admin::admin_routes())
@@ -98,12 +178,30 @@ pub fn build_app(state: Arc<AppState>) -> Router {
98
  .merge(admin_routes)
99
  .layer(CompressionLayer::new());
100
 
101
- let mut app = Router::new()
102
- .route(
103
  "/{api_key}/{id_type}/poster-default/{id_value}",
104
  axum::routing::get(routes::poster::handler),
105
- )
106
- .merge(compressed_routes);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
107
 
108
  // Serve static frontend files when STATIC_DIR is set.
109
  // Falls back to index.html for SPA client-side routing.
@@ -113,10 +211,46 @@ pub fn build_app(state: Arc<AppState>) -> Router {
113
  app = app.fallback_service(ServeDir::new(dir).fallback(ServeFile::new(index)));
114
  }
115
 
116
- app.layer(middleware::from_fn(
117
- handlers::middleware::validate_origin,
118
- ))
119
- .layer(TraceLayer::new_for_http())
120
- .layer(CorsLayer::permissive())
121
- .with_state(state)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
122
  }
 
11
  use std::sync::Arc;
12
 
13
  use ab_glyph::FontArc;
14
+ use axum::http::header::{self, HeaderValue};
15
+ use axum::http::Request;
16
  use axum::middleware;
17
  use axum::Router;
18
  use dashmap::DashMap;
19
  use sea_orm::DatabaseConnection;
20
  use tower_http::compression::CompressionLayer;
21
+ use tower_http::cors::{AllowHeaders, AllowMethods, AllowOrigin, CorsLayer};
22
+ use tower_http::set_header::SetResponseHeaderLayer;
23
+ use tower_http::trace::{MakeSpan, TraceLayer};
24
  use zeroize::Zeroizing;
25
 
26
  use cache::MemCacheEntry;
 
84
  )",
85
  ];
86
 
87
+ fn build_cors_layer(config: &Config) -> CorsLayer {
88
+ match config.cors_origin {
89
+ Some(ref origin) => CorsLayer::new()
90
+ .allow_origin(AllowOrigin::exact(
91
+ HeaderValue::from_str(origin).expect("valid CORS_ORIGIN"),
92
+ ))
93
+ .allow_methods(AllowMethods::list([
94
+ axum::http::Method::GET,
95
+ axum::http::Method::POST,
96
+ axum::http::Method::DELETE,
97
+ ]))
98
+ .allow_headers(AllowHeaders::list([
99
+ header::CONTENT_TYPE,
100
+ header::AUTHORIZATION,
101
+ ]))
102
+ .allow_credentials(true),
103
+ None => CorsLayer::new(),
104
+ }
105
+ }
106
+
107
+ fn redact_path(path: &str) -> String {
108
+ if !path.starts_with("/api/") {
109
+ // Poster route: /{api_key}/... -> /[REDACTED]/...
110
+ match path[1..].find('/') {
111
+ Some(pos) => format!("/[REDACTED]{}", &path[1 + pos..]),
112
+ None => "/[REDACTED]".into(),
113
+ }
114
+ } else {
115
+ path.to_string()
116
+ }
117
+ }
118
+
119
+ #[derive(Clone)]
120
+ struct RedactedMakeSpan;
121
+
122
+ impl<B> MakeSpan<B> for RedactedMakeSpan {
123
+ fn make_span(&mut self, req: &Request<B>) -> tracing::Span {
124
+ let redacted_uri = redact_path(req.uri().path());
125
+ tracing::info_span!("request", method = %req.method(), uri = %redacted_uri, version = ?req.version())
126
+ }
127
+ }
128
+
129
+ #[cfg(not(any(test, feature = "test-support")))]
130
+ #[derive(Debug, Clone)]
131
+ struct PosterKeyExtractor;
132
+
133
+ #[cfg(not(any(test, feature = "test-support")))]
134
+ impl tower_governor::key_extractor::KeyExtractor for PosterKeyExtractor {
135
+ type Key = String;
136
+
137
+ fn extract<T>(
138
+ &self,
139
+ req: &Request<T>,
140
+ ) -> Result<Self::Key, tower_governor::GovernorError> {
141
+ let path = req.uri().path();
142
+ let api_key = path.split('/').nth(1).unwrap_or("unknown");
143
+ let key_prefix = &api_key[..api_key.len().min(16)];
144
+
145
+ // Extract IP from headers or connection info
146
+ let ip = req
147
+ .headers()
148
+ .get("x-forwarded-for")
149
+ .and_then(|v| v.to_str().ok())
150
+ .and_then(|s| s.split(',').next())
151
+ .map(|s| s.trim().to_string())
152
+ .or_else(|| {
153
+ req.headers()
154
+ .get("x-real-ip")
155
+ .and_then(|v| v.to_str().ok())
156
+ .map(|s| s.to_string())
157
+ })
158
+ .unwrap_or_else(|| "unknown".to_string());
159
+
160
+ Ok(format!("{key_prefix}:{ip}"))
161
+ }
162
+ }
163
+
164
  pub fn build_app(state: Arc<AppState>) -> Router {
165
  let admin_routes = routes::api_keys::api_key_routes()
166
  .merge(routes::admin::admin_routes())
 
178
  .merge(admin_routes)
179
  .layer(CompressionLayer::new());
180
 
181
+ let poster_route = {
182
+ let router = Router::new().route(
183
  "/{api_key}/{id_type}/poster-default/{id_value}",
184
  axum::routing::get(routes::poster::handler),
185
+ );
186
+
187
+ #[cfg(not(any(test, feature = "test-support")))]
188
+ let router = {
189
+ use tower_governor::{governor::GovernorConfigBuilder, GovernorLayer};
190
+
191
+ let governor_conf = GovernorConfigBuilder::default()
192
+ .per_second(1)
193
+ .burst_size(120)
194
+ .key_extractor(PosterKeyExtractor)
195
+ .finish()
196
+ .expect("valid governor config");
197
+
198
+ router.layer(GovernorLayer::new(governor_conf))
199
+ };
200
+
201
+ router
202
+ };
203
+
204
+ let mut app = Router::new().merge(poster_route).merge(compressed_routes);
205
 
206
  // Serve static frontend files when STATIC_DIR is set.
207
  // Falls back to index.html for SPA client-side routing.
 
211
  app = app.fallback_service(ServeDir::new(dir).fallback(ServeFile::new(index)));
212
  }
213
 
214
+ let cors_layer = build_cors_layer(&state.config);
215
+
216
+ app = app.layer(TraceLayer::new_for_http().make_span_with(RedactedMakeSpan));
217
+
218
+ if state.secure_cookies {
219
+ app = app.layer(SetResponseHeaderLayer::if_not_present(
220
+ header::STRICT_TRANSPORT_SECURITY,
221
+ HeaderValue::from_static("max-age=63072000; includeSubDomains"),
222
+ ));
223
+ }
224
+
225
+ app.layer(cors_layer).with_state(state)
226
+ }
227
+
228
+ #[cfg(test)]
229
+ mod tests {
230
+ use super::*;
231
+
232
+ #[test]
233
+ fn redact_path_api_route_unchanged() {
234
+ assert_eq!(redact_path("/api/auth/status"), "/api/auth/status");
235
+ assert_eq!(redact_path("/api/keys"), "/api/keys");
236
+ }
237
+
238
+ #[test]
239
+ fn redact_path_poster_route_hides_key() {
240
+ assert_eq!(
241
+ redact_path("/abc123def456/imdb/poster-default/tt1234567.jpg"),
242
+ "/[REDACTED]/imdb/poster-default/tt1234567.jpg"
243
+ );
244
+ }
245
+
246
+ #[test]
247
+ fn redact_path_single_segment() {
248
+ assert_eq!(redact_path("/abc123def456"), "/[REDACTED]");
249
+ }
250
+
251
+ #[test]
252
+ fn redact_path_root() {
253
+ // "/" — path[1..] is empty, find('/') returns None
254
+ assert_eq!(redact_path("/"), "/[REDACTED]");
255
+ }
256
  }
api/src/poster/generate.rs CHANGED
@@ -35,7 +35,7 @@ pub async fn generate_poster(params: PosterParams<'_>) -> Result<Vec<u8>, AppErr
35
  poster_stale_secs,
36
  } = params;
37
  // Fetch base poster, using cache
38
- let poster_cache = cache::poster_cache_path(cache_dir, poster_path);
39
  let poster_bytes = if let Some(entry) = cache::read(&poster_cache, poster_stale_secs).await {
40
  if entry.is_stale {
41
  // Stale — refetch in foreground (rare with default 0 = never stale)
 
35
  poster_stale_secs,
36
  } = params;
37
  // Fetch base poster, using cache
38
+ let poster_cache = cache::poster_cache_path(cache_dir, poster_path)?;
39
  let poster_bytes = if let Some(entry) = cache::read(&poster_cache, poster_stale_secs).await {
40
  if entry.is_stale {
41
  // Stale — refetch in foreground (rare with default 0 = never stale)
api/src/routes/poster.rs CHANGED
@@ -80,7 +80,7 @@ async fn handle_inner(
80
  let id_type = IdType::parse(id_type_str)?;
81
  let id_value = id_value_jpg.strip_suffix(".jpg").unwrap_or(id_value_jpg);
82
 
83
- let cache_path = cache::cache_path(&state.config.cache_dir, id_type_str, id_value);
84
  let cache_key = format!("{id_type_str}/{id_value}");
85
 
86
  // Check in-memory poster cache first
 
80
  let id_type = IdType::parse(id_type_str)?;
81
  let id_value = id_value_jpg.strip_suffix(".jpg").unwrap_or(id_value_jpg);
82
 
83
+ let cache_path = cache::cache_path(&state.config.cache_dir, id_type_str, id_value)?;
84
  let cache_key = format!("{id_type_str}/{id_value}");
85
 
86
  // Check in-memory poster cache first
api/src/services/validation.rs CHANGED
@@ -15,11 +15,11 @@ pub fn validate_username(username: &str) -> Result<(), AppError> {
15
  pub fn validate_password(password: &str) -> Result<(), AppError> {
16
  if password.is_empty()
17
  || password.len() < 8
 
18
  || password.chars().any(char::is_control)
19
  {
20
  return Err(AppError::BadRequest(
21
- "Invalid password: must be at least 8 characters and not contain control characters"
22
- .into(),
23
  ));
24
  }
25
  Ok(())
@@ -88,4 +88,16 @@ mod tests {
88
  fn validate_password_exactly_8_chars() {
89
  assert!(validate_password("12345678").is_ok());
90
  }
 
 
 
 
 
 
 
 
 
 
 
 
91
  }
 
15
  pub fn validate_password(password: &str) -> Result<(), AppError> {
16
  if password.is_empty()
17
  || password.len() < 8
18
+ || password.len() > 256
19
  || password.chars().any(char::is_control)
20
  {
21
  return Err(AppError::BadRequest(
22
+ "Invalid password: must be 8-256 characters and not contain control characters".into(),
 
23
  ));
24
  }
25
  Ok(())
 
88
  fn validate_password_exactly_8_chars() {
89
  assert!(validate_password("12345678").is_ok());
90
  }
91
+
92
+ #[test]
93
+ fn validate_password_exactly_256_chars() {
94
+ let pw = "a".repeat(256);
95
+ assert!(validate_password(&pw).is_ok());
96
+ }
97
+
98
+ #[test]
99
+ fn validate_password_257_chars_rejected() {
100
+ let pw = "a".repeat(257);
101
+ assert!(validate_password(&pw).is_err());
102
+ }
103
  }
api/tests/common/mod.rs CHANGED
@@ -10,7 +10,31 @@ use openposterdb_api::config::Config;
10
  use openposterdb_api::services::tmdb::TmdbClient;
11
  use openposterdb_api::{build_app, AppState, FONT_BYTES, SCHEMA_SQL};
12
 
13
- pub async fn setup_test_app() -> (axum::Router, Arc<AppState>) {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
  let sqlite_opts = sqlx::sqlite::SqliteConnectOptions::new()
15
  .filename(":memory:")
16
  .create_if_missing(true);
@@ -67,6 +91,7 @@ pub async fn setup_test_app() -> (axum::Router, Arc<AppState>) {
67
  mdblist_api_key: None,
68
  poster_mem_cache_mb: 1,
69
  static_dir: None,
 
70
  },
71
  tmdb: TmdbClient::new("test".into(), http.clone()),
72
  omdb: None,
@@ -76,7 +101,7 @@ pub async fn setup_test_app() -> (axum::Router, Arc<AppState>) {
76
  refresh_locks,
77
  db,
78
  jwt_secret,
79
- secure_cookies: false,
80
  api_key_cache,
81
  poster_inflight,
82
  id_cache,
@@ -89,6 +114,10 @@ pub async fn setup_test_app() -> (axum::Router, Arc<AppState>) {
89
  (app, state)
90
  }
91
 
 
 
 
 
92
  /// Helper to perform setup and get back an access token.
93
  pub async fn setup_admin(app: &axum::Router) -> String {
94
  use axum::body::Body;
 
10
  use openposterdb_api::services::tmdb::TmdbClient;
11
  use openposterdb_api::{build_app, AppState, FONT_BYTES, SCHEMA_SQL};
12
 
13
+ pub struct TestAppOptions {
14
+ pub cors_origin: Option<String>,
15
+ pub secure_cookies: bool,
16
+ }
17
+
18
+ impl Default for TestAppOptions {
19
+ fn default() -> Self {
20
+ Self {
21
+ cors_origin: None,
22
+ secure_cookies: false,
23
+ }
24
+ }
25
+ }
26
+
27
+ pub async fn setup_test_app_with_options(opts: TestAppOptions) -> (axum::Router, Arc<AppState>) {
28
+ let cors_origin = opts.cors_origin;
29
+ let secure_cookies = opts.secure_cookies;
30
+ _setup_test_app(cors_origin, secure_cookies).await
31
+ }
32
+
33
+ pub async fn setup_test_app_with_cors(cors_origin: Option<String>) -> (axum::Router, Arc<AppState>) {
34
+ _setup_test_app(cors_origin, false).await
35
+ }
36
+
37
+ async fn _setup_test_app(cors_origin: Option<String>, secure_cookies: bool) -> (axum::Router, Arc<AppState>) {
38
  let sqlite_opts = sqlx::sqlite::SqliteConnectOptions::new()
39
  .filename(":memory:")
40
  .create_if_missing(true);
 
91
  mdblist_api_key: None,
92
  poster_mem_cache_mb: 1,
93
  static_dir: None,
94
+ cors_origin,
95
  },
96
  tmdb: TmdbClient::new("test".into(), http.clone()),
97
  omdb: None,
 
101
  refresh_locks,
102
  db,
103
  jwt_secret,
104
+ secure_cookies,
105
  api_key_cache,
106
  poster_inflight,
107
  id_cache,
 
114
  (app, state)
115
  }
116
 
117
+ pub async fn setup_test_app() -> (axum::Router, Arc<AppState>) {
118
+ setup_test_app_with_cors(None).await
119
+ }
120
+
121
  /// Helper to perform setup and get back an access token.
122
  pub async fn setup_admin(app: &axum::Router) -> String {
123
  use axum::body::Body;
api/tests/middleware.rs CHANGED
@@ -5,20 +5,6 @@ use axum::http::{Request, StatusCode};
5
  use http_body_util::BodyExt;
6
  use tower::ServiceExt;
7
 
8
- #[tokio::test]
9
- async fn origin_validation_get_without_origin_allowed() {
10
- let (app, _state) = common::setup_test_app().await;
11
-
12
- let req = Request::builder()
13
- .uri("/api/auth/status")
14
- .body(Body::empty())
15
- .unwrap();
16
-
17
- let res = app.oneshot(req).await.unwrap();
18
- // GET without origin should pass (no CORS_ORIGIN env set in tests)
19
- assert_eq!(res.status(), StatusCode::OK);
20
- }
21
-
22
  #[tokio::test]
23
  async fn auth_middleware_missing_header() {
24
  let (app, _state) = common::setup_test_app().await;
 
5
  use http_body_util::BodyExt;
6
  use tower::ServiceExt;
7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
  #[tokio::test]
9
  async fn auth_middleware_missing_header() {
10
  let (app, _state) = common::setup_test_app().await;
api/tests/security.rs CHANGED
@@ -1,7 +1,5 @@
1
  mod common;
2
 
3
- use std::sync::Mutex;
4
-
5
  use axum::body::Body;
6
  use axum::http::{Request, StatusCode};
7
  use http_body_util::BodyExt;
@@ -12,97 +10,74 @@ fn json_body(json: serde_json::Value) -> Body {
12
  Body::from(json.to_string())
13
  }
14
 
15
- // All tests in this file share a process. Since some tests modify the
16
- // CORS_ORIGIN env var, we must serialize ALL tests to prevent interference.
17
- static ENV_MUTEX: Mutex<()> = Mutex::new(());
18
-
19
- fn clear_cors() {
20
- unsafe { std::env::remove_var("CORS_ORIGIN") };
21
- }
22
-
23
- fn set_cors(origin: &str) {
24
- unsafe { std::env::set_var("CORS_ORIGIN", origin) };
25
- }
26
-
27
- // --- CORS origin enforcement ---
28
 
29
  #[tokio::test]
30
- async fn cors_post_without_origin_rejected_when_cors_origin_set() {
31
- let _guard = ENV_MUTEX.lock().unwrap();
32
- set_cors("https://example.com");
33
-
34
  let (app, _state) = common::setup_test_app().await;
35
 
36
  let req = Request::builder()
37
- .method("POST")
38
  .uri("/api/auth/setup")
39
- .header("content-type", "application/json")
40
- .body(json_body(serde_json::json!({
41
- "username": "admin",
42
- "password": "testpassword123"
43
- })))
44
  .unwrap();
45
 
46
  let res = app.oneshot(req).await.unwrap();
47
- assert_eq!(res.status(), StatusCode::FORBIDDEN);
48
-
49
- clear_cors();
50
  }
51
 
52
  #[tokio::test]
53
- async fn cors_post_with_wrong_origin_rejected() {
54
- let _guard = ENV_MUTEX.lock().unwrap();
55
- set_cors("https://example.com");
56
-
57
- let (app, _state) = common::setup_test_app().await;
58
 
59
  let req = Request::builder()
60
- .method("POST")
61
  .uri("/api/auth/setup")
62
- .header("content-type", "application/json")
63
- .header("origin", "https://evil.com")
64
- .body(json_body(serde_json::json!({
65
- "username": "admin",
66
- "password": "testpassword123"
67
- })))
68
  .unwrap();
69
 
70
  let res = app.oneshot(req).await.unwrap();
71
- assert_eq!(res.status(), StatusCode::FORBIDDEN);
72
-
73
- clear_cors();
 
 
74
  }
75
 
76
  #[tokio::test]
77
- async fn cors_post_with_correct_origin_allowed() {
78
- let _guard = ENV_MUTEX.lock().unwrap();
79
- set_cors("https://example.com");
80
-
81
- let (app, _state) = common::setup_test_app().await;
82
 
83
  let req = Request::builder()
84
- .method("POST")
85
  .uri("/api/auth/setup")
86
- .header("content-type", "application/json")
87
- .header("origin", "https://example.com")
88
- .body(json_body(serde_json::json!({
89
- "username": "admin",
90
- "password": "testpassword123"
91
- })))
92
  .unwrap();
93
 
94
  let res = app.oneshot(req).await.unwrap();
95
- assert_eq!(res.status(), StatusCode::OK);
96
-
97
- clear_cors();
 
 
 
 
98
  }
99
 
100
  #[tokio::test]
101
  async fn cors_get_allowed_even_with_cors_origin_set() {
102
- let _guard = ENV_MUTEX.lock().unwrap();
103
- set_cors("https://example.com");
104
-
105
- let (app, _state) = common::setup_test_app().await;
106
 
107
  let req = Request::builder()
108
  .uri("/api/auth/status")
@@ -111,16 +86,12 @@ async fn cors_get_allowed_even_with_cors_origin_set() {
111
 
112
  let res = app.oneshot(req).await.unwrap();
113
  assert_eq!(res.status(), StatusCode::OK);
114
-
115
- clear_cors();
116
  }
117
 
118
  #[tokio::test]
119
- async fn cors_delete_without_origin_rejected() {
120
- let _guard = ENV_MUTEX.lock().unwrap();
121
- set_cors("https://example.com");
122
-
123
- let (app, _state) = common::setup_test_app().await;
124
 
125
  let req = Request::builder()
126
  .method("DELETE")
@@ -130,18 +101,18 @@ async fn cors_delete_without_origin_rejected() {
130
  .unwrap();
131
 
132
  let res = app.oneshot(req).await.unwrap();
133
- assert_eq!(res.status(), StatusCode::FORBIDDEN);
134
-
135
- clear_cors();
 
 
 
136
  }
137
 
138
  // --- Refresh token expiry ---
139
 
140
  #[tokio::test]
141
  async fn refresh_with_expired_token_returns_401() {
142
- let _guard = ENV_MUTEX.lock().unwrap();
143
- clear_cors();
144
-
145
  let (app, state) = common::setup_test_app().await;
146
 
147
  // Setup admin
@@ -185,9 +156,6 @@ async fn refresh_with_expired_token_returns_401() {
185
 
186
  #[tokio::test]
187
  async fn concurrent_setup_only_one_succeeds() {
188
- let _guard = ENV_MUTEX.lock().unwrap();
189
- clear_cors();
190
-
191
  let (app, _state) = common::setup_test_app().await;
192
 
193
  let app1 = app.clone();
@@ -235,9 +203,6 @@ async fn concurrent_setup_only_one_succeeds() {
235
 
236
  #[tokio::test]
237
  async fn invalid_api_key_cached_returns_401_consistently() {
238
- let _guard = ENV_MUTEX.lock().unwrap();
239
- clear_cors();
240
-
241
  let (app, _state) = common::setup_test_app().await;
242
 
243
  // First request with invalid key
@@ -261,9 +226,6 @@ async fn invalid_api_key_cached_returns_401_consistently() {
261
 
262
  #[tokio::test]
263
  async fn deleted_api_key_rejected_after_cache_invalidation() {
264
- let _guard = ENV_MUTEX.lock().unwrap();
265
- clear_cors();
266
-
267
  let (app, state) = common::setup_test_app().await;
268
  let token = common::setup_admin(&app).await;
269
 
@@ -315,9 +277,6 @@ async fn deleted_api_key_rejected_after_cache_invalidation() {
315
 
316
  #[tokio::test]
317
  async fn setup_rejects_short_password() {
318
- let _guard = ENV_MUTEX.lock().unwrap();
319
- clear_cors();
320
-
321
  let (app, _state) = common::setup_test_app().await;
322
 
323
  let req = Request::builder()
@@ -336,9 +295,6 @@ async fn setup_rejects_short_password() {
336
 
337
  #[tokio::test]
338
  async fn setup_rejects_empty_username() {
339
- let _guard = ENV_MUTEX.lock().unwrap();
340
- clear_cors();
341
-
342
  let (app, _state) = common::setup_test_app().await;
343
 
344
  let req = Request::builder()
@@ -357,9 +313,6 @@ async fn setup_rejects_empty_username() {
357
 
358
  #[tokio::test]
359
  async fn setup_rejects_username_with_whitespace() {
360
- let _guard = ENV_MUTEX.lock().unwrap();
361
- clear_cors();
362
-
363
  let (app, _state) = common::setup_test_app().await;
364
 
365
  let req = Request::builder()
@@ -380,9 +333,6 @@ async fn setup_rejects_username_with_whitespace() {
380
 
381
  #[tokio::test]
382
  async fn expired_jwt_rejected() {
383
- let _guard = ENV_MUTEX.lock().unwrap();
384
- clear_cors();
385
-
386
  let (app, state) = common::setup_test_app().await;
387
 
388
  let claims = serde_json::json!({
@@ -411,9 +361,6 @@ async fn expired_jwt_rejected() {
411
 
412
  #[tokio::test]
413
  async fn jwt_with_wrong_secret_rejected() {
414
- let _guard = ENV_MUTEX.lock().unwrap();
415
- clear_cors();
416
-
417
  let (app, _state) = common::setup_test_app().await;
418
 
419
  let wrong_secret = vec![0xCD; 32];
@@ -445,9 +392,6 @@ async fn jwt_with_wrong_secret_rejected() {
445
 
446
  #[tokio::test]
447
  async fn poster_endpoint_invalid_id_type() {
448
- let _guard = ENV_MUTEX.lock().unwrap();
449
- clear_cors();
450
-
451
  let (app, _state) = common::setup_test_app().await;
452
  let token = common::setup_admin(&app).await;
453
 
@@ -478,9 +422,6 @@ async fn poster_endpoint_invalid_id_type() {
478
 
479
  #[tokio::test]
480
  async fn refresh_with_fabricated_token_returns_401() {
481
- let _guard = ENV_MUTEX.lock().unwrap();
482
- clear_cors();
483
-
484
  let (app, _state) = common::setup_test_app().await;
485
  common::setup_admin(&app).await;
486
 
@@ -499,9 +440,6 @@ async fn refresh_with_fabricated_token_returns_401() {
499
 
500
  #[tokio::test]
501
  async fn delete_nonexistent_api_key_succeeds() {
502
- let _guard = ENV_MUTEX.lock().unwrap();
503
- clear_cors();
504
-
505
  let (app, _state) = common::setup_test_app().await;
506
  let token = common::setup_admin(&app).await;
507
 
@@ -515,3 +453,127 @@ async fn delete_nonexistent_api_key_succeeds() {
515
  let res = app.oneshot(req).await.unwrap();
516
  assert_eq!(res.status(), StatusCode::OK);
517
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  mod common;
2
 
 
 
3
  use axum::body::Body;
4
  use axum::http::{Request, StatusCode};
5
  use http_body_util::BodyExt;
 
10
  Body::from(json.to_string())
11
  }
12
 
13
+ // --- CORS origin enforcement (via preflight OPTIONS requests) ---
 
 
 
 
 
 
 
 
 
 
 
 
14
 
15
  #[tokio::test]
16
+ async fn cors_preflight_without_origin_config_rejected() {
17
+ // No CORS origin configured — CorsLayer::new() rejects all cross-origin
 
 
18
  let (app, _state) = common::setup_test_app().await;
19
 
20
  let req = Request::builder()
21
+ .method("OPTIONS")
22
  .uri("/api/auth/setup")
23
+ .header("origin", "https://example.com")
24
+ .header("access-control-request-method", "POST")
25
+ .body(Body::empty())
 
 
26
  .unwrap();
27
 
28
  let res = app.oneshot(req).await.unwrap();
29
+ // No Access-Control-Allow-Origin header should be present
30
+ assert!(res.headers().get("access-control-allow-origin").is_none());
 
31
  }
32
 
33
  #[tokio::test]
34
+ async fn cors_preflight_with_correct_origin_allowed() {
35
+ let (app, _state) =
36
+ common::setup_test_app_with_cors(Some("https://example.com".into())).await;
 
 
37
 
38
  let req = Request::builder()
39
+ .method("OPTIONS")
40
  .uri("/api/auth/setup")
41
+ .header("origin", "https://example.com")
42
+ .header("access-control-request-method", "POST")
43
+ .body(Body::empty())
 
 
 
44
  .unwrap();
45
 
46
  let res = app.oneshot(req).await.unwrap();
47
+ let acao = res
48
+ .headers()
49
+ .get("access-control-allow-origin")
50
+ .and_then(|v| v.to_str().ok());
51
+ assert_eq!(acao, Some("https://example.com"));
52
  }
53
 
54
  #[tokio::test]
55
+ async fn cors_preflight_with_wrong_origin_rejected() {
56
+ let (app, _state) =
57
+ common::setup_test_app_with_cors(Some("https://example.com".into())).await;
 
 
58
 
59
  let req = Request::builder()
60
+ .method("OPTIONS")
61
  .uri("/api/auth/setup")
62
+ .header("origin", "https://evil.com")
63
+ .header("access-control-request-method", "POST")
64
+ .body(Body::empty())
 
 
 
65
  .unwrap();
66
 
67
  let res = app.oneshot(req).await.unwrap();
68
+ // CorsLayer echoes the configured origin, not the request origin.
69
+ // The browser compares and rejects when they don't match.
70
+ let acao = res
71
+ .headers()
72
+ .get("access-control-allow-origin")
73
+ .and_then(|v| v.to_str().ok());
74
+ assert_ne!(acao, Some("https://evil.com"), "should not allow wrong origin");
75
  }
76
 
77
  #[tokio::test]
78
  async fn cors_get_allowed_even_with_cors_origin_set() {
79
+ let (app, _state) =
80
+ common::setup_test_app_with_cors(Some("https://example.com".into())).await;
 
 
81
 
82
  let req = Request::builder()
83
  .uri("/api/auth/status")
 
86
 
87
  let res = app.oneshot(req).await.unwrap();
88
  assert_eq!(res.status(), StatusCode::OK);
 
 
89
  }
90
 
91
  #[tokio::test]
92
+ async fn cors_delete_without_origin_no_cors_headers() {
93
+ let (app, _state) =
94
+ common::setup_test_app_with_cors(Some("https://example.com".into())).await;
 
 
95
 
96
  let req = Request::builder()
97
  .method("DELETE")
 
101
  .unwrap();
102
 
103
  let res = app.oneshot(req).await.unwrap();
104
+ // Without matching origin, browser will block the response
105
+ let acao = res
106
+ .headers()
107
+ .get("access-control-allow-origin")
108
+ .and_then(|v| v.to_str().ok());
109
+ assert_ne!(acao, Some("https://evil.com"));
110
  }
111
 
112
  // --- Refresh token expiry ---
113
 
114
  #[tokio::test]
115
  async fn refresh_with_expired_token_returns_401() {
 
 
 
116
  let (app, state) = common::setup_test_app().await;
117
 
118
  // Setup admin
 
156
 
157
  #[tokio::test]
158
  async fn concurrent_setup_only_one_succeeds() {
 
 
 
159
  let (app, _state) = common::setup_test_app().await;
160
 
161
  let app1 = app.clone();
 
203
 
204
  #[tokio::test]
205
  async fn invalid_api_key_cached_returns_401_consistently() {
 
 
 
206
  let (app, _state) = common::setup_test_app().await;
207
 
208
  // First request with invalid key
 
226
 
227
  #[tokio::test]
228
  async fn deleted_api_key_rejected_after_cache_invalidation() {
 
 
 
229
  let (app, state) = common::setup_test_app().await;
230
  let token = common::setup_admin(&app).await;
231
 
 
277
 
278
  #[tokio::test]
279
  async fn setup_rejects_short_password() {
 
 
 
280
  let (app, _state) = common::setup_test_app().await;
281
 
282
  let req = Request::builder()
 
295
 
296
  #[tokio::test]
297
  async fn setup_rejects_empty_username() {
 
 
 
298
  let (app, _state) = common::setup_test_app().await;
299
 
300
  let req = Request::builder()
 
313
 
314
  #[tokio::test]
315
  async fn setup_rejects_username_with_whitespace() {
 
 
 
316
  let (app, _state) = common::setup_test_app().await;
317
 
318
  let req = Request::builder()
 
333
 
334
  #[tokio::test]
335
  async fn expired_jwt_rejected() {
 
 
 
336
  let (app, state) = common::setup_test_app().await;
337
 
338
  let claims = serde_json::json!({
 
361
 
362
  #[tokio::test]
363
  async fn jwt_with_wrong_secret_rejected() {
 
 
 
364
  let (app, _state) = common::setup_test_app().await;
365
 
366
  let wrong_secret = vec![0xCD; 32];
 
392
 
393
  #[tokio::test]
394
  async fn poster_endpoint_invalid_id_type() {
 
 
 
395
  let (app, _state) = common::setup_test_app().await;
396
  let token = common::setup_admin(&app).await;
397
 
 
422
 
423
  #[tokio::test]
424
  async fn refresh_with_fabricated_token_returns_401() {
 
 
 
425
  let (app, _state) = common::setup_test_app().await;
426
  common::setup_admin(&app).await;
427
 
 
440
 
441
  #[tokio::test]
442
  async fn delete_nonexistent_api_key_succeeds() {
 
 
 
443
  let (app, _state) = common::setup_test_app().await;
444
  let token = common::setup_admin(&app).await;
445
 
 
453
  let res = app.oneshot(req).await.unwrap();
454
  assert_eq!(res.status(), StatusCode::OK);
455
  }
456
+
457
+ // --- Path traversal prevention ---
458
+
459
+ #[tokio::test]
460
+ async fn poster_endpoint_rejects_path_traversal() {
461
+ let (app, _state) = common::setup_test_app().await;
462
+ let token = common::setup_admin(&app).await;
463
+
464
+ // Create a valid API key
465
+ let req = Request::builder()
466
+ .method("POST")
467
+ .uri("/api/keys")
468
+ .header("content-type", "application/json")
469
+ .header("authorization", format!("Bearer {token}"))
470
+ .body(json_body(serde_json::json!({"name": "test"})))
471
+ .unwrap();
472
+ let res = app.clone().oneshot(req).await.unwrap();
473
+ let body = res.into_body().collect().await.unwrap().to_bytes();
474
+ let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
475
+ let api_key = json["key"].as_str().unwrap();
476
+
477
+ // Attempt path traversal in id_value
478
+ let req = Request::builder()
479
+ .uri(format!("/{api_key}/imdb/poster-default/..%2F..%2Fetc%2Fpasswd.jpg"))
480
+ .body(Body::empty())
481
+ .unwrap();
482
+
483
+ let res = app.oneshot(req).await.unwrap();
484
+ assert_eq!(res.status(), StatusCode::BAD_REQUEST);
485
+ }
486
+
487
+ // --- Error redaction (integration) ---
488
+
489
+ #[tokio::test]
490
+ async fn internal_error_response_is_redacted() {
491
+ let (app, _state) = common::setup_test_app().await;
492
+ let token = common::setup_admin(&app).await;
493
+
494
+ // Create a valid API key
495
+ let req = Request::builder()
496
+ .method("POST")
497
+ .uri("/api/keys")
498
+ .header("content-type", "application/json")
499
+ .header("authorization", format!("Bearer {token}"))
500
+ .body(json_body(serde_json::json!({"name": "test"})))
501
+ .unwrap();
502
+ let res = app.clone().oneshot(req).await.unwrap();
503
+ let body = res.into_body().collect().await.unwrap().to_bytes();
504
+ let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
505
+ let api_key = json["key"].as_str().unwrap();
506
+
507
+ // Request a poster that will fail internally (fake TMDB key)
508
+ let req = Request::builder()
509
+ .uri(format!("/{api_key}/imdb/poster-default/tt0000001.jpg"))
510
+ .body(Body::empty())
511
+ .unwrap();
512
+
513
+ let res = app.oneshot(req).await.unwrap();
514
+ assert_eq!(res.status(), StatusCode::INTERNAL_SERVER_ERROR);
515
+ let body = res.into_body().collect().await.unwrap().to_bytes();
516
+ let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
517
+ let error_msg = json["error"].as_str().unwrap();
518
+ // Must not leak internal details like URLs, connection errors, etc.
519
+ assert_eq!(error_msg, "Internal server error");
520
+ }
521
+
522
+ // --- HSTS header ---
523
+
524
+ #[tokio::test]
525
+ async fn hsts_header_present_when_secure_cookies() {
526
+ let (app, _state) = common::setup_test_app_with_options(common::TestAppOptions {
527
+ secure_cookies: true,
528
+ ..Default::default()
529
+ })
530
+ .await;
531
+
532
+ let req = Request::builder()
533
+ .uri("/api/auth/status")
534
+ .body(Body::empty())
535
+ .unwrap();
536
+
537
+ let res = app.oneshot(req).await.unwrap();
538
+ assert_eq!(res.status(), StatusCode::OK);
539
+ let hsts = res
540
+ .headers()
541
+ .get("strict-transport-security")
542
+ .and_then(|v| v.to_str().ok());
543
+ assert_eq!(hsts, Some("max-age=63072000; includeSubDomains"));
544
+ }
545
+
546
+ #[tokio::test]
547
+ async fn hsts_header_absent_when_not_secure() {
548
+ let (app, _state) = common::setup_test_app().await;
549
+
550
+ let req = Request::builder()
551
+ .uri("/api/auth/status")
552
+ .body(Body::empty())
553
+ .unwrap();
554
+
555
+ let res = app.oneshot(req).await.unwrap();
556
+ assert_eq!(res.status(), StatusCode::OK);
557
+ assert!(res.headers().get("strict-transport-security").is_none());
558
+ }
559
+
560
+ // --- Password max length (integration) ---
561
+
562
+ #[tokio::test]
563
+ async fn setup_rejects_too_long_password() {
564
+ let (app, _state) = common::setup_test_app().await;
565
+ let long_pw = "a".repeat(257);
566
+
567
+ let req = Request::builder()
568
+ .method("POST")
569
+ .uri("/api/auth/setup")
570
+ .header("content-type", "application/json")
571
+ .body(json_body(serde_json::json!({
572
+ "username": "admin",
573
+ "password": long_pw
574
+ })))
575
+ .unwrap();
576
+
577
+ let res = app.oneshot(req).await.unwrap();
578
+ assert_eq!(res.status(), StatusCode::BAD_REQUEST);
579
+ }