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 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
124fn 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
144fn 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
171fn 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(¶m.name).cloned().unwrap_or(Value::Null);
225 bound.push(json_to_param(&value, ¶m.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 _ => {
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 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
268fn 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
287fn 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 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.description.as_deref().unwrap_or("object of unrecognized type"),
343 );
344 }
345
346 let (schema, name) = parse_path(&endpoint.path)?;
347
348 let (input_schema, _output_schema) =
349 resolved_schemas_for(&self.config.api_version, &endpoint.operation_id).ok_or_else(
350 || {
351 anyhow::anyhow!(
352 "no resolved schema found for operation '{}' under api_version '{}'",
353 endpoint.operation_id,
354 self.config.api_version
355 )
356 },
357 )?;
358 let params = ordered_params(input_schema);
359
360 let empty = Map::new();
361 let args_map = args.as_object().unwrap_or(&empty);
362 let body = args_map
363 .get("body")
364 .and_then(Value::as_object)
365 .cloned()
366 .unwrap_or_default();
367 let execution_database = resolve_execution_database(&body, &self.config)?;
368
369 let (sql, bound) = build_statement(
370 schema,
371 name,
372 endpoint.description.as_deref(),
373 ¶ms,
374 &body,
375 execution_database.as_deref(),
376 )?;
377
378 let auth_method = auth_manager.resolve_tds_auth().await?;
379
380 let (host, port) = self.config.host_and_port();
381 let mut tiberius_config = tiberius::Config::new();
382 tiberius_config.host(host);
383 tiberius_config.port(port);
384 tiberius_config.authentication(auth_method);
385 if self.config.trust_server_cert {
386 tiberius_config.trust_cert();
394 }
395
396 let pool_key = format!("{host}:{port}");
397 let pool =
398 sql_pool::cached_pool(&pool_key, tiberius_config, self.config.pool_max_size).await?;
399 let mut conn = pool.get().await.map_err(|err| {
400 anyhow::anyhow!("failed to obtain a pooled SQL Server connection: {err}")
401 })?;
402
403 let bound_refs: Vec<&dyn ToSql> = bound.iter().map(|param| param.as_ref()).collect();
404 let stream = conn
405 .query(&sql, &bound_refs)
406 .await
407 .map_err(classify_tiberius_error)?;
408 let rows = stream
409 .into_first_result()
410 .await
411 .map_err(classify_tiberius_error)?;
412
413 let json_rows: Vec<Value> = rows
414 .iter()
415 .map(|row| {
416 let mut obj = Map::new();
417 for (column, data) in row.cells() {
418 obj.insert(column.name().to_string(), column_data_to_json(data));
419 }
420 Value::Object(obj)
421 })
422 .collect();
423 Ok(Value::Array(json_rows))
424 }
425}
426
427#[cfg(test)]
428mod tests {
429 use super::*;
430
431 #[test]
432 fn is_writable_kind_treats_views_and_functions_as_read_only() {
433 assert!(!is_writable_kind(Some("VIEW")));
434 assert!(!is_writable_kind(Some("SQL_SCALAR_FUNCTION")));
435 assert!(!is_writable_kind(Some("SQL_INLINE_TABLE_VALUED_FUNCTION")));
436 assert!(!is_writable_kind(Some("SQL_TABLE_VALUED_FUNCTION")));
437 assert!(!is_writable_kind(Some("CLR_TABLE_VALUED_FUNCTION")));
438 }
439
440 #[test]
441 fn is_writable_kind_treats_procedures_and_unknown_kinds_as_writable() {
442 assert!(is_writable_kind(Some("SQL_STORED_PROCEDURE")));
443 assert!(is_writable_kind(Some("EXTENDED_STORED_PROCEDURE")));
444 assert!(is_writable_kind(Some("CLR_STORED_PROCEDURE")));
445 assert!(is_writable_kind(None), "an unrecognized kind must fail closed");
446 }
447
448 #[test]
449 fn parse_path_splits_schema_name() {
450 assert_eq!(
451 parse_path("/INFORMATION_SCHEMA/COLUMNS").unwrap(),
452 ("INFORMATION_SCHEMA", "COLUMNS")
453 );
454 }
455
456 #[test]
457 fn parse_path_rejects_a_path_with_too_few_segments() {
458 assert!(parse_path("/COLUMNS").is_err());
459 }
460
461 #[test]
462 fn quote_ident_doubles_embedded_closing_brackets() {
463 assert_eq!(quote_ident("weird]name"), "[weird]]name]");
464 }
465
466 #[test]
467 fn validate_ident_accepts_alphanumeric_and_underscore() {
468 assert!(validate_ident("sp_who2").is_ok());
469 assert!(validate_ident("INFORMATION_SCHEMA").is_ok());
470 }
471
472 #[test]
473 fn validate_ident_rejects_anything_else() {
474 assert!(validate_ident("").is_err());
475 assert!(validate_ident("robert'; drop table endpoints;--").is_err());
476 assert!(validate_ident("weird]name").is_err());
477 assert!(validate_ident("has space").is_err());
478 }
479
480 #[test]
481 fn parse_path_rejects_a_path_with_an_unsafe_segment() {
482 assert!(parse_path("/sys/sp_who; DROP TABLE endpoints--").is_err());
483 }
484
485 #[test]
486 fn build_statement_selects_from_a_view_with_no_parameters() {
487 let (sql, bound) = build_statement(
488 "INFORMATION_SCHEMA",
489 "COLUMNS",
490 Some("VIEW"),
491 &[],
492 &Map::new(),
493 None,
494 )
495 .unwrap();
496 assert_eq!(sql, "SELECT * FROM [INFORMATION_SCHEMA].[COLUMNS]");
497 assert!(bound.is_empty());
498 }
499
500 #[test]
501 fn build_statement_execs_a_proc_with_named_parameters() {
502 let params = vec![
503 Param {
504 name: "objname".to_string(),
505 ordinal: 1,
506 x_sql_type: "nvarchar(1035)".to_string(),
507 },
508 Param {
509 name: "newname".to_string(),
510 ordinal: 2,
511 x_sql_type: "sysname".to_string(),
512 },
513 ];
514 let mut body = Map::new();
515 body.insert("objname".to_string(), Value::String("t1".to_string()));
516 body.insert("newname".to_string(), Value::String("t2".to_string()));
517 let (sql, bound) = build_statement(
518 "sys",
519 "sp_rename",
520 Some("SQL_STORED_PROCEDURE"),
521 ¶ms,
522 &body,
523 Some("master"),
524 )
525 .unwrap();
526 assert_eq!(
527 sql,
528 "EXEC [master].[sys].[sp_rename] @objname = @P1, @newname = @P2"
529 );
530 assert_eq!(bound.len(), 2);
531 }
532
533 #[test]
544 fn build_statement_uses_at_prefixed_names_not_bracket_quoting_for_named_exec_arguments() {
545 let params = vec![Param {
546 name: "table_name".to_string(),
547 ordinal: 1,
548 x_sql_type: "nvarchar(384)".to_string(),
549 }];
550 let mut body = Map::new();
551 body.insert(
552 "table_name".to_string(),
553 Value::String("databases".to_string()),
554 );
555 let (sql, _bound) = build_statement(
556 "sys",
557 "sp_columns",
558 Some("SQL_STORED_PROCEDURE"),
559 ¶ms,
560 &body,
561 None,
562 )
563 .unwrap();
564 assert_eq!(sql, "EXEC [sys].[sp_columns] @table_name = @P1");
565 assert!(!sql.contains("[table_name]"));
566 }
567
568 #[test]
569 fn build_statement_selects_from_a_function_with_positional_placeholders() {
570 let params = vec![Param {
571 name: "session_id".to_string(),
572 ordinal: 1,
573 x_sql_type: "smallint".to_string(),
574 }];
575 let mut body = Map::new();
576 body.insert("session_id".to_string(), Value::from(52));
577 let (sql, bound) = build_statement(
578 "sys",
579 "dm_exec_sql_text",
580 Some("SQL_INLINE_TABLE_VALUED_FUNCTION"),
581 ¶ms,
582 &body,
583 Some("master"),
584 )
585 .unwrap();
586 assert_eq!(sql, "SELECT * FROM [master].[sys].[dm_exec_sql_text](@P1)");
587 assert_eq!(bound.len(), 1);
588 }
589
590 #[test]
591 fn build_statement_omits_the_database_qualifier_by_default() {
592 let (sql, bound) =
593 build_statement("dbo", "widgets", Some("VIEW"), &[], &Map::new(), None).unwrap();
594 assert_eq!(sql, "SELECT * FROM [dbo].[widgets]");
595 assert!(bound.is_empty());
596 }
597
598 #[test]
599 fn build_statement_three_part_qualifies_with_a_requested_execution_database() {
600 let (sql, bound) = build_statement(
601 "dbo",
602 "widgets",
603 Some("VIEW"),
604 &[],
605 &Map::new(),
606 Some("reporting"),
607 )
608 .unwrap();
609 assert_eq!(sql, "SELECT * FROM [reporting].[dbo].[widgets]");
610 assert!(bound.is_empty());
611 }
612
613 #[test]
614 fn build_statement_execs_a_parameterless_proc() {
615 let (sql, bound) = build_statement(
616 "sys",
617 "sp_who",
618 Some("SQL_STORED_PROCEDURE"),
619 &[],
620 &Map::new(),
621 None,
622 )
623 .unwrap();
624 assert_eq!(sql, "EXEC [sys].[sp_who]");
625 assert!(bound.is_empty());
626 }
627
628 #[test]
629 fn ordered_params_excludes_the_synthetic_execution_database_property() {
630 let schema = serde_json::json!({
631 "properties": {
632 "body": { "$ref": "#/$defs/sys_sp_who_Request" }
633 },
634 "$defs": {
635 "sys_sp_who_Request": {
636 "properties": {
637 "loginame": { "x-sql-ordinal": 1, "x-sql-type": "sysname" },
638 "execution_database": { "type": "string" }
639 }
640 }
641 }
642 });
643
644 let params = ordered_params(&schema);
645 assert_eq!(params.len(), 1);
646 assert_eq!(params[0].name, "loginame");
647 }
648
649 #[test]
650 fn resolve_execution_database_prefers_the_body_property_over_the_configured_default() {
651 let mut body = Map::new();
652 body.insert(
653 EXECUTION_DATABASE_PARAM.to_string(),
654 Value::String("reporting".to_string()),
655 );
656 let mut config = test_config();
657 config.default_database = Some("fallback".to_string());
658 assert_eq!(
659 resolve_execution_database(&body, &config)
660 .unwrap()
661 .as_deref(),
662 Some("reporting")
663 );
664 }
665
666 #[test]
667 fn resolve_execution_database_falls_back_to_the_configured_default() {
668 let mut config = test_config();
669 config.default_database = Some("fallback".to_string());
670 assert_eq!(
671 resolve_execution_database(&Map::new(), &config)
672 .unwrap()
673 .as_deref(),
674 Some("fallback")
675 );
676 }
677
678 #[test]
679 fn resolve_execution_database_is_none_when_nothing_is_configured_or_supplied() {
680 assert_eq!(
681 resolve_execution_database(&Map::new(), &test_config()).unwrap(),
682 None
683 );
684 }
685
686 #[test]
687 fn resolve_execution_database_rejects_a_non_string_body_value() {
688 let mut body = Map::new();
689 body.insert(EXECUTION_DATABASE_PARAM.to_string(), Value::from(42));
690 assert!(resolve_execution_database(&body, &test_config()).is_err());
691 }
692
693 #[test]
694 fn resolve_execution_database_rejects_an_unsafe_body_value() {
695 let mut body = Map::new();
696 body.insert(
697 EXECUTION_DATABASE_PARAM.to_string(),
698 Value::String("robert'; drop table endpoints;--".to_string()),
699 );
700 assert!(resolve_execution_database(&body, &test_config()).is_err());
701 }
702
703 #[test]
704 fn resolve_execution_database_rejects_an_unsafe_configured_default() {
705 let mut config = test_config();
706 config.default_database = Some("has space".to_string());
707 assert!(resolve_execution_database(&Map::new(), &config).is_err());
708 }
709
710 fn test_config() -> Config {
711 Config {
712 url: "localhost".to_string(),
713 auth_method: crate::core::config_schema::AuthMethod::SqlServer,
714 sql_port: 1433,
715 pool_max_size: 10,
716 trust_server_cert: true,
717 api_version: "2025".to_string(),
718 log_level: "info".to_string(),
719 rate_limit: 100,
720 timeout_ms: 30_000,
721 cache_size: 500,
722 retry_attempts: 3,
723 transport: crate::core::config_schema::Transport::Stdio,
724 host: "127.0.0.1".to_string(),
725 port: 3000,
726 cors_allow: None,
727 default_database: None,
728 read_only: true,
729 }
730 }
731
732 #[test]
733 fn ordered_params_follow_the_schema_ordinals() {
734 let schema = serde_json::json!({
739 "properties": {
740 "body": { "$ref": "#/$defs/sys_example_Request" }
741 },
742 "$defs": {
743 "sys_example_Request": {
744 "properties": {
745 "second": { "x-sql-ordinal": 2, "x-sql-type": "int" },
746 "first": { "x-sql-ordinal": 1, "x-sql-type": "nvarchar(20)" }
747 }
748 }
749 }
750 });
751
752 let params = ordered_params(&schema);
753 assert_eq!(params.len(), 2);
754 assert_eq!(params[0].name, "first");
755 assert_eq!(params[0].x_sql_type, "nvarchar(20)");
756 assert_eq!(params[1].name, "second");
757 }
758
759 #[test]
767 fn ordered_params_resolves_the_body_ref_wrapper() {
768 let schema = serde_json::json!({
769 "properties": {
770 "body": { "$ref": "#/$defs/sys_sp_columns_Request" }
771 },
772 "$defs": {
773 "sys_sp_columns_Request": {
774 "properties": {
775 "table_name": { "x-sql-ordinal": 1, "x-sql-type": "nvarchar(384)" },
776 "table_owner": { "x-sql-ordinal": 2, "x-sql-type": "nvarchar(384)" }
777 }
778 }
779 }
780 });
781
782 let params = ordered_params(&schema);
783 assert_eq!(params.len(), 2);
784 assert_eq!(params[0].name, "table_name");
785 assert_eq!(params[1].name, "table_owner");
786 assert!(params.iter().all(|p| p.name != "body"));
787 }
788
789 #[test]
790 fn ordered_params_resolves_an_inline_body_without_a_ref() {
791 let schema = serde_json::json!({
792 "properties": {
793 "body": {
794 "properties": {
795 "only": { "x-sql-ordinal": 1, "x-sql-type": "int" }
796 }
797 }
798 }
799 });
800
801 let params = ordered_params(&schema);
802 assert_eq!(params.len(), 1);
803 assert_eq!(params[0].name, "only");
804 }
805
806 #[test]
807 fn ordered_params_is_empty_for_a_schema_with_no_body_property() {
808 let schema = serde_json::json!({ "properties": {} });
809 assert!(ordered_params(&schema).is_empty());
810 }
811
812 #[test]
813 fn build_statement_rejects_an_unsafe_parameter_name() {
814 let params = vec![Param {
815 name: "unsafe name".to_string(),
816 ordinal: 1,
817 x_sql_type: "int".to_string(),
818 }];
819
820 assert!(
821 build_statement(
822 "sys",
823 "sp_example",
824 Some("SQL_STORED_PROCEDURE"),
825 ¶ms,
826 &Map::new(),
827 None,
828 )
829 .is_err()
830 );
831 }
832
833 #[test]
834 fn severity_category_maps_11_through_16_to_400_equivalent() {
835 for class in [11, 12, 13, 14 - 1, 15, 16] {
836 assert_eq!(severity_category(class), "statement/user error (400-equivalent)");
837 }
838 }
839
840 #[test]
841 fn severity_category_maps_14_to_403_equivalent() {
842 assert_eq!(severity_category(14), "permission denied (403-equivalent)");
843 }
844
845 #[test]
846 fn severity_category_maps_17_through_25_to_500_equivalent() {
847 for class in [17, 18, 20, 25] {
848 assert_eq!(severity_category(class), "fatal/resource error (500-equivalent)");
849 }
850 }
851
852 #[test]
853 fn severity_category_boundary_at_16_vs_17() {
854 assert_eq!(severity_category(16), "statement/user error (400-equivalent)");
855 assert_eq!(severity_category(17), "fatal/resource error (500-equivalent)");
856 }
857
858 #[test]
859 fn protocol_errors_are_classified_as_server_failures() {
860 let error =
861 classify_tiberius_error(tiberius::error::Error::Protocol("invalid packet".into()));
862 assert_eq!(
863 error.to_string(),
864 "SQL Server connection/protocol error (500-equivalent): Protocol error: invalid packet"
865 );
866 }
867}