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 build_statement(
185 schema: &str,
186 name: &str,
187 kind: Option<&str>,
188 params: &[Param],
189 body: &Map<String, Value>,
190 execution_database: Option<&str>,
191) -> anyhow::Result<(String, Vec<Box<dyn ToSql>>)> {
192 let qualified = match execution_database {
193 Some(db) => format!(
194 "{}.{}.{}",
195 quote_ident(db),
196 quote_ident(schema),
197 quote_ident(name)
198 ),
199 None => format!("{}.{}", quote_ident(schema), quote_ident(name)),
200 };
201
202 let mut bound: Vec<Box<dyn ToSql>> = Vec::with_capacity(params.len());
203 for param in params {
204 let value = body.get(¶m.name).cloned().unwrap_or(Value::Null);
205 bound.push(json_to_param(&value, ¶m.x_sql_type)?);
206 }
207
208 let sql = match kind {
209 Some("VIEW") => format!("SELECT * FROM {qualified}"),
210 Some(k) if k.ends_with("_FUNCTION") || k.contains("TABLE_VALUED_FUNCTION") => {
211 let placeholders = (1..=bound.len())
212 .map(|i| format!("@P{i}"))
213 .collect::<Vec<_>>()
214 .join(", ");
215 format!("SELECT * FROM {qualified}({placeholders})")
216 }
217 _ => {
224 if bound.is_empty() {
225 format!("EXEC {qualified}")
226 } else {
227 let mut assignments = Vec::with_capacity(params.len());
228 for (i, p) in params.iter().enumerate() {
229 assignments.push(format!("@{} = @P{}", validate_ident(&p.name)?, i + 1));
239 }
240 format!("EXEC {qualified} {}", assignments.join(", "))
241 }
242 }
243 };
244
245 Ok((sql, bound))
246}
247
248fn severity_category(class: u8) -> &'static str {
258 if class >= 17 {
259 "fatal/resource error (500-equivalent)"
260 } else if class == 14 {
261 "permission denied (403-equivalent)"
262 } else {
263 "statement/user error (400-equivalent)"
264 }
265}
266
267fn classify_tiberius_error(err: tiberius::error::Error) -> anyhow::Error {
277 use tiberius::error::Error as TError;
278 match &err {
279 TError::Server(token) => {
280 let (number, state, class, message, procedure, line) = (
281 token.code(),
282 token.state(),
283 token.class(),
284 token.message(),
285 token.procedure(),
286 token.line(),
287 );
288 let category = severity_category(class);
289 anyhow::anyhow!(
290 "SQL Server error {number} (severity {class}, state {state}) in '{procedure}' line {line}: {message} [{category}]"
291 )
292 }
293 other => anyhow::anyhow!("SQL Server connection/protocol error (500-equivalent): {other}"),
294 }
295}
296
297pub struct ApiClient {
298 config: Config,
299}
300
301impl ApiClient {
302 pub fn new(config: Config) -> Self {
303 Self { config }
304 }
305
306 pub async fn execute(
313 &self,
314 endpoint: &EndpointRecord,
315 args: &Value,
316 auth_manager: &mut AuthManager,
317 ) -> anyhow::Result<Value> {
318 let (schema, name) = parse_path(&endpoint.path)?;
319
320 let (input_schema, _output_schema) =
321 resolved_schemas_for(&self.config.api_version, &endpoint.operation_id).ok_or_else(
322 || {
323 anyhow::anyhow!(
324 "no resolved schema found for operation '{}' under api_version '{}'",
325 endpoint.operation_id,
326 self.config.api_version
327 )
328 },
329 )?;
330 let params = ordered_params(input_schema);
331
332 let empty = Map::new();
333 let args_map = args.as_object().unwrap_or(&empty);
334 let body = args_map
335 .get("body")
336 .and_then(Value::as_object)
337 .cloned()
338 .unwrap_or_default();
339 let execution_database = resolve_execution_database(&body, &self.config)?;
340
341 let (sql, bound) = build_statement(
342 schema,
343 name,
344 endpoint.description.as_deref(),
345 ¶ms,
346 &body,
347 execution_database.as_deref(),
348 )?;
349
350 let auth_method = auth_manager.resolve_tds_auth().await?;
351
352 let (host, port) = self.config.host_and_port();
353 let mut tiberius_config = tiberius::Config::new();
354 tiberius_config.host(host);
355 tiberius_config.port(port);
356 tiberius_config.authentication(auth_method);
357 if self.config.trust_server_cert {
358 tiberius_config.trust_cert();
366 }
367
368 let pool_key = format!("{host}:{port}");
369 let pool =
370 sql_pool::cached_pool(&pool_key, tiberius_config, self.config.pool_max_size).await?;
371 let mut conn = pool.get().await.map_err(|err| {
372 anyhow::anyhow!("failed to obtain a pooled SQL Server connection: {err}")
373 })?;
374
375 let bound_refs: Vec<&dyn ToSql> = bound.iter().map(|param| param.as_ref()).collect();
376 let stream = conn
377 .query(&sql, &bound_refs)
378 .await
379 .map_err(classify_tiberius_error)?;
380 let rows = stream
381 .into_first_result()
382 .await
383 .map_err(classify_tiberius_error)?;
384
385 let json_rows: Vec<Value> = rows
386 .iter()
387 .map(|row| {
388 let mut obj = Map::new();
389 for (column, data) in row.cells() {
390 obj.insert(column.name().to_string(), column_data_to_json(data));
391 }
392 Value::Object(obj)
393 })
394 .collect();
395 Ok(Value::Array(json_rows))
396 }
397}
398
399#[cfg(test)]
400mod tests {
401 use super::*;
402
403 #[test]
404 fn parse_path_splits_schema_name() {
405 assert_eq!(
406 parse_path("/INFORMATION_SCHEMA/COLUMNS").unwrap(),
407 ("INFORMATION_SCHEMA", "COLUMNS")
408 );
409 }
410
411 #[test]
412 fn parse_path_rejects_a_path_with_too_few_segments() {
413 assert!(parse_path("/COLUMNS").is_err());
414 }
415
416 #[test]
417 fn quote_ident_doubles_embedded_closing_brackets() {
418 assert_eq!(quote_ident("weird]name"), "[weird]]name]");
419 }
420
421 #[test]
422 fn validate_ident_accepts_alphanumeric_and_underscore() {
423 assert!(validate_ident("sp_who2").is_ok());
424 assert!(validate_ident("INFORMATION_SCHEMA").is_ok());
425 }
426
427 #[test]
428 fn validate_ident_rejects_anything_else() {
429 assert!(validate_ident("").is_err());
430 assert!(validate_ident("robert'; drop table endpoints;--").is_err());
431 assert!(validate_ident("weird]name").is_err());
432 assert!(validate_ident("has space").is_err());
433 }
434
435 #[test]
436 fn parse_path_rejects_a_path_with_an_unsafe_segment() {
437 assert!(parse_path("/sys/sp_who; DROP TABLE endpoints--").is_err());
438 }
439
440 #[test]
441 fn build_statement_selects_from_a_view_with_no_parameters() {
442 let (sql, bound) = build_statement(
443 "INFORMATION_SCHEMA",
444 "COLUMNS",
445 Some("VIEW"),
446 &[],
447 &Map::new(),
448 None,
449 )
450 .unwrap();
451 assert_eq!(sql, "SELECT * FROM [INFORMATION_SCHEMA].[COLUMNS]");
452 assert!(bound.is_empty());
453 }
454
455 #[test]
456 fn build_statement_execs_a_proc_with_named_parameters() {
457 let params = vec![
458 Param {
459 name: "objname".to_string(),
460 ordinal: 1,
461 x_sql_type: "nvarchar(1035)".to_string(),
462 },
463 Param {
464 name: "newname".to_string(),
465 ordinal: 2,
466 x_sql_type: "sysname".to_string(),
467 },
468 ];
469 let mut body = Map::new();
470 body.insert("objname".to_string(), Value::String("t1".to_string()));
471 body.insert("newname".to_string(), Value::String("t2".to_string()));
472 let (sql, bound) = build_statement(
473 "sys",
474 "sp_rename",
475 Some("SQL_STORED_PROCEDURE"),
476 ¶ms,
477 &body,
478 Some("master"),
479 )
480 .unwrap();
481 assert_eq!(
482 sql,
483 "EXEC [master].[sys].[sp_rename] @objname = @P1, @newname = @P2"
484 );
485 assert_eq!(bound.len(), 2);
486 }
487
488 #[test]
499 fn build_statement_uses_at_prefixed_names_not_bracket_quoting_for_named_exec_arguments() {
500 let params = vec![Param {
501 name: "table_name".to_string(),
502 ordinal: 1,
503 x_sql_type: "nvarchar(384)".to_string(),
504 }];
505 let mut body = Map::new();
506 body.insert(
507 "table_name".to_string(),
508 Value::String("databases".to_string()),
509 );
510 let (sql, _bound) = build_statement(
511 "sys",
512 "sp_columns",
513 Some("SQL_STORED_PROCEDURE"),
514 ¶ms,
515 &body,
516 None,
517 )
518 .unwrap();
519 assert_eq!(sql, "EXEC [sys].[sp_columns] @table_name = @P1");
520 assert!(!sql.contains("[table_name]"));
521 }
522
523 #[test]
524 fn build_statement_selects_from_a_function_with_positional_placeholders() {
525 let params = vec![Param {
526 name: "session_id".to_string(),
527 ordinal: 1,
528 x_sql_type: "smallint".to_string(),
529 }];
530 let mut body = Map::new();
531 body.insert("session_id".to_string(), Value::from(52));
532 let (sql, bound) = build_statement(
533 "sys",
534 "dm_exec_sql_text",
535 Some("SQL_INLINE_TABLE_VALUED_FUNCTION"),
536 ¶ms,
537 &body,
538 Some("master"),
539 )
540 .unwrap();
541 assert_eq!(sql, "SELECT * FROM [master].[sys].[dm_exec_sql_text](@P1)");
542 assert_eq!(bound.len(), 1);
543 }
544
545 #[test]
546 fn build_statement_omits_the_database_qualifier_by_default() {
547 let (sql, bound) =
548 build_statement("dbo", "widgets", Some("VIEW"), &[], &Map::new(), None).unwrap();
549 assert_eq!(sql, "SELECT * FROM [dbo].[widgets]");
550 assert!(bound.is_empty());
551 }
552
553 #[test]
554 fn build_statement_three_part_qualifies_with_a_requested_execution_database() {
555 let (sql, bound) = build_statement(
556 "dbo",
557 "widgets",
558 Some("VIEW"),
559 &[],
560 &Map::new(),
561 Some("reporting"),
562 )
563 .unwrap();
564 assert_eq!(sql, "SELECT * FROM [reporting].[dbo].[widgets]");
565 assert!(bound.is_empty());
566 }
567
568 #[test]
569 fn build_statement_execs_a_parameterless_proc() {
570 let (sql, bound) = build_statement(
571 "sys",
572 "sp_who",
573 Some("SQL_STORED_PROCEDURE"),
574 &[],
575 &Map::new(),
576 None,
577 )
578 .unwrap();
579 assert_eq!(sql, "EXEC [sys].[sp_who]");
580 assert!(bound.is_empty());
581 }
582
583 #[test]
584 fn ordered_params_excludes_the_synthetic_execution_database_property() {
585 let schema = serde_json::json!({
586 "properties": {
587 "body": { "$ref": "#/$defs/sys_sp_who_Request" }
588 },
589 "$defs": {
590 "sys_sp_who_Request": {
591 "properties": {
592 "loginame": { "x-sql-ordinal": 1, "x-sql-type": "sysname" },
593 "execution_database": { "type": "string" }
594 }
595 }
596 }
597 });
598
599 let params = ordered_params(&schema);
600 assert_eq!(params.len(), 1);
601 assert_eq!(params[0].name, "loginame");
602 }
603
604 #[test]
605 fn resolve_execution_database_prefers_the_body_property_over_the_configured_default() {
606 let mut body = Map::new();
607 body.insert(
608 EXECUTION_DATABASE_PARAM.to_string(),
609 Value::String("reporting".to_string()),
610 );
611 let mut config = test_config();
612 config.default_database = Some("fallback".to_string());
613 assert_eq!(
614 resolve_execution_database(&body, &config)
615 .unwrap()
616 .as_deref(),
617 Some("reporting")
618 );
619 }
620
621 #[test]
622 fn resolve_execution_database_falls_back_to_the_configured_default() {
623 let mut config = test_config();
624 config.default_database = Some("fallback".to_string());
625 assert_eq!(
626 resolve_execution_database(&Map::new(), &config)
627 .unwrap()
628 .as_deref(),
629 Some("fallback")
630 );
631 }
632
633 #[test]
634 fn resolve_execution_database_is_none_when_nothing_is_configured_or_supplied() {
635 assert_eq!(
636 resolve_execution_database(&Map::new(), &test_config()).unwrap(),
637 None
638 );
639 }
640
641 #[test]
642 fn resolve_execution_database_rejects_a_non_string_body_value() {
643 let mut body = Map::new();
644 body.insert(EXECUTION_DATABASE_PARAM.to_string(), Value::from(42));
645 assert!(resolve_execution_database(&body, &test_config()).is_err());
646 }
647
648 #[test]
649 fn resolve_execution_database_rejects_an_unsafe_body_value() {
650 let mut body = Map::new();
651 body.insert(
652 EXECUTION_DATABASE_PARAM.to_string(),
653 Value::String("robert'; drop table endpoints;--".to_string()),
654 );
655 assert!(resolve_execution_database(&body, &test_config()).is_err());
656 }
657
658 #[test]
659 fn resolve_execution_database_rejects_an_unsafe_configured_default() {
660 let mut config = test_config();
661 config.default_database = Some("has space".to_string());
662 assert!(resolve_execution_database(&Map::new(), &config).is_err());
663 }
664
665 fn test_config() -> Config {
666 Config {
667 url: "localhost".to_string(),
668 auth_method: crate::core::config_schema::AuthMethod::SqlServer,
669 sql_port: 1433,
670 pool_max_size: 10,
671 trust_server_cert: true,
672 api_version: "2025".to_string(),
673 log_level: "info".to_string(),
674 rate_limit: 100,
675 timeout_ms: 30_000,
676 cache_size: 500,
677 retry_attempts: 3,
678 transport: crate::core::config_schema::Transport::Stdio,
679 host: "127.0.0.1".to_string(),
680 port: 3000,
681 cors_allow: None,
682 default_database: None,
683 }
684 }
685
686 #[test]
687 fn ordered_params_follow_the_schema_ordinals() {
688 let schema = serde_json::json!({
693 "properties": {
694 "body": { "$ref": "#/$defs/sys_example_Request" }
695 },
696 "$defs": {
697 "sys_example_Request": {
698 "properties": {
699 "second": { "x-sql-ordinal": 2, "x-sql-type": "int" },
700 "first": { "x-sql-ordinal": 1, "x-sql-type": "nvarchar(20)" }
701 }
702 }
703 }
704 });
705
706 let params = ordered_params(&schema);
707 assert_eq!(params.len(), 2);
708 assert_eq!(params[0].name, "first");
709 assert_eq!(params[0].x_sql_type, "nvarchar(20)");
710 assert_eq!(params[1].name, "second");
711 }
712
713 #[test]
721 fn ordered_params_resolves_the_body_ref_wrapper() {
722 let schema = serde_json::json!({
723 "properties": {
724 "body": { "$ref": "#/$defs/sys_sp_columns_Request" }
725 },
726 "$defs": {
727 "sys_sp_columns_Request": {
728 "properties": {
729 "table_name": { "x-sql-ordinal": 1, "x-sql-type": "nvarchar(384)" },
730 "table_owner": { "x-sql-ordinal": 2, "x-sql-type": "nvarchar(384)" }
731 }
732 }
733 }
734 });
735
736 let params = ordered_params(&schema);
737 assert_eq!(params.len(), 2);
738 assert_eq!(params[0].name, "table_name");
739 assert_eq!(params[1].name, "table_owner");
740 assert!(params.iter().all(|p| p.name != "body"));
741 }
742
743 #[test]
744 fn ordered_params_resolves_an_inline_body_without_a_ref() {
745 let schema = serde_json::json!({
746 "properties": {
747 "body": {
748 "properties": {
749 "only": { "x-sql-ordinal": 1, "x-sql-type": "int" }
750 }
751 }
752 }
753 });
754
755 let params = ordered_params(&schema);
756 assert_eq!(params.len(), 1);
757 assert_eq!(params[0].name, "only");
758 }
759
760 #[test]
761 fn ordered_params_is_empty_for_a_schema_with_no_body_property() {
762 let schema = serde_json::json!({ "properties": {} });
763 assert!(ordered_params(&schema).is_empty());
764 }
765
766 #[test]
767 fn build_statement_rejects_an_unsafe_parameter_name() {
768 let params = vec![Param {
769 name: "unsafe name".to_string(),
770 ordinal: 1,
771 x_sql_type: "int".to_string(),
772 }];
773
774 assert!(
775 build_statement(
776 "sys",
777 "sp_example",
778 Some("SQL_STORED_PROCEDURE"),
779 ¶ms,
780 &Map::new(),
781 None,
782 )
783 .is_err()
784 );
785 }
786
787 #[test]
788 fn severity_category_maps_11_through_16_to_400_equivalent() {
789 for class in [11, 12, 13, 14 - 1, 15, 16] {
790 assert_eq!(severity_category(class), "statement/user error (400-equivalent)");
791 }
792 }
793
794 #[test]
795 fn severity_category_maps_14_to_403_equivalent() {
796 assert_eq!(severity_category(14), "permission denied (403-equivalent)");
797 }
798
799 #[test]
800 fn severity_category_maps_17_through_25_to_500_equivalent() {
801 for class in [17, 18, 20, 25] {
802 assert_eq!(severity_category(class), "fatal/resource error (500-equivalent)");
803 }
804 }
805
806 #[test]
807 fn severity_category_boundary_at_16_vs_17() {
808 assert_eq!(severity_category(16), "statement/user error (400-equivalent)");
809 assert_eq!(severity_category(17), "fatal/resource error (500-equivalent)");
810 }
811
812 #[test]
813 fn protocol_errors_are_classified_as_server_failures() {
814 let error =
815 classify_tiberius_error(tiberius::error::Error::Protocol("invalid packet".into()));
816 assert_eq!(
817 error.to_string(),
818 "SQL Server connection/protocol error (500-equivalent): Protocol error: invalid packet"
819 );
820 }
821}