Skip to main content

gadk_session/toolauth/
credential.rs

1// Copyright 2026 Chris Olson
2// Portions derived from ADK-Go (https://github.com/google/adk-go), Copyright 2026 Google LLC.
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8//     http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! Credentials: HTTP, OAuth2 and service-account credentials and the [`Credential`] that wraps
17//! them.
18//!
19//! The credentials are adk-python's pydantic models: each field is written under its camelCase
20//! alias and read under the alias or its snake_case Python name, the alias winning when an object
21//! has both (the snake_case value is then dropped). Keys that match no field are kept in `extra`
22//! and written back after the fields. JSON types must match the fields exactly: `"3600"` is not
23//! an integer and `"true"` is not a bool. Errors never quote the rejected value.
24
25use std::borrow::Cow;
26use std::collections::BTreeMap;
27
28use serde::{Deserialize, Deserializer, Serialize, Serializer};
29use serde_json::value::RawValue;
30
31use super::Extra;
32use super::model_json::{
33    GoMarshal, GoUnmarshal, ObjectWriter, decode_object, deserialize_go, extra_eq, go_string,
34    go_string_list, go_string_map, serialize_go,
35};
36
37/// The kind of a credential, open like `SchemeType`; decode rejects anything but the five.
38#[derive(Debug, Clone, PartialEq, Eq, Hash)]
39pub struct CredentialType(Cow<'static, str>);
40
41impl CredentialType {
42    /// `"apiKey"`: an API key in [`Credential::api_key`].
43    pub const API_KEY: CredentialType = CredentialType(Cow::Borrowed("apiKey"));
44    /// `"http"`: HTTP authentication in [`Credential::http`].
45    pub const HTTP: CredentialType = CredentialType(Cow::Borrowed("http"));
46    /// `"oauth2"`: OAuth 2.0 in [`Credential::oauth2`].
47    pub const OAUTH2: CredentialType = CredentialType(Cow::Borrowed("oauth2"));
48    /// `"openIdConnect"`: OpenID Connect, carried in [`Credential::oauth2`].
49    pub const OPEN_ID_CONNECT: CredentialType = CredentialType(Cow::Borrowed("openIdConnect"));
50    /// `"serviceAccount"`: a Google service account in [`Credential::service_account`].
51    pub const SERVICE_ACCOUNT: CredentialType = CredentialType(Cow::Borrowed("serviceAccount"));
52
53    /// Wraps any string. Only the five constants decode inside a [`Credential`].
54    pub fn new(s: impl Into<Cow<'static, str>>) -> Self {
55        CredentialType(s.into())
56    }
57
58    /// The wire string, e.g. `"oauth2"`.
59    pub fn as_str(&self) -> &str {
60        &self.0
61    }
62}
63
64impl Default for CredentialType {
65    // "".
66    fn default() -> Self {
67        CredentialType(Cow::Borrowed(""))
68    }
69}
70
71impl From<&'static str> for CredentialType {
72    fn from(s: &'static str) -> Self {
73        CredentialType(Cow::Borrowed(s))
74    }
75}
76
77impl From<String> for CredentialType {
78    fn from(s: String) -> Self {
79        CredentialType(Cow::Owned(s))
80    }
81}
82
83/// A JSON string. Any string decodes; [`Credential`]'s decode
84/// is what rejects an unknown type.
85impl Serialize for CredentialType {
86    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
87        s.serialize_str(self.as_str())
88    }
89}
90
91impl<'de> Deserialize<'de> for CredentialType {
92    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
93        String::deserialize(d).map(CredentialType::from)
94    }
95}
96
97/// Writes `serde::Serialize` and `serde::Deserialize` for a model through its own encoder and
98/// decoder.
99macro_rules! go_serde {
100    ($($ty:ty),* $(,)?) => {$(
101        impl Serialize for $ty {
102            fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
103                serialize_go(self, s)
104            }
105        }
106
107        impl<'de> Deserialize<'de> for $ty {
108            fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
109                deserialize_go(d)
110            }
111        }
112    )*};
113}
114
115go_serde!(
116    HttpCredentials,
117    HttpAuth,
118    OAuth2Auth,
119    ServiceAccountCredential,
120    ServiceAccount,
121    Credential,
122);
123
124/// Writes each non-empty string field; empty ones are omitted.
125fn non_empty(w: &mut ObjectWriter, fields: &[(&str, &String)]) {
126    for (alias, value) in fields {
127        if !value.is_empty() {
128            w.field(alias, &go_string(value));
129        }
130    }
131}
132
133/// The secrets of an HTTP credential: a username and password for basic auth, or a token for
134/// bearer auth. Empty fields are omitted when written.
135#[derive(Clone, Default)]
136pub struct HttpCredentials {
137    /// `"username"`: the basic-auth user name.
138    pub username: String,
139    /// `"password"`: the basic-auth password.
140    pub password: String,
141    /// `"token"`: the bearer (or other scheme) token.
142    pub token: String,
143    /// Unknown keys, written back after the fields.
144    pub extra: Extra,
145}
146
147const HTTP_CREDENTIALS_FIELDS: &[&str] = &["username", "password", "token"];
148
149impl GoUnmarshal for HttpCredentials {
150    fn go_unmarshal(raw: &RawValue) -> Result<Self, String> {
151        const T: &str = "HttpCredentials";
152        let mut d = decode_object(raw, T, HTTP_CREDENTIALS_FIELDS, true, &[])?;
153        Ok(HttpCredentials {
154            username: d.take("username", T, "String")?.unwrap_or_default(),
155            password: d.take("password", T, "String")?.unwrap_or_default(),
156            token: d.take("token", T, "String")?.unwrap_or_default(),
157            extra: d.extra,
158        })
159    }
160}
161
162impl GoMarshal for HttpCredentials {
163    fn go_marshal(&self) -> String {
164        let mut w = ObjectWriter::new();
165        non_empty(
166            &mut w,
167            &[
168                ("username", &self.username),
169                ("password", &self.password),
170                ("token", &self.token),
171            ],
172        );
173        w.finish(&self.extra, HTTP_CREDENTIALS_FIELDS, true)
174    }
175}
176
177impl PartialEq for HttpCredentials {
178    fn eq(&self, other: &Self) -> bool {
179        self.username == other.username
180            && self.password == other.password
181            && self.token == other.token
182            && extra_eq(&self.extra, &other.extra)
183    }
184}
185
186/// An HTTP credential: the scheme (e.g. `basic`, `bearer`), its secrets and optional extra
187/// request headers.
188#[derive(Clone, Default)]
189pub struct HttpAuth {
190    /// Required on decode.
191    pub scheme: String,
192    /// Required on decode.
193    pub credentials: HttpCredentials,
194    /// "additionalHeaders", omitzero.
195    pub additional_headers: Option<BTreeMap<String, String>>,
196    /// Unknown keys, written back after the fields.
197    pub extra: Extra,
198}
199
200const HTTP_AUTH_FIELDS: &[&str] = &["scheme", "credentials", "additionalHeaders"];
201
202impl GoUnmarshal for HttpAuth {
203    /// Decodes an [`HttpAuth`]: scheme and credentials are required.
204    fn go_unmarshal(raw: &RawValue) -> Result<Self, String> {
205        const T: &str = "HttpAuth";
206        let mut d = decode_object(raw, T, HTTP_AUTH_FIELDS, true, &["scheme", "credentials"])?;
207        Ok(HttpAuth {
208            scheme: d.take("scheme", T, "String")?.unwrap_or_default(),
209            credentials: d
210                .take("credentials", T, "HttpCredentials")?
211                .unwrap_or_default(),
212            additional_headers: d.take_string_map("additionalHeaders", T)?,
213            extra: d.extra,
214        })
215    }
216}
217
218impl GoMarshal for HttpAuth {
219    /// Encodes an [`HttpAuth`]: credentials are written as `{}` even when empty.
220    fn go_marshal(&self) -> String {
221        let mut w = ObjectWriter::new();
222        w.field("scheme", &go_string(&self.scheme));
223        w.field("credentials", &self.credentials.go_marshal());
224        if let Some(headers) = &self.additional_headers {
225            w.field("additionalHeaders", &go_string_map(headers));
226        }
227        w.finish(&self.extra, HTTP_AUTH_FIELDS, true)
228    }
229}
230
231impl PartialEq for HttpAuth {
232    fn eq(&self, other: &Self) -> bool {
233        self.scheme == other.scheme
234            && self.credentials == other.credentials
235            && self.additional_headers == other.additional_headers
236            && extra_eq(&self.extra, &other.extra)
237    }
238}
239
240/// An OAuth 2.0 (or OpenID Connect) credential: the client registration, the state of an
241/// authorization-code exchange, and the tokens it produced. Empty strings and zero integers are
242/// omitted when written.
243#[derive(Clone, Default)]
244pub struct OAuth2Auth {
245    /// `"clientId"`: the OAuth client ID.
246    pub client_id: String,
247    /// `"clientSecret"`: the OAuth client secret.
248    pub client_secret: String,
249    /// `"authUri"`: the authorization URL the end user is sent to.
250    pub auth_uri: String,
251    /// `"nonce"`: the OpenID Connect nonce.
252    pub nonce: String,
253    /// `"state"`: the OAuth `state` parameter of the authorization request.
254    pub state: String,
255    /// `"redirectUri"`: the redirect URI registered for the client.
256    pub redirect_uri: String,
257    /// `"authResponseUri"`: the full redirect URL the client returned after consent.
258    pub auth_response_uri: String,
259    /// `"authCode"`: the authorization code.
260    pub auth_code: String,
261    /// `"accessToken"`: the access token.
262    pub access_token: String,
263    /// `"refreshToken"`: the refresh token.
264    pub refresh_token: String,
265    /// `"idToken"`: the OpenID Connect ID token.
266    pub id_token: String,
267    /// `"expiresAt"`: when the access token expires; omitted when 0.
268    pub expires_at: i64,
269    /// `"expiresIn"`: the access token lifetime as reported by the token endpoint; omitted when
270    /// 0.
271    pub expires_in: i64,
272    /// `"audience"`: the requested token audience.
273    pub audience: String,
274    /// `"prompt"`: the OAuth `prompt` parameter.
275    pub prompt: String,
276    /// `"codeVerifier"`: the PKCE code verifier.
277    pub code_verifier: String,
278    /// `"codeChallengeMethod"`: the PKCE code challenge method.
279    pub code_challenge_method: String,
280    /// Written as "client_secret_basic" when empty.
281    pub token_endpoint_auth_method: String,
282    /// Unknown keys, written back after the fields.
283    pub extra: Extra,
284}
285
286const OAUTH2_AUTH_FIELDS: &[&str] = &[
287    "clientId",
288    "clientSecret",
289    "authUri",
290    "nonce",
291    "state",
292    "redirectUri",
293    "authResponseUri",
294    "authCode",
295    "accessToken",
296    "refreshToken",
297    "idToken",
298    "expiresAt",
299    "expiresIn",
300    "audience",
301    "prompt",
302    "codeVerifier",
303    "codeChallengeMethod",
304    "tokenEndpointAuthMethod",
305];
306
307impl GoUnmarshal for OAuth2Auth {
308    /// Decodes an [`OAuth2Auth`]: rejects a token endpoint auth method other than
309    /// client_secret_basic, client_secret_post, client_secret_jwt and private_key_jwt.
310    fn go_unmarshal(raw: &RawValue) -> Result<Self, String> {
311        const T: &str = "OAuth2Auth";
312        let mut d = decode_object(raw, T, OAUTH2_AUTH_FIELDS, true, &[])?;
313        let mut s = |alias: &str| -> Result<String, String> {
314            Ok(d.take(alias, T, "String")?.unwrap_or_default())
315        };
316        let client_id = s("clientId")?;
317        let client_secret = s("clientSecret")?;
318        let auth_uri = s("authUri")?;
319        let nonce = s("nonce")?;
320        let state = s("state")?;
321        let redirect_uri = s("redirectUri")?;
322        let auth_response_uri = s("authResponseUri")?;
323        let auth_code = s("authCode")?;
324        let access_token = s("accessToken")?;
325        let refresh_token = s("refreshToken")?;
326        let id_token = s("idToken")?;
327        let expires_at = d.take_i64("expiresAt", T)?.unwrap_or_default();
328        let expires_in = d.take_i64("expiresIn", T)?.unwrap_or_default();
329        let mut s = |alias: &str| -> Result<String, String> {
330            Ok(d.take(alias, T, "String")?.unwrap_or_default())
331        };
332        let audience = s("audience")?;
333        let prompt = s("prompt")?;
334        let code_verifier = s("codeVerifier")?;
335        let code_challenge_method = s("codeChallengeMethod")?;
336        let token_endpoint_auth_method = s("tokenEndpointAuthMethod")?;
337        match token_endpoint_auth_method.as_str() {
338            ""
339            | "client_secret_basic"
340            | "client_secret_post"
341            | "client_secret_jwt"
342            | "private_key_jwt" => {}
343            _ => return Err("toolauth: OAuth2Auth: unsupported tokenEndpointAuthMethod".to_owned()),
344        }
345        Ok(OAuth2Auth {
346            client_id,
347            client_secret,
348            auth_uri,
349            nonce,
350            state,
351            redirect_uri,
352            auth_response_uri,
353            auth_code,
354            access_token,
355            refresh_token,
356            id_token,
357            expires_at,
358            expires_in,
359            audience,
360            prompt,
361            code_verifier,
362            code_challenge_method,
363            token_endpoint_auth_method,
364            extra: d.extra,
365        })
366    }
367}
368
369impl GoMarshal for OAuth2Auth {
370    /// Encodes an [`OAuth2Auth`]: an empty token endpoint auth method is written as
371    /// client_secret_basic, which is what adk-python sends.
372    fn go_marshal(&self) -> String {
373        let mut w = ObjectWriter::new();
374        non_empty(
375            &mut w,
376            &[
377                ("clientId", &self.client_id),
378                ("clientSecret", &self.client_secret),
379                ("authUri", &self.auth_uri),
380                ("nonce", &self.nonce),
381                ("state", &self.state),
382                ("redirectUri", &self.redirect_uri),
383                ("authResponseUri", &self.auth_response_uri),
384                ("authCode", &self.auth_code),
385                ("accessToken", &self.access_token),
386                ("refreshToken", &self.refresh_token),
387                ("idToken", &self.id_token),
388            ],
389        );
390        if self.expires_at != 0 {
391            w.field("expiresAt", &self.expires_at.to_string());
392        }
393        if self.expires_in != 0 {
394            w.field("expiresIn", &self.expires_in.to_string());
395        }
396        non_empty(
397            &mut w,
398            &[
399                ("audience", &self.audience),
400                ("prompt", &self.prompt),
401                ("codeVerifier", &self.code_verifier),
402                ("codeChallengeMethod", &self.code_challenge_method),
403            ],
404        );
405        let method = if self.token_endpoint_auth_method.is_empty() {
406            "client_secret_basic"
407        } else {
408            &self.token_endpoint_auth_method
409        };
410        w.field("tokenEndpointAuthMethod", &go_string(method));
411        w.finish(&self.extra, OAUTH2_AUTH_FIELDS, true)
412    }
413}
414
415impl PartialEq for OAuth2Auth {
416    fn eq(&self, other: &Self) -> bool {
417        self.client_id == other.client_id
418            && self.client_secret == other.client_secret
419            && self.auth_uri == other.auth_uri
420            && self.nonce == other.nonce
421            && self.state == other.state
422            && self.redirect_uri == other.redirect_uri
423            && self.auth_response_uri == other.auth_response_uri
424            && self.auth_code == other.auth_code
425            && self.access_token == other.access_token
426            && self.refresh_token == other.refresh_token
427            && self.id_token == other.id_token
428            && self.expires_at == other.expires_at
429            && self.expires_in == other.expires_in
430            && self.audience == other.audience
431            && self.prompt == other.prompt
432            && self.code_verifier == other.code_verifier
433            && self.code_challenge_method == other.code_challenge_method
434            && self.token_endpoint_auth_method == other.token_endpoint_auth_method
435            && extra_eq(&self.extra, &other.extra)
436    }
437}
438
439/// A Google service-account key, as in a downloaded JSON key file. Decoding requires every field
440/// but `type`; every field is written, even when empty.
441#[derive(Clone, Default)]
442pub struct ServiceAccountCredential {
443    /// `"type"`: the key type, normally `service_account`.
444    pub r#type: String,
445    /// `"projectId"`: the Google Cloud project ID.
446    pub project_id: String,
447    /// `"privateKeyId"`: the ID of the private key.
448    pub private_key_id: String,
449    /// `"privateKey"`: the PEM-encoded private key.
450    pub private_key: String,
451    /// `"clientEmail"`: the service account's email address.
452    pub client_email: String,
453    /// `"clientId"`: the service account's client ID.
454    pub client_id: String,
455    /// `"authUri"`: the OAuth authorization endpoint.
456    pub auth_uri: String,
457    /// `"tokenUri"`: the OAuth token endpoint.
458    pub token_uri: String,
459    /// `"authProviderX509CertUrl"`: the URL of the auth provider's X.509 certificates.
460    pub auth_provider_x509_cert_url: String,
461    /// `"clientX509CertUrl"`: the URL of the service account's X.509 certificate.
462    pub client_x509_cert_url: String,
463    /// `"universeDomain"`: the Google Cloud universe domain.
464    pub universe_domain: String,
465    /// Unknown keys, written back after the fields.
466    pub extra: Extra,
467}
468
469const SERVICE_ACCOUNT_CREDENTIAL_FIELDS: &[&str] = &[
470    "type",
471    "projectId",
472    "privateKeyId",
473    "privateKey",
474    "clientEmail",
475    "clientId",
476    "authUri",
477    "tokenUri",
478    "authProviderX509CertUrl",
479    "clientX509CertUrl",
480    "universeDomain",
481];
482
483impl GoUnmarshal for ServiceAccountCredential {
484    /// Decodes a [`ServiceAccountCredential`]: reads a key file too, whose names are
485    /// snake_case. Every field but type is required.
486    fn go_unmarshal(raw: &RawValue) -> Result<Self, String> {
487        const T: &str = "ServiceAccountCredential";
488        let mut d = decode_object(
489            raw,
490            T,
491            SERVICE_ACCOUNT_CREDENTIAL_FIELDS,
492            true,
493            &SERVICE_ACCOUNT_CREDENTIAL_FIELDS[1..],
494        )?;
495        let mut s = |alias: &str| -> Result<String, String> {
496            Ok(d.take(alias, T, "String")?.unwrap_or_default())
497        };
498        Ok(ServiceAccountCredential {
499            r#type: s("type")?,
500            project_id: s("projectId")?,
501            private_key_id: s("privateKeyId")?,
502            private_key: s("privateKey")?,
503            client_email: s("clientEmail")?,
504            client_id: s("clientId")?,
505            auth_uri: s("authUri")?,
506            token_uri: s("tokenUri")?,
507            auth_provider_x509_cert_url: s("authProviderX509CertUrl")?,
508            client_x509_cert_url: s("clientX509CertUrl")?,
509            universe_domain: s("universeDomain")?,
510            extra: d.extra,
511        })
512    }
513}
514
515impl GoMarshal for ServiceAccountCredential {
516    /// Encodes a [`ServiceAccountCredential`]: every field is written, even when empty.
517    fn go_marshal(&self) -> String {
518        let mut w = ObjectWriter::new();
519        let fields = [
520            ("type", &self.r#type),
521            ("projectId", &self.project_id),
522            ("privateKeyId", &self.private_key_id),
523            ("privateKey", &self.private_key),
524            ("clientEmail", &self.client_email),
525            ("clientId", &self.client_id),
526            ("authUri", &self.auth_uri),
527            ("tokenUri", &self.token_uri),
528            ("authProviderX509CertUrl", &self.auth_provider_x509_cert_url),
529            ("clientX509CertUrl", &self.client_x509_cert_url),
530            ("universeDomain", &self.universe_domain),
531        ];
532        for (alias, value) in fields {
533            w.field(alias, &go_string(value));
534        }
535        w.finish(&self.extra, SERVICE_ACCOUNT_CREDENTIAL_FIELDS, true)
536    }
537}
538
539impl PartialEq for ServiceAccountCredential {
540    fn eq(&self, other: &Self) -> bool {
541        self.r#type == other.r#type
542            && self.project_id == other.project_id
543            && self.private_key_id == other.private_key_id
544            && self.private_key == other.private_key
545            && self.client_email == other.client_email
546            && self.client_id == other.client_id
547            && self.auth_uri == other.auth_uri
548            && self.token_uri == other.token_uri
549            && self.auth_provider_x509_cert_url == other.auth_provider_x509_cert_url
550            && self.client_x509_cert_url == other.client_x509_cert_url
551            && self.universe_domain == other.universe_domain
552            && extra_eq(&self.extra, &other.extra)
553    }
554}
555
556/// A service-account credential: either an explicit key or Application Default Credentials, with
557/// the scopes to request or, for an ID token, its audience. Decoding rejects a value with neither
558/// a key nor `useDefaultCredential`, and `useIdToken` without an audience.
559#[derive(Clone, Default)]
560pub struct ServiceAccount {
561    /// `"serviceAccountCredential"`: the key; required unless
562    /// [`use_default_credential`](Self::use_default_credential) is set.
563    pub service_account_credential: Option<ServiceAccountCredential>,
564    /// omitzero.
565    pub scopes: Option<Vec<String>>,
566    /// Always written.
567    pub use_default_credential: bool,
568    /// Always written.
569    pub use_id_token: bool,
570    /// `"audience"`: the ID token audience; required with
571    /// [`use_id_token`](Self::use_id_token).
572    pub audience: String,
573    /// Unknown keys, written back after the fields.
574    pub extra: Extra,
575}
576
577const SERVICE_ACCOUNT_FIELDS: &[&str] = &[
578    "serviceAccountCredential",
579    "scopes",
580    "useDefaultCredential",
581    "useIdToken",
582    "audience",
583];
584
585impl GoUnmarshal for ServiceAccount {
586    /// Decodes a [`ServiceAccount`]: rejects neither a key nor ADC, and an ID token without
587    /// an audience.
588    fn go_unmarshal(raw: &RawValue) -> Result<Self, String> {
589        const T: &str = "ServiceAccount";
590        let mut d = decode_object(raw, T, SERVICE_ACCOUNT_FIELDS, true, &[])?;
591        let sa = ServiceAccount {
592            service_account_credential: d.take(
593                "serviceAccountCredential",
594                T,
595                "ServiceAccountCredential",
596            )?,
597            scopes: d.take_string_list("scopes", T)?,
598            use_default_credential: d
599                .take("useDefaultCredential", T, "bool")?
600                .unwrap_or_default(),
601            use_id_token: d.take("useIdToken", T, "bool")?.unwrap_or_default(),
602            audience: d.take("audience", T, "String")?.unwrap_or_default(),
603            extra: d.extra,
604        };
605        if !sa.use_default_credential && sa.service_account_credential.is_none() {
606            return Err("toolauth: ServiceAccount: serviceAccountCredential is required unless useDefaultCredential is set".to_owned());
607        }
608        if sa.use_id_token && sa.audience.is_empty() {
609            return Err(
610                "toolauth: ServiceAccount: audience is required with useIdToken".to_owned(),
611            );
612        }
613        Ok(sa)
614    }
615}
616
617impl GoMarshal for ServiceAccount {
618    fn go_marshal(&self) -> String {
619        let mut w = ObjectWriter::new();
620        if let Some(key) = &self.service_account_credential {
621            w.field("serviceAccountCredential", &key.go_marshal());
622        }
623        if let Some(scopes) = &self.scopes {
624            w.field("scopes", &go_string_list(scopes));
625        }
626        w.field("useDefaultCredential", go_bool(self.use_default_credential));
627        w.field("useIdToken", go_bool(self.use_id_token));
628        non_empty(&mut w, &[("audience", &self.audience)]);
629        w.finish(&self.extra, SERVICE_ACCOUNT_FIELDS, true)
630    }
631}
632
633fn go_bool(b: bool) -> &'static str {
634    if b { "true" } else { "false" }
635}
636
637impl PartialEq for ServiceAccount {
638    fn eq(&self, other: &Self) -> bool {
639        self.service_account_credential == other.service_account_credential
640            && self.scopes == other.scopes
641            && self.use_default_credential == other.use_default_credential
642            && self.use_id_token == other.use_id_token
643            && self.audience == other.audience
644            && extra_eq(&self.extra, &other.extra)
645    }
646}
647
648/// A credential: its [`CredentialType`] and the matching payload. Decoding rejects a missing or
649/// unknown auth type and an invalid payload in any field; it does not check that the payload
650/// matches the type.
651#[derive(Clone, Default)]
652pub struct Credential {
653    /// `"authType"`: the credential kind. Required on decode.
654    pub auth_type: CredentialType,
655    /// `"resourceRef"`: a reference to the resource the credential is for; omitted when empty.
656    pub resource_ref: String,
657    /// `"apiKey"`: the API key, for [`CredentialType::API_KEY`]; omitted when empty.
658    pub api_key: String,
659    /// `"http"`: the HTTP credential, for [`CredentialType::HTTP`].
660    pub http: Option<HttpAuth>,
661    /// `"serviceAccount"`: the service account, for [`CredentialType::SERVICE_ACCOUNT`].
662    pub service_account: Option<ServiceAccount>,
663    /// `"oauth2"`: the OAuth 2.0 credential, for [`CredentialType::OAUTH2`] and
664    /// [`CredentialType::OPEN_ID_CONNECT`].
665    pub oauth2: Option<OAuth2Auth>,
666    /// Unknown keys, written back after the fields.
667    pub extra: Extra,
668}
669
670const CREDENTIAL_FIELDS: &[&str] = &[
671    "authType",
672    "resourceRef",
673    "apiKey",
674    "http",
675    "serviceAccount",
676    "oauth2",
677];
678
679impl GoUnmarshal for Credential {
680    /// Decodes a [`Credential`]: rejects a missing or unknown auth type and an invalid
681    /// credential in any field.
682    fn go_unmarshal(raw: &RawValue) -> Result<Self, String> {
683        const T: &str = "Credential";
684        let mut d = decode_object(raw, T, CREDENTIAL_FIELDS, true, &["authType"])?;
685        let c = Credential {
686            auth_type: d.take("authType", T, "CredentialType")?.unwrap_or_default(),
687            resource_ref: d.take("resourceRef", T, "String")?.unwrap_or_default(),
688            api_key: d.take("apiKey", T, "String")?.unwrap_or_default(),
689            http: d.take("http", T, "HttpAuth")?,
690            service_account: d.take("serviceAccount", T, "ServiceAccount")?,
691            oauth2: d.take("oauth2", T, "OAuth2Auth")?,
692            extra: d.extra,
693        };
694        let known = [
695            CredentialType::API_KEY,
696            CredentialType::HTTP,
697            CredentialType::OAUTH2,
698            CredentialType::OPEN_ID_CONNECT,
699            CredentialType::SERVICE_ACCOUNT,
700        ];
701        if !known.contains(&c.auth_type) {
702            return Err("toolauth: Credential: unknown authType".to_owned());
703        }
704        Ok(c)
705    }
706}
707
708impl GoMarshal for Credential {
709    fn go_marshal(&self) -> String {
710        let mut w = ObjectWriter::new();
711        w.field("authType", &go_string(self.auth_type.as_str()));
712        non_empty(
713            &mut w,
714            &[
715                ("resourceRef", &self.resource_ref),
716                ("apiKey", &self.api_key),
717            ],
718        );
719        if let Some(http) = &self.http {
720            w.field("http", &http.go_marshal());
721        }
722        if let Some(sa) = &self.service_account {
723            w.field("serviceAccount", &sa.go_marshal());
724        }
725        if let Some(oauth2) = &self.oauth2 {
726            w.field("oauth2", &oauth2.go_marshal());
727        }
728        w.finish(&self.extra, CREDENTIAL_FIELDS, true)
729    }
730}
731
732impl PartialEq for Credential {
733    fn eq(&self, other: &Self) -> bool {
734        self.auth_type == other.auth_type
735            && self.resource_ref == other.resource_ref
736            && self.api_key == other.api_key
737            && self.http == other.http
738            && self.service_account == other.service_account
739            && self.oauth2 == other.oauth2
740            && extra_eq(&self.extra, &other.extra)
741    }
742}