1use 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
31const EXECUTION_DATABASE_PARAM: &str = "execution_database";
39
40fn 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
56fn 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
82fn quote_ident(ident: &str) -> String {
88 format!("[{}]", ident.replace(']', "]]"))
89}
90
91fn single_known_database(input_schema: &Value) -> Option<String> {
104 let description = request_properties(input_schema)?
105 .get(EXECUTION_DATABASE_PARAM)?
106 .get("description")?
107 .as_str()?;
108 let after_marker = description.split("found, identically, in: ").nth(1)?;
109 let database_list = after_marker.split(". ").next()?;
110 let mut databases = database_list.split(", ").map(str::trim);
111 let only = databases.next().filter(|s| !s.is_empty())?;
112 match databases.next() {
113 None => Some(only.to_string()),
114 Some(_) => None,
115 }
116}
117
118fn resolve_execution_database(
134 body: &Map<String, Value>,
135 input_schema: &Value,
136 config: &Config,
137) -> anyhow::Result<Option<String>> {
138 if let Some(value) = body.get(EXECUTION_DATABASE_PARAM) {
139 let requested = value
140 .as_str()
141 .ok_or_else(|| anyhow::anyhow!("'{EXECUTION_DATABASE_PARAM}' must be a string"))?;
142 return Ok(Some(validate_ident(requested)?.to_string()));
143 }
144 if let Some(database) = single_known_database(input_schema) {
145 return Ok(Some(validate_ident(&database)?.to_string()));
146 }
147 config
148 .default_database
149 .as_deref()
150 .map(validate_ident)
151 .transpose()
152 .map(|opt| opt.map(str::to_string))
153}
154
155struct Param {
156 name: String,
157 ordinal: u64,
158 x_sql_type: String,
159}
160
161fn request_properties(input_schema: &Value) -> Option<&Map<String, Value>> {
171 let body_schema = input_schema.get("properties")?.get("body")?;
172 let resolved = match body_schema.get("$ref").and_then(Value::as_str) {
173 Some(reference) => reference
174 .strip_prefix("#/$defs/")
175 .and_then(|name| input_schema.get("$defs")?.get(name))?,
176 None => body_schema,
177 };
178 resolved.get("properties").and_then(Value::as_object)
179}
180
181fn ordered_params(input_schema: &Value) -> Vec<Param> {
187 let mut params: Vec<Param> = request_properties(input_schema)
188 .into_iter()
189 .flatten()
190 .filter(|(name, _)| name.as_str() != EXECUTION_DATABASE_PARAM)
191 .map(|(name, schema)| Param {
192 name: name.clone(),
193 ordinal: schema
194 .get("x-sql-ordinal")
195 .and_then(Value::as_u64)
196 .unwrap_or(0),
197 x_sql_type: schema
198 .get("x-sql-type")
199 .and_then(Value::as_str)
200 .unwrap_or("nvarchar(max)")
201 .to_string(),
202 })
203 .collect();
204 params.sort_by_key(|p| p.ordinal);
205 params
206}
207
208fn is_writable_kind(kind: Option<&str>) -> bool {
234 let normalized = kind.map(|k| k.replace('_', " "));
248 match normalized.as_deref() {
249 Some("VIEW") => false,
250 Some(k) if k.ends_with(" FUNCTION") || k.contains("TABLE VALUED FUNCTION") => false,
251 _ => true,
252 }
253}
254
255fn build_statement(
256 schema: &str,
257 name: &str,
258 kind: Option<&str>,
259 params: &[Param],
260 body: &Map<String, Value>,
261 execution_database: Option<&str>,
262) -> anyhow::Result<(String, Vec<Box<dyn ToSql>>)> {
263 let qualified = match execution_database {
264 Some(db) => format!(
265 "{}.{}.{}",
266 quote_ident(db),
267 quote_ident(schema),
268 quote_ident(name)
269 ),
270 None => format!("{}.{}", quote_ident(schema), quote_ident(name)),
271 };
272
273 let mut bound: Vec<Box<dyn ToSql>> = Vec::with_capacity(params.len());
274 for param in params {
275 let value = body.get(¶m.name).cloned().unwrap_or(Value::Null);
276 bound.push(json_to_param(&value, ¶m.x_sql_type)?);
277 }
278
279 let normalized_kind = kind.map(|k| k.replace('_', " "));
284 let sql = match normalized_kind.as_deref() {
285 Some("VIEW") => format!("SELECT * FROM {qualified}"),
286 Some(k) if k.contains("TABLE VALUED FUNCTION") => {
290 let placeholders = (1..=bound.len())
291 .map(|i| format!("@P{i}"))
292 .collect::<Vec<_>>()
293 .join(", ");
294 format!("SELECT * FROM {qualified}({placeholders})")
295 }
296 Some(k) if k.ends_with(" FUNCTION") => {
301 let placeholders = (1..=bound.len())
302 .map(|i| format!("@P{i}"))
303 .collect::<Vec<_>>()
304 .join(", ");
305 format!("SELECT {qualified}({placeholders})")
306 }
307 _ => {
314 if bound.is_empty() {
315 format!("EXEC {qualified}")
316 } else {
317 let mut assignments = Vec::with_capacity(params.len());
318 for (i, p) in params.iter().enumerate() {
319 assignments.push(format!("@{} = @P{}", validate_ident(&p.name)?, i + 1));
329 }
330 format!("EXEC {qualified} {}", assignments.join(", "))
331 }
332 }
333 };
334
335 Ok((sql, bound))
336}
337
338fn severity_category(class: u8) -> &'static str {
348 if class >= 17 {
349 "fatal/resource error (500-equivalent)"
350 } else if class == 14 {
351 "permission denied (403-equivalent)"
352 } else {
353 "statement/user error (400-equivalent)"
354 }
355}
356
357fn classify_tiberius_error(err: tiberius::error::Error) -> anyhow::Error {
367 use tiberius::error::Error as TError;
368 match &err {
369 TError::Server(token) => {
370 let (number, state, class, message, procedure, line) = (
371 token.code(),
372 token.state(),
373 token.class(),
374 token.message(),
375 token.procedure(),
376 token.line(),
377 );
378 let category = severity_category(class);
379 anyhow::anyhow!(
380 "SQL Server error {number} (severity {class}, state {state}) in '{procedure}' line {line}: {message} [{category}]"
381 )
382 }
383 other => anyhow::anyhow!("SQL Server connection/protocol error (500-equivalent): {other}"),
384 }
385}
386
387pub struct ApiClient {
388 config: Config,
389}
390
391impl ApiClient {
392 pub fn new(config: Config) -> Self {
393 Self { config }
394 }
395
396 pub async fn execute(
403 &self,
404 endpoint: &EndpointRecord,
405 args: &Value,
406 auth_manager: &mut AuthManager,
407 ) -> anyhow::Result<Value> {
408 if self.config.read_only && is_writable_kind(endpoint.description.as_deref()) {
409 anyhow::bail!(
410 "operation '{}' is a {} and cannot run while read_only is enabled; set read_only to false to allow it",
411 endpoint.operation_id,
412 endpoint
413 .description
414 .as_deref()
415 .unwrap_or("object of unrecognized type"),
416 );
417 }
418
419 let (schema, name) = parse_path(&endpoint.path)?;
420
421 let (input_schema, _output_schema) =
422 resolved_schemas_for(&self.config.api_version, &endpoint.operation_id).ok_or_else(
423 || {
424 anyhow::anyhow!(
425 "no resolved schema found for operation '{}' under api_version '{}'",
426 endpoint.operation_id,
427 self.config.api_version
428 )
429 },
430 )?;
431 let params = ordered_params(input_schema);
432
433 let empty = Map::new();
434 let args_map = args.as_object().unwrap_or(&empty);
435 let body = args_map
436 .get("body")
437 .and_then(Value::as_object)
438 .cloned()
439 .unwrap_or_default();
440 let execution_database = resolve_execution_database(&body, input_schema, &self.config)?;
441
442 let (sql, bound) = build_statement(
443 schema,
444 name,
445 endpoint.description.as_deref(),
446 ¶ms,
447 &body,
448 execution_database.as_deref(),
449 )?;
450
451 let auth_method = auth_manager.resolve_tds_auth().await?;
452
453 let (host, port) = self.config.host_and_port();
454 let mut tiberius_config = tiberius::Config::new();
455 tiberius_config.host(host);
456 tiberius_config.port(port);
457 tiberius_config.authentication(auth_method);
458 if self.config.trust_server_cert {
459 tiberius_config.trust_cert();
467 }
468
469 let pool_key = format!("{host}:{port}");
470 let pool =
471 sql_pool::cached_pool(&pool_key, tiberius_config, self.config.pool_max_size).await?;
472 let mut conn = pool.get().await.map_err(|err| {
473 anyhow::anyhow!("failed to obtain a pooled SQL Server connection: {err}")
474 })?;
475
476 let bound_refs: Vec<&dyn ToSql> = bound.iter().map(|param| param.as_ref()).collect();
477 let stream = conn
478 .query(&sql, &bound_refs)
479 .await
480 .map_err(classify_tiberius_error)?;
481 let rows = stream
482 .into_first_result()
483 .await
484 .map_err(classify_tiberius_error)?;
485
486 let json_rows: Vec<Value> = rows
487 .iter()
488 .map(|row| {
489 let mut obj = Map::new();
490 for (column, data) in row.cells() {
491 obj.insert(column.name().to_string(), column_data_to_json(data));
492 }
493 Value::Object(obj)
494 })
495 .collect();
496 Ok(Value::Array(json_rows))
497 }
498}
499
500#[cfg(test)]
501mod tests {
502 use super::*;
503
504 #[test]
505 fn is_writable_kind_treats_views_and_functions_as_read_only() {
506 assert!(!is_writable_kind(Some("VIEW")));
507 assert!(!is_writable_kind(Some("SQL_SCALAR_FUNCTION")));
508 assert!(!is_writable_kind(Some("SQL_INLINE_TABLE_VALUED_FUNCTION")));
509 assert!(!is_writable_kind(Some("SQL_TABLE_VALUED_FUNCTION")));
510 assert!(!is_writable_kind(Some("CLR_TABLE_VALUED_FUNCTION")));
511 }
512
513 #[test]
522 fn is_writable_kind_treats_the_shipped_stores_space_separated_kinds_as_read_only() {
523 assert!(!is_writable_kind(Some("VIEW")));
524 assert!(!is_writable_kind(Some("SQL SCALAR FUNCTION")));
525 assert!(!is_writable_kind(Some("CLR SCALAR FUNCTION")));
526 assert!(!is_writable_kind(Some("SQL INLINE TABLE VALUED FUNCTION")));
527 assert!(!is_writable_kind(Some("SQL TABLE VALUED FUNCTION")));
528 }
529
530 #[test]
531 fn is_writable_kind_treats_procedures_and_unknown_kinds_as_writable() {
532 assert!(is_writable_kind(Some("SQL_STORED_PROCEDURE")));
533 assert!(is_writable_kind(Some("EXTENDED_STORED_PROCEDURE")));
534 assert!(is_writable_kind(Some("CLR_STORED_PROCEDURE")));
535 assert!(is_writable_kind(Some("SQL STORED PROCEDURE")));
536 assert!(is_writable_kind(Some("CLR STORED PROCEDURE")));
537 assert!(
538 is_writable_kind(None),
539 "an unrecognized kind must fail closed"
540 );
541 }
542
543 #[test]
544 fn parse_path_splits_schema_name() {
545 assert_eq!(
546 parse_path("/INFORMATION_SCHEMA/COLUMNS").unwrap(),
547 ("INFORMATION_SCHEMA", "COLUMNS")
548 );
549 }
550
551 #[test]
552 fn parse_path_rejects_a_path_with_too_few_segments() {
553 assert!(parse_path("/COLUMNS").is_err());
554 }
555
556 #[test]
557 fn quote_ident_doubles_embedded_closing_brackets() {
558 assert_eq!(quote_ident("weird]name"), "[weird]]name]");
559 }
560
561 #[test]
562 fn validate_ident_accepts_alphanumeric_and_underscore() {
563 assert!(validate_ident("sp_who2").is_ok());
564 assert!(validate_ident("INFORMATION_SCHEMA").is_ok());
565 }
566
567 #[test]
568 fn validate_ident_rejects_anything_else() {
569 assert!(validate_ident("").is_err());
570 assert!(validate_ident("robert'; drop table endpoints;--").is_err());
571 assert!(validate_ident("weird]name").is_err());
572 assert!(validate_ident("has space").is_err());
573 }
574
575 #[test]
576 fn parse_path_rejects_a_path_with_an_unsafe_segment() {
577 assert!(parse_path("/sys/sp_who; DROP TABLE endpoints--").is_err());
578 }
579
580 #[test]
581 fn build_statement_selects_from_a_view_with_no_parameters() {
582 let (sql, bound) = build_statement(
583 "INFORMATION_SCHEMA",
584 "COLUMNS",
585 Some("VIEW"),
586 &[],
587 &Map::new(),
588 None,
589 )
590 .unwrap();
591 assert_eq!(sql, "SELECT * FROM [INFORMATION_SCHEMA].[COLUMNS]");
592 assert!(bound.is_empty());
593 }
594
595 #[test]
596 fn build_statement_execs_a_proc_with_named_parameters() {
597 let params = vec![
598 Param {
599 name: "objname".to_string(),
600 ordinal: 1,
601 x_sql_type: "nvarchar(1035)".to_string(),
602 },
603 Param {
604 name: "newname".to_string(),
605 ordinal: 2,
606 x_sql_type: "sysname".to_string(),
607 },
608 ];
609 let mut body = Map::new();
610 body.insert("objname".to_string(), Value::String("t1".to_string()));
611 body.insert("newname".to_string(), Value::String("t2".to_string()));
612 let (sql, bound) = build_statement(
613 "sys",
614 "sp_rename",
615 Some("SQL_STORED_PROCEDURE"),
616 ¶ms,
617 &body,
618 Some("master"),
619 )
620 .unwrap();
621 assert_eq!(
622 sql,
623 "EXEC [master].[sys].[sp_rename] @objname = @P1, @newname = @P2"
624 );
625 assert_eq!(bound.len(), 2);
626 }
627
628 #[test]
639 fn build_statement_uses_at_prefixed_names_not_bracket_quoting_for_named_exec_arguments() {
640 let params = vec![Param {
641 name: "table_name".to_string(),
642 ordinal: 1,
643 x_sql_type: "nvarchar(384)".to_string(),
644 }];
645 let mut body = Map::new();
646 body.insert(
647 "table_name".to_string(),
648 Value::String("databases".to_string()),
649 );
650 let (sql, _bound) = build_statement(
651 "sys",
652 "sp_columns",
653 Some("SQL_STORED_PROCEDURE"),
654 ¶ms,
655 &body,
656 None,
657 )
658 .unwrap();
659 assert_eq!(sql, "EXEC [sys].[sp_columns] @table_name = @P1");
660 assert!(!sql.contains("[table_name]"));
661 }
662
663 #[test]
664 fn build_statement_selects_from_a_function_with_positional_placeholders() {
665 let params = vec![Param {
666 name: "session_id".to_string(),
667 ordinal: 1,
668 x_sql_type: "smallint".to_string(),
669 }];
670 let mut body = Map::new();
671 body.insert("session_id".to_string(), Value::from(52));
672 let (sql, bound) = build_statement(
673 "sys",
674 "dm_exec_sql_text",
675 Some("SQL_INLINE_TABLE_VALUED_FUNCTION"),
676 ¶ms,
677 &body,
678 Some("master"),
679 )
680 .unwrap();
681 assert_eq!(sql, "SELECT * FROM [master].[sys].[dm_exec_sql_text](@P1)");
682 assert_eq!(bound.len(), 1);
683 }
684
685 #[test]
692 fn build_statement_selects_from_a_function_with_the_shipped_stores_space_separated_kind() {
693 let params = vec![Param {
694 name: "session_id".to_string(),
695 ordinal: 1,
696 x_sql_type: "smallint".to_string(),
697 }];
698 let mut body = Map::new();
699 body.insert("session_id".to_string(), Value::from(52));
700 let (sql, bound) = build_statement(
701 "sys",
702 "dm_exec_sql_text",
703 Some("SQL TABLE VALUED FUNCTION"),
704 ¶ms,
705 &body,
706 None,
707 )
708 .unwrap();
709 assert_eq!(sql, "SELECT * FROM [sys].[dm_exec_sql_text](@P1)");
710 assert_eq!(bound.len(), 1);
711 }
712
713 #[test]
721 fn build_statement_calls_a_scalar_function_without_a_from_clause() {
722 let params = vec![Param {
723 name: "id".to_string(),
724 ordinal: 1,
725 x_sql_type: "int".to_string(),
726 }];
727 let mut body = Map::new();
728 body.insert("id".to_string(), Value::from(1));
729 for kind in ["SQL_SCALAR_FUNCTION", "SQL SCALAR FUNCTION"] {
730 let (sql, bound) =
731 build_statement("dbo", "widget_price", Some(kind), ¶ms, &body, None).unwrap();
732 assert_eq!(sql, "SELECT [dbo].[widget_price](@P1)");
733 assert_eq!(bound.len(), 1);
734 }
735 }
736
737 #[test]
738 fn build_statement_omits_the_database_qualifier_by_default() {
739 let (sql, bound) =
740 build_statement("dbo", "widgets", Some("VIEW"), &[], &Map::new(), None).unwrap();
741 assert_eq!(sql, "SELECT * FROM [dbo].[widgets]");
742 assert!(bound.is_empty());
743 }
744
745 #[test]
746 fn build_statement_three_part_qualifies_with_a_requested_execution_database() {
747 let (sql, bound) = build_statement(
748 "dbo",
749 "widgets",
750 Some("VIEW"),
751 &[],
752 &Map::new(),
753 Some("reporting"),
754 )
755 .unwrap();
756 assert_eq!(sql, "SELECT * FROM [reporting].[dbo].[widgets]");
757 assert!(bound.is_empty());
758 }
759
760 #[test]
761 fn build_statement_execs_a_parameterless_proc() {
762 let (sql, bound) = build_statement(
763 "sys",
764 "sp_who",
765 Some("SQL_STORED_PROCEDURE"),
766 &[],
767 &Map::new(),
768 None,
769 )
770 .unwrap();
771 assert_eq!(sql, "EXEC [sys].[sp_who]");
772 assert!(bound.is_empty());
773 }
774
775 #[test]
776 fn single_known_database_recovers_the_lone_database_from_the_generated_description() {
777 let schema = serde_json::json!({
778 "properties": {
779 "body": {
780 "properties": {
781 "execution_database": {
782 "description": "This object was found, identically, in: msdb. \
783 If omitted, the server's configured default \
784 database is used.",
785 }
786 }
787 }
788 }
789 });
790 assert_eq!(single_known_database(&schema).as_deref(), Some("msdb"));
791 }
792
793 #[test]
794 fn single_known_database_is_none_for_a_multi_database_operation() {
795 let schema = serde_json::json!({
796 "properties": {
797 "body": {
798 "properties": {
799 "execution_database": {
800 "description": "This object was found, identically, in: master, \
801 model, msdb. If omitted, ...",
802 }
803 }
804 }
805 }
806 });
807 assert_eq!(single_known_database(&schema), None);
808 }
809
810 #[test]
811 fn single_known_database_is_none_when_the_schema_has_no_execution_database_property() {
812 let schema = serde_json::json!({ "properties": { "body": { "properties": {} } } });
813 assert_eq!(single_known_database(&schema), None);
814 }
815
816 #[test]
817 fn ordered_params_excludes_the_synthetic_execution_database_property() {
818 let schema = serde_json::json!({
819 "properties": {
820 "body": { "$ref": "#/$defs/sys_sp_who_Request" }
821 },
822 "$defs": {
823 "sys_sp_who_Request": {
824 "properties": {
825 "loginame": { "x-sql-ordinal": 1, "x-sql-type": "sysname" },
826 "execution_database": { "type": "string" }
827 }
828 }
829 }
830 });
831
832 let params = ordered_params(&schema);
833 assert_eq!(params.len(), 1);
834 assert_eq!(params[0].name, "loginame");
835 }
836
837 fn schema_found_in(found_in: &[&str]) -> Value {
843 serde_json::json!({
844 "properties": {
845 "body": {
846 "properties": {
847 "execution_database": {
848 "type": "string",
849 "description": format!(
850 "Optional execution context: the database to run this \
851 operation against. This object was found, identically, in: \
852 {}. If omitted, the server's configured default database is \
853 used if one was set up (optional, see setup); otherwise the \
854 connection's own current database context applies.",
855 found_in.join(", "),
856 ),
857 }
858 }
859 }
860 }
861 })
862 }
863
864 fn no_execution_database_schema() -> Value {
865 serde_json::json!({ "properties": { "body": { "properties": {} } } })
866 }
867
868 #[test]
869 fn resolve_execution_database_prefers_the_body_property_over_everything_else() {
870 let mut body = Map::new();
871 body.insert(
872 EXECUTION_DATABASE_PARAM.to_string(),
873 Value::String("reporting".to_string()),
874 );
875 let mut config = test_config();
876 config.default_database = Some("fallback".to_string());
877 assert_eq!(
878 resolve_execution_database(&body, &schema_found_in(&["msdb"]), &config)
879 .unwrap()
880 .as_deref(),
881 Some("reporting")
882 );
883 }
884
885 #[test]
891 fn resolve_execution_database_prefers_the_operations_single_known_database_over_the_configured_default()
892 {
893 let mut config = test_config();
894 config.default_database = Some("master".to_string());
895 assert_eq!(
896 resolve_execution_database(&Map::new(), &schema_found_in(&["msdb"]), &config)
897 .unwrap()
898 .as_deref(),
899 Some("msdb")
900 );
901 }
902
903 #[test]
904 fn resolve_execution_database_does_not_guess_when_the_operation_is_multi_database() {
905 let mut config = test_config();
906 config.default_database = Some("fallback".to_string());
907 assert_eq!(
908 resolve_execution_database(
909 &Map::new(),
910 &schema_found_in(&["master", "model", "msdb"]),
911 &config,
912 )
913 .unwrap()
914 .as_deref(),
915 Some("fallback"),
916 );
917 }
918
919 #[test]
920 fn resolve_execution_database_falls_back_to_the_configured_default() {
921 let mut config = test_config();
922 config.default_database = Some("fallback".to_string());
923 assert_eq!(
924 resolve_execution_database(&Map::new(), &no_execution_database_schema(), &config)
925 .unwrap()
926 .as_deref(),
927 Some("fallback")
928 );
929 }
930
931 #[test]
932 fn resolve_execution_database_is_none_when_nothing_is_configured_or_supplied() {
933 assert_eq!(
934 resolve_execution_database(
935 &Map::new(),
936 &no_execution_database_schema(),
937 &test_config()
938 )
939 .unwrap(),
940 None
941 );
942 }
943
944 #[test]
945 fn resolve_execution_database_rejects_a_non_string_body_value() {
946 let mut body = Map::new();
947 body.insert(EXECUTION_DATABASE_PARAM.to_string(), Value::from(42));
948 assert!(
949 resolve_execution_database(&body, &no_execution_database_schema(), &test_config())
950 .is_err()
951 );
952 }
953
954 #[test]
955 fn resolve_execution_database_rejects_an_unsafe_body_value() {
956 let mut body = Map::new();
957 body.insert(
958 EXECUTION_DATABASE_PARAM.to_string(),
959 Value::String("robert'; drop table endpoints;--".to_string()),
960 );
961 assert!(
962 resolve_execution_database(&body, &no_execution_database_schema(), &test_config())
963 .is_err()
964 );
965 }
966
967 #[test]
968 fn resolve_execution_database_rejects_an_unsafe_configured_default() {
969 let mut config = test_config();
970 config.default_database = Some("has space".to_string());
971 assert!(
972 resolve_execution_database(&Map::new(), &no_execution_database_schema(), &config)
973 .is_err()
974 );
975 }
976
977 fn test_config() -> Config {
978 Config {
979 url: "localhost".to_string(),
980 auth_method: crate::core::config_schema::AuthMethod::SqlServer,
981 sql_port: 1433,
982 pool_max_size: 10,
983 trust_server_cert: true,
984 api_version: "2025".to_string(),
985 log_level: "info".to_string(),
986 rate_limit: 100,
987 timeout_ms: 30_000,
988 cache_size: 500,
989 retry_attempts: 3,
990 transport: crate::core::config_schema::Transport::Stdio,
991 host: "127.0.0.1".to_string(),
992 port: 3000,
993 cors_allow: None,
994 default_database: None,
995 read_only: true,
996 }
997 }
998
999 #[test]
1000 fn ordered_params_follow_the_schema_ordinals() {
1001 let schema = serde_json::json!({
1006 "properties": {
1007 "body": { "$ref": "#/$defs/sys_example_Request" }
1008 },
1009 "$defs": {
1010 "sys_example_Request": {
1011 "properties": {
1012 "second": { "x-sql-ordinal": 2, "x-sql-type": "int" },
1013 "first": { "x-sql-ordinal": 1, "x-sql-type": "nvarchar(20)" }
1014 }
1015 }
1016 }
1017 });
1018
1019 let params = ordered_params(&schema);
1020 assert_eq!(params.len(), 2);
1021 assert_eq!(params[0].name, "first");
1022 assert_eq!(params[0].x_sql_type, "nvarchar(20)");
1023 assert_eq!(params[1].name, "second");
1024 }
1025
1026 #[test]
1034 fn ordered_params_resolves_the_body_ref_wrapper() {
1035 let schema = serde_json::json!({
1036 "properties": {
1037 "body": { "$ref": "#/$defs/sys_sp_columns_Request" }
1038 },
1039 "$defs": {
1040 "sys_sp_columns_Request": {
1041 "properties": {
1042 "table_name": { "x-sql-ordinal": 1, "x-sql-type": "nvarchar(384)" },
1043 "table_owner": { "x-sql-ordinal": 2, "x-sql-type": "nvarchar(384)" }
1044 }
1045 }
1046 }
1047 });
1048
1049 let params = ordered_params(&schema);
1050 assert_eq!(params.len(), 2);
1051 assert_eq!(params[0].name, "table_name");
1052 assert_eq!(params[1].name, "table_owner");
1053 assert!(params.iter().all(|p| p.name != "body"));
1054 }
1055
1056 #[test]
1057 fn ordered_params_resolves_an_inline_body_without_a_ref() {
1058 let schema = serde_json::json!({
1059 "properties": {
1060 "body": {
1061 "properties": {
1062 "only": { "x-sql-ordinal": 1, "x-sql-type": "int" }
1063 }
1064 }
1065 }
1066 });
1067
1068 let params = ordered_params(&schema);
1069 assert_eq!(params.len(), 1);
1070 assert_eq!(params[0].name, "only");
1071 }
1072
1073 #[test]
1074 fn ordered_params_is_empty_for_a_schema_with_no_body_property() {
1075 let schema = serde_json::json!({ "properties": {} });
1076 assert!(ordered_params(&schema).is_empty());
1077 }
1078
1079 #[test]
1080 fn build_statement_rejects_an_unsafe_parameter_name() {
1081 let params = vec![Param {
1082 name: "unsafe name".to_string(),
1083 ordinal: 1,
1084 x_sql_type: "int".to_string(),
1085 }];
1086
1087 assert!(
1088 build_statement(
1089 "sys",
1090 "sp_example",
1091 Some("SQL_STORED_PROCEDURE"),
1092 ¶ms,
1093 &Map::new(),
1094 None,
1095 )
1096 .is_err()
1097 );
1098 }
1099
1100 #[test]
1101 fn severity_category_maps_11_through_16_to_400_equivalent() {
1102 for class in [11, 12, 13, 14 - 1, 15, 16] {
1103 assert_eq!(
1104 severity_category(class),
1105 "statement/user error (400-equivalent)"
1106 );
1107 }
1108 }
1109
1110 #[test]
1111 fn severity_category_maps_14_to_403_equivalent() {
1112 assert_eq!(severity_category(14), "permission denied (403-equivalent)");
1113 }
1114
1115 #[test]
1116 fn severity_category_maps_17_through_25_to_500_equivalent() {
1117 for class in [17, 18, 20, 25] {
1118 assert_eq!(
1119 severity_category(class),
1120 "fatal/resource error (500-equivalent)"
1121 );
1122 }
1123 }
1124
1125 #[test]
1126 fn severity_category_boundary_at_16_vs_17() {
1127 assert_eq!(
1128 severity_category(16),
1129 "statement/user error (400-equivalent)"
1130 );
1131 assert_eq!(
1132 severity_category(17),
1133 "fatal/resource error (500-equivalent)"
1134 );
1135 }
1136
1137 #[test]
1138 fn protocol_errors_are_classified_as_server_failures() {
1139 let error =
1140 classify_tiberius_error(tiberius::error::Error::Protocol("invalid packet".into()));
1141 assert_eq!(
1142 error.to_string(),
1143 "SQL Server connection/protocol error (500-equivalent): Protocol error: invalid packet"
1144 );
1145 }
1146}