athena-gateway 3.18.0

Portable gateway request contracts and normalization primitives for Athena
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
//! Portable `/gateway/query` request parsing and planning helpers.
//!
//! This module owns the request-domain logic that can be shared across route
//! adapters: body parsing, SQL normalization, schema validation, bounded
//! relation-select rewrite planning, and derived gateway read-right
//! calculation. Runtime adapters keep backend resolution, auth enforcement,
//! deferred queueing, logging, and HTTP response construction.

use athena_driver::postgresql::raw_sql::{
    normalize_sql_query, query_contains_create_table_statement,
};
use serde_json::Value;

use crate::{
    GatewayRelationSelectRewrite, GatewaySqlExecutionMode, GatewaySqlRequest,
    StructuredGatewayFetchPlan, build_structured_fetch_plan, normalize_gateway_schema_name,
    query_right, read_right_for_resource, try_rewrite_relation_select_query,
};

/// Validation errors for parsing `/gateway/query` request bodies.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum GatewayQueryRequestParseError {
    /// The HTTP body was empty.
    MissingBody,
    /// The HTTP body was not valid JSON.
    InvalidJson(String),
    /// The JSON body did not match the canonical `/gateway/query` shape.
    InvalidPayload(String),
}

impl GatewayQueryRequestParseError {
    /// Returns the stable public summary used by route adapters.
    pub const fn summary(&self) -> &'static str {
        match self {
            Self::MissingBody | Self::InvalidJson(_) | Self::InvalidPayload(_) => {
                "Invalid request body"
            }
        }
    }

    /// Returns the stable public detail string used by route adapters.
    pub fn detail(&self) -> String {
        match self {
            Self::MissingBody => "request body is required for /gateway/query".to_string(),
            Self::InvalidJson(message) => {
                format!("malformed JSON payload for /gateway/query: {message}")
            }
            Self::InvalidPayload(message) => {
                format!("invalid /gateway/query payload: {message}")
            }
        }
    }
}

/// Structured rewrite plan for relation-select compatibility queries.
#[derive(Debug, Clone)]
pub struct GatewayQueryCompatibilityPlan {
    /// Normalized compatibility rewrite details derived from the SQL query.
    pub rewrite: GatewayRelationSelectRewrite,
    /// Structured fetch plan compiled from the compatibility request body.
    pub structured_fetch_plan: StructuredGatewayFetchPlan,
}

/// Portable request plan derived from a canonical `/gateway/query` payload.
#[derive(Debug, Clone)]
pub struct GatewayQueryRequestPlan {
    /// Query text after gateway-compatible normalization.
    pub normalized_query: String,
    /// Optional validated schema override to apply to PostgreSQL execution.
    pub schema_name: Option<String>,
    /// Defaulted execution mode used by runtime adapters.
    pub execution_mode: GatewaySqlExecutionMode,
    /// Optional bounded compatibility rewrite for relation-select SQL.
    pub compatibility: Option<GatewayQueryCompatibilityPlan>,
}

impl GatewayQueryRequestPlan {
    /// Returns the gateway rights required to execute the planned query.
    pub fn required_rights(&self) -> Vec<String> {
        if let Some(compatibility) = self.compatibility.as_ref() {
            let mut rights = vec![query_right()];
            rights.extend(
                compatibility
                    .structured_fetch_plan
                    .resource_names()
                    .into_iter()
                    .map(|resource| read_right_for_resource(Some(&resource))),
            );
            rights.sort();
            rights.dedup();
            rights
        } else {
            vec![query_right()]
        }
    }

    /// Reports whether the normalized query still satisfies the deadpool
    /// single-statement execution constraints.
    pub fn allows_deadpool_execution(&self) -> bool {
        self.execution_mode == GatewaySqlExecutionMode::SingleTransaction
            && !query_contains_create_table_statement(&self.normalized_query)
    }
}

/// Validation errors for portable `/gateway/query` planning.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum GatewayQueryRequestPlanError {
    /// The normalized query string was empty after trimming and semicolon cleanup.
    EmptyQuery,
    /// The optional schema selector was invalid.
    InvalidSchemaName(String),
    /// The bounded relation-select compatibility query could not be planned.
    InvalidRelationSelectCompatibility(String),
}

impl GatewayQueryRequestPlanError {
    /// Returns the stable public summary used by route adapters.
    pub const fn summary(&self) -> &'static str {
        match self {
            Self::EmptyQuery => "Invalid query",
            Self::InvalidSchemaName(_) => "Invalid schema_name",
            Self::InvalidRelationSelectCompatibility(_) => {
                "Invalid relation-select compatibility query"
            }
        }
    }

    /// Returns the stable public detail string used by route adapters.
    pub fn detail(&self) -> String {
        match self {
            Self::EmptyQuery => "Query cannot be empty or contain only semicolons.".to_string(),
            Self::InvalidSchemaName(message)
            | Self::InvalidRelationSelectCompatibility(message) => message.clone(),
        }
    }
}

/// Parses the canonical `/gateway/query` request payload from raw bytes.
pub fn parse_gateway_query_request_body(
    body: &[u8],
) -> Result<GatewaySqlRequest, GatewayQueryRequestParseError> {
    if body.is_empty() {
        return Err(GatewayQueryRequestParseError::MissingBody);
    }

    let raw_body: Value = serde_json::from_slice(body)
        .map_err(|err| GatewayQueryRequestParseError::InvalidJson(err.to_string()))?;

    serde_json::from_value(raw_body)
        .map_err(|err| GatewayQueryRequestParseError::InvalidPayload(err.to_string()))
}

/// Builds the portable `/gateway/query` execution plan.
///
/// When `assume_postgres` is `false`, the plan still normalizes the SQL and
/// schema selector but skips bounded relation-select rewrites.
pub fn build_gateway_query_request_plan(
    request: &GatewaySqlRequest,
    assume_postgres: bool,
    force_camel_case_to_snake_case: bool,
) -> Result<GatewayQueryRequestPlan, GatewayQueryRequestPlanError> {
    let normalized_query = normalize_sql_query(&request.query);
    if normalized_query.is_empty() {
        return Err(GatewayQueryRequestPlanError::EmptyQuery);
    }

    let schema_name = normalize_gateway_schema_name(request.schema_name.as_deref())
        .map_err(GatewayQueryRequestPlanError::InvalidSchemaName)?;
    let execution_mode = request.execution_mode.unwrap_or_default();

    let compatibility = if assume_postgres {
        match try_rewrite_relation_select_query(&normalized_query, schema_name.as_deref()) {
            Ok(Some(rewrite)) => {
                let structured_fetch_plan = match build_structured_fetch_plan(
                    &rewrite.request_body,
                    force_camel_case_to_snake_case,
                ) {
                    Ok(Some(plan)) => plan,
                    Ok(None) => {
                        return Err(
                            GatewayQueryRequestPlanError::InvalidRelationSelectCompatibility(
                                "Compatibility rewrite did not produce a structured select plan."
                                    .to_string(),
                            ),
                        );
                    }
                    Err(err) => {
                        return Err(
                            GatewayQueryRequestPlanError::InvalidRelationSelectCompatibility(err),
                        );
                    }
                };

                Some(GatewayQueryCompatibilityPlan {
                    rewrite,
                    structured_fetch_plan,
                })
            }
            Ok(None) => None,
            Err(err) => {
                return Err(GatewayQueryRequestPlanError::InvalidRelationSelectCompatibility(err));
            }
        }
    } else {
        None
    };

    Ok(GatewayQueryRequestPlan {
        normalized_query,
        schema_name,
        execution_mode,
        compatibility,
    })
}

#[cfg(test)]
mod tests {
    use super::{
        GatewayQueryRequestParseError, GatewayQueryRequestPlanError,
        build_gateway_query_request_plan, parse_gateway_query_request_body,
    };
    use crate::GatewaySqlExecutionMode;
    use serde_json::json;

    #[test]
    fn parse_gateway_query_request_requires_body() {
        let err = parse_gateway_query_request_body(&[]).expect_err("missing body should fail");

        assert_eq!(err, GatewayQueryRequestParseError::MissingBody);
        assert_eq!(err.summary(), "Invalid request body");
        assert_eq!(err.detail(), "request body is required for /gateway/query");
    }

    #[test]
    fn parse_gateway_query_request_rejects_malformed_json() {
        let err = parse_gateway_query_request_body(br#"{"query":"SELECT 1""#)
            .expect_err("malformed json should fail");

        match err {
            GatewayQueryRequestParseError::InvalidJson(message) => {
                assert!(message.contains("EOF"));
            }
            other => panic!("expected invalid json error, got {other:?}"),
        }
    }

    #[test]
    fn parse_gateway_query_request_rejects_invalid_payload_shape() {
        let err = parse_gateway_query_request_body(
            serde_json::to_vec(&json!({ "schema_name": "public" }))
                .expect("json should serialize")
                .as_slice(),
        )
        .expect_err("missing query should fail");

        match err {
            GatewayQueryRequestParseError::InvalidPayload(message) => {
                assert!(message.contains("missing field `query`"));
            }
            other => panic!("expected invalid payload error, got {other:?}"),
        }
    }

    #[test]
    fn query_plan_rejects_empty_queries() {
        let request = parse_gateway_query_request_body(
            serde_json::to_vec(&json!({ "query": " ; ; " }))
                .expect("json should serialize")
                .as_slice(),
        )
        .expect("request should parse");

        let err = build_gateway_query_request_plan(&request, true, false)
            .expect_err("empty query should fail");

        assert_eq!(err, GatewayQueryRequestPlanError::EmptyQuery);
        assert_eq!(err.summary(), "Invalid query");
        assert_eq!(
            err.detail(),
            "Query cannot be empty or contain only semicolons."
        );
    }

    #[test]
    fn query_plan_rejects_invalid_schema_names() {
        let request = parse_gateway_query_request_body(
            serde_json::to_vec(&json!({
                "query": "SELECT 1",
                "schema_name": "public;drop schema public"
            }))
            .expect("json should serialize")
            .as_slice(),
        )
        .expect("request should parse");

        let err = build_gateway_query_request_plan(&request, true, false)
            .expect_err("invalid schema name should fail");

        match err {
            GatewayQueryRequestPlanError::InvalidSchemaName(message) => {
                assert!(message.contains("schema_name"));
            }
            other => panic!("expected invalid schema name, got {other:?}"),
        }
    }

    #[test]
    fn query_plan_skips_relation_rewrite_for_non_postgres_targets() {
        let request = parse_gateway_query_request_body(
            serde_json::to_vec(&json!({
                "query": "SELECT cs.user_id,users:athena.users(id) FROM public.chat_subscriptions AS cs WHERE cs.user_id = '1'",
                "execution_mode": "per_statement"
            }))
            .expect("json should serialize")
            .as_slice(),
        )
        .expect("request should parse");

        let plan =
            build_gateway_query_request_plan(&request, false, false).expect("plan should build");

        assert_eq!(plan.execution_mode, GatewaySqlExecutionMode::PerStatement);
        assert!(plan.compatibility.is_none());
        assert_eq!(plan.required_rights(), vec!["gateway.query".to_string()]);
        assert!(!plan.allows_deadpool_execution());
    }

    #[test]
    fn query_plan_builds_relation_select_compatibility_and_rights() {
        let request = parse_gateway_query_request_body(
            serde_json::to_vec(&json!({
                "query": "SELECT cs.user_id,users:athena.users(id,username) FROM public.chat_subscriptions AS cs INNER JOIN athena.users u ON u.id = cs.user_id WHERE u.username = 'alice'"
            }))
            .expect("json should serialize")
            .as_slice(),
        )
        .expect("request should parse");

        let plan =
            build_gateway_query_request_plan(&request, true, false).expect("plan should build");

        let compatibility = plan
            .compatibility
            .as_ref()
            .expect("rewrite should be planned");
        assert_eq!(compatibility.rewrite.table.table_name, "chat_subscriptions");
        assert_eq!(
            compatibility.rewrite.table.schema_name.as_deref(),
            Some("public")
        );
        assert_eq!(
            compatibility.structured_fetch_plan.resource_names(),
            vec!["chat_subscriptions".to_string(), "users".to_string()]
        );
        assert_eq!(
            plan.required_rights(),
            vec![
                "chat_subscriptions.read".to_string(),
                "gateway.query".to_string(),
                "users.read".to_string(),
            ]
        );
        assert!(plan.allows_deadpool_execution());
    }

    #[test]
    fn query_plan_rejects_invalid_relation_select_compatibility_queries() {
        let request = parse_gateway_query_request_body(
            serde_json::to_vec(&json!({
                "query": "SELECT user_id,users:athena.users(id) FROM public.chat_subscriptions cs INNER JOIN athena.users u ON u.id = cs.user_id AND u.username = 'alice'"
            }))
            .expect("json should serialize")
            .as_slice(),
        )
        .expect("request should parse");

        let err = build_gateway_query_request_plan(&request, true, false)
            .expect_err("invalid compatibility query should fail");

        match err {
            GatewayQueryRequestPlanError::InvalidRelationSelectCompatibility(message) => {
                assert!(message.contains("single equality predicate"));
            }
            other => panic!("expected compatibility error, got {other:?}"),
        }
    }

    #[test]
    fn query_plan_disallows_deadpool_for_create_table_queries() {
        let request = parse_gateway_query_request_body(
            serde_json::to_vec(&json!({
                "query": "CREATE TABLE users (id uuid primary key)"
            }))
            .expect("json should serialize")
            .as_slice(),
        )
        .expect("request should parse");

        let plan =
            build_gateway_query_request_plan(&request, true, false).expect("plan should build");

        assert!(!plan.allows_deadpool_execution());
    }
}