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.
184/// Whether `kind` (an operation's catalog `sys.objects.type_desc`) can
185/// perform a write, mirroring `build_statement`'s own classification.
186/// `VIEW` and any `*_FUNCTION` kind cannot: a view is only ever queried
187/// with a bare `SELECT`, and T-SQL functions are language-level prohibited
188/// from having side effects (SQL Server rejects a `CREATE FUNCTION` body
189/// containing `INSERT`/`UPDATE`/`DELETE` outside a table variable), so
190/// both are genuinely engine-guaranteed read-only, not just app-level
191/// convention. Everything else -- `SQL_STORED_PROCEDURE`,
192/// `EXTENDED_STORED_PROCEDURE`, or a missing/unrecognized classification
193/// (an older store built before `description` carried this classification)
194/// -- has no such guarantee and is treated as write-capable, failing
195/// closed rather than assuming an unknown kind is safe.
196fn is_writable_kind(kind: Option<&str>) -> bool {
197    match kind {
198        Some("VIEW") => false,
199        Some(k) if k.ends_with("_FUNCTION") || k.contains("TABLE_VALUED_FUNCTION") => false,
200        _ => true,
201    }
202}
203
204fn build_statement(
205    schema: &str,
206    name: &str,
207    kind: Option<&str>,
208    params: &[Param],
209    body: &Map<String, Value>,
210    execution_database: Option<&str>,
211) -> anyhow::Result<(String, Vec<Box<dyn ToSql>>)> {
212    let qualified = match execution_database {
213        Some(db) => format!(
214            "{}.{}.{}",
215            quote_ident(db),
216            quote_ident(schema),
217            quote_ident(name)
218        ),
219        None => format!("{}.{}", quote_ident(schema), quote_ident(name)),
220    };
221
222    let mut bound: Vec<Box<dyn ToSql>> = Vec::with_capacity(params.len());
223    for param in params {
224        let value = body.get(&param.name).cloned().unwrap_or(Value::Null);
225        bound.push(json_to_param(&value, &param.x_sql_type)?);
226    }
227
228    let sql = match kind {
229        Some("VIEW") => format!("SELECT * FROM {qualified}"),
230        Some(k) if k.ends_with("_FUNCTION") || k.contains("TABLE_VALUED_FUNCTION") => {
231            let placeholders = (1..=bound.len())
232                .map(|i| format!("@P{i}"))
233                .collect::<Vec<_>>()
234                .join(", ");
235            format!("SELECT * FROM {qualified}({placeholders})")
236        }
237        // Stored procedures (SQL_STORED_PROCEDURE/EXTENDED_STORED_PROCEDURE)
238        // and the `kind.is_none()` fallback (an older store built before
239        // `description` carried this classification) both take the EXEC
240        // path -- named parameter syntax, so a proc with only optional
241        // parameters and no arguments supplied still works (`bound` empty
242        // produces a bare `EXEC name`).
243        _ => {
244            if bound.is_empty() {
245                format!("EXEC {qualified}")
246            } else {
247                let mut assignments = Vec::with_capacity(params.len());
248                for (i, p) in params.iter().enumerate() {
249                    // Named EXEC-argument syntax requires the `@` sigil
250                    // directly on the parameter name (`EXEC proc @param =
251                    // value`, not `EXEC proc [param] = value` or
252                    // `EXEC proc param = value`) -- bracket-quoting is for
253                    // object identifiers, not parameter references, and
254                    // using it here produced a syntax error on every
255                    // parameterized stored-procedure call. `validate_ident`
256                    // still runs first for the same defense-in-depth reason
257                    // as the object-identifier path above.
258                    assignments.push(format!("@{} = @P{}", validate_ident(&p.name)?, i + 1));
259                }
260                format!("EXEC {qualified} {}", assignments.join(", "))
261            }
262        }
263    };
264
265    Ok((sql, bound))
266}
267
268/// The severity-to-status-category mapping documented on every generated
269/// operation's 400/403/500 responses (see `docs/sqlserver-eda-openapi-pipeline
270/// /README.md`'s "OpenAPI mapping convention") -- pulled out of
271/// `classify_tiberius_error` as its own pure function so this classification
272/// logic is unit-testable directly. `tiberius::tds::codec::TokenError`'s
273/// fields are all `pub(crate)` with no public constructor, so a
274/// `tiberius::error::Error::Server(_)` can never be built from outside the
275/// crate for a test to exercise the branch that reads `class` off it --
276/// this function is what actually stays testable.
277fn severity_category(class: u8) -> &'static str {
278    if class >= 17 {
279        "fatal/resource error (500-equivalent)"
280    } else if class == 14 {
281        "permission denied (403-equivalent)"
282    } else {
283        "statement/user error (400-equivalent)"
284    }
285}
286
287/// Maps a `tiberius` error to this project's synthetic 400/403/500 split
288/// (see `docs/sqlserver-eda-openapi-pipeline/README.md`'s "OpenAPI mapping
289/// convention" -- SQL Server severity 11-16 statement errors are `400`,
290/// severity-14 permission errors are `403`, severity 17-25 engine/fatal
291/// errors are `500`), rather than surfacing the raw driver error
292/// undifferentiated. Returned as a JSON value matching
293/// `components.schemas.SqlServerError` shape rather than a bare string, so
294/// callers get the same structured error either way they might have gotten
295/// it from a real synchronous SQL Server error.
296fn classify_tiberius_error(err: tiberius::error::Error) -> anyhow::Error {
297    use tiberius::error::Error as TError;
298    match &err {
299        TError::Server(token) => {
300            let (number, state, class, message, procedure, line) = (
301                token.code(),
302                token.state(),
303                token.class(),
304                token.message(),
305                token.procedure(),
306                token.line(),
307            );
308            let category = severity_category(class);
309            anyhow::anyhow!(
310                "SQL Server error {number} (severity {class}, state {state}) in '{procedure}' line {line}: {message} [{category}]"
311            )
312        }
313        other => anyhow::anyhow!("SQL Server connection/protocol error (500-equivalent): {other}"),
314    }
315}
316
317pub struct ApiClient {
318    config: Config,
319}
320
321impl ApiClient {
322    pub fn new(config: Config) -> Self {
323        Self { config }
324    }
325
326    /// Executes `endpoint` against the configured SQL Server instance.
327    /// `auth_manager` resolves to a `tiberius::AuthMethod` (see
328    /// `auth::auth_manager::AuthManager::resolve_tds_auth`) from the
329    /// server's own configured credentials -- there is no per-request
330    /// credential override; SQL Server auth is always this server's own
331    /// configured identity, not something a caller supplies per call.
332    pub async fn execute(
333        &self,
334        endpoint: &EndpointRecord,
335        args: &Value,
336        auth_manager: &mut AuthManager,
337    ) -> anyhow::Result<Value> {
338        if self.config.read_only && is_writable_kind(endpoint.description.as_deref()) {
339            anyhow::bail!(
340                "operation '{}' is a {} and cannot run while read_only is enabled; set read_only to false to allow it",
341                endpoint.operation_id,
342                endpoint
343                    .description
344                    .as_deref()
345                    .unwrap_or("object of unrecognized type"),
346            );
347        }
348
349        let (schema, name) = parse_path(&endpoint.path)?;
350
351        let (input_schema, _output_schema) =
352            resolved_schemas_for(&self.config.api_version, &endpoint.operation_id).ok_or_else(
353                || {
354                    anyhow::anyhow!(
355                        "no resolved schema found for operation '{}' under api_version '{}'",
356                        endpoint.operation_id,
357                        self.config.api_version
358                    )
359                },
360            )?;
361        let params = ordered_params(input_schema);
362
363        let empty = Map::new();
364        let args_map = args.as_object().unwrap_or(&empty);
365        let body = args_map
366            .get("body")
367            .and_then(Value::as_object)
368            .cloned()
369            .unwrap_or_default();
370        let execution_database = resolve_execution_database(&body, &self.config)?;
371
372        let (sql, bound) = build_statement(
373            schema,
374            name,
375            endpoint.description.as_deref(),
376            &params,
377            &body,
378            execution_database.as_deref(),
379        )?;
380
381        let auth_method = auth_manager.resolve_tds_auth().await?;
382
383        let (host, port) = self.config.host_and_port();
384        let mut tiberius_config = tiberius::Config::new();
385        tiberius_config.host(host);
386        tiberius_config.port(port);
387        tiberius_config.authentication(auth_method);
388        if self.config.trust_server_cert {
389            // Curated system-catalog objects, not user data -- trusting the
390            // server cert matches this project's primary use case (a local
391            // Docker/dev instance with a self-signed cert; see
392            // docs/sqlserver-eda-openapi-pipeline/docker-compose.yml)
393            // rather than requiring every operator to supply a CA bundle
394            // before the first query works. Set `trust_server_cert: false`
395            // for a production instance with a real CA-signed cert.
396            tiberius_config.trust_cert();
397        }
398
399        let pool_key = format!("{host}:{port}");
400        let pool =
401            sql_pool::cached_pool(&pool_key, tiberius_config, self.config.pool_max_size).await?;
402        let mut conn = pool.get().await.map_err(|err| {
403            anyhow::anyhow!("failed to obtain a pooled SQL Server connection: {err}")
404        })?;
405
406        let bound_refs: Vec<&dyn ToSql> = bound.iter().map(|param| param.as_ref()).collect();
407        let stream = conn
408            .query(&sql, &bound_refs)
409            .await
410            .map_err(classify_tiberius_error)?;
411        let rows = stream
412            .into_first_result()
413            .await
414            .map_err(classify_tiberius_error)?;
415
416        let json_rows: Vec<Value> = rows
417            .iter()
418            .map(|row| {
419                let mut obj = Map::new();
420                for (column, data) in row.cells() {
421                    obj.insert(column.name().to_string(), column_data_to_json(data));
422                }
423                Value::Object(obj)
424            })
425            .collect();
426        Ok(Value::Array(json_rows))
427    }
428}
429
430#[cfg(test)]
431mod tests {
432    use super::*;
433
434    #[test]
435    fn is_writable_kind_treats_views_and_functions_as_read_only() {
436        assert!(!is_writable_kind(Some("VIEW")));
437        assert!(!is_writable_kind(Some("SQL_SCALAR_FUNCTION")));
438        assert!(!is_writable_kind(Some("SQL_INLINE_TABLE_VALUED_FUNCTION")));
439        assert!(!is_writable_kind(Some("SQL_TABLE_VALUED_FUNCTION")));
440        assert!(!is_writable_kind(Some("CLR_TABLE_VALUED_FUNCTION")));
441    }
442
443    #[test]
444    fn is_writable_kind_treats_procedures_and_unknown_kinds_as_writable() {
445        assert!(is_writable_kind(Some("SQL_STORED_PROCEDURE")));
446        assert!(is_writable_kind(Some("EXTENDED_STORED_PROCEDURE")));
447        assert!(is_writable_kind(Some("CLR_STORED_PROCEDURE")));
448        assert!(
449            is_writable_kind(None),
450            "an unrecognized kind must fail closed"
451        );
452    }
453
454    #[test]
455    fn parse_path_splits_schema_name() {
456        assert_eq!(
457            parse_path("/INFORMATION_SCHEMA/COLUMNS").unwrap(),
458            ("INFORMATION_SCHEMA", "COLUMNS")
459        );
460    }
461
462    #[test]
463    fn parse_path_rejects_a_path_with_too_few_segments() {
464        assert!(parse_path("/COLUMNS").is_err());
465    }
466
467    #[test]
468    fn quote_ident_doubles_embedded_closing_brackets() {
469        assert_eq!(quote_ident("weird]name"), "[weird]]name]");
470    }
471
472    #[test]
473    fn validate_ident_accepts_alphanumeric_and_underscore() {
474        assert!(validate_ident("sp_who2").is_ok());
475        assert!(validate_ident("INFORMATION_SCHEMA").is_ok());
476    }
477
478    #[test]
479    fn validate_ident_rejects_anything_else() {
480        assert!(validate_ident("").is_err());
481        assert!(validate_ident("robert'; drop table endpoints;--").is_err());
482        assert!(validate_ident("weird]name").is_err());
483        assert!(validate_ident("has space").is_err());
484    }
485
486    #[test]
487    fn parse_path_rejects_a_path_with_an_unsafe_segment() {
488        assert!(parse_path("/sys/sp_who; DROP TABLE endpoints--").is_err());
489    }
490
491    #[test]
492    fn build_statement_selects_from_a_view_with_no_parameters() {
493        let (sql, bound) = build_statement(
494            "INFORMATION_SCHEMA",
495            "COLUMNS",
496            Some("VIEW"),
497            &[],
498            &Map::new(),
499            None,
500        )
501        .unwrap();
502        assert_eq!(sql, "SELECT * FROM [INFORMATION_SCHEMA].[COLUMNS]");
503        assert!(bound.is_empty());
504    }
505
506    #[test]
507    fn build_statement_execs_a_proc_with_named_parameters() {
508        let params = vec![
509            Param {
510                name: "objname".to_string(),
511                ordinal: 1,
512                x_sql_type: "nvarchar(1035)".to_string(),
513            },
514            Param {
515                name: "newname".to_string(),
516                ordinal: 2,
517                x_sql_type: "sysname".to_string(),
518            },
519        ];
520        let mut body = Map::new();
521        body.insert("objname".to_string(), Value::String("t1".to_string()));
522        body.insert("newname".to_string(), Value::String("t2".to_string()));
523        let (sql, bound) = build_statement(
524            "sys",
525            "sp_rename",
526            Some("SQL_STORED_PROCEDURE"),
527            &params,
528            &body,
529            Some("master"),
530        )
531        .unwrap();
532        assert_eq!(
533            sql,
534            "EXEC [master].[sys].[sp_rename] @objname = @P1, @newname = @P2"
535        );
536        assert_eq!(bound.len(), 2);
537    }
538
539    /// Regression test for incident 26-07-05700-04: every parameterized
540    /// stored-procedure `call` (e.g. `sp_columns`, `sp_executesql`) failed
541    /// with SQL Server error 102 "Incorrect syntax near '='", no matter
542    /// what argument keys the caller supplied, because the generated
543    /// assignment list bracket-quoted the parameter name (`[table_name] =
544    /// @P1`) instead of prefixing it with `@` (`@table_name = @P1`) --
545    /// bracket-quoting is valid for object identifiers, not for named
546    /// EXEC arguments. This asserts the `@`-prefixed form specifically, so
547    /// a future edit can't silently reintroduce bracket-quoting here even
548    /// if it still happens to produce syntactically-plausible-looking SQL.
549    #[test]
550    fn build_statement_uses_at_prefixed_names_not_bracket_quoting_for_named_exec_arguments() {
551        let params = vec![Param {
552            name: "table_name".to_string(),
553            ordinal: 1,
554            x_sql_type: "nvarchar(384)".to_string(),
555        }];
556        let mut body = Map::new();
557        body.insert(
558            "table_name".to_string(),
559            Value::String("databases".to_string()),
560        );
561        let (sql, _bound) = build_statement(
562            "sys",
563            "sp_columns",
564            Some("SQL_STORED_PROCEDURE"),
565            &params,
566            &body,
567            None,
568        )
569        .unwrap();
570        assert_eq!(sql, "EXEC [sys].[sp_columns] @table_name = @P1");
571        assert!(!sql.contains("[table_name]"));
572    }
573
574    #[test]
575    fn build_statement_selects_from_a_function_with_positional_placeholders() {
576        let params = vec![Param {
577            name: "session_id".to_string(),
578            ordinal: 1,
579            x_sql_type: "smallint".to_string(),
580        }];
581        let mut body = Map::new();
582        body.insert("session_id".to_string(), Value::from(52));
583        let (sql, bound) = build_statement(
584            "sys",
585            "dm_exec_sql_text",
586            Some("SQL_INLINE_TABLE_VALUED_FUNCTION"),
587            &params,
588            &body,
589            Some("master"),
590        )
591        .unwrap();
592        assert_eq!(sql, "SELECT * FROM [master].[sys].[dm_exec_sql_text](@P1)");
593        assert_eq!(bound.len(), 1);
594    }
595
596    #[test]
597    fn build_statement_omits_the_database_qualifier_by_default() {
598        let (sql, bound) =
599            build_statement("dbo", "widgets", Some("VIEW"), &[], &Map::new(), None).unwrap();
600        assert_eq!(sql, "SELECT * FROM [dbo].[widgets]");
601        assert!(bound.is_empty());
602    }
603
604    #[test]
605    fn build_statement_three_part_qualifies_with_a_requested_execution_database() {
606        let (sql, bound) = build_statement(
607            "dbo",
608            "widgets",
609            Some("VIEW"),
610            &[],
611            &Map::new(),
612            Some("reporting"),
613        )
614        .unwrap();
615        assert_eq!(sql, "SELECT * FROM [reporting].[dbo].[widgets]");
616        assert!(bound.is_empty());
617    }
618
619    #[test]
620    fn build_statement_execs_a_parameterless_proc() {
621        let (sql, bound) = build_statement(
622            "sys",
623            "sp_who",
624            Some("SQL_STORED_PROCEDURE"),
625            &[],
626            &Map::new(),
627            None,
628        )
629        .unwrap();
630        assert_eq!(sql, "EXEC [sys].[sp_who]");
631        assert!(bound.is_empty());
632    }
633
634    #[test]
635    fn ordered_params_excludes_the_synthetic_execution_database_property() {
636        let schema = serde_json::json!({
637            "properties": {
638                "body": { "$ref": "#/$defs/sys_sp_who_Request" }
639            },
640            "$defs": {
641                "sys_sp_who_Request": {
642                    "properties": {
643                        "loginame": { "x-sql-ordinal": 1, "x-sql-type": "sysname" },
644                        "execution_database": { "type": "string" }
645                    }
646                }
647            }
648        });
649
650        let params = ordered_params(&schema);
651        assert_eq!(params.len(), 1);
652        assert_eq!(params[0].name, "loginame");
653    }
654
655    #[test]
656    fn resolve_execution_database_prefers_the_body_property_over_the_configured_default() {
657        let mut body = Map::new();
658        body.insert(
659            EXECUTION_DATABASE_PARAM.to_string(),
660            Value::String("reporting".to_string()),
661        );
662        let mut config = test_config();
663        config.default_database = Some("fallback".to_string());
664        assert_eq!(
665            resolve_execution_database(&body, &config)
666                .unwrap()
667                .as_deref(),
668            Some("reporting")
669        );
670    }
671
672    #[test]
673    fn resolve_execution_database_falls_back_to_the_configured_default() {
674        let mut config = test_config();
675        config.default_database = Some("fallback".to_string());
676        assert_eq!(
677            resolve_execution_database(&Map::new(), &config)
678                .unwrap()
679                .as_deref(),
680            Some("fallback")
681        );
682    }
683
684    #[test]
685    fn resolve_execution_database_is_none_when_nothing_is_configured_or_supplied() {
686        assert_eq!(
687            resolve_execution_database(&Map::new(), &test_config()).unwrap(),
688            None
689        );
690    }
691
692    #[test]
693    fn resolve_execution_database_rejects_a_non_string_body_value() {
694        let mut body = Map::new();
695        body.insert(EXECUTION_DATABASE_PARAM.to_string(), Value::from(42));
696        assert!(resolve_execution_database(&body, &test_config()).is_err());
697    }
698
699    #[test]
700    fn resolve_execution_database_rejects_an_unsafe_body_value() {
701        let mut body = Map::new();
702        body.insert(
703            EXECUTION_DATABASE_PARAM.to_string(),
704            Value::String("robert'; drop table endpoints;--".to_string()),
705        );
706        assert!(resolve_execution_database(&body, &test_config()).is_err());
707    }
708
709    #[test]
710    fn resolve_execution_database_rejects_an_unsafe_configured_default() {
711        let mut config = test_config();
712        config.default_database = Some("has space".to_string());
713        assert!(resolve_execution_database(&Map::new(), &config).is_err());
714    }
715
716    fn test_config() -> Config {
717        Config {
718            url: "localhost".to_string(),
719            auth_method: crate::core::config_schema::AuthMethod::SqlServer,
720            sql_port: 1433,
721            pool_max_size: 10,
722            trust_server_cert: true,
723            api_version: "2025".to_string(),
724            log_level: "info".to_string(),
725            rate_limit: 100,
726            timeout_ms: 30_000,
727            cache_size: 500,
728            retry_attempts: 3,
729            transport: crate::core::config_schema::Transport::Stdio,
730            host: "127.0.0.1".to_string(),
731            port: 3000,
732            cors_allow: None,
733            default_database: None,
734            read_only: true,
735        }
736    }
737
738    #[test]
739    fn ordered_params_follow_the_schema_ordinals() {
740        // Matches the real shape every generated schema actually has (see
741        // `generated_schemas.json`): parameters live under `$defs`, `$ref`'d
742        // from the top-level `body` property, not as flat top-level
743        // properties.
744        let schema = serde_json::json!({
745            "properties": {
746                "body": { "$ref": "#/$defs/sys_example_Request" }
747            },
748            "$defs": {
749                "sys_example_Request": {
750                    "properties": {
751                        "second": { "x-sql-ordinal": 2, "x-sql-type": "int" },
752                        "first": { "x-sql-ordinal": 1, "x-sql-type": "nvarchar(20)" }
753                    }
754                }
755            }
756        });
757
758        let params = ordered_params(&schema);
759        assert_eq!(params.len(), 2);
760        assert_eq!(params[0].name, "first");
761        assert_eq!(params[0].x_sql_type, "nvarchar(20)");
762        assert_eq!(params[1].name, "second");
763    }
764
765    /// Regression test for incident 26-07-05700-04's underlying second bug:
766    /// `ordered_params` used to read the schema's literal top-level
767    /// `properties` map, which for every real generated schema is just
768    /// `{"body": {"$ref": ...}}` -- so every parameterized operation
769    /// collapsed to a single fake `body` parameter (observed live as
770    /// `EXEC ... @body = @P1` instead of the real named arguments) rather
771    /// than the operation's actual parameters.
772    #[test]
773    fn ordered_params_resolves_the_body_ref_wrapper() {
774        let schema = serde_json::json!({
775            "properties": {
776                "body": { "$ref": "#/$defs/sys_sp_columns_Request" }
777            },
778            "$defs": {
779                "sys_sp_columns_Request": {
780                    "properties": {
781                        "table_name": { "x-sql-ordinal": 1, "x-sql-type": "nvarchar(384)" },
782                        "table_owner": { "x-sql-ordinal": 2, "x-sql-type": "nvarchar(384)" }
783                    }
784                }
785            }
786        });
787
788        let params = ordered_params(&schema);
789        assert_eq!(params.len(), 2);
790        assert_eq!(params[0].name, "table_name");
791        assert_eq!(params[1].name, "table_owner");
792        assert!(params.iter().all(|p| p.name != "body"));
793    }
794
795    #[test]
796    fn ordered_params_resolves_an_inline_body_without_a_ref() {
797        let schema = serde_json::json!({
798            "properties": {
799                "body": {
800                    "properties": {
801                        "only": { "x-sql-ordinal": 1, "x-sql-type": "int" }
802                    }
803                }
804            }
805        });
806
807        let params = ordered_params(&schema);
808        assert_eq!(params.len(), 1);
809        assert_eq!(params[0].name, "only");
810    }
811
812    #[test]
813    fn ordered_params_is_empty_for_a_schema_with_no_body_property() {
814        let schema = serde_json::json!({ "properties": {} });
815        assert!(ordered_params(&schema).is_empty());
816    }
817
818    #[test]
819    fn build_statement_rejects_an_unsafe_parameter_name() {
820        let params = vec![Param {
821            name: "unsafe name".to_string(),
822            ordinal: 1,
823            x_sql_type: "int".to_string(),
824        }];
825
826        assert!(
827            build_statement(
828                "sys",
829                "sp_example",
830                Some("SQL_STORED_PROCEDURE"),
831                &params,
832                &Map::new(),
833                None,
834            )
835            .is_err()
836        );
837    }
838
839    #[test]
840    fn severity_category_maps_11_through_16_to_400_equivalent() {
841        for class in [11, 12, 13, 14 - 1, 15, 16] {
842            assert_eq!(
843                severity_category(class),
844                "statement/user error (400-equivalent)"
845            );
846        }
847    }
848
849    #[test]
850    fn severity_category_maps_14_to_403_equivalent() {
851        assert_eq!(severity_category(14), "permission denied (403-equivalent)");
852    }
853
854    #[test]
855    fn severity_category_maps_17_through_25_to_500_equivalent() {
856        for class in [17, 18, 20, 25] {
857            assert_eq!(
858                severity_category(class),
859                "fatal/resource error (500-equivalent)"
860            );
861        }
862    }
863
864    #[test]
865    fn severity_category_boundary_at_16_vs_17() {
866        assert_eq!(
867            severity_category(16),
868            "statement/user error (400-equivalent)"
869        );
870        assert_eq!(
871            severity_category(17),
872            "fatal/resource error (500-equivalent)"
873        );
874    }
875
876    #[test]
877    fn protocol_errors_are_classified_as_server_failures() {
878        let error =
879            classify_tiberius_error(tiberius::error::Error::Protocol("invalid packet".into()));
880        assert_eq!(
881            error.to_string(),
882            "SQL Server connection/protocol error (500-equivalent): Protocol error: invalid packet"
883        );
884    }
885}