fraiseql-server 2.14.1

HTTP server for FraiseQL v2 GraphQL engine
Documentation
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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
// Note: the #421 page-size precedence logic (`page_size_precedence`) and its unit
// tests moved to `fraiseql_core::runtime` alongside `RuntimeConfig::from_compiled_schema`,
// the single seam every server constructor now routes through (H16).

// ── initialization_tests ──────────────────────────────────────────────────────

mod initialization_tests {
    use super::super::initialization::is_manifest_url_ssrf_blocked;

    /// H12: a field marked for at-rest encryption must refuse to boot — the write path does
    /// not encrypt, so it would be stored in plaintext.
    #[test]
    fn field_encryption_marker_refuses_boot() {
        use fraiseql_core::schema::{
            CompiledSchema, FieldDefinition, FieldEncryptionConfig, FieldType, TypeDefinition,
        };

        use super::super::initialization::field_encryption_unsupported_check;

        let mut user = TypeDefinition::new("User", "v_user");
        user.fields
            .push(FieldDefinition::new("email", FieldType::String).with_encryption(
                FieldEncryptionConfig {
                    key_reference: "keys/user-email".to_string(),
                    algorithm:     "AES-256-GCM".to_string(),
                },
            ));
        let schema = CompiledSchema {
            types: vec![user],
            ..CompiledSchema::default()
        };

        let result = field_encryption_unsupported_check(&schema);
        assert!(
            matches!(&result, Err(crate::ServerError::ConfigError(msg)) if msg.contains("User.email")),
            "a field marked for encryption must refuse to boot and name the field (H12): {result:?}"
        );
    }

    #[test]
    fn no_field_encryption_boots_fine() {
        use fraiseql_core::schema::{CompiledSchema, FieldDefinition, FieldType, TypeDefinition};

        use super::super::initialization::field_encryption_unsupported_check;

        let mut user = TypeDefinition::new("User", "v_user");
        user.fields.push(FieldDefinition::new("email", FieldType::String));
        let schema = CompiledSchema {
            types: vec![user],
            ..CompiledSchema::default()
        };
        assert!(
            field_encryption_unsupported_check(&schema).is_ok(),
            "a schema with no encryption-marked fields boots normally"
        );
    }

    /// #379: `[security] persisted_queries_only = true` forces the trusted-document
    /// store into Strict mode (reject any non-persisted operation), regardless of the
    /// declared `[security.trusted_documents].mode`. Without the flag, the declared
    /// mode is honored.
    #[test]
    fn persisted_queries_only_forces_strict_mode() {
        use super::super::initialization::effective_trusted_doc_mode;
        use crate::trusted_documents::TrustedDocumentMode;

        // The flag forces Strict even when the declared mode is permissive.
        assert_eq!(
            effective_trusted_doc_mode("permissive", true),
            TrustedDocumentMode::Strict,
            "persisted_queries_only=true must force Strict over a permissive declared mode"
        );
        assert_eq!(effective_trusted_doc_mode("strict", true), TrustedDocumentMode::Strict);

        // Without the flag, the declared mode is honored.
        assert_eq!(effective_trusted_doc_mode("strict", false), TrustedDocumentMode::Strict);
        assert_eq!(
            effective_trusted_doc_mode("permissive", false),
            TrustedDocumentMode::Permissive,
            "without the flag, a permissive schema stays permissive"
        );

        // An unknown/empty declared mode defaults to Permissive unless the flag forces Strict.
        assert_eq!(effective_trusted_doc_mode("", false), TrustedDocumentMode::Permissive);
        assert_eq!(effective_trusted_doc_mode("", true), TrustedDocumentMode::Strict);
    }

    #[test]
    fn ssrf_blocks_localhost_by_name() {
        assert!(is_manifest_url_ssrf_blocked("http://localhost/manifest.json"));
    }

    #[test]
    fn ssrf_blocks_localhost_uppercase() {
        assert!(is_manifest_url_ssrf_blocked("http://LOCALHOST/manifest.json"));
    }

    #[test]
    fn ssrf_blocks_ipv4_loopback() {
        assert!(is_manifest_url_ssrf_blocked("http://127.0.0.1/manifest.json"));
    }

    #[test]
    fn ssrf_blocks_ipv4_private_192_168() {
        assert!(is_manifest_url_ssrf_blocked("http://192.168.1.100/manifest.json"));
    }

    #[test]
    fn ssrf_blocks_ipv4_private_10_x() {
        assert!(is_manifest_url_ssrf_blocked("http://10.0.0.1/manifest.json"));
    }

    #[test]
    fn ssrf_blocks_ipv4_private_172_16() {
        assert!(is_manifest_url_ssrf_blocked("http://172.16.0.1/manifest.json"));
    }

    #[test]
    fn ssrf_blocks_ipv4_link_local() {
        assert!(is_manifest_url_ssrf_blocked("http://169.254.1.1/manifest.json"));
    }

    #[test]
    fn ssrf_blocks_ipv6_loopback() {
        assert!(is_manifest_url_ssrf_blocked("http://[::1]/manifest.json"));
    }

    #[test]
    fn ssrf_blocks_ipv6_unspecified() {
        assert!(is_manifest_url_ssrf_blocked("http://[::]/manifest.json"));
    }

    #[test]
    fn ssrf_blocks_ipv6_ula() {
        // fc00::/7 range
        assert!(is_manifest_url_ssrf_blocked("http://[fd00::1]/manifest.json"));
    }

    #[test]
    fn ssrf_blocks_unparseable_url() {
        assert!(is_manifest_url_ssrf_blocked("not a url at all"));
    }

    #[test]
    fn ssrf_allows_public_https() {
        assert!(!is_manifest_url_ssrf_blocked("https://cdn.example.com/manifest.json"));
    }

    #[test]
    fn ssrf_allows_public_ipv4() {
        // 93.184.216.34 is example.com — a real public address
        assert!(!is_manifest_url_ssrf_blocked("http://93.184.216.34/manifest.json"));
    }

    #[test]
    fn ssrf_allows_public_ipv6_global() {
        // 2001:db8:: is documentation range — treated as public by is_manifest_url_ssrf_blocked
        assert!(!is_manifest_url_ssrf_blocked("http://[2001:db8::1]/manifest.json"));
    }

    // #360: PKCE must not be served without [security.state_encryption] in production.
    #[cfg(feature = "auth")]
    #[test]
    fn pkce_without_state_encryption_is_fatal_in_production() {
        use super::super::initialization::pkce_state_encryption_check;
        let result = pkce_state_encryption_check(
            // has_state_encryption
            false, // is_production
            true,
        );
        assert!(
            result.is_err(),
            "PKCE without state encryption must refuse to boot in production (#360)"
        );
    }

    #[cfg(feature = "auth")]
    #[test]
    fn pkce_without_state_encryption_is_a_warning_in_development() {
        use super::super::initialization::pkce_state_encryption_check;
        assert!(
            pkce_state_encryption_check(false, false).is_ok(),
            "development mode downgrades the missing-state-encryption error to a warning"
        );
    }

    #[cfg(feature = "auth")]
    #[test]
    fn pkce_with_state_encryption_is_always_ok() {
        use super::super::initialization::pkce_state_encryption_check;
        assert!(pkce_state_encryption_check(true, true).is_ok());
        assert!(pkce_state_encryption_check(true, false).is_ok());
    }

    // H7: error sanitization defaults to ON in production when the schema declares
    // no explicit `error_sanitization` config, and OFF in development. An explicit
    // compiled config overrides either way.
    #[test]
    fn error_sanitizer_secure_default_is_environment_aware() {
        use super::super::initialization::build_error_sanitizer;

        // No explicit config: production sanitizes, development stays verbose.
        assert!(
            build_error_sanitizer(None, true).is_enabled(),
            "production must sanitize 5xx by default (H7)"
        );
        assert!(
            !build_error_sanitizer(None, false).is_enabled(),
            "development keeps verbose errors by default"
        );
    }

    #[test]
    fn explicit_error_sanitization_config_overrides_environment_default() {
        use super::super::initialization::build_error_sanitizer;
        use crate::config::error_sanitization::ErrorSanitizationConfig;

        // Operator explicitly disables in production → respected (not forced on).
        let off = ErrorSanitizationConfig {
            enabled: false,
            ..ErrorSanitizationConfig::default()
        };
        assert!(!build_error_sanitizer(Some(off), true).is_enabled());

        // Operator explicitly enables in development → respected.
        let on = ErrorSanitizationConfig {
            enabled: true,
            ..ErrorSanitizationConfig::default()
        };
        assert!(build_error_sanitizer(Some(on), false).is_enabled());
    }

    // #356: the binary cannot enforce failed_login_* lockout (no first-factor login).
    use super::super::initialization::failed_login_lockout_check;
    use crate::middleware::rate_limit::{
        DEFAULT_FAILED_LOGIN_LOCKOUT_SECS, DEFAULT_FAILED_LOGIN_MAX_ATTEMPTS,
    };

    #[test]
    fn failed_login_default_values_boot_silently_even_in_production() {
        // Defaults ride along with any [security.rate_limiting] section and signal no
        // intent, so they must never block startup.
        assert!(
            failed_login_lockout_check(
                DEFAULT_FAILED_LOGIN_MAX_ATTEMPTS,
                DEFAULT_FAILED_LOGIN_LOCKOUT_SECS,
                true,
            )
            .is_ok()
        );
    }

    #[test]
    fn failed_login_tuned_value_is_fatal_in_production() {
        // A tuned max_attempts expects a control the binary cannot provide.
        assert!(failed_login_lockout_check(5, DEFAULT_FAILED_LOGIN_LOCKOUT_SECS, true).is_err());
        // A tuned lockout window is equally fatal.
        assert!(failed_login_lockout_check(DEFAULT_FAILED_LOGIN_MAX_ATTEMPTS, 60, true).is_err());
    }

    #[test]
    fn failed_login_tuned_value_is_a_warning_in_development() {
        assert!(failed_login_lockout_check(5, 60, false).is_ok());
    }

    // #618: trusting X-Forwarded-For from all proxies (empty CIDR list) now REFUSES to
    // boot in production and downgrades to a warning in development — the 2.13 deprecation
    // (#609) promised this. An explicit ["0.0.0.0/0"] opt-in is safe (non-empty list).
    use super::super::initialization::proxy_trust_check;

    #[test]
    fn proxy_trust_all_by_omission_refuses_boot_in_production() {
        // trust + no CIDRs (None) → refuse in production, with an actionable message.
        let err = proxy_trust_check(true, None, true).expect_err("must refuse to boot");
        let msg = format!("{err}");
        assert!(msg.contains("trusted_proxy_cidrs"), "names the fix: {msg}");
        assert!(msg.contains("0.0.0.0/0"), "names the explicit trust-all opt-in: {msg}");
    }

    #[test]
    fn proxy_trust_empty_list_refuses_boot_in_production() {
        // An explicitly empty list is the same permissive posture as omission.
        assert!(proxy_trust_check(true, Some(&[]), true).is_err());
    }

    #[test]
    fn proxy_trust_all_by_omission_is_a_warning_in_development() {
        // Development downgrades to a warning (boot proceeds), matching failed_login.
        assert!(proxy_trust_check(true, None, false).is_ok());
        assert!(proxy_trust_check(true, Some(&[]), false).is_ok());
    }

    #[test]
    fn proxy_trust_explicit_trust_all_is_ok_even_in_production() {
        // ["0.0.0.0/0"] is the sanctioned explicit opt-in — a deliberate, non-empty list,
        // so it neither errors nor warns, in production or development.
        let cidrs = vec!["0.0.0.0/0".to_string()];
        assert!(proxy_trust_check(true, Some(&cidrs), true).is_ok());
        assert!(proxy_trust_check(true, Some(&cidrs), false).is_ok());
    }

    #[test]
    fn proxy_trust_restricted_cidrs_are_ok_in_production() {
        let cidrs = vec!["10.0.0.0/8".to_string()];
        assert!(proxy_trust_check(true, Some(&cidrs), true).is_ok());
    }

    #[test]
    fn proxy_trust_disabled_is_ok() {
        // trust_proxy_headers = false → the CIDR list is irrelevant; never errors/warns.
        assert!(proxy_trust_check(false, None, true).is_ok());
        assert!(proxy_trust_check(false, None, false).is_ok());
    }

    // #350: a configured non-Postgres observer transport that cannot run must fail
    // loud (refuse boot in production), never silently fall back to PostgreSQL.
    #[cfg(feature = "observers")]
    mod observer_transport {
        use fraiseql_observers::config::TransportKind;

        use crate::server::initialization::observer_transport_check;

        #[test]
        fn postgres_is_always_ok() {
            // The default transport needs no broker and never blocks boot.
            assert!(observer_transport_check(TransportKind::Postgres, false, false, true).is_ok());
            assert!(observer_transport_check(TransportKind::Postgres, false, false, false).is_ok());
        }

        #[test]
        fn in_memory_is_always_ok() {
            // The in-memory transport is always compiled and needs no broker.
            assert!(observer_transport_check(TransportKind::InMemory, false, false, true).is_ok());
        }

        #[test]
        fn nats_not_compiled_in_is_fatal_in_production() {
            // transport = "nats" without the observers-nats feature cannot run.
            assert!(observer_transport_check(TransportKind::Nats, false, true, true).is_err());
        }

        #[test]
        fn nats_not_compiled_in_is_a_warning_in_development() {
            assert!(observer_transport_check(TransportKind::Nats, false, true, false).is_ok());
        }

        #[test]
        fn nats_without_url_is_fatal_in_production() {
            assert!(observer_transport_check(TransportKind::Nats, true, false, true).is_err());
        }

        #[test]
        fn nats_without_url_is_a_warning_in_development() {
            assert!(observer_transport_check(TransportKind::Nats, true, false, false).is_ok());
        }

        #[test]
        fn nats_compiled_with_url_is_ok() {
            assert!(observer_transport_check(TransportKind::Nats, true, true, true).is_ok());
        }
    }
}

// ── lifecycle_tests ───────────────────────────────────────────────────────────
//
// Drain semantics for the per-server lifecycle [`JoinSet`] introduced by F021.
// Replaces the previous fire-and-forget `tokio::spawn` calls. A drain after a
// graceful shutdown must abort and await every long-running lifecycle task so
// no background work survives the server's `serve_with_shutdown` return.

#[cfg(test)]
mod lifecycle_tests {
    use std::time::Duration;

    use super::super::lifecycle::drain_lifecycle_tasks;

    #[tokio::test]
    async fn drain_lifecycle_tasks_aborts_infinite_loops() {
        let mut tasks: tokio::task::JoinSet<()> = tokio::task::JoinSet::new();

        // Spawn three infinite loops — the exact pattern used by PKCE cleanup,
        // SIGUSR1 reload, and usage flush in lifecycle.rs. None of them would
        // ever return on their own.
        for _ in 0..3 {
            tasks.spawn(async {
                let mut ticker = tokio::time::interval(Duration::from_secs(60));
                loop {
                    ticker.tick().await;
                }
            });
        }

        // The drain helper must abort all three under the configured timeout.
        let drain =
            tokio::time::timeout(Duration::from_secs(5), drain_lifecycle_tasks(tasks, 5)).await;
        assert!(
            drain.is_ok(),
            "drain_lifecycle_tasks must abort infinite-loop tasks within the timeout"
        );
    }

    #[tokio::test]
    async fn drain_lifecycle_tasks_returns_quickly_for_empty_set() {
        // No tasks → drain returns immediately, well under the timeout.
        let tasks: tokio::task::JoinSet<()> = tokio::task::JoinSet::new();
        let drain =
            tokio::time::timeout(Duration::from_secs(1), drain_lifecycle_tasks(tasks, 5)).await;
        assert!(drain.is_ok(), "drain on an empty JoinSet must be a no-op");
    }
}