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 classify_tiberius_error(err: tiberius::error::Error) -> anyhow::Error {
258 use tiberius::error::Error as TError;
259 match &err {
260 TError::Server(token) => {
261 let (number, state, class, message, procedure, line) = (
262 token.code(),
263 token.state(),
264 token.class(),
265 token.message(),
266 token.procedure(),
267 token.line(),
268 );
269 let category = if class >= 17 {
270 "fatal/resource error (500-equivalent)"
271 } else if class == 14 {
272 "permission denied (403-equivalent)"
273 } else {
274 "statement/user error (400-equivalent)"
275 };
276 anyhow::anyhow!(
277 "SQL Server error {number} (severity {class}, state {state}) in '{procedure}' line {line}: {message} [{category}]"
278 )
279 }
280 other => anyhow::anyhow!("SQL Server connection/protocol error (500-equivalent): {other}"),
281 }
282}
283
284pub struct ApiClient {
285 config: Config,
286}
287
288impl ApiClient {
289 pub fn new(config: Config) -> Self {
290 Self { config }
291 }
292
293 pub async fn execute(
300 &self,
301 endpoint: &EndpointRecord,
302 args: &Value,
303 auth_manager: &mut AuthManager,
304 ) -> anyhow::Result<Value> {
305 let (schema, name) = parse_path(&endpoint.path)?;
306
307 let (input_schema, _output_schema) =
308 resolved_schemas_for(&self.config.api_version, &endpoint.operation_id).ok_or_else(
309 || {
310 anyhow::anyhow!(
311 "no resolved schema found for operation '{}' under api_version '{}'",
312 endpoint.operation_id,
313 self.config.api_version
314 )
315 },
316 )?;
317 let params = ordered_params(input_schema);
318
319 let empty = Map::new();
320 let args_map = args.as_object().unwrap_or(&empty);
321 let body = args_map
322 .get("body")
323 .and_then(Value::as_object)
324 .cloned()
325 .unwrap_or_default();
326 let execution_database = resolve_execution_database(&body, &self.config)?;
327
328 let (sql, bound) = build_statement(
329 schema,
330 name,
331 endpoint.description.as_deref(),
332 ¶ms,
333 &body,
334 execution_database.as_deref(),
335 )?;
336
337 let auth_method = auth_manager.resolve_tds_auth().await?;
338
339 let (host, port) = self.config.host_and_port();
340 let mut tiberius_config = tiberius::Config::new();
341 tiberius_config.host(host);
342 tiberius_config.port(port);
343 tiberius_config.authentication(auth_method);
344 if self.config.trust_server_cert {
345 tiberius_config.trust_cert();
353 }
354
355 let pool_key = format!("{host}:{port}");
356 let pool =
357 sql_pool::cached_pool(&pool_key, tiberius_config, self.config.pool_max_size).await?;
358 let mut conn = pool.get().await.map_err(|err| {
359 anyhow::anyhow!("failed to obtain a pooled SQL Server connection: {err}")
360 })?;
361
362 let bound_refs: Vec<&dyn ToSql> = bound.iter().map(|param| param.as_ref()).collect();
363 let stream = conn
364 .query(&sql, &bound_refs)
365 .await
366 .map_err(classify_tiberius_error)?;
367 let rows = stream
368 .into_first_result()
369 .await
370 .map_err(classify_tiberius_error)?;
371
372 let json_rows: Vec<Value> = rows
373 .iter()
374 .map(|row| {
375 let mut obj = Map::new();
376 for (column, data) in row.cells() {
377 obj.insert(column.name().to_string(), column_data_to_json(data));
378 }
379 Value::Object(obj)
380 })
381 .collect();
382 Ok(Value::Array(json_rows))
383 }
384}
385
386#[cfg(test)]
387mod tests {
388 use super::*;
389
390 #[test]
391 fn parse_path_splits_schema_name() {
392 assert_eq!(
393 parse_path("/INFORMATION_SCHEMA/COLUMNS").unwrap(),
394 ("INFORMATION_SCHEMA", "COLUMNS")
395 );
396 }
397
398 #[test]
399 fn parse_path_rejects_a_path_with_too_few_segments() {
400 assert!(parse_path("/COLUMNS").is_err());
401 }
402
403 #[test]
404 fn quote_ident_doubles_embedded_closing_brackets() {
405 assert_eq!(quote_ident("weird]name"), "[weird]]name]");
406 }
407
408 #[test]
409 fn validate_ident_accepts_alphanumeric_and_underscore() {
410 assert!(validate_ident("sp_who2").is_ok());
411 assert!(validate_ident("INFORMATION_SCHEMA").is_ok());
412 }
413
414 #[test]
415 fn validate_ident_rejects_anything_else() {
416 assert!(validate_ident("").is_err());
417 assert!(validate_ident("robert'; drop table endpoints;--").is_err());
418 assert!(validate_ident("weird]name").is_err());
419 assert!(validate_ident("has space").is_err());
420 }
421
422 #[test]
423 fn parse_path_rejects_a_path_with_an_unsafe_segment() {
424 assert!(parse_path("/sys/sp_who; DROP TABLE endpoints--").is_err());
425 }
426
427 #[test]
428 fn build_statement_selects_from_a_view_with_no_parameters() {
429 let (sql, bound) = build_statement(
430 "INFORMATION_SCHEMA",
431 "COLUMNS",
432 Some("VIEW"),
433 &[],
434 &Map::new(),
435 None,
436 )
437 .unwrap();
438 assert_eq!(sql, "SELECT * FROM [INFORMATION_SCHEMA].[COLUMNS]");
439 assert!(bound.is_empty());
440 }
441
442 #[test]
443 fn build_statement_execs_a_proc_with_named_parameters() {
444 let params = vec![
445 Param {
446 name: "objname".to_string(),
447 ordinal: 1,
448 x_sql_type: "nvarchar(1035)".to_string(),
449 },
450 Param {
451 name: "newname".to_string(),
452 ordinal: 2,
453 x_sql_type: "sysname".to_string(),
454 },
455 ];
456 let mut body = Map::new();
457 body.insert("objname".to_string(), Value::String("t1".to_string()));
458 body.insert("newname".to_string(), Value::String("t2".to_string()));
459 let (sql, bound) = build_statement(
460 "sys",
461 "sp_rename",
462 Some("SQL_STORED_PROCEDURE"),
463 ¶ms,
464 &body,
465 Some("master"),
466 )
467 .unwrap();
468 assert_eq!(
469 sql,
470 "EXEC [master].[sys].[sp_rename] @objname = @P1, @newname = @P2"
471 );
472 assert_eq!(bound.len(), 2);
473 }
474
475 #[test]
486 fn build_statement_uses_at_prefixed_names_not_bracket_quoting_for_named_exec_arguments() {
487 let params = vec![Param {
488 name: "table_name".to_string(),
489 ordinal: 1,
490 x_sql_type: "nvarchar(384)".to_string(),
491 }];
492 let mut body = Map::new();
493 body.insert(
494 "table_name".to_string(),
495 Value::String("databases".to_string()),
496 );
497 let (sql, _bound) = build_statement(
498 "sys",
499 "sp_columns",
500 Some("SQL_STORED_PROCEDURE"),
501 ¶ms,
502 &body,
503 None,
504 )
505 .unwrap();
506 assert_eq!(sql, "EXEC [sys].[sp_columns] @table_name = @P1");
507 assert!(!sql.contains("[table_name]"));
508 }
509
510 #[test]
511 fn build_statement_selects_from_a_function_with_positional_placeholders() {
512 let params = vec![Param {
513 name: "session_id".to_string(),
514 ordinal: 1,
515 x_sql_type: "smallint".to_string(),
516 }];
517 let mut body = Map::new();
518 body.insert("session_id".to_string(), Value::from(52));
519 let (sql, bound) = build_statement(
520 "sys",
521 "dm_exec_sql_text",
522 Some("SQL_INLINE_TABLE_VALUED_FUNCTION"),
523 ¶ms,
524 &body,
525 Some("master"),
526 )
527 .unwrap();
528 assert_eq!(sql, "SELECT * FROM [master].[sys].[dm_exec_sql_text](@P1)");
529 assert_eq!(bound.len(), 1);
530 }
531
532 #[test]
533 fn build_statement_omits_the_database_qualifier_by_default() {
534 let (sql, bound) =
535 build_statement("dbo", "widgets", Some("VIEW"), &[], &Map::new(), None).unwrap();
536 assert_eq!(sql, "SELECT * FROM [dbo].[widgets]");
537 assert!(bound.is_empty());
538 }
539
540 #[test]
541 fn build_statement_three_part_qualifies_with_a_requested_execution_database() {
542 let (sql, bound) = build_statement(
543 "dbo",
544 "widgets",
545 Some("VIEW"),
546 &[],
547 &Map::new(),
548 Some("reporting"),
549 )
550 .unwrap();
551 assert_eq!(sql, "SELECT * FROM [reporting].[dbo].[widgets]");
552 assert!(bound.is_empty());
553 }
554
555 #[test]
556 fn build_statement_execs_a_parameterless_proc() {
557 let (sql, bound) = build_statement(
558 "sys",
559 "sp_who",
560 Some("SQL_STORED_PROCEDURE"),
561 &[],
562 &Map::new(),
563 None,
564 )
565 .unwrap();
566 assert_eq!(sql, "EXEC [sys].[sp_who]");
567 assert!(bound.is_empty());
568 }
569
570 #[test]
571 fn ordered_params_excludes_the_synthetic_execution_database_property() {
572 let schema = serde_json::json!({
573 "properties": {
574 "body": { "$ref": "#/$defs/sys_sp_who_Request" }
575 },
576 "$defs": {
577 "sys_sp_who_Request": {
578 "properties": {
579 "loginame": { "x-sql-ordinal": 1, "x-sql-type": "sysname" },
580 "execution_database": { "type": "string" }
581 }
582 }
583 }
584 });
585
586 let params = ordered_params(&schema);
587 assert_eq!(params.len(), 1);
588 assert_eq!(params[0].name, "loginame");
589 }
590
591 #[test]
592 fn resolve_execution_database_prefers_the_body_property_over_the_configured_default() {
593 let mut body = Map::new();
594 body.insert(
595 EXECUTION_DATABASE_PARAM.to_string(),
596 Value::String("reporting".to_string()),
597 );
598 let mut config = test_config();
599 config.default_database = Some("fallback".to_string());
600 assert_eq!(
601 resolve_execution_database(&body, &config)
602 .unwrap()
603 .as_deref(),
604 Some("reporting")
605 );
606 }
607
608 #[test]
609 fn resolve_execution_database_falls_back_to_the_configured_default() {
610 let mut config = test_config();
611 config.default_database = Some("fallback".to_string());
612 assert_eq!(
613 resolve_execution_database(&Map::new(), &config)
614 .unwrap()
615 .as_deref(),
616 Some("fallback")
617 );
618 }
619
620 #[test]
621 fn resolve_execution_database_is_none_when_nothing_is_configured_or_supplied() {
622 assert_eq!(
623 resolve_execution_database(&Map::new(), &test_config()).unwrap(),
624 None
625 );
626 }
627
628 fn test_config() -> Config {
629 Config {
630 url: "localhost".to_string(),
631 auth_method: crate::core::config_schema::AuthMethod::SqlServer,
632 sql_port: 1433,
633 pool_max_size: 10,
634 trust_server_cert: true,
635 api_version: "2025".to_string(),
636 log_level: "info".to_string(),
637 rate_limit: 100,
638 timeout_ms: 30_000,
639 cache_size: 500,
640 retry_attempts: 3,
641 transport: crate::core::config_schema::Transport::Stdio,
642 host: "127.0.0.1".to_string(),
643 port: 3000,
644 cors_allow: None,
645 default_database: None,
646 }
647 }
648
649 #[test]
650 fn ordered_params_follow_the_schema_ordinals() {
651 let schema = serde_json::json!({
656 "properties": {
657 "body": { "$ref": "#/$defs/sys_example_Request" }
658 },
659 "$defs": {
660 "sys_example_Request": {
661 "properties": {
662 "second": { "x-sql-ordinal": 2, "x-sql-type": "int" },
663 "first": { "x-sql-ordinal": 1, "x-sql-type": "nvarchar(20)" }
664 }
665 }
666 }
667 });
668
669 let params = ordered_params(&schema);
670 assert_eq!(params.len(), 2);
671 assert_eq!(params[0].name, "first");
672 assert_eq!(params[0].x_sql_type, "nvarchar(20)");
673 assert_eq!(params[1].name, "second");
674 }
675
676 #[test]
684 fn ordered_params_resolves_the_body_ref_wrapper() {
685 let schema = serde_json::json!({
686 "properties": {
687 "body": { "$ref": "#/$defs/sys_sp_columns_Request" }
688 },
689 "$defs": {
690 "sys_sp_columns_Request": {
691 "properties": {
692 "table_name": { "x-sql-ordinal": 1, "x-sql-type": "nvarchar(384)" },
693 "table_owner": { "x-sql-ordinal": 2, "x-sql-type": "nvarchar(384)" }
694 }
695 }
696 }
697 });
698
699 let params = ordered_params(&schema);
700 assert_eq!(params.len(), 2);
701 assert_eq!(params[0].name, "table_name");
702 assert_eq!(params[1].name, "table_owner");
703 assert!(params.iter().all(|p| p.name != "body"));
704 }
705
706 #[test]
707 fn ordered_params_resolves_an_inline_body_without_a_ref() {
708 let schema = serde_json::json!({
709 "properties": {
710 "body": {
711 "properties": {
712 "only": { "x-sql-ordinal": 1, "x-sql-type": "int" }
713 }
714 }
715 }
716 });
717
718 let params = ordered_params(&schema);
719 assert_eq!(params.len(), 1);
720 assert_eq!(params[0].name, "only");
721 }
722
723 #[test]
724 fn ordered_params_is_empty_for_a_schema_with_no_body_property() {
725 let schema = serde_json::json!({ "properties": {} });
726 assert!(ordered_params(&schema).is_empty());
727 }
728
729 #[test]
730 fn build_statement_rejects_an_unsafe_parameter_name() {
731 let params = vec![Param {
732 name: "unsafe name".to_string(),
733 ordinal: 1,
734 x_sql_type: "int".to_string(),
735 }];
736
737 assert!(
738 build_statement(
739 "sys",
740 "sp_example",
741 Some("SQL_STORED_PROCEDURE"),
742 ¶ms,
743 &Map::new(),
744 None,
745 )
746 .is_err()
747 );
748 }
749
750 #[test]
751 fn protocol_errors_are_classified_as_server_failures() {
752 let error =
753 classify_tiberius_error(tiberius::error::Error::Protocol("invalid packet".into()));
754 assert_eq!(
755 error.to_string(),
756 "SQL Server connection/protocol error (500-equivalent): Protocol error: invalid packet"
757 );
758 }
759}