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) = build_statement(
731 "dbo",
732 "widget_price",
733 Some(kind),
734 ¶ms,
735 &body,
736 None,
737 )
738 .unwrap();
739 assert_eq!(sql, "SELECT [dbo].[widget_price](@P1)");
740 assert_eq!(bound.len(), 1);
741 }
742 }
743
744 #[test]
745 fn build_statement_omits_the_database_qualifier_by_default() {
746 let (sql, bound) =
747 build_statement("dbo", "widgets", Some("VIEW"), &[], &Map::new(), None).unwrap();
748 assert_eq!(sql, "SELECT * FROM [dbo].[widgets]");
749 assert!(bound.is_empty());
750 }
751
752 #[test]
753 fn build_statement_three_part_qualifies_with_a_requested_execution_database() {
754 let (sql, bound) = build_statement(
755 "dbo",
756 "widgets",
757 Some("VIEW"),
758 &[],
759 &Map::new(),
760 Some("reporting"),
761 )
762 .unwrap();
763 assert_eq!(sql, "SELECT * FROM [reporting].[dbo].[widgets]");
764 assert!(bound.is_empty());
765 }
766
767 #[test]
768 fn build_statement_execs_a_parameterless_proc() {
769 let (sql, bound) = build_statement(
770 "sys",
771 "sp_who",
772 Some("SQL_STORED_PROCEDURE"),
773 &[],
774 &Map::new(),
775 None,
776 )
777 .unwrap();
778 assert_eq!(sql, "EXEC [sys].[sp_who]");
779 assert!(bound.is_empty());
780 }
781
782 #[test]
783 fn single_known_database_recovers_the_lone_database_from_the_generated_description() {
784 let schema = serde_json::json!({
785 "properties": {
786 "body": {
787 "properties": {
788 "execution_database": {
789 "description": "This object was found, identically, in: msdb. \
790 If omitted, the server's configured default \
791 database is used.",
792 }
793 }
794 }
795 }
796 });
797 assert_eq!(single_known_database(&schema).as_deref(), Some("msdb"));
798 }
799
800 #[test]
801 fn single_known_database_is_none_for_a_multi_database_operation() {
802 let schema = serde_json::json!({
803 "properties": {
804 "body": {
805 "properties": {
806 "execution_database": {
807 "description": "This object was found, identically, in: master, \
808 model, msdb. If omitted, ...",
809 }
810 }
811 }
812 }
813 });
814 assert_eq!(single_known_database(&schema), None);
815 }
816
817 #[test]
818 fn single_known_database_is_none_when_the_schema_has_no_execution_database_property() {
819 let schema = serde_json::json!({ "properties": { "body": { "properties": {} } } });
820 assert_eq!(single_known_database(&schema), None);
821 }
822
823 #[test]
824 fn ordered_params_excludes_the_synthetic_execution_database_property() {
825 let schema = serde_json::json!({
826 "properties": {
827 "body": { "$ref": "#/$defs/sys_sp_who_Request" }
828 },
829 "$defs": {
830 "sys_sp_who_Request": {
831 "properties": {
832 "loginame": { "x-sql-ordinal": 1, "x-sql-type": "sysname" },
833 "execution_database": { "type": "string" }
834 }
835 }
836 }
837 });
838
839 let params = ordered_params(&schema);
840 assert_eq!(params.len(), 1);
841 assert_eq!(params[0].name, "loginame");
842 }
843
844 fn schema_found_in(found_in: &[&str]) -> Value {
850 serde_json::json!({
851 "properties": {
852 "body": {
853 "properties": {
854 "execution_database": {
855 "type": "string",
856 "description": format!(
857 "Optional execution context: the database to run this \
858 operation against. This object was found, identically, in: \
859 {}. If omitted, the server's configured default database is \
860 used if one was set up (optional, see setup); otherwise the \
861 connection's own current database context applies.",
862 found_in.join(", "),
863 ),
864 }
865 }
866 }
867 }
868 })
869 }
870
871 fn no_execution_database_schema() -> Value {
872 serde_json::json!({ "properties": { "body": { "properties": {} } } })
873 }
874
875 #[test]
876 fn resolve_execution_database_prefers_the_body_property_over_everything_else() {
877 let mut body = Map::new();
878 body.insert(
879 EXECUTION_DATABASE_PARAM.to_string(),
880 Value::String("reporting".to_string()),
881 );
882 let mut config = test_config();
883 config.default_database = Some("fallback".to_string());
884 assert_eq!(
885 resolve_execution_database(&body, &schema_found_in(&["msdb"]), &config)
886 .unwrap()
887 .as_deref(),
888 Some("reporting")
889 );
890 }
891
892 #[test]
898 fn resolve_execution_database_prefers_the_operations_single_known_database_over_the_configured_default()
899 {
900 let mut config = test_config();
901 config.default_database = Some("master".to_string());
902 assert_eq!(
903 resolve_execution_database(&Map::new(), &schema_found_in(&["msdb"]), &config)
904 .unwrap()
905 .as_deref(),
906 Some("msdb")
907 );
908 }
909
910 #[test]
911 fn resolve_execution_database_does_not_guess_when_the_operation_is_multi_database() {
912 let mut config = test_config();
913 config.default_database = Some("fallback".to_string());
914 assert_eq!(
915 resolve_execution_database(
916 &Map::new(),
917 &schema_found_in(&["master", "model", "msdb"]),
918 &config,
919 )
920 .unwrap()
921 .as_deref(),
922 Some("fallback"),
923 );
924 }
925
926 #[test]
927 fn resolve_execution_database_falls_back_to_the_configured_default() {
928 let mut config = test_config();
929 config.default_database = Some("fallback".to_string());
930 assert_eq!(
931 resolve_execution_database(&Map::new(), &no_execution_database_schema(), &config)
932 .unwrap()
933 .as_deref(),
934 Some("fallback")
935 );
936 }
937
938 #[test]
939 fn resolve_execution_database_is_none_when_nothing_is_configured_or_supplied() {
940 assert_eq!(
941 resolve_execution_database(&Map::new(), &no_execution_database_schema(), &test_config())
942 .unwrap(),
943 None
944 );
945 }
946
947 #[test]
948 fn resolve_execution_database_rejects_a_non_string_body_value() {
949 let mut body = Map::new();
950 body.insert(EXECUTION_DATABASE_PARAM.to_string(), Value::from(42));
951 assert!(
952 resolve_execution_database(&body, &no_execution_database_schema(), &test_config())
953 .is_err()
954 );
955 }
956
957 #[test]
958 fn resolve_execution_database_rejects_an_unsafe_body_value() {
959 let mut body = Map::new();
960 body.insert(
961 EXECUTION_DATABASE_PARAM.to_string(),
962 Value::String("robert'; drop table endpoints;--".to_string()),
963 );
964 assert!(
965 resolve_execution_database(&body, &no_execution_database_schema(), &test_config())
966 .is_err()
967 );
968 }
969
970 #[test]
971 fn resolve_execution_database_rejects_an_unsafe_configured_default() {
972 let mut config = test_config();
973 config.default_database = Some("has space".to_string());
974 assert!(
975 resolve_execution_database(&Map::new(), &no_execution_database_schema(), &config)
976 .is_err()
977 );
978 }
979
980 fn test_config() -> Config {
981 Config {
982 url: "localhost".to_string(),
983 auth_method: crate::core::config_schema::AuthMethod::SqlServer,
984 sql_port: 1433,
985 pool_max_size: 10,
986 trust_server_cert: true,
987 api_version: "2025".to_string(),
988 log_level: "info".to_string(),
989 rate_limit: 100,
990 timeout_ms: 30_000,
991 cache_size: 500,
992 retry_attempts: 3,
993 transport: crate::core::config_schema::Transport::Stdio,
994 host: "127.0.0.1".to_string(),
995 port: 3000,
996 cors_allow: None,
997 default_database: None,
998 read_only: true,
999 }
1000 }
1001
1002 #[test]
1003 fn ordered_params_follow_the_schema_ordinals() {
1004 let schema = serde_json::json!({
1009 "properties": {
1010 "body": { "$ref": "#/$defs/sys_example_Request" }
1011 },
1012 "$defs": {
1013 "sys_example_Request": {
1014 "properties": {
1015 "second": { "x-sql-ordinal": 2, "x-sql-type": "int" },
1016 "first": { "x-sql-ordinal": 1, "x-sql-type": "nvarchar(20)" }
1017 }
1018 }
1019 }
1020 });
1021
1022 let params = ordered_params(&schema);
1023 assert_eq!(params.len(), 2);
1024 assert_eq!(params[0].name, "first");
1025 assert_eq!(params[0].x_sql_type, "nvarchar(20)");
1026 assert_eq!(params[1].name, "second");
1027 }
1028
1029 #[test]
1037 fn ordered_params_resolves_the_body_ref_wrapper() {
1038 let schema = serde_json::json!({
1039 "properties": {
1040 "body": { "$ref": "#/$defs/sys_sp_columns_Request" }
1041 },
1042 "$defs": {
1043 "sys_sp_columns_Request": {
1044 "properties": {
1045 "table_name": { "x-sql-ordinal": 1, "x-sql-type": "nvarchar(384)" },
1046 "table_owner": { "x-sql-ordinal": 2, "x-sql-type": "nvarchar(384)" }
1047 }
1048 }
1049 }
1050 });
1051
1052 let params = ordered_params(&schema);
1053 assert_eq!(params.len(), 2);
1054 assert_eq!(params[0].name, "table_name");
1055 assert_eq!(params[1].name, "table_owner");
1056 assert!(params.iter().all(|p| p.name != "body"));
1057 }
1058
1059 #[test]
1060 fn ordered_params_resolves_an_inline_body_without_a_ref() {
1061 let schema = serde_json::json!({
1062 "properties": {
1063 "body": {
1064 "properties": {
1065 "only": { "x-sql-ordinal": 1, "x-sql-type": "int" }
1066 }
1067 }
1068 }
1069 });
1070
1071 let params = ordered_params(&schema);
1072 assert_eq!(params.len(), 1);
1073 assert_eq!(params[0].name, "only");
1074 }
1075
1076 #[test]
1077 fn ordered_params_is_empty_for_a_schema_with_no_body_property() {
1078 let schema = serde_json::json!({ "properties": {} });
1079 assert!(ordered_params(&schema).is_empty());
1080 }
1081
1082 #[test]
1083 fn build_statement_rejects_an_unsafe_parameter_name() {
1084 let params = vec![Param {
1085 name: "unsafe name".to_string(),
1086 ordinal: 1,
1087 x_sql_type: "int".to_string(),
1088 }];
1089
1090 assert!(
1091 build_statement(
1092 "sys",
1093 "sp_example",
1094 Some("SQL_STORED_PROCEDURE"),
1095 ¶ms,
1096 &Map::new(),
1097 None,
1098 )
1099 .is_err()
1100 );
1101 }
1102
1103 #[test]
1104 fn severity_category_maps_11_through_16_to_400_equivalent() {
1105 for class in [11, 12, 13, 14 - 1, 15, 16] {
1106 assert_eq!(
1107 severity_category(class),
1108 "statement/user error (400-equivalent)"
1109 );
1110 }
1111 }
1112
1113 #[test]
1114 fn severity_category_maps_14_to_403_equivalent() {
1115 assert_eq!(severity_category(14), "permission denied (403-equivalent)");
1116 }
1117
1118 #[test]
1119 fn severity_category_maps_17_through_25_to_500_equivalent() {
1120 for class in [17, 18, 20, 25] {
1121 assert_eq!(
1122 severity_category(class),
1123 "fatal/resource error (500-equivalent)"
1124 );
1125 }
1126 }
1127
1128 #[test]
1129 fn severity_category_boundary_at_16_vs_17() {
1130 assert_eq!(
1131 severity_category(16),
1132 "statement/user error (400-equivalent)"
1133 );
1134 assert_eq!(
1135 severity_category(17),
1136 "fatal/resource error (500-equivalent)"
1137 );
1138 }
1139
1140 #[test]
1141 fn protocol_errors_are_classified_as_server_failures() {
1142 let error =
1143 classify_tiberius_error(tiberius::error::Error::Protocol("invalid packet".into()));
1144 assert_eq!(
1145 error.to_string(),
1146 "SQL Server connection/protocol error (500-equivalent): Protocol error: invalid packet"
1147 );
1148 }
1149}