fraiseql-server 2.15.0

HTTP server for FraiseQL v2 GraphQL engine
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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
//! GraphQL error response handling.
//!
//! Implements GraphQL spec-compliant error responses with:
//! - Error codes for client-side handling
//! - Location tracking in queries
//! - Extensions for custom error data

use axum::{
    Json,
    http::StatusCode,
    response::{IntoResponse, Response},
};
use serde::Serialize;

/// GraphQL error code enumeration.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
#[non_exhaustive]
pub enum ErrorCode {
    /// Validation error.
    ValidationError,
    /// Parse error.
    ParseError,
    /// Request error.
    RequestError,
    /// Authentication required.
    Unauthenticated,
    /// Access denied.
    Forbidden,
    /// Internal server error.
    InternalServerError,
    /// Database error.
    DatabaseError,
    /// Client-input data exception (SQLSTATE class 22, e.g. a malformed value that
    /// failed a cast) — the request was invalid, not the server (HTTP 400).
    BadUserInput,
    /// Integrity-constraint violation (SQLSTATE class 23, e.g. not-null / unique /
    /// foreign-key / check) caused by client input (HTTP 400).
    ConstraintViolation,
    /// Timeout error.
    Timeout,
    /// Rate limit exceeded.
    RateLimitExceeded,
    /// Not found.
    NotFound,
    /// Conflict.
    Conflict,
    /// Circuit breaker open — federation entity temporarily unavailable.
    CircuitBreakerOpen,
    /// Service temporarily unavailable (e.g. a suspended tenant). Maps to HTTP
    /// 503 and carries a `Retry-After` header when a retry hint is known.
    ServiceUnavailable,
    /// Persisted query not found — client must re-send the full query body.
    PersistedQueryNotFound,
    /// Persisted query hash mismatch — SHA-256 of body does not match provided hash.
    PersistedQueryMismatch,
    /// Raw query forbidden — trusted documents strict mode requires a documentId.
    ForbiddenQuery,
    /// Document not found — the provided documentId is not in the trusted manifest.
    DocumentNotFound,
    /// Operation not allowed for the HTTP method (e.g. a mutation sent over GET).
    MethodNotAllowed,
    /// The request exceeded a configured size ceiling (HTTP 413).
    ///
    /// Distinct from [`RequestError`](Self::RequestError): the request was
    /// well-formed, it was simply too large. `graphql_get_handler` documents 413
    /// for the `max_get_query_bytes` ceiling and used to return 400 (#731).
    PayloadTooLarge,
    /// Introspection query rejected by the configured introspection policy
    /// (`{ __schema }` / `{ __type }` blocked, or permitted only for
    /// authenticated users). A well-formed GraphQL request, so it returns
    /// 200 + `errors[]`.
    IntrospectionDisabled,
    /// Operation cost exceeded a per-request cost budget (#379). A well-formed
    /// request rejected by policy; retrying the same operation cannot succeed,
    /// so this is 200 + `errors[]` (spec §7.1.2) — never a 429 inviting a
    /// pointless retry.
    OperationCostExceeded,
    /// The rolling per-tenant cost budget window is exhausted (#379).
    /// Retryable once the window resets: 429 with a `Retry-After` hint.
    /// Distinct from [`RateLimitExceeded`](Self::RateLimitExceeded) so a
    /// client can tell cost throttling from request-count throttling.
    CostBudgetExhausted,
}

impl ErrorCode {
    /// Whether an error carrying this code has a message written by the database
    /// driver, and so must not be forwarded verbatim when sanitization is on.
    ///
    /// **Provenance, not HTTP class, decides whether a message is safe to forward.**
    /// #413 reclassified SQLSTATE class 22/23 as client faults so they return 400
    /// instead of 500 — right for the status, but it also moved them out of the
    /// sanitizer's reach, and those are precisely the failures a caller can provoke on
    /// demand. The set the sanitizer could rewrite became the complement of the set an
    /// attacker could trigger, while the compiled artefact still advertised
    /// `sanitize_database_errors: true` (#1153).
    ///
    /// Including the two 400-class codes is precise rather than broad:
    /// [`BadUserInput`](Self::BadUserInput) and
    /// [`ConstraintViolation`](Self::ConstraintViolation) are each constructed in
    /// exactly one place — the `E::Database` arm of
    /// [`GraphQLError::from_fraiseql_error`] and its REST mirror — so no hand-written
    /// validation message can wear one and be blanked by mistake.
    ///
    /// The REST surface asks the same question through
    /// `RestError::carries_database_text`, whose spelling is pinned to this one by
    /// `database_text_codes_agree_across_surfaces`.
    #[must_use]
    pub const fn carries_database_text(self) -> bool {
        matches!(
            self,
            Self::InternalServerError
                | Self::DatabaseError
                | Self::BadUserInput
                | Self::ConstraintViolation
        )
    }

    /// Get HTTP status code for this error.
    ///
    /// Follows the [GraphQL over HTTP spec](https://graphql.github.io/graphql-over-http/):
    /// a well-formed GraphQL request that fails validation or parsing returns **200 OK**
    /// with `{"errors": [...]}` in the body — never a 4xx — so that standard HTTP clients
    /// can read the error message rather than raising a transport-level exception.
    ///
    /// Only [`RequestError`](Self::RequestError) uses 400, because it indicates a truly
    /// malformed HTTP request (missing `query` field, unreadable JSON body) that was never
    /// a valid GraphQL request to begin with.
    #[must_use]
    pub const fn status_code(self) -> StatusCode {
        match self {
            // Spec §7.1.2: well-formed requests that fail GraphQL validation, parsing,
            // or APQ "not found" (signal for client to re-send with query body)
            // MUST return 2xx.
            Self::ValidationError
            | Self::ParseError
            | Self::PersistedQueryNotFound
            | Self::IntrospectionDisabled
            | Self::OperationCostExceeded => StatusCode::OK,
            // Truly malformed HTTP request (missing `query` field, unparseable JSON body),
            // APQ hash mismatch, forbidden queries, or missing trusted documents.
            Self::RequestError
            | Self::PersistedQueryMismatch
            | Self::ForbiddenQuery
            | Self::DocumentNotFound
            | Self::BadUserInput
            | Self::ConstraintViolation => StatusCode::BAD_REQUEST,
            Self::Unauthenticated => StatusCode::UNAUTHORIZED,
            Self::Forbidden => StatusCode::FORBIDDEN,
            Self::NotFound => StatusCode::NOT_FOUND,
            Self::Conflict => StatusCode::CONFLICT,
            Self::RateLimitExceeded | Self::CostBudgetExhausted => StatusCode::TOO_MANY_REQUESTS,
            // 408 means "the client took too long to send its request". A
            // server-side execution timeout is a 504 (#731).
            Self::Timeout => StatusCode::GATEWAY_TIMEOUT,
            Self::PayloadTooLarge => StatusCode::PAYLOAD_TOO_LARGE,
            Self::InternalServerError | Self::DatabaseError => StatusCode::INTERNAL_SERVER_ERROR,
            Self::CircuitBreakerOpen | Self::ServiceUnavailable => StatusCode::SERVICE_UNAVAILABLE,
            // GraphQL-over-HTTP: a mutation sent over GET is rejected at the transport
            // layer (405), not returned as a 2xx GraphQL error.
            Self::MethodNotAllowed => StatusCode::METHOD_NOT_ALLOWED,
        }
    }
}

/// A Postgres SQLSTATE class that indicates a **client-input** fault (HTTP 4xx)
/// rather than a server fault (HTTP 5xx).
///
/// Shared by the GraphQL and REST error mappers so both transports classify a
/// `FraiseQLError::Database` identically (#413).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ClientInputSqlState {
    /// SQLSTATE class `22` — data exception (e.g. `22P02` invalid text representation:
    /// a malformed `uuid`/`inet`/`numeric` value that failed a cast).
    DataException,
    /// SQLSTATE class `23` — integrity constraint violation (`23502` not-null,
    /// `23503` foreign-key, `23505` unique, `23514` check).
    IntegrityConstraint,
}

/// Classify a Postgres SQLSTATE as a client-input fault, if it is one.
///
/// Returns `None` for every other class (connection loss, internal `PLpgSQL` faults,
/// …) and for an absent SQLSTATE — those stay HTTP 500 / `DATABASE_ERROR`.
pub(crate) fn classify_client_input_sqlstate(
    sql_state: Option<&str>,
) -> Option<ClientInputSqlState> {
    match sql_state {
        Some(s) if s.starts_with("22") => Some(ClientInputSqlState::DataException),
        Some(s) if s.starts_with("23") => Some(ClientInputSqlState::IntegrityConstraint),
        _ => None,
    }
}

/// Error location in GraphQL query.
#[derive(Debug, Clone, Serialize)]
pub struct ErrorLocation {
    /// Line number (1-indexed).
    pub line:   usize,
    /// Column number (1-indexed).
    pub column: usize,
}

/// GraphQL error following spec.
#[derive(Debug, Clone, Serialize)]
pub struct GraphQLError {
    /// Error message.
    pub message: String,

    /// Error code for client handling.
    pub code: ErrorCode,

    /// Location in query where error occurred.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub locations: Option<Vec<ErrorLocation>>,

    /// Path to field that caused error.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub path: Option<Vec<String>>,

    /// Additional error information.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub extensions: Option<ErrorExtensions>,
}

/// Additional error context and debugging information.
#[derive(Debug, Clone, Serialize)]
pub struct ErrorExtensions {
    /// Error category.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub category: Option<String>,

    /// HTTP status code.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub status: Option<u16>,

    /// Request ID for tracking.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub request_id: Option<String>,

    /// Seconds until the client may retry (set for `CircuitBreakerOpen` errors).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub retry_after_secs: Option<u64>,

    /// Internal error detail (SQL fragment, stack trace, etc.).
    ///
    /// Stripped from responses when error sanitization is enabled.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub detail: Option<String>,
}

/// GraphQL response with errors.
#[derive(Debug, Serialize)]
pub struct ErrorResponse {
    /// Errors that occurred.
    pub errors: Vec<GraphQLError>,
}

impl GraphQLError {
    /// Create a new GraphQL error.
    pub fn new(message: impl Into<String>, code: ErrorCode) -> Self {
        Self {
            message: message.into(),
            code,
            locations: None,
            path: None,
            extensions: None,
        }
    }

    /// Add location to error.
    #[must_use]
    pub fn with_location(mut self, line: usize, column: usize) -> Self {
        self.locations = Some(vec![ErrorLocation { line, column }]);
        self
    }

    /// Add path to error.
    #[must_use]
    pub fn with_path(mut self, path: Vec<String>) -> Self {
        self.path = Some(path);
        self
    }

    /// Add extensions to error.
    #[must_use]
    pub fn with_extensions(mut self, extensions: ErrorExtensions) -> Self {
        self.extensions = Some(extensions);
        self
    }

    /// Add request ID for distributed tracing.
    #[must_use]
    pub fn with_request_id(mut self, request_id: impl Into<String>) -> Self {
        let request_id = request_id.into();
        let extensions = self.extensions.take().unwrap_or(ErrorExtensions {
            category:         None,
            status:           None,
            request_id:       None,
            retry_after_secs: None,
            detail:           None,
        });

        self.extensions = Some(ErrorExtensions {
            request_id: Some(request_id),
            ..extensions
        });
        self
    }

    /// Validation error.
    pub fn validation(message: impl Into<String>) -> Self {
        Self::new(message, ErrorCode::ValidationError)
    }

    /// Parse error with hint for common syntax issues.
    pub fn parse(message: impl Into<String>) -> Self {
        Self::new(message, ErrorCode::ParseError)
    }

    /// Request error with validation details.
    pub fn request(message: impl Into<String>) -> Self {
        Self::new(message, ErrorCode::RequestError)
    }

    /// Method-not-allowed error (e.g. a mutation sent over HTTP GET). Maps to 405.
    pub fn method_not_allowed(message: impl Into<String>) -> Self {
        Self::new(message, ErrorCode::MethodNotAllowed)
    }

    /// Database error - includes connection, timeout, and query errors.
    pub fn database(message: impl Into<String>) -> Self {
        Self::new(message, ErrorCode::DatabaseError)
    }

    /// Idempotency conflict (#747): an `Idempotency-Key` was reused with a
    /// different request body. Maps to HTTP 409 Conflict.
    #[must_use]
    pub fn idempotency_conflict() -> Self {
        Self::new("Idempotency-Key reused with a different request body", ErrorCode::Conflict)
    }

    /// Internal server error - unexpected conditions.
    pub fn internal(message: impl Into<String>) -> Self {
        Self::new(message, ErrorCode::InternalServerError)
    }

    /// Execution error during GraphQL resolver execution.
    ///
    /// # Deprecation
    ///
    /// Prefer [`GraphQLError::from_fraiseql_error`] on the hot path; it preserves
    /// the specific error variant so clients and the sanitizer receive the correct code.
    /// This method remains for ad-hoc internal errors that do not originate from a
    /// `FraiseQLError`.
    #[doc(hidden)]
    #[must_use]
    pub fn execution(message: &str) -> Self {
        Self::new(message, ErrorCode::InternalServerError)
    }

    /// Unauthenticated error - authentication token is missing or invalid.
    #[must_use]
    pub fn unauthenticated() -> Self {
        Self::new("Authentication required", ErrorCode::Unauthenticated)
    }

    /// Forbidden error - user lacks permission to access resource.
    #[must_use]
    pub fn forbidden() -> Self {
        Self::new("Access denied", ErrorCode::Forbidden)
    }

    /// Not found error - requested resource does not exist.
    pub fn not_found(message: impl Into<String>) -> Self {
        Self::new(message, ErrorCode::NotFound)
    }

    /// Timeout error - operation took too long and was cancelled.
    pub fn timeout(operation: impl Into<String>) -> Self {
        Self::new(format!("{} exceeded timeout", operation.into()), ErrorCode::Timeout)
    }

    /// Payload-too-large error — a request exceeded a configured size ceiling.
    pub fn payload_too_large(message: impl Into<String>) -> Self {
        Self::new(message, ErrorCode::PayloadTooLarge)
    }

    /// Rate limit error - too many requests from client.
    pub fn rate_limited(message: impl Into<String>) -> Self {
        Self::new(message, ErrorCode::RateLimitExceeded)
    }

    /// Create an operation-cost-exceeded error (#379): the operation's
    /// estimated cost is over a per-request budget. Not retryable.
    #[must_use]
    pub fn operation_cost_exceeded(message: impl Into<String>) -> Self {
        Self::new(message, ErrorCode::OperationCostExceeded)
    }

    /// Create a cost-budget-exhausted error (#379): the rolling per-tenant
    /// cost window is spent. Retryable after `retry_after_secs`.
    #[must_use]
    pub fn cost_budget_exhausted(message: impl Into<String>, retry_after_secs: u64) -> Self {
        Self::new(message, ErrorCode::CostBudgetExhausted).with_extensions(ErrorExtensions {
            category:         Some("COST_BUDGET_EXHAUSTED".to_string()),
            status:           Some(429),
            request_id:       None,
            retry_after_secs: Some(retry_after_secs),
            detail:           None,
        })
    }

    /// Construct a typed [`GraphQLError`] from a [`fraiseql_core::error::FraiseQLError`] executor
    /// error.
    ///
    /// Maps specific core error variants to their closest HTTP-semantic equivalent,
    /// preserving type information for correct client handling and sanitizer routing.
    #[must_use]
    pub fn from_fraiseql_error(err: &fraiseql_core::error::FraiseQLError) -> Self {
        use fraiseql_core::error::FraiseQLError as E;
        match err {
            // Classify client-input DB faults (SQLSTATE 22xxx/23xxx) as 400 rather than
            // 500 (#413); genuine server faults (other classes, no SQLSTATE, connection
            // pool) stay 500 / DATABASE_ERROR.
            E::Database { sql_state, .. } => {
                match classify_client_input_sqlstate(sql_state.as_deref()) {
                    Some(ClientInputSqlState::DataException) => {
                        Self::new(err.to_string(), ErrorCode::BadUserInput)
                    },
                    Some(ClientInputSqlState::IntegrityConstraint) => {
                        Self::new(err.to_string(), ErrorCode::ConstraintViolation)
                    },
                    None => Self::database(err.to_string()),
                }
            },
            E::ConnectionPool { .. } => Self::database(err.to_string()),
            E::Parse { .. } => Self::parse(err.to_string()),
            E::Validation { .. } | E::UnknownField { .. } | E::UnknownType { .. } => {
                Self::validation(err.to_string())
            },
            E::NotFound { .. } => Self::not_found(err.to_string()),
            E::Conflict { .. } => Self::new(err.to_string(), ErrorCode::Conflict),
            E::Authorization { .. } => Self::forbidden(),
            E::Authentication { .. } => Self::unauthenticated(),
            E::Timeout { .. } => Self::new(err.to_string(), ErrorCode::Timeout),
            E::RateLimited { message, .. } => Self::rate_limited(message.clone()),
            // Cancelled, Configuration, Internal, and any future variants
            _ => Self::internal(err.to_string()),
        }
    }

    /// Persisted query not found — client must re-send the full query body.
    #[must_use]
    pub fn persisted_query_not_found() -> Self {
        Self::new("PersistedQueryNotFound", ErrorCode::PersistedQueryNotFound)
    }

    /// Persisted query hash mismatch — SHA-256 of body does not match the provided hash.
    #[must_use]
    pub fn persisted_query_mismatch() -> Self {
        Self::new("provided sha does not match query", ErrorCode::PersistedQueryMismatch)
    }

    /// Raw query forbidden — trusted documents strict mode requires a documentId.
    #[must_use]
    pub fn forbidden_query() -> Self {
        Self::new(
            "Raw queries are not permitted. Send a documentId instead.",
            ErrorCode::ForbiddenQuery,
        )
    }

    /// Document not found — the provided documentId is not in the trusted manifest.
    pub fn document_not_found(doc_id: impl Into<String>) -> Self {
        Self::new(format!("Unknown document: {}", doc_id.into()), ErrorCode::DocumentNotFound)
    }

    /// Introspection query rejected by the configured introspection policy (#453).
    ///
    /// Surfaced as a GraphQL error in `errors[]` with HTTP 200 — a well-formed
    /// query that the active policy does not permit, not a transport fault.
    #[must_use]
    pub fn introspection_disabled(detail: impl Into<String>) -> Self {
        Self::new(detail, ErrorCode::IntrospectionDisabled)
    }

    /// Circuit breaker open — federation entity temporarily unavailable.
    ///
    /// The response will carry a `Retry-After` header set to `retry_after_secs`.
    #[must_use]
    pub fn circuit_breaker_open(entity: &str, retry_after_secs: u64) -> Self {
        Self::new(
            format!(
                "Federation entity '{entity}' is temporarily unavailable. \
                 Please retry after {retry_after_secs} seconds."
            ),
            ErrorCode::CircuitBreakerOpen,
        )
        .with_extensions(ErrorExtensions {
            category:         Some("CIRCUIT_BREAKER".to_string()),
            status:           Some(503),
            request_id:       None,
            retry_after_secs: Some(retry_after_secs),
            detail:           None,
        })
    }

    /// Service temporarily unavailable (HTTP 503), e.g. a suspended tenant.
    ///
    /// When `retry_after_secs` is set the response carries a matching
    /// `Retry-After` header (see [`ErrorResponse`]'s `IntoResponse`).
    #[must_use]
    pub fn service_unavailable(message: impl Into<String>, retry_after_secs: Option<u64>) -> Self {
        Self::new(message, ErrorCode::ServiceUnavailable).with_extensions(ErrorExtensions {
            category: Some("SERVICE_UNAVAILABLE".to_string()),
            status: Some(503),
            request_id: None,
            retry_after_secs,
            detail: None,
        })
    }
}

impl ErrorResponse {
    /// Create new error response.
    #[must_use]
    pub const fn new(errors: Vec<GraphQLError>) -> Self {
        Self { errors }
    }

    /// Create from single error.
    #[must_use]
    pub fn from_error(error: GraphQLError) -> Self {
        Self {
            errors: vec![error],
        }
    }
}

impl IntoResponse for ErrorResponse {
    fn into_response(self) -> Response {
        let status = self
            .errors
            .first()
            .map_or(StatusCode::INTERNAL_SERVER_ERROR, |e| e.code.status_code());

        let retry_after = self
            .errors
            .first()
            .and_then(|e| e.extensions.as_ref())
            .and_then(|ext| ext.retry_after_secs);

        let mut response = (status, Json(self)).into_response();

        if let Some(secs) = retry_after {
            if let Ok(value) = secs.to_string().parse() {
                response.headers_mut().insert(axum::http::header::RETRY_AFTER, value);
            }
        }

        response
    }
}

impl From<GraphQLError> for ErrorResponse {
    fn from(error: GraphQLError) -> Self {
        Self::from_error(error)
    }
}