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_partial_ungrouped_credential_resolves_to_nothing() {
498 let bedrock = CredentialFormSchema {
502 fields: vec![
503 FormField::password("access_key_id", "Access Key ID")
504 .required()
505 .env("AWS_ACCESS_KEY_ID"),
506 FormField::password("secret_access_key", "Secret Access Key")
507 .required()
508 .env("AWS_SECRET_ACCESS_KEY"),
509 FormField::text("region", "Region").env("AWS_REGION"),
510 ],
511 instructions_markdown: String::new(),
512 };
513 assert!(
514 bedrock
515 .resolve_from_env(lookup(&[("AWS_REGION", "eu-west-1")]))
516 .is_empty()
517 );
518 assert!(
519 bedrock
520 .resolve_from_env(lookup(&[
521 ("AWS_ACCESS_KEY_ID", "AKIA"),
522 ("AWS_REGION", "eu-west-1"),
523 ]))
524 .is_empty()
525 );
526 assert_eq!(
528 bedrock.resolve_from_env(lookup(&[
529 ("AWS_ACCESS_KEY_ID", "AKIA"),
530 ("AWS_SECRET_ACCESS_KEY", "shh"),
531 ("AWS_REGION", "eu-west-1"),
532 ])),
533 BTreeMap::from([
534 ("access_key_id".to_string(), "AKIA".to_string()),
535 ("secret_access_key".to_string(), "shh".to_string()),
536 ("region".to_string(), "eu-west-1".to_string()),
537 ])
538 );
539 }
540
541 #[test]
542 fn a_group_resolves_only_when_all_of_its_required_fields_are_present() {
543 let schema = grouped_schema();
544 assert!(
546 schema
547 .resolve_from_env(lookup(&[("AZURE_TENANT_ID", "tenant")]))
548 .is_empty()
549 );
550 assert_eq!(
551 schema.resolve_from_env(lookup(&[
552 ("AZURE_TENANT_ID", "tenant"),
553 ("AZURE_CLIENT_SECRET", "secret"),
554 ])),
555 BTreeMap::from([
556 ("tenant_id".to_string(), "tenant".to_string()),
557 ("client_secret".to_string(), "secret".to_string()),
558 ])
559 );
560 }
561
562 #[test]
563 fn the_first_complete_group_wins_and_never_mixes_methods() {
564 let resolved = grouped_schema().resolve_from_env(lookup(&[
565 ("AZURE_AI_API_KEY", "key"),
566 ("AZURE_TENANT_ID", "tenant"),
567 ("AZURE_CLIENT_SECRET", "secret"),
568 ]));
569 assert_eq!(
570 resolved,
571 BTreeMap::from([("api_key".to_string(), "key".to_string())])
572 );
573 }
574
575 #[test]
576 fn an_optional_group_field_rides_along_with_its_complete_group() {
577 let resolved = grouped_schema().resolve_from_env(lookup(&[
578 ("AZURE_TENANT_ID", "tenant"),
579 ("AZURE_CLIENT_SECRET", "secret"),
580 ("AZURE_SCOPE", "scope"),
581 ]));
582 assert_eq!(resolved.get("scope").map(String::as_str), Some("scope"));
583 }
584}
585
586#[cfg(test)]
587mod tests {
588 use super::*;
589
590 fn map(pairs: &[(&str, &str)]) -> BTreeMap<String, String> {
591 pairs
592 .iter()
593 .map(|(key, value)| (key.to_string(), value.to_string()))
594 .collect()
595 }
596
597 #[test]
598 fn assembly_uses_literal_legacy_and_deterministic_json_formats() {
599 for (fields, expected) in [
600 (vec![], None),
601 (vec![("api_key", " \t\n"), ("region", "")], None),
602 (
603 vec![("api_key", " key with spaces "), ("region", " \n")],
604 Some(" key with spaces "),
605 ),
606 (
607 vec![
608 ("secret_access_key", "SECRET"),
609 ("region", ""),
610 ("access_key_id", "AKID"),
611 ],
612 Some(r#"{"access_key_id":"AKID","secret_access_key":"SECRET"}"#),
613 ),
614 (vec![("tenant_id", "one")], Some(r#"{"tenant_id":"one"}"#)),
615 (
616 vec![("api_key", "quote\"slash\\line\n"), ("region", "west")],
617 Some(r#"{"api_key":"quote\"slash\\line\n","region":"west"}"#),
618 ),
619 ] {
620 assert_eq!(
621 assemble_credential_document(&map(&fields)).as_deref(),
622 expected,
623 "{fields:?}"
624 );
625 }
626 }
627
628 #[test]
629 fn parsing_preserves_legacy_documents_and_opaque_fallback_exactly() {
630 assert_eq!(parse_credential_document(None), BTreeMap::new());
631 assert_eq!(
632 parse_credential_document(Some(
633 r#"{"tenant_id":"t","client_id":"c","client_secret":"s"}"#
634 )),
635 map(&[
636 ("tenant_id", "t"),
637 ("client_id", "c"),
638 ("client_secret", "s")
639 ])
640 );
641 assert_eq!(
642 parse_credential_document(Some(
643 r#"{"access_key_id":"AKID","secret_access_key":"SECRET","ignored":42,"empty":""}"#
644 )),
645 map(&[
646 ("access_key_id", "AKID"),
647 ("secret_access_key", "SECRET"),
648 ("empty", "")
649 ])
650 );
651 for opaque in [
652 "sk-raw-key",
653 "",
654 " ",
655 "not { json",
656 "{}",
657 r#"{"number":42}"#,
658 "[1,2]",
659 "null",
660 r#""json string""#,
661 ] {
662 assert_eq!(
663 parse_credential_document(Some(opaque)),
664 map(&[("api_key", opaque)]),
665 "opaque {opaque:?}"
666 );
667 }
668 }
669
670 #[test]
671 fn single_method_schema_requires_nonblank_key_but_accepts_unknown_optional_fields() {
672 let schema = CredentialFormSchema::api_key("VENDOR_API_KEY", "Get a key");
673 assert_eq!(
674 serde_json::to_value(&schema).unwrap(),
675 serde_json::json!({
676 "fields": [{
677 "name":"api_key",
678 "label":"API Key",
679 "field_type":"password",
680 "required":true,
681 "env":["VENDOR_API_KEY"]
682 }],
683 "instructions_markdown":"Get a key"
684 })
685 );
686 for fields in [
687 map(&[]),
688 map(&[("api_key", " \t\n")]),
689 map(&[("unknown", "value")]),
690 ] {
691 assert_eq!(schema.validate(&fields), ["API Key is required."]);
692 }
693 assert!(
694 schema
695 .validate(&map(&[("api_key", " key "), ("unknown", "value")]))
696 .is_empty()
697 );
698 assert!(
699 CredentialFormSchema::empty()
700 .validate(&map(&[("unknown", "value")]))
701 .is_empty()
702 );
703 }
704
705 #[test]
706 fn grouped_validation_requires_complete_touched_methods_in_declaration_order() {
707 let schema = CredentialFormSchema {
708 fields: vec![
709 FormField::text("endpoint", "Endpoint").required(),
710 FormField::password("api_key", "API Key")
711 .required()
712 .in_group("API key"),
713 FormField::text("tenant_id", "Tenant ID")
714 .required()
715 .in_group("OAuth"),
716 FormField::text("scope", "Scope").in_group("OAuth"),
717 FormField::text("client_id", "Client ID")
718 .required()
719 .in_group("OAuth"),
720 FormField::password("client_secret", "Client Secret")
721 .required()
722 .in_group("OAuth"),
723 ],
724 instructions_markdown: String::new(),
725 };
726 for (fields, expected) in [
727 (vec![], vec!["Endpoint is required."]),
728 (
729 vec![("endpoint", "url")],
730 vec!["Provide credentials for one of the available methods."],
731 ),
732 (vec![("endpoint", "url"), ("api_key", "k")], vec![]),
733 (vec![("api_key", "k")], vec!["Endpoint is required."]),
734 (
735 vec![
736 ("endpoint", "url"),
737 ("tenant_id", "t"),
738 ("client_id", "c"),
739 ("client_secret", "s"),
740 ],
741 vec![],
742 ),
743 (
744 vec![("endpoint", "url"), ("tenant_id", "t")],
745 vec![
746 "Client ID (OAuth) is required.",
747 "Client Secret (OAuth) is required.",
748 ],
749 ),
750 (
751 vec![
752 ("endpoint", "url"),
753 ("api_key", "k"),
754 ("tenant_id", "t"),
755 ("client_id", " \n"),
756 ],
757 vec![
758 "Client ID (OAuth) is required.",
759 "Client Secret (OAuth) is required.",
760 ],
761 ),
762 (
763 vec![("endpoint", "url"), ("scope", "optional-but-touched")],
764 vec![
765 "Tenant ID (OAuth) is required.",
766 "Client ID (OAuth) is required.",
767 "Client Secret (OAuth) is required.",
768 ],
769 ),
770 ] {
771 assert_eq!(schema.validate(&map(&fields)), expected, "{fields:?}");
772 }
773 }
774}