Skip to main content

everruns_contracts/
credential_schema.rs

1// Shared credential form schema
2//
3// Declarative description of the credential fields an integration needs,
4// rendered by the Settings UI and validated before saving. Shared by two
5// front doors (see knowledge/foundations/providers.md "Credentials"):
6//
7// - Provider drivers (`DriverDescriptor::credential_schema`) — org-scoped
8//   vendor accounts that power agent execution.
9// - Connectors (`Connector::form_schema`) — user-scoped
10//   accounts on external services used by tools.
11//
12// Multi-field credentials (Bedrock AWS keys, Microsoft Entra ID OAuth) are
13// declared as discrete typed fields rather than a single opaque password the
14// operator hand-authors as JSON. The submitted field map is assembled into a
15// single credential document (`assemble_credential_document`) that is stored in
16// the existing envelope-encrypted credential field, and parsed back into a
17// typed field map at driver-construction time (`parse_credential_document`).
18// Keeping the storage shape a JSON document means existing Bedrock/MAI rows —
19// which already store such a document — keep resolving unchanged.
20
21use std::collections::BTreeMap;
22
23use serde::Serialize;
24
25/// Describes the form fields and instructions for entering a credential.
26#[derive(Debug, Clone, Serialize)]
27#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
28pub struct CredentialFormSchema {
29    /// Input fields to render.
30    pub fields: Vec<FormField>,
31    /// Markdown instructions shown above the form (how to get the key, etc.).
32    pub instructions_markdown: String,
33}
34
35impl CredentialFormSchema {
36    /// Schema with no fields (keyless integrations, e.g. test simulators).
37    pub fn empty() -> Self {
38        Self {
39            fields: Vec::new(),
40            instructions_markdown: String::new(),
41        }
42    }
43
44    /// The common single-field API key schema.
45    ///
46    /// `api_key_env` is the environment variable the driver's vendor reads for
47    /// this key (`OPENAI_API_KEY`, `ANTHROPIC_API_KEY`, ...). It is a required
48    /// argument, not a default: nothing outside the driver can know the right
49    /// name, and a driver that had to stay silent about it would be resolved by
50    /// guesswork instead.
51    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    /// Declare a further variable the vendor also honors for the `api_key`
66    /// field, tried after the one [`api_key`](Self::api_key) named.
67    ///
68    /// For vendors that renamed their variable and kept reading the old one
69    /// (`GEMINI_API_KEY` then `GOOGLE_API_KEY`).
70    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    /// Resolve this schema's fields from an environment lookup.
78    ///
79    /// Each field takes the first of its declared variables that holds a
80    /// non-empty value. The result then follows the same rules
81    /// [`validate`](Self::validate) enforces, so a partially configured
82    /// environment yields nothing rather than a half-configured provider:
83    /// every ungrouped required field must have resolved, and a group
84    /// contributes its fields only when every required field in it resolved,
85    /// the first complete group in declaration order winning.
86    ///
87    /// The result is the field map [`assemble_credential_document`] stores, so
88    /// an env-resolved credential and an operator-entered one reach the driver
89    /// in the same shape. An empty map means the environment carries no usable
90    /// credential for this driver.
91    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        // Ungrouped required fields are mandatory, exactly as in `validate`.
102        // Without this an incomplete environment resolves to a partial
103        // credential and builds a broken provider, rather than falling through
104        // to whatever the caller configures explicitly. A shell carrying only
105        // `AWS_REGION` is the everyday case.
106        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    /// Whether the schema declares any mutually-exclusive credential groups
153    /// (e.g. "API key" *or* "OAuth"). When it does, at least one complete group
154    /// is required by [`CredentialFormSchema::validate`].
155    pub fn has_groups(&self) -> bool {
156        self.fields.iter().any(|f| f.group.is_some())
157    }
158
159    /// Validate a submitted field map against this schema.
160    ///
161    /// Rules:
162    /// - Every ungrouped required field must be present and non-empty.
163    /// - Fields sharing a `group` label form a mutually-exclusive alternative
164    ///   (e.g. MAI's "API key" group vs its "Entra ID OAuth" group). A group is
165    ///   *touched* when any of its fields has a value; a touched group must have
166    ///   all of its required fields filled (no partially-entered OAuth blocks).
167    /// - When the schema declares any groups, at least one group must be
168    ///   complete, so a provider cannot be saved with no credential at all.
169    ///
170    /// Returns the list of human-readable validation errors; empty means valid.
171    /// Unknown keys are ignored — drivers read only the fields they declare.
172    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        // Ungrouped required fields are always mandatory.
177        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        // Grouped fields: collect group labels in declaration order.
188        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/// A single form field.
228#[derive(Debug, Clone, Default, Serialize)]
229#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
230pub struct FormField {
231    /// Field name used as the key when submitting (e.g. "api_key").
232    pub name: String,
233    /// Label shown next to the input.
234    pub label: String,
235    /// Input type.
236    pub field_type: FieldType,
237    /// Whether the field is required.
238    pub required: bool,
239    /// Placeholder text inside the input.
240    #[serde(skip_serializing_if = "Option::is_none")]
241    pub placeholder: Option<String>,
242    /// Help text shown below the input.
243    #[serde(skip_serializing_if = "Option::is_none")]
244    pub help_text: Option<String>,
245    /// Default value the UI pre-fills (e.g. an OAuth scope or AWS region). The
246    /// stored credential omits unfilled optional fields, so drivers still apply
247    /// their own defaults; this only seeds the form input.
248    #[serde(skip_serializing_if = "Option::is_none")]
249    pub default_value: Option<String>,
250    /// Mutually-exclusive group label this field belongs to. Fields sharing a
251    /// label are one alternative credential method (e.g. "API key" vs "OAuth");
252    /// ungrouped fields are always part of the credential. `None` for the
253    /// common single-method case.
254    #[serde(skip_serializing_if = "Option::is_none")]
255    pub group: Option<String>,
256    /// Environment variables this field can be read from in standalone/dev use,
257    /// most preferred first.
258    ///
259    /// Declared by the driver, because only the driver knows what its vendor's
260    /// own SDK reads: `AWS_ACCESS_KEY_ID` for Bedrock, `AZURE_TENANT_ID` for
261    /// MAI's Entra group, `ANTHROPIC_API_KEY` for Anthropic. Later entries are
262    /// alternates the vendor also honors (`GOOGLE_API_KEY`,
263    /// `AWS_DEFAULT_REGION`), not a second field.
264    ///
265    /// Empty means the field cannot be supplied from the environment, so a
266    /// group containing a required field with no variable never resolves from
267    /// env alone. Server credential resolution ignores this entirely.
268    #[serde(skip_serializing_if = "Vec::is_empty")]
269    pub env: Vec<String>,
270}
271
272impl FormField {
273    /// A field of the given type with no extra metadata.
274    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    /// A masked password/secret field.
289    pub fn password(name: impl Into<String>, label: impl Into<String>) -> Self {
290        Self::new(name, label, FieldType::Password)
291    }
292
293    /// A plain text field.
294    pub fn text(name: impl Into<String>, label: impl Into<String>) -> Self {
295        Self::new(name, label, FieldType::Text)
296    }
297
298    /// Mark the field as required.
299    pub fn required(mut self) -> Self {
300        self.required = true;
301        self
302    }
303
304    /// Set placeholder text.
305    pub fn with_placeholder(mut self, placeholder: impl Into<String>) -> Self {
306        self.placeholder = Some(placeholder.into());
307        self
308    }
309
310    /// Set help text shown below the input.
311    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    /// Set a default value the form pre-fills.
317    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    /// Assign the field to a mutually-exclusive credential group.
323    pub fn in_group(mut self, group: impl Into<String>) -> Self {
324        self.group = Some(group.into());
325        self
326    }
327
328    /// Declare the environment variable this field is read from, following the
329    /// vendor's own SDK convention.
330    pub fn env(mut self, name: impl Into<String>) -> Self {
331        self.env.push(name.into());
332        self
333    }
334
335    /// Declare a further variable the vendor also honors, tried after the ones
336    /// already declared.
337    pub fn env_fallback(self, name: impl Into<String>) -> Self {
338        self.env(name)
339    }
340
341    /// The first declared variable that holds a non-empty value.
342    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/// Input field type for rendering.
353#[derive(Debug, Clone, Copy, Default, Serialize)]
354#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
355#[serde(rename_all = "snake_case")]
356pub enum FieldType {
357    /// Masked password/secret input.
358    #[default]
359    Password,
360    /// Plain text input.
361    Text,
362    /// URL input.
363    Url,
364}
365
366/// Assemble a submitted credential field map into the single document string
367/// that is envelope-encrypted and stored.
368///
369/// Empty values are dropped so unfilled optional fields are not persisted. A
370/// lone `api_key` field is stored as the raw key (the long-standing simple
371/// shape), so single-key providers and the dev env-var fallback keep their
372/// exact storage format. Any other field set is stored as a deterministic JSON
373/// object keyed by field name — the shape Bedrock and MAI already use.
374///
375/// Returns `None` when nothing was supplied (no credential to store).
376#[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
394/// Parse a stored credential document back into a typed field map.
395///
396/// A JSON object of string values (Bedrock/MAI multi-field documents) parses
397/// into its fields. Anything else — a raw API key, or a legacy non-JSON
398/// credential — is treated as the `api_key` field, so existing single-key
399/// providers keep resolving without re-encryption.
400pub 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        // A JSON object that carried no string fields is not a credential
414        // document we understand; fall back to treating it as an opaque key.
415        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        // An empty value is not a value, so the alternate still wins.
482        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        // AWS_REGION alone is an everyday shell state and is not a credential.
499        // Returning just the region here would build a provider that fails at
500        // its first request instead of falling through to explicit config.
501        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        // Both required fields present: the optional region rides along.
527        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        // A half-populated OAuth block configures nothing.
545        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}