Skip to main content

sqlserver_mcp_catalog/services/
api_client.rs

1// SQL Server 2025 - master/msdb/model combined catalog MCP server.
2//
3// Real transport: a pooled TDS connection to SQL Server (via `tiberius`),
4// replacing mcpify's originally-generated `reqwest`-based HTTP client.
5// These OpenAPI operations are synthetic (see
6// docs/sqlserver-eda-openapi-pipeline/README.md's "OpenAPI mapping
7// convention") -- there is no real HTTP endpoint on the other end, so
8// `endpoint.path`/`endpoint.method` don't describe an HTTP request; they
9// encode `/<schema>/<name>` (set by `tools/generate_openapi.py`, one path per
10// deduplicated operation -- see that script's `build_operations()`) and are
11// always `POST`. `endpoint.description` carries the object's
12// `sys.objects.type_desc` (`VIEW` / `SQL_STORED_PROCEDURE` /
13// `SQL_INLINE_TABLE_VALUED_FUNCTION` / `EXTENDED_STORED_PROCEDURE` / ...),
14// which determines the actual T-SQL shape: a bare `SELECT` for views,
15// `SELECT ... FROM name(args)` for table-valued functions and `SELECT
16// name(args)` for scalar functions (positional args -- no named-parameter
17// call syntax exists for a function call), or `EXEC name @p = v, ...` for
18// stored procedures (named, so param order and optional/defaulted params
19// don't matter).
20
21use serde_json::{Map, Value};
22use tiberius::ToSql;
23
24use crate::auth::auth_manager::AuthManager;
25use crate::core::config_schema::Config;
26use crate::data::store::EndpointRecord;
27use crate::services::sql_pool;
28use crate::services::sql_type::{column_data_to_json, json_to_param};
29use crate::validation::validator::resolved_schemas_for;
30
31/// The synthetic request-body property documenting an operation's execution
32/// context (see `docs/sqlserver-eda-openapi-pipeline/tools/generate_openapi.py`'s
33/// `EXECUTION_DATABASE_PARAM`) -- not a real SQL Server parameter of the
34/// underlying object, so it's pulled out of `body` and used to qualify the
35/// call rather than being bound as a `@P<n>` argument. Every generated
36/// operation carries this property (see `ordered_params`'s exclusion of it),
37/// so this name is reserved across the whole generated store.
38const EXECUTION_DATABASE_PARAM: &str = "execution_database";
39
40/// Parses `endpoint.path`'s `/<schema>/<name>` shape (set by
41/// `docs/sqlserver-eda-openapi-pipeline/tools/generate_openapi.py`) into its
42/// two parts. Unlike the old per-database-prefixed path convention, which
43/// database to actually run against is no longer baked into the path at
44/// generation time (a deduplicated operation may exist identically in more
45/// than one of master/msdb/model) -- see `resolve_execution_database`.
46fn parse_path(path: &str) -> anyhow::Result<(&str, &str)> {
47    let mut parts = path.trim_start_matches('/').splitn(2, '/');
48    match (parts.next(), parts.next()) {
49        (Some(schema), Some(name)) if !schema.is_empty() && !name.is_empty() => {
50            Ok((validate_ident(schema)?, validate_ident(name)?))
51        }
52        _ => anyhow::bail!("endpoint path '{path}' is not in the expected /<schema>/<name> shape"),
53    }
54}
55
56/// Rejects any identifier containing a character outside `[A-Za-z0-9_]` --
57/// every identifier passed through here (`db`/`schema`/`name`, stored
58/// procedure parameter names) comes from this project's own generated spec
59/// (looked up from the local SQLite store by `operation_id`, never built
60/// from a caller-supplied string), and every name in the curated object
61/// set this pipeline targets is already plain alphanumeric/underscore --
62/// see docs/sqlserver-eda-openapi-pipeline/sql/eda/allowlist.yaml. This is
63/// defense-in-depth on top of `quote_ident`'s bracket-escaping, not a
64/// response to any known injection path: T-SQL has no way to bind an
65/// object/parameter *name* as a query parameter (only values), so an
66/// identifier that ever did contain attacker-influenced text would bypass
67/// the parameterized-value protection `services::sql_type::json_to_param`
68/// provides for every argument *value*. Failing loudly here on an
69/// unexpected character is preferable to silently trusting it.
70fn validate_ident(ident: &str) -> anyhow::Result<&str> {
71    if !ident.is_empty()
72        && ident
73            .bytes()
74            .all(|b| b.is_ascii_alphanumeric() || b == b'_')
75    {
76        Ok(ident)
77    } else {
78        anyhow::bail!("identifier '{ident}' contains characters outside [A-Za-z0-9_]")
79    }
80}
81
82/// Brackets a SQL Server identifier, doubling any embedded `]` -- a second,
83/// independent layer under `validate_ident`'s charset allow-list, kept
84/// rather than dropped now that the allow-list exists, since a future
85/// change loosening the allow-list (e.g. to admit `$`/`#`-prefixed names)
86/// should not silently lose this escaping.
87fn quote_ident(ident: &str) -> String {
88    format!("[{}]", ident.replace(']', "]]"))
89}
90
91/// Resolves an operation's execution-context database: the caller-supplied
92/// `execution_database` body property (see `EXECUTION_DATABASE_PARAM`) if
93/// present, else the server's configured `Config::default_database` if one
94/// was set up (optional, see `cli::setup_wizard`), else `None` -- meaning
95/// `build_statement` two-part-qualifies the call and lets the connection's
96/// own current database context resolve it (equivalent to `DB_NAME()`/
97/// `DB_ID()`). This three-tier fallback applies uniformly to every
98/// operation now, not just ones documented in a particular database --
99/// see `build_statement`'s doc comment.
100fn resolve_execution_database(
101    body: &Map<String, Value>,
102    config: &Config,
103) -> anyhow::Result<Option<String>> {
104    if let Some(value) = body.get(EXECUTION_DATABASE_PARAM) {
105        let requested = value
106            .as_str()
107            .ok_or_else(|| anyhow::anyhow!("'{EXECUTION_DATABASE_PARAM}' must be a string"))?;
108        return Ok(Some(validate_ident(requested)?.to_string()));
109    }
110    config
111        .default_database
112        .as_deref()
113        .map(validate_ident)
114        .transpose()
115        .map(|opt| opt.map(str::to_string))
116}
117
118struct Param {
119    name: String,
120    ordinal: u64,
121    x_sql_type: String,
122}
123
124/// Every operation's generated input schema wraps its real parameters one
125/// level down, under a single top-level `body` property (mcpify's
126/// request-body convention -- see `ApiClient::execute`'s own `body`
127/// extraction from the caller's `args`, which this mirrors), almost always
128/// as a `$ref` into the schema's own `$defs` rather than an inline object.
129/// Resolves that wrapper (and its `$ref`, if present) to the real
130/// parameter-name map. Returns `None` for a schema with no `body` property
131/// at all (a parameterless operation), which `ordered_params` below treats
132/// as zero parameters.
133fn request_properties(input_schema: &Value) -> Option<&Map<String, Value>> {
134    let body_schema = input_schema.get("properties")?.get("body")?;
135    let resolved = match body_schema.get("$ref").and_then(Value::as_str) {
136        Some(reference) => reference
137            .strip_prefix("#/$defs/")
138            .and_then(|name| input_schema.get("$defs")?.get(name))?,
139        None => body_schema,
140    };
141    resolved.get("properties").and_then(Value::as_object)
142}
143
144/// Reads `properties`/`x-sql-ordinal`/`x-sql-type` off a resolved input
145/// schema (see `tools/generate_openapi.py`'s `build_request_schema`),
146/// sorted by declared ordinal -- required for a table-valued function's
147/// positional call syntax, and used for stored procedures' named syntax
148/// mainly for a deterministic/readable generated statement.
149fn ordered_params(input_schema: &Value) -> Vec<Param> {
150    let mut params: Vec<Param> = request_properties(input_schema)
151        .into_iter()
152        .flatten()
153        .filter(|(name, _)| name.as_str() != EXECUTION_DATABASE_PARAM)
154        .map(|(name, schema)| Param {
155            name: name.clone(),
156            ordinal: schema
157                .get("x-sql-ordinal")
158                .and_then(Value::as_u64)
159                .unwrap_or(0),
160            x_sql_type: schema
161                .get("x-sql-type")
162                .and_then(Value::as_str)
163                .unwrap_or("nvarchar(max)")
164                .to_string(),
165        })
166        .collect();
167    params.sort_by_key(|p| p.ordinal);
168    params
169}
170
171/// Builds the T-SQL text (with `@P1`/`@P2`/... placeholders) and the
172/// matching positionally-ordered bound parameters for one operation call.
173///
174/// `execution_database` is the resolved value of the synthetic
175/// `execution_database` request property (see `resolve_execution_database`)
176/// -- every operation now behaves the way only `sandbox`-tagged operations
177/// used to: three-part-qualified (`db.schema.name`) when a database is
178/// known, two-part-qualified (`schema.name`, resolved against the
179/// connection's own current database context) when it isn't. There is no
180/// per-operation baked-in database anymore -- a deduplicated operation may
181/// exist identically in more than one of master/msdb/model (see
182/// `docs/sqlserver-eda-openapi-pipeline/README.md`'s "OpenAPI mapping
183/// convention"), so which one to actually hit is always resolved per call.
184fn build_statement(
185    schema: &str,
186    name: &str,
187    kind: Option<&str>,
188    params: &[Param],
189    body: &Map<String, Value>,
190    execution_database: Option<&str>,
191) -> anyhow::Result<(String, Vec<Box<dyn ToSql>>)> {
192    let qualified = match execution_database {
193        Some(db) => format!(
194            "{}.{}.{}",
195            quote_ident(db),
196            quote_ident(schema),
197            quote_ident(name)
198        ),
199        None => format!("{}.{}", quote_ident(schema), quote_ident(name)),
200    };
201
202    let mut bound: Vec<Box<dyn ToSql>> = Vec::with_capacity(params.len());
203    for param in params {
204        let value = body.get(&param.name).cloned().unwrap_or(Value::Null);
205        bound.push(json_to_param(&value, &param.x_sql_type)?);
206    }
207
208    let sql = match kind {
209        Some("VIEW") => format!("SELECT * FROM {qualified}"),
210        Some(k) if k.ends_with("_FUNCTION") || k.contains("TABLE_VALUED_FUNCTION") => {
211            let placeholders = (1..=bound.len())
212                .map(|i| format!("@P{i}"))
213                .collect::<Vec<_>>()
214                .join(", ");
215            format!("SELECT * FROM {qualified}({placeholders})")
216        }
217        // Stored procedures (SQL_STORED_PROCEDURE/EXTENDED_STORED_PROCEDURE)
218        // and the `kind.is_none()` fallback (an older store built before
219        // `description` carried this classification) both take the EXEC
220        // path -- named parameter syntax, so a proc with only optional
221        // parameters and no arguments supplied still works (`bound` empty
222        // produces a bare `EXEC name`).
223        _ => {
224            if bound.is_empty() {
225                format!("EXEC {qualified}")
226            } else {
227                let mut assignments = Vec::with_capacity(params.len());
228                for (i, p) in params.iter().enumerate() {
229                    // Named EXEC-argument syntax requires the `@` sigil
230                    // directly on the parameter name (`EXEC proc @param =
231                    // value`, not `EXEC proc [param] = value` or
232                    // `EXEC proc param = value`) -- bracket-quoting is for
233                    // object identifiers, not parameter references, and
234                    // using it here produced a syntax error on every
235                    // parameterized stored-procedure call. `validate_ident`
236                    // still runs first for the same defense-in-depth reason
237                    // as the object-identifier path above.
238                    assignments.push(format!("@{} = @P{}", validate_ident(&p.name)?, i + 1));
239                }
240                format!("EXEC {qualified} {}", assignments.join(", "))
241            }
242        }
243    };
244
245    Ok((sql, bound))
246}
247
248/// The severity-to-status-category mapping documented on every generated
249/// operation's 400/403/500 responses (see `docs/sqlserver-eda-openapi-pipeline
250/// /README.md`'s "OpenAPI mapping convention") -- pulled out of
251/// `classify_tiberius_error` as its own pure function so this classification
252/// logic is unit-testable directly. `tiberius::tds::codec::TokenError`'s
253/// fields are all `pub(crate)` with no public constructor, so a
254/// `tiberius::error::Error::Server(_)` can never be built from outside the
255/// crate for a test to exercise the branch that reads `class` off it --
256/// this function is what actually stays testable.
257fn severity_category(class: u8) -> &'static str {
258    if class >= 17 {
259        "fatal/resource error (500-equivalent)"
260    } else if class == 14 {
261        "permission denied (403-equivalent)"
262    } else {
263        "statement/user error (400-equivalent)"
264    }
265}
266
267/// Maps a `tiberius` error to this project's synthetic 400/403/500 split
268/// (see `docs/sqlserver-eda-openapi-pipeline/README.md`'s "OpenAPI mapping
269/// convention" -- SQL Server severity 11-16 statement errors are `400`,
270/// severity-14 permission errors are `403`, severity 17-25 engine/fatal
271/// errors are `500`), rather than surfacing the raw driver error
272/// undifferentiated. Returned as a JSON value matching
273/// `components.schemas.SqlServerError` shape rather than a bare string, so
274/// callers get the same structured error either way they might have gotten
275/// it from a real synchronous SQL Server error.
276fn classify_tiberius_error(err: tiberius::error::Error) -> anyhow::Error {
277    use tiberius::error::Error as TError;
278    match &err {
279        TError::Server(token) => {
280            let (number, state, class, message, procedure, line) = (
281                token.code(),
282                token.state(),
283                token.class(),
284                token.message(),
285                token.procedure(),
286                token.line(),
287            );
288            let category = severity_category(class);
289            anyhow::anyhow!(
290                "SQL Server error {number} (severity {class}, state {state}) in '{procedure}' line {line}: {message} [{category}]"
291            )
292        }
293        other => anyhow::anyhow!("SQL Server connection/protocol error (500-equivalent): {other}"),
294    }
295}
296
297pub struct ApiClient {
298    config: Config,
299}
300
301impl ApiClient {
302    pub fn new(config: Config) -> Self {
303        Self { config }
304    }
305
306    /// Executes `endpoint` against the configured SQL Server instance.
307    /// `auth_manager` resolves to a `tiberius::AuthMethod` (see
308    /// `auth::auth_manager::AuthManager::resolve_tds_auth`) from the
309    /// server's own configured credentials -- there is no per-request
310    /// credential override; SQL Server auth is always this server's own
311    /// configured identity, not something a caller supplies per call.
312    pub async fn execute(
313        &self,
314        endpoint: &EndpointRecord,
315        args: &Value,
316        auth_manager: &mut AuthManager,
317    ) -> anyhow::Result<Value> {
318        let (schema, name) = parse_path(&endpoint.path)?;
319
320        let (input_schema, _output_schema) =
321            resolved_schemas_for(&self.config.api_version, &endpoint.operation_id).ok_or_else(
322                || {
323                    anyhow::anyhow!(
324                        "no resolved schema found for operation '{}' under api_version '{}'",
325                        endpoint.operation_id,
326                        self.config.api_version
327                    )
328                },
329            )?;
330        let params = ordered_params(input_schema);
331
332        let empty = Map::new();
333        let args_map = args.as_object().unwrap_or(&empty);
334        let body = args_map
335            .get("body")
336            .and_then(Value::as_object)
337            .cloned()
338            .unwrap_or_default();
339        let execution_database = resolve_execution_database(&body, &self.config)?;
340
341        let (sql, bound) = build_statement(
342            schema,
343            name,
344            endpoint.description.as_deref(),
345            &params,
346            &body,
347            execution_database.as_deref(),
348        )?;
349
350        let auth_method = auth_manager.resolve_tds_auth().await?;
351
352        let (host, port) = self.config.host_and_port();
353        let mut tiberius_config = tiberius::Config::new();
354        tiberius_config.host(host);
355        tiberius_config.port(port);
356        tiberius_config.authentication(auth_method);
357        if self.config.trust_server_cert {
358            // Curated system-catalog objects, not user data -- trusting the
359            // server cert matches this project's primary use case (a local
360            // Docker/dev instance with a self-signed cert; see
361            // docs/sqlserver-eda-openapi-pipeline/docker-compose.yml)
362            // rather than requiring every operator to supply a CA bundle
363            // before the first query works. Set `trust_server_cert: false`
364            // for a production instance with a real CA-signed cert.
365            tiberius_config.trust_cert();
366        }
367
368        let pool_key = format!("{host}:{port}");
369        let pool =
370            sql_pool::cached_pool(&pool_key, tiberius_config, self.config.pool_max_size).await?;
371        let mut conn = pool.get().await.map_err(|err| {
372            anyhow::anyhow!("failed to obtain a pooled SQL Server connection: {err}")
373        })?;
374
375        let bound_refs: Vec<&dyn ToSql> = bound.iter().map(|param| param.as_ref()).collect();
376        let stream = conn
377            .query(&sql, &bound_refs)
378            .await
379            .map_err(classify_tiberius_error)?;
380        let rows = stream
381            .into_first_result()
382            .await
383            .map_err(classify_tiberius_error)?;
384
385        let json_rows: Vec<Value> = rows
386            .iter()
387            .map(|row| {
388                let mut obj = Map::new();
389                for (column, data) in row.cells() {
390                    obj.insert(column.name().to_string(), column_data_to_json(data));
391                }
392                Value::Object(obj)
393            })
394            .collect();
395        Ok(Value::Array(json_rows))
396    }
397}
398
399#[cfg(test)]
400mod tests {
401    use super::*;
402
403    #[test]
404    fn parse_path_splits_schema_name() {
405        assert_eq!(
406            parse_path("/INFORMATION_SCHEMA/COLUMNS").unwrap(),
407            ("INFORMATION_SCHEMA", "COLUMNS")
408        );
409    }
410
411    #[test]
412    fn parse_path_rejects_a_path_with_too_few_segments() {
413        assert!(parse_path("/COLUMNS").is_err());
414    }
415
416    #[test]
417    fn quote_ident_doubles_embedded_closing_brackets() {
418        assert_eq!(quote_ident("weird]name"), "[weird]]name]");
419    }
420
421    #[test]
422    fn validate_ident_accepts_alphanumeric_and_underscore() {
423        assert!(validate_ident("sp_who2").is_ok());
424        assert!(validate_ident("INFORMATION_SCHEMA").is_ok());
425    }
426
427    #[test]
428    fn validate_ident_rejects_anything_else() {
429        assert!(validate_ident("").is_err());
430        assert!(validate_ident("robert'; drop table endpoints;--").is_err());
431        assert!(validate_ident("weird]name").is_err());
432        assert!(validate_ident("has space").is_err());
433    }
434
435    #[test]
436    fn parse_path_rejects_a_path_with_an_unsafe_segment() {
437        assert!(parse_path("/sys/sp_who; DROP TABLE endpoints--").is_err());
438    }
439
440    #[test]
441    fn build_statement_selects_from_a_view_with_no_parameters() {
442        let (sql, bound) = build_statement(
443            "INFORMATION_SCHEMA",
444            "COLUMNS",
445            Some("VIEW"),
446            &[],
447            &Map::new(),
448            None,
449        )
450        .unwrap();
451        assert_eq!(sql, "SELECT * FROM [INFORMATION_SCHEMA].[COLUMNS]");
452        assert!(bound.is_empty());
453    }
454
455    #[test]
456    fn build_statement_execs_a_proc_with_named_parameters() {
457        let params = vec![
458            Param {
459                name: "objname".to_string(),
460                ordinal: 1,
461                x_sql_type: "nvarchar(1035)".to_string(),
462            },
463            Param {
464                name: "newname".to_string(),
465                ordinal: 2,
466                x_sql_type: "sysname".to_string(),
467            },
468        ];
469        let mut body = Map::new();
470        body.insert("objname".to_string(), Value::String("t1".to_string()));
471        body.insert("newname".to_string(), Value::String("t2".to_string()));
472        let (sql, bound) = build_statement(
473            "sys",
474            "sp_rename",
475            Some("SQL_STORED_PROCEDURE"),
476            &params,
477            &body,
478            Some("master"),
479        )
480        .unwrap();
481        assert_eq!(
482            sql,
483            "EXEC [master].[sys].[sp_rename] @objname = @P1, @newname = @P2"
484        );
485        assert_eq!(bound.len(), 2);
486    }
487
488    /// Regression test for incident 26-07-05700-04: every parameterized
489    /// stored-procedure `call` (e.g. `sp_columns`, `sp_executesql`) failed
490    /// with SQL Server error 102 "Incorrect syntax near '='", no matter
491    /// what argument keys the caller supplied, because the generated
492    /// assignment list bracket-quoted the parameter name (`[table_name] =
493    /// @P1`) instead of prefixing it with `@` (`@table_name = @P1`) --
494    /// bracket-quoting is valid for object identifiers, not for named
495    /// EXEC arguments. This asserts the `@`-prefixed form specifically, so
496    /// a future edit can't silently reintroduce bracket-quoting here even
497    /// if it still happens to produce syntactically-plausible-looking SQL.
498    #[test]
499    fn build_statement_uses_at_prefixed_names_not_bracket_quoting_for_named_exec_arguments() {
500        let params = vec![Param {
501            name: "table_name".to_string(),
502            ordinal: 1,
503            x_sql_type: "nvarchar(384)".to_string(),
504        }];
505        let mut body = Map::new();
506        body.insert(
507            "table_name".to_string(),
508            Value::String("databases".to_string()),
509        );
510        let (sql, _bound) = build_statement(
511            "sys",
512            "sp_columns",
513            Some("SQL_STORED_PROCEDURE"),
514            &params,
515            &body,
516            None,
517        )
518        .unwrap();
519        assert_eq!(sql, "EXEC [sys].[sp_columns] @table_name = @P1");
520        assert!(!sql.contains("[table_name]"));
521    }
522
523    #[test]
524    fn build_statement_selects_from_a_function_with_positional_placeholders() {
525        let params = vec![Param {
526            name: "session_id".to_string(),
527            ordinal: 1,
528            x_sql_type: "smallint".to_string(),
529        }];
530        let mut body = Map::new();
531        body.insert("session_id".to_string(), Value::from(52));
532        let (sql, bound) = build_statement(
533            "sys",
534            "dm_exec_sql_text",
535            Some("SQL_INLINE_TABLE_VALUED_FUNCTION"),
536            &params,
537            &body,
538            Some("master"),
539        )
540        .unwrap();
541        assert_eq!(sql, "SELECT * FROM [master].[sys].[dm_exec_sql_text](@P1)");
542        assert_eq!(bound.len(), 1);
543    }
544
545    #[test]
546    fn build_statement_omits_the_database_qualifier_by_default() {
547        let (sql, bound) =
548            build_statement("dbo", "widgets", Some("VIEW"), &[], &Map::new(), None).unwrap();
549        assert_eq!(sql, "SELECT * FROM [dbo].[widgets]");
550        assert!(bound.is_empty());
551    }
552
553    #[test]
554    fn build_statement_three_part_qualifies_with_a_requested_execution_database() {
555        let (sql, bound) = build_statement(
556            "dbo",
557            "widgets",
558            Some("VIEW"),
559            &[],
560            &Map::new(),
561            Some("reporting"),
562        )
563        .unwrap();
564        assert_eq!(sql, "SELECT * FROM [reporting].[dbo].[widgets]");
565        assert!(bound.is_empty());
566    }
567
568    #[test]
569    fn build_statement_execs_a_parameterless_proc() {
570        let (sql, bound) = build_statement(
571            "sys",
572            "sp_who",
573            Some("SQL_STORED_PROCEDURE"),
574            &[],
575            &Map::new(),
576            None,
577        )
578        .unwrap();
579        assert_eq!(sql, "EXEC [sys].[sp_who]");
580        assert!(bound.is_empty());
581    }
582
583    #[test]
584    fn ordered_params_excludes_the_synthetic_execution_database_property() {
585        let schema = serde_json::json!({
586            "properties": {
587                "body": { "$ref": "#/$defs/sys_sp_who_Request" }
588            },
589            "$defs": {
590                "sys_sp_who_Request": {
591                    "properties": {
592                        "loginame": { "x-sql-ordinal": 1, "x-sql-type": "sysname" },
593                        "execution_database": { "type": "string" }
594                    }
595                }
596            }
597        });
598
599        let params = ordered_params(&schema);
600        assert_eq!(params.len(), 1);
601        assert_eq!(params[0].name, "loginame");
602    }
603
604    #[test]
605    fn resolve_execution_database_prefers_the_body_property_over_the_configured_default() {
606        let mut body = Map::new();
607        body.insert(
608            EXECUTION_DATABASE_PARAM.to_string(),
609            Value::String("reporting".to_string()),
610        );
611        let mut config = test_config();
612        config.default_database = Some("fallback".to_string());
613        assert_eq!(
614            resolve_execution_database(&body, &config)
615                .unwrap()
616                .as_deref(),
617            Some("reporting")
618        );
619    }
620
621    #[test]
622    fn resolve_execution_database_falls_back_to_the_configured_default() {
623        let mut config = test_config();
624        config.default_database = Some("fallback".to_string());
625        assert_eq!(
626            resolve_execution_database(&Map::new(), &config)
627                .unwrap()
628                .as_deref(),
629            Some("fallback")
630        );
631    }
632
633    #[test]
634    fn resolve_execution_database_is_none_when_nothing_is_configured_or_supplied() {
635        assert_eq!(
636            resolve_execution_database(&Map::new(), &test_config()).unwrap(),
637            None
638        );
639    }
640
641    #[test]
642    fn resolve_execution_database_rejects_a_non_string_body_value() {
643        let mut body = Map::new();
644        body.insert(EXECUTION_DATABASE_PARAM.to_string(), Value::from(42));
645        assert!(resolve_execution_database(&body, &test_config()).is_err());
646    }
647
648    #[test]
649    fn resolve_execution_database_rejects_an_unsafe_body_value() {
650        let mut body = Map::new();
651        body.insert(
652            EXECUTION_DATABASE_PARAM.to_string(),
653            Value::String("robert'; drop table endpoints;--".to_string()),
654        );
655        assert!(resolve_execution_database(&body, &test_config()).is_err());
656    }
657
658    #[test]
659    fn resolve_execution_database_rejects_an_unsafe_configured_default() {
660        let mut config = test_config();
661        config.default_database = Some("has space".to_string());
662        assert!(resolve_execution_database(&Map::new(), &config).is_err());
663    }
664
665    fn test_config() -> Config {
666        Config {
667            url: "localhost".to_string(),
668            auth_method: crate::core::config_schema::AuthMethod::SqlServer,
669            sql_port: 1433,
670            pool_max_size: 10,
671            trust_server_cert: true,
672            api_version: "2025".to_string(),
673            log_level: "info".to_string(),
674            rate_limit: 100,
675            timeout_ms: 30_000,
676            cache_size: 500,
677            retry_attempts: 3,
678            transport: crate::core::config_schema::Transport::Stdio,
679            host: "127.0.0.1".to_string(),
680            port: 3000,
681            cors_allow: None,
682            default_database: None,
683        }
684    }
685
686    #[test]
687    fn ordered_params_follow_the_schema_ordinals() {
688        // Matches the real shape every generated schema actually has (see
689        // `generated_schemas.json`): parameters live under `$defs`, `$ref`'d
690        // from the top-level `body` property, not as flat top-level
691        // properties.
692        let schema = serde_json::json!({
693            "properties": {
694                "body": { "$ref": "#/$defs/sys_example_Request" }
695            },
696            "$defs": {
697                "sys_example_Request": {
698                    "properties": {
699                        "second": { "x-sql-ordinal": 2, "x-sql-type": "int" },
700                        "first": { "x-sql-ordinal": 1, "x-sql-type": "nvarchar(20)" }
701                    }
702                }
703            }
704        });
705
706        let params = ordered_params(&schema);
707        assert_eq!(params.len(), 2);
708        assert_eq!(params[0].name, "first");
709        assert_eq!(params[0].x_sql_type, "nvarchar(20)");
710        assert_eq!(params[1].name, "second");
711    }
712
713    /// Regression test for incident 26-07-05700-04's underlying second bug:
714    /// `ordered_params` used to read the schema's literal top-level
715    /// `properties` map, which for every real generated schema is just
716    /// `{"body": {"$ref": ...}}` -- so every parameterized operation
717    /// collapsed to a single fake `body` parameter (observed live as
718    /// `EXEC ... @body = @P1` instead of the real named arguments) rather
719    /// than the operation's actual parameters.
720    #[test]
721    fn ordered_params_resolves_the_body_ref_wrapper() {
722        let schema = serde_json::json!({
723            "properties": {
724                "body": { "$ref": "#/$defs/sys_sp_columns_Request" }
725            },
726            "$defs": {
727                "sys_sp_columns_Request": {
728                    "properties": {
729                        "table_name": { "x-sql-ordinal": 1, "x-sql-type": "nvarchar(384)" },
730                        "table_owner": { "x-sql-ordinal": 2, "x-sql-type": "nvarchar(384)" }
731                    }
732                }
733            }
734        });
735
736        let params = ordered_params(&schema);
737        assert_eq!(params.len(), 2);
738        assert_eq!(params[0].name, "table_name");
739        assert_eq!(params[1].name, "table_owner");
740        assert!(params.iter().all(|p| p.name != "body"));
741    }
742
743    #[test]
744    fn ordered_params_resolves_an_inline_body_without_a_ref() {
745        let schema = serde_json::json!({
746            "properties": {
747                "body": {
748                    "properties": {
749                        "only": { "x-sql-ordinal": 1, "x-sql-type": "int" }
750                    }
751                }
752            }
753        });
754
755        let params = ordered_params(&schema);
756        assert_eq!(params.len(), 1);
757        assert_eq!(params[0].name, "only");
758    }
759
760    #[test]
761    fn ordered_params_is_empty_for_a_schema_with_no_body_property() {
762        let schema = serde_json::json!({ "properties": {} });
763        assert!(ordered_params(&schema).is_empty());
764    }
765
766    #[test]
767    fn build_statement_rejects_an_unsafe_parameter_name() {
768        let params = vec![Param {
769            name: "unsafe name".to_string(),
770            ordinal: 1,
771            x_sql_type: "int".to_string(),
772        }];
773
774        assert!(
775            build_statement(
776                "sys",
777                "sp_example",
778                Some("SQL_STORED_PROCEDURE"),
779                &params,
780                &Map::new(),
781                None,
782            )
783            .is_err()
784        );
785    }
786
787    #[test]
788    fn severity_category_maps_11_through_16_to_400_equivalent() {
789        for class in [11, 12, 13, 14 - 1, 15, 16] {
790            assert_eq!(severity_category(class), "statement/user error (400-equivalent)");
791        }
792    }
793
794    #[test]
795    fn severity_category_maps_14_to_403_equivalent() {
796        assert_eq!(severity_category(14), "permission denied (403-equivalent)");
797    }
798
799    #[test]
800    fn severity_category_maps_17_through_25_to_500_equivalent() {
801        for class in [17, 18, 20, 25] {
802            assert_eq!(severity_category(class), "fatal/resource error (500-equivalent)");
803        }
804    }
805
806    #[test]
807    fn severity_category_boundary_at_16_vs_17() {
808        assert_eq!(severity_category(16), "statement/user error (400-equivalent)");
809        assert_eq!(severity_category(17), "fatal/resource error (500-equivalent)");
810    }
811
812    #[test]
813    fn protocol_errors_are_classified_as_server_failures() {
814        let error =
815            classify_tiberius_error(tiberius::error::Error::Protocol("invalid packet".into()));
816        assert_eq!(
817            error.to_string(),
818            "SQL Server connection/protocol error (500-equivalent): Protocol error: invalid packet"
819        );
820    }
821}