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
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 ¶ms,
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 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 ¶ms,
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 #[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 ¶ms,
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 ¶ms,
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 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 #[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 ¶ms,
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}