1use std::collections::BTreeMap;
22
23use serde::Serialize;
24
25#[derive(Debug, Clone, Serialize)]
27#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
28pub struct CredentialFormSchema {
29 pub fields: Vec<FormField>,
31 pub instructions_markdown: String,
33}
34
35impl CredentialFormSchema {
36 pub fn empty() -> Self {
38 Self {
39 fields: Vec::new(),
40 instructions_markdown: String::new(),
41 }
42 }
43
44 pub fn api_key(
52 api_key_env: impl Into<String>,
53 instructions_markdown: impl Into<String>,
54 ) -> Self {
55 Self {
56 fields: vec![
57 FormField::password("api_key", "API Key")
58 .required()
59 .env(api_key_env),
60 ],
61 instructions_markdown: instructions_markdown.into(),
62 }
63 }
64
65 pub fn with_api_key_fallback_env(mut self, api_key_env: impl Into<String>) -> Self {
71 if let Some(field) = self.fields.iter_mut().find(|field| field.name == "api_key") {
72 field.env.push(api_key_env.into());
73 }
74 self
75 }
76
77 pub fn resolve_from_env<F>(&self, lookup: F) -> BTreeMap<String, String>
92 where
93 F: Fn(&str) -> Option<String>,
94 {
95 let resolved: Vec<(&FormField, Option<String>)> = self
96 .fields
97 .iter()
98 .map(|field| (field, field.resolve_env(&lookup)))
99 .collect();
100
101 let ungrouped_satisfied = resolved
107 .iter()
108 .filter(|(field, _)| field.group.is_none() && field.required)
109 .all(|(_, value)| value.is_some());
110 if !ungrouped_satisfied {
111 return BTreeMap::new();
112 }
113
114 let mut fields = BTreeMap::new();
115 let mut group_taken = false;
116 let mut seen_groups: Vec<&str> = Vec::new();
117
118 for (field, value) in &resolved {
119 let Some(group) = field.group.as_deref() else {
120 if let Some(value) = value {
121 fields.insert(field.name.clone(), value.clone());
122 }
123 continue;
124 };
125 if seen_groups.contains(&group) {
126 continue;
127 }
128 seen_groups.push(group);
129 if group_taken {
130 continue;
131 }
132 let members = resolved
133 .iter()
134 .filter(|(member, _)| member.group.as_deref() == Some(group));
135 let complete = members
136 .clone()
137 .all(|(member, value)| !member.required || value.is_some());
138 if !complete {
139 continue;
140 }
141 for (member, value) in members {
142 if let Some(value) = value {
143 fields.insert(member.name.clone(), value.clone());
144 }
145 }
146 group_taken = true;
147 }
148
149 fields
150 }
151
152 pub fn has_groups(&self) -> bool {
156 self.fields.iter().any(|f| f.group.is_some())
157 }
158
159 pub fn validate(&self, fields: &BTreeMap<String, String>) -> Vec<String> {
173 let filled = |name: &str| fields.get(name).is_some_and(|v| !v.trim().is_empty());
174 let mut errors = Vec::new();
175
176 for field in self.fields.iter().filter(|f| f.group.is_none()) {
178 if field.required && !filled(&field.name) {
179 errors.push(format!("{} is required.", field.label));
180 }
181 }
182
183 if !self.has_groups() {
184 return errors;
185 }
186
187 let mut group_labels: Vec<&str> = Vec::new();
189 for field in &self.fields {
190 if let Some(group) = field.group.as_deref()
191 && !group_labels.contains(&group)
192 {
193 group_labels.push(group);
194 }
195 }
196
197 let mut any_group_complete = false;
198 for label in group_labels {
199 let group_fields: Vec<&FormField> = self
200 .fields
201 .iter()
202 .filter(|f| f.group.as_deref() == Some(label))
203 .collect();
204 let touched = group_fields.iter().any(|f| filled(&f.name));
205 let complete = group_fields.iter().all(|f| !f.required || filled(&f.name));
206 if touched && !complete {
207 for field in group_fields
208 .iter()
209 .filter(|f| f.required && !filled(&f.name))
210 {
211 errors.push(format!("{} ({}) is required.", field.label, label));
212 }
213 }
214 if complete && touched {
215 any_group_complete = true;
216 }
217 }
218
219 if !any_group_complete && errors.is_empty() {
220 errors.push("Provide credentials for one of the available methods.".to_string());
221 }
222
223 errors
224 }
225}
226
227#[derive(Debug, Clone, Default, Serialize)]
229#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
230pub struct FormField {
231 pub name: String,
233 pub label: String,
235 pub field_type: FieldType,
237 pub required: bool,
239 #[serde(skip_serializing_if = "Option::is_none")]
241 pub placeholder: Option<String>,
242 #[serde(skip_serializing_if = "Option::is_none")]
244 pub help_text: Option<String>,
245 #[serde(skip_serializing_if = "Option::is_none")]
249 pub default_value: Option<String>,
250 #[serde(skip_serializing_if = "Option::is_none")]
255 pub group: Option<String>,
256 #[serde(skip_serializing_if = "Vec::is_empty")]
269 pub env: Vec<String>,
270}
271
272impl FormField {
273 fn new(name: impl Into<String>, label: impl Into<String>, field_type: FieldType) -> Self {
275 Self {
276 name: name.into(),
277 label: label.into(),
278 field_type,
279 required: false,
280 placeholder: None,
281 help_text: None,
282 default_value: None,
283 group: None,
284 env: Vec::new(),
285 }
286 }
287
288 pub fn password(name: impl Into<String>, label: impl Into<String>) -> Self {
290 Self::new(name, label, FieldType::Password)
291 }
292
293 pub fn text(name: impl Into<String>, label: impl Into<String>) -> Self {
295 Self::new(name, label, FieldType::Text)
296 }
297
298 pub fn required(mut self) -> Self {
300 self.required = true;
301 self
302 }
303
304 pub fn with_placeholder(mut self, placeholder: impl Into<String>) -> Self {
306 self.placeholder = Some(placeholder.into());
307 self
308 }
309
310 pub fn with_help(mut self, help_text: impl Into<String>) -> Self {
312 self.help_text = Some(help_text.into());
313 self
314 }
315
316 pub fn with_default(mut self, default_value: impl Into<String>) -> Self {
318 self.default_value = Some(default_value.into());
319 self
320 }
321
322 pub fn in_group(mut self, group: impl Into<String>) -> Self {
324 self.group = Some(group.into());
325 self
326 }
327
328 pub fn env(mut self, name: impl Into<String>) -> Self {
331 self.env.push(name.into());
332 self
333 }
334
335 pub fn env_fallback(self, name: impl Into<String>) -> Self {
338 self.env(name)
339 }
340
341 fn resolve_env<F>(&self, lookup: &F) -> Option<String>
343 where
344 F: Fn(&str) -> Option<String>,
345 {
346 self.env
347 .iter()
348 .find_map(|name| lookup(name).filter(|value| !value.trim().is_empty()))
349 }
350}
351
352#[derive(Debug, Clone, Copy, Default, Serialize)]
354#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
355#[serde(rename_all = "snake_case")]
356pub enum FieldType {
357 #[default]
359 Password,
360 Text,
362 Url,
364}
365
366#[expect(
377 clippy::expect_used,
378 reason = "String keys and values always serialize as a JSON object"
379)]
380pub fn assemble_credential_document(fields: &BTreeMap<String, String>) -> Option<String> {
381 let non_empty: BTreeMap<&str, &str> = fields
382 .iter()
383 .filter(|(_, v)| !v.trim().is_empty())
384 .map(|(k, v)| (k.as_str(), v.as_str()))
385 .collect();
386
387 match non_empty.len() {
388 0 => None,
389 1 if non_empty.contains_key("api_key") => Some(non_empty["api_key"].to_string()),
390 _ => Some(serde_json::to_string(&non_empty).expect("string map serializes")),
391 }
392}
393
394pub fn parse_credential_document(document: Option<&str>) -> BTreeMap<String, String> {
401 let Some(document) = document else {
402 return BTreeMap::new();
403 };
404
405 if let Ok(serde_json::Value::Object(map)) = serde_json::from_str::<serde_json::Value>(document)
406 {
407 let mut fields = BTreeMap::new();
408 for (key, value) in map {
409 if let serde_json::Value::String(s) = value {
410 fields.insert(key, s);
411 }
412 }
413 if !fields.is_empty() {
416 return fields;
417 }
418 }
419
420 BTreeMap::from([("api_key".to_string(), document.to_string())])
421}
422
423#[cfg(test)]
424mod env_tests {
425 use super::*;
426
427 fn lookup(entries: &'static [(&'static str, &'static str)]) -> impl Fn(&str) -> Option<String> {
428 move |name: &str| {
429 entries
430 .iter()
431 .find(|(key, _)| *key == name)
432 .map(|(_, value)| value.to_string())
433 }
434 }
435
436 fn grouped_schema() -> CredentialFormSchema {
437 CredentialFormSchema {
438 fields: vec![
439 FormField::password("api_key", "API Key")
440 .required()
441 .in_group("API key")
442 .env("AZURE_AI_API_KEY"),
443 FormField::text("tenant_id", "Tenant")
444 .required()
445 .in_group("OAuth")
446 .env("AZURE_TENANT_ID"),
447 FormField::password("client_secret", "Secret")
448 .required()
449 .in_group("OAuth")
450 .env("AZURE_CLIENT_SECRET"),
451 FormField::text("scope", "Scope")
452 .in_group("OAuth")
453 .env("AZURE_SCOPE"),
454 ],
455 instructions_markdown: String::new(),
456 }
457 }
458
459 #[test]
460 fn a_field_takes_its_first_declared_variable_that_has_a_value() {
461 let schema = CredentialFormSchema {
462 fields: vec![
463 FormField::password("api_key", "API Key")
464 .required()
465 .env("GEMINI_API_KEY")
466 .env_fallback("GOOGLE_API_KEY"),
467 ],
468 instructions_markdown: String::new(),
469 };
470 assert_eq!(
471 schema.resolve_from_env(lookup(&[
472 ("GEMINI_API_KEY", "preferred"),
473 ("GOOGLE_API_KEY", "alternate"),
474 ])),
475 BTreeMap::from([("api_key".to_string(), "preferred".to_string())])
476 );
477 assert_eq!(
478 schema.resolve_from_env(lookup(&[("GOOGLE_API_KEY", "alternate")])),
479 BTreeMap::from([("api_key".to_string(), "alternate".to_string())])
480 );
481 assert_eq!(
483 schema.resolve_from_env(lookup(&[
484 ("GEMINI_API_KEY", " "),
485 ("GOOGLE_API_KEY", "alternate"),
486 ])),
487 BTreeMap::from([("api_key".to_string(), "alternate".to_string())])
488 );
489 assert!(
490 schema
491 .resolve_from_env(lookup(&[("OPENAI_API_KEY", "other")]))
492 .is_empty()
493 );
494 }
495
496 #[test]
497 fn a_field_declaring_no_variable_never_resolves_from_the_environment() {
498 let schema = CredentialFormSchema {
499 fields: vec![FormField::password("api_key", "API Key").required()],
500 instructions_markdown: String::new(),
501 };
502 assert!(
503 schema
504 .resolve_from_env(lookup(&[("API_KEY", "set"), ("OPENAI_API_KEY", "set")]))
505 .is_empty()
506 );
507 }
508
509 #[test]
510 fn a_partial_ungrouped_credential_resolves_to_nothing() {
511 let bedrock = CredentialFormSchema {
515 fields: vec![
516 FormField::password("access_key_id", "Access Key ID")
517 .required()
518 .env("AWS_ACCESS_KEY_ID"),
519 FormField::password("secret_access_key", "Secret Access Key")
520 .required()
521 .env("AWS_SECRET_ACCESS_KEY"),
522 FormField::text("region", "Region").env("AWS_REGION"),
523 ],
524 instructions_markdown: String::new(),
525 };
526 assert!(
527 bedrock
528 .resolve_from_env(lookup(&[("AWS_REGION", "eu-west-1")]))
529 .is_empty()
530 );
531 assert!(
532 bedrock
533 .resolve_from_env(lookup(&[
534 ("AWS_ACCESS_KEY_ID", "AKIA"),
535 ("AWS_REGION", "eu-west-1"),
536 ]))
537 .is_empty()
538 );
539 assert_eq!(
541 bedrock.resolve_from_env(lookup(&[
542 ("AWS_ACCESS_KEY_ID", "AKIA"),
543 ("AWS_SECRET_ACCESS_KEY", "shh"),
544 ("AWS_REGION", "eu-west-1"),
545 ])),
546 BTreeMap::from([
547 ("access_key_id".to_string(), "AKIA".to_string()),
548 ("secret_access_key".to_string(), "shh".to_string()),
549 ("region".to_string(), "eu-west-1".to_string()),
550 ])
551 );
552 }
553
554 #[test]
555 fn a_group_resolves_only_when_all_of_its_required_fields_are_present() {
556 let schema = grouped_schema();
557 assert!(
559 schema
560 .resolve_from_env(lookup(&[("AZURE_TENANT_ID", "tenant")]))
561 .is_empty()
562 );
563 assert_eq!(
564 schema.resolve_from_env(lookup(&[
565 ("AZURE_TENANT_ID", "tenant"),
566 ("AZURE_CLIENT_SECRET", "secret"),
567 ])),
568 BTreeMap::from([
569 ("tenant_id".to_string(), "tenant".to_string()),
570 ("client_secret".to_string(), "secret".to_string()),
571 ])
572 );
573 }
574
575 #[test]
576 fn the_first_complete_group_wins_and_never_mixes_methods() {
577 let resolved = grouped_schema().resolve_from_env(lookup(&[
578 ("AZURE_AI_API_KEY", "key"),
579 ("AZURE_TENANT_ID", "tenant"),
580 ("AZURE_CLIENT_SECRET", "secret"),
581 ]));
582 assert_eq!(
583 resolved,
584 BTreeMap::from([("api_key".to_string(), "key".to_string())])
585 );
586 }
587
588 #[test]
589 fn an_optional_group_field_rides_along_with_its_complete_group() {
590 let resolved = grouped_schema().resolve_from_env(lookup(&[
591 ("AZURE_TENANT_ID", "tenant"),
592 ("AZURE_CLIENT_SECRET", "secret"),
593 ("AZURE_SCOPE", "scope"),
594 ]));
595 assert_eq!(resolved.get("scope").map(String::as_str), Some("scope"));
596 }
597
598 #[test]
599 fn a_resolved_map_assembles_into_the_same_document_the_form_produces() {
600 let resolved = grouped_schema().resolve_from_env(lookup(&[
601 ("AZURE_TENANT_ID", "tenant"),
602 ("AZURE_CLIENT_SECRET", "secret"),
603 ]));
604 assert_eq!(
605 assemble_credential_document(&resolved),
606 Some(r#"{"client_secret":"secret","tenant_id":"tenant"}"#.to_string())
607 );
608 }
609}
610
611#[cfg(test)]
612mod tests {
613 use super::*;
614
615 fn map(pairs: &[(&str, &str)]) -> BTreeMap<String, String> {
616 pairs
617 .iter()
618 .map(|(key, value)| (key.to_string(), value.to_string()))
619 .collect()
620 }
621
622 #[test]
623 fn assembly_uses_literal_legacy_and_deterministic_json_formats() {
624 for (fields, expected) in [
625 (vec![], None),
626 (vec![("api_key", " \t\n"), ("region", "")], None),
627 (
628 vec![("api_key", " key with spaces "), ("region", " \n")],
629 Some(" key with spaces "),
630 ),
631 (
632 vec![
633 ("secret_access_key", "SECRET"),
634 ("region", ""),
635 ("access_key_id", "AKID"),
636 ],
637 Some(r#"{"access_key_id":"AKID","secret_access_key":"SECRET"}"#),
638 ),
639 (vec![("tenant_id", "one")], Some(r#"{"tenant_id":"one"}"#)),
640 (
641 vec![("api_key", "quote\"slash\\line\n"), ("region", "west")],
642 Some(r#"{"api_key":"quote\"slash\\line\n","region":"west"}"#),
643 ),
644 ] {
645 assert_eq!(
646 assemble_credential_document(&map(&fields)).as_deref(),
647 expected,
648 "{fields:?}"
649 );
650 }
651 }
652
653 #[test]
654 fn parsing_preserves_legacy_documents_and_opaque_fallback_exactly() {
655 assert_eq!(parse_credential_document(None), BTreeMap::new());
656 assert_eq!(
657 parse_credential_document(Some(
658 r#"{"tenant_id":"t","client_id":"c","client_secret":"s"}"#
659 )),
660 map(&[
661 ("tenant_id", "t"),
662 ("client_id", "c"),
663 ("client_secret", "s")
664 ])
665 );
666 assert_eq!(
667 parse_credential_document(Some(
668 r#"{"access_key_id":"AKID","secret_access_key":"SECRET","ignored":42,"empty":""}"#
669 )),
670 map(&[
671 ("access_key_id", "AKID"),
672 ("secret_access_key", "SECRET"),
673 ("empty", "")
674 ])
675 );
676 for opaque in [
677 "sk-raw-key",
678 "",
679 " ",
680 "not { json",
681 "{}",
682 r#"{"number":42}"#,
683 "[1,2]",
684 "null",
685 r#""json string""#,
686 ] {
687 assert_eq!(
688 parse_credential_document(Some(opaque)),
689 map(&[("api_key", opaque)]),
690 "opaque {opaque:?}"
691 );
692 }
693 }
694
695 #[test]
696 fn single_method_schema_requires_nonblank_key_but_accepts_unknown_optional_fields() {
697 let schema = CredentialFormSchema::api_key("VENDOR_API_KEY", "Get a key");
698 assert_eq!(
699 serde_json::to_value(&schema).unwrap(),
700 serde_json::json!({
701 "fields": [{
702 "name":"api_key",
703 "label":"API Key",
704 "field_type":"password",
705 "required":true,
706 "env":["VENDOR_API_KEY"]
707 }],
708 "instructions_markdown":"Get a key"
709 })
710 );
711 for fields in [
712 map(&[]),
713 map(&[("api_key", " \t\n")]),
714 map(&[("unknown", "value")]),
715 ] {
716 assert_eq!(schema.validate(&fields), ["API Key is required."]);
717 }
718 assert!(
719 schema
720 .validate(&map(&[("api_key", " key "), ("unknown", "value")]))
721 .is_empty()
722 );
723 assert!(
724 CredentialFormSchema::empty()
725 .validate(&map(&[("unknown", "value")]))
726 .is_empty()
727 );
728 }
729
730 #[test]
731 fn grouped_validation_requires_complete_touched_methods_in_declaration_order() {
732 let schema = CredentialFormSchema {
733 fields: vec![
734 FormField::text("endpoint", "Endpoint").required(),
735 FormField::password("api_key", "API Key")
736 .required()
737 .in_group("API key"),
738 FormField::text("tenant_id", "Tenant ID")
739 .required()
740 .in_group("OAuth"),
741 FormField::text("scope", "Scope").in_group("OAuth"),
742 FormField::text("client_id", "Client ID")
743 .required()
744 .in_group("OAuth"),
745 FormField::password("client_secret", "Client Secret")
746 .required()
747 .in_group("OAuth"),
748 ],
749 instructions_markdown: String::new(),
750 };
751 for (fields, expected) in [
752 (vec![], vec!["Endpoint is required."]),
753 (
754 vec![("endpoint", "url")],
755 vec!["Provide credentials for one of the available methods."],
756 ),
757 (vec![("endpoint", "url"), ("api_key", "k")], vec![]),
758 (vec![("api_key", "k")], vec!["Endpoint is required."]),
759 (
760 vec![
761 ("endpoint", "url"),
762 ("tenant_id", "t"),
763 ("client_id", "c"),
764 ("client_secret", "s"),
765 ],
766 vec![],
767 ),
768 (
769 vec![("endpoint", "url"), ("tenant_id", "t")],
770 vec![
771 "Client ID (OAuth) is required.",
772 "Client Secret (OAuth) is required.",
773 ],
774 ),
775 (
776 vec![
777 ("endpoint", "url"),
778 ("api_key", "k"),
779 ("tenant_id", "t"),
780 ("client_id", " \n"),
781 ],
782 vec![
783 "Client ID (OAuth) is required.",
784 "Client Secret (OAuth) is required.",
785 ],
786 ),
787 (
788 vec![("endpoint", "url"), ("scope", "optional-but-touched")],
789 vec![
790 "Tenant ID (OAuth) is required.",
791 "Client ID (OAuth) is required.",
792 "Client Secret (OAuth) is required.",
793 ],
794 ),
795 ] {
796 assert_eq!(schema.validate(&map(&fields)), expected, "{fields:?}");
797 }
798 }
799}