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_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        // AWS_REGION alone is an everyday shell state and is not a credential.
512        // Returning just the region here would build a provider that fails at
513        // its first request instead of falling through to explicit config.
514        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        // Both required fields present: the optional region rides along.
540        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        // A half-populated OAuth block configures nothing.
558        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}