gadk-session 0.2.1

Sessions, events and the in-memory session service for gadk
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
// Copyright 2026 Chris Olson
// Portions derived from ADK-Go (https://github.com/google/adk-go), Copyright 2026 Google LLC.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Credentials: HTTP, OAuth2 and service-account credentials and the [`Credential`] that wraps
//! them.
//!
//! The credentials are adk-python's pydantic models: each field is written under its camelCase
//! alias and read under the alias or its snake_case Python name, the alias winning when an object
//! has both (the snake_case value is then dropped). Keys that match no field are kept in `extra`
//! and written back after the fields. JSON types must match the fields exactly: `"3600"` is not
//! an integer and `"true"` is not a bool. Errors never quote the rejected value.

use std::borrow::Cow;
use std::collections::BTreeMap;

use serde::{Deserialize, Deserializer, Serialize, Serializer};
use serde_json::value::RawValue;

use super::Extra;
use super::model_json::{
    GoMarshal, GoUnmarshal, ObjectWriter, decode_object, deserialize_go, extra_eq, go_string,
    go_string_list, go_string_map, serialize_go,
};

/// The kind of a credential, open like `SchemeType`; decode rejects anything but the five.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CredentialType(Cow<'static, str>);

impl CredentialType {
    pub const API_KEY: CredentialType = CredentialType(Cow::Borrowed("apiKey"));
    pub const HTTP: CredentialType = CredentialType(Cow::Borrowed("http"));
    pub const OAUTH2: CredentialType = CredentialType(Cow::Borrowed("oauth2"));
    pub const OPEN_ID_CONNECT: CredentialType = CredentialType(Cow::Borrowed("openIdConnect"));
    pub const SERVICE_ACCOUNT: CredentialType = CredentialType(Cow::Borrowed("serviceAccount"));

    pub fn new(s: impl Into<Cow<'static, str>>) -> Self {
        CredentialType(s.into())
    }

    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl Default for CredentialType {
    // "".
    fn default() -> Self {
        CredentialType(Cow::Borrowed(""))
    }
}

impl From<&'static str> for CredentialType {
    fn from(s: &'static str) -> Self {
        CredentialType(Cow::Borrowed(s))
    }
}

impl From<String> for CredentialType {
    fn from(s: String) -> Self {
        CredentialType(Cow::Owned(s))
    }
}

/// A JSON string. Any string decodes; [`Credential`]'s decode
/// is what rejects an unknown type.
impl Serialize for CredentialType {
    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
        s.serialize_str(self.as_str())
    }
}

impl<'de> Deserialize<'de> for CredentialType {
    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
        String::deserialize(d).map(CredentialType::from)
    }
}

/// Writes `serde::Serialize` and `serde::Deserialize` for a model through its own encoder and
/// decoder.
macro_rules! go_serde {
    ($($ty:ty),* $(,)?) => {$(
        impl Serialize for $ty {
            fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
                serialize_go(self, s)
            }
        }

        impl<'de> Deserialize<'de> for $ty {
            fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
                deserialize_go(d)
            }
        }
    )*};
}

go_serde!(
    HttpCredentials,
    HttpAuth,
    OAuth2Auth,
    ServiceAccountCredential,
    ServiceAccount,
    Credential,
);

/// Writes each non-empty string field; empty ones are omitted.
fn non_empty(w: &mut ObjectWriter, fields: &[(&str, &String)]) {
    for (alias, value) in fields {
        if !value.is_empty() {
            w.field(alias, &go_string(value));
        }
    }
}

#[derive(Clone, Default)]
pub struct HttpCredentials {
    pub username: String,
    pub password: String,
    pub token: String,
    pub extra: Extra,
}

const HTTP_CREDENTIALS_FIELDS: &[&str] = &["username", "password", "token"];

impl GoUnmarshal for HttpCredentials {
    fn go_unmarshal(raw: &RawValue) -> Result<Self, String> {
        const T: &str = "HTTPCredentials";
        let mut d = decode_object(raw, T, HTTP_CREDENTIALS_FIELDS, true, &[])?;
        Ok(HttpCredentials {
            username: d.take("username", T, "string")?.unwrap_or_default(),
            password: d.take("password", T, "string")?.unwrap_or_default(),
            token: d.take("token", T, "string")?.unwrap_or_default(),
            extra: d.extra,
        })
    }
}

impl GoMarshal for HttpCredentials {
    fn go_marshal(&self) -> String {
        let mut w = ObjectWriter::new();
        non_empty(
            &mut w,
            &[
                ("username", &self.username),
                ("password", &self.password),
                ("token", &self.token),
            ],
        );
        w.finish(&self.extra, HTTP_CREDENTIALS_FIELDS, true)
    }
}

impl PartialEq for HttpCredentials {
    fn eq(&self, other: &Self) -> bool {
        self.username == other.username
            && self.password == other.password
            && self.token == other.token
            && extra_eq(&self.extra, &other.extra)
    }
}

#[derive(Clone, Default)]
pub struct HttpAuth {
    /// Required on decode.
    pub scheme: String,
    /// Required on decode.
    pub credentials: HttpCredentials,
    /// "additionalHeaders", omitzero.
    pub additional_headers: Option<BTreeMap<String, String>>,
    pub extra: Extra,
}

const HTTP_AUTH_FIELDS: &[&str] = &["scheme", "credentials", "additionalHeaders"];

impl GoUnmarshal for HttpAuth {
    /// Decodes an [`HttpAuth`]: scheme and credentials are required.
    fn go_unmarshal(raw: &RawValue) -> Result<Self, String> {
        const T: &str = "HTTPAuth";
        let mut d = decode_object(raw, T, HTTP_AUTH_FIELDS, true, &["scheme", "credentials"])?;
        Ok(HttpAuth {
            scheme: d.take("scheme", T, "string")?.unwrap_or_default(),
            credentials: d
                .take("credentials", T, "toolauth.HTTPCredentials")?
                .unwrap_or_default(),
            additional_headers: d.take_string_map("additionalHeaders", T)?,
            extra: d.extra,
        })
    }
}

impl GoMarshal for HttpAuth {
    /// Encodes an [`HttpAuth`]: credentials are written as `{}` even when empty.
    fn go_marshal(&self) -> String {
        let mut w = ObjectWriter::new();
        w.field("scheme", &go_string(&self.scheme));
        w.field("credentials", &self.credentials.go_marshal());
        if let Some(headers) = &self.additional_headers {
            w.field("additionalHeaders", &go_string_map(headers));
        }
        w.finish(&self.extra, HTTP_AUTH_FIELDS, true)
    }
}

impl PartialEq for HttpAuth {
    fn eq(&self, other: &Self) -> bool {
        self.scheme == other.scheme
            && self.credentials == other.credentials
            && self.additional_headers == other.additional_headers
            && extra_eq(&self.extra, &other.extra)
    }
}

#[derive(Clone, Default)]
pub struct OAuth2Auth {
    pub client_id: String,
    pub client_secret: String,
    pub auth_uri: String,
    pub nonce: String,
    pub state: String,
    pub redirect_uri: String,
    pub auth_response_uri: String,
    pub auth_code: String,
    pub access_token: String,
    pub refresh_token: String,
    pub id_token: String,
    pub expires_at: i64,
    pub expires_in: i64,
    pub audience: String,
    pub prompt: String,
    pub code_verifier: String,
    pub code_challenge_method: String,
    /// Written as "client_secret_basic" when empty.
    pub token_endpoint_auth_method: String,
    pub extra: Extra,
}

const OAUTH2_AUTH_FIELDS: &[&str] = &[
    "clientId",
    "clientSecret",
    "authUri",
    "nonce",
    "state",
    "redirectUri",
    "authResponseUri",
    "authCode",
    "accessToken",
    "refreshToken",
    "idToken",
    "expiresAt",
    "expiresIn",
    "audience",
    "prompt",
    "codeVerifier",
    "codeChallengeMethod",
    "tokenEndpointAuthMethod",
];

impl GoUnmarshal for OAuth2Auth {
    /// Decodes an [`OAuth2Auth`]: rejects a token endpoint auth method other than
    /// client_secret_basic, client_secret_post, client_secret_jwt and private_key_jwt.
    fn go_unmarshal(raw: &RawValue) -> Result<Self, String> {
        const T: &str = "OAuth2Auth";
        let mut d = decode_object(raw, T, OAUTH2_AUTH_FIELDS, true, &[])?;
        let mut s = |alias: &str| -> Result<String, String> {
            Ok(d.take(alias, T, "string")?.unwrap_or_default())
        };
        let client_id = s("clientId")?;
        let client_secret = s("clientSecret")?;
        let auth_uri = s("authUri")?;
        let nonce = s("nonce")?;
        let state = s("state")?;
        let redirect_uri = s("redirectUri")?;
        let auth_response_uri = s("authResponseUri")?;
        let auth_code = s("authCode")?;
        let access_token = s("accessToken")?;
        let refresh_token = s("refreshToken")?;
        let id_token = s("idToken")?;
        let expires_at = d.take_i64("expiresAt", T)?.unwrap_or_default();
        let expires_in = d.take_i64("expiresIn", T)?.unwrap_or_default();
        let mut s = |alias: &str| -> Result<String, String> {
            Ok(d.take(alias, T, "string")?.unwrap_or_default())
        };
        let audience = s("audience")?;
        let prompt = s("prompt")?;
        let code_verifier = s("codeVerifier")?;
        let code_challenge_method = s("codeChallengeMethod")?;
        let token_endpoint_auth_method = s("tokenEndpointAuthMethod")?;
        match token_endpoint_auth_method.as_str() {
            ""
            | "client_secret_basic"
            | "client_secret_post"
            | "client_secret_jwt"
            | "private_key_jwt" => {}
            _ => return Err("toolauth: OAuth2Auth: unsupported tokenEndpointAuthMethod".to_owned()),
        }
        Ok(OAuth2Auth {
            client_id,
            client_secret,
            auth_uri,
            nonce,
            state,
            redirect_uri,
            auth_response_uri,
            auth_code,
            access_token,
            refresh_token,
            id_token,
            expires_at,
            expires_in,
            audience,
            prompt,
            code_verifier,
            code_challenge_method,
            token_endpoint_auth_method,
            extra: d.extra,
        })
    }
}

impl GoMarshal for OAuth2Auth {
    /// Encodes an [`OAuth2Auth`]: an empty token endpoint auth method is written as
    /// client_secret_basic, which is what adk-python sends.
    fn go_marshal(&self) -> String {
        let mut w = ObjectWriter::new();
        non_empty(
            &mut w,
            &[
                ("clientId", &self.client_id),
                ("clientSecret", &self.client_secret),
                ("authUri", &self.auth_uri),
                ("nonce", &self.nonce),
                ("state", &self.state),
                ("redirectUri", &self.redirect_uri),
                ("authResponseUri", &self.auth_response_uri),
                ("authCode", &self.auth_code),
                ("accessToken", &self.access_token),
                ("refreshToken", &self.refresh_token),
                ("idToken", &self.id_token),
            ],
        );
        if self.expires_at != 0 {
            w.field("expiresAt", &self.expires_at.to_string());
        }
        if self.expires_in != 0 {
            w.field("expiresIn", &self.expires_in.to_string());
        }
        non_empty(
            &mut w,
            &[
                ("audience", &self.audience),
                ("prompt", &self.prompt),
                ("codeVerifier", &self.code_verifier),
                ("codeChallengeMethod", &self.code_challenge_method),
            ],
        );
        let method = if self.token_endpoint_auth_method.is_empty() {
            "client_secret_basic"
        } else {
            &self.token_endpoint_auth_method
        };
        w.field("tokenEndpointAuthMethod", &go_string(method));
        w.finish(&self.extra, OAUTH2_AUTH_FIELDS, true)
    }
}

impl PartialEq for OAuth2Auth {
    fn eq(&self, other: &Self) -> bool {
        self.client_id == other.client_id
            && self.client_secret == other.client_secret
            && self.auth_uri == other.auth_uri
            && self.nonce == other.nonce
            && self.state == other.state
            && self.redirect_uri == other.redirect_uri
            && self.auth_response_uri == other.auth_response_uri
            && self.auth_code == other.auth_code
            && self.access_token == other.access_token
            && self.refresh_token == other.refresh_token
            && self.id_token == other.id_token
            && self.expires_at == other.expires_at
            && self.expires_in == other.expires_in
            && self.audience == other.audience
            && self.prompt == other.prompt
            && self.code_verifier == other.code_verifier
            && self.code_challenge_method == other.code_challenge_method
            && self.token_endpoint_auth_method == other.token_endpoint_auth_method
            && extra_eq(&self.extra, &other.extra)
    }
}

#[derive(Clone, Default)]
pub struct ServiceAccountCredential {
    pub r#type: String,
    pub project_id: String,
    pub private_key_id: String,
    pub private_key: String,
    pub client_email: String,
    pub client_id: String,
    pub auth_uri: String,
    pub token_uri: String,
    pub auth_provider_x509_cert_url: String,
    pub client_x509_cert_url: String,
    pub universe_domain: String,
    pub extra: Extra,
}

const SERVICE_ACCOUNT_CREDENTIAL_FIELDS: &[&str] = &[
    "type",
    "projectId",
    "privateKeyId",
    "privateKey",
    "clientEmail",
    "clientId",
    "authUri",
    "tokenUri",
    "authProviderX509CertUrl",
    "clientX509CertUrl",
    "universeDomain",
];

impl GoUnmarshal for ServiceAccountCredential {
    /// Decodes a [`ServiceAccountCredential`]: reads a key file too, whose names are
    /// snake_case. Every field but type is required.
    fn go_unmarshal(raw: &RawValue) -> Result<Self, String> {
        const T: &str = "ServiceAccountCredential";
        let mut d = decode_object(
            raw,
            T,
            SERVICE_ACCOUNT_CREDENTIAL_FIELDS,
            true,
            &SERVICE_ACCOUNT_CREDENTIAL_FIELDS[1..],
        )?;
        let mut s = |alias: &str| -> Result<String, String> {
            Ok(d.take(alias, T, "string")?.unwrap_or_default())
        };
        Ok(ServiceAccountCredential {
            r#type: s("type")?,
            project_id: s("projectId")?,
            private_key_id: s("privateKeyId")?,
            private_key: s("privateKey")?,
            client_email: s("clientEmail")?,
            client_id: s("clientId")?,
            auth_uri: s("authUri")?,
            token_uri: s("tokenUri")?,
            auth_provider_x509_cert_url: s("authProviderX509CertUrl")?,
            client_x509_cert_url: s("clientX509CertUrl")?,
            universe_domain: s("universeDomain")?,
            extra: d.extra,
        })
    }
}

impl GoMarshal for ServiceAccountCredential {
    /// Encodes a [`ServiceAccountCredential`]: every field is written, even when empty.
    fn go_marshal(&self) -> String {
        let mut w = ObjectWriter::new();
        let fields = [
            ("type", &self.r#type),
            ("projectId", &self.project_id),
            ("privateKeyId", &self.private_key_id),
            ("privateKey", &self.private_key),
            ("clientEmail", &self.client_email),
            ("clientId", &self.client_id),
            ("authUri", &self.auth_uri),
            ("tokenUri", &self.token_uri),
            ("authProviderX509CertUrl", &self.auth_provider_x509_cert_url),
            ("clientX509CertUrl", &self.client_x509_cert_url),
            ("universeDomain", &self.universe_domain),
        ];
        for (alias, value) in fields {
            w.field(alias, &go_string(value));
        }
        w.finish(&self.extra, SERVICE_ACCOUNT_CREDENTIAL_FIELDS, true)
    }
}

impl PartialEq for ServiceAccountCredential {
    fn eq(&self, other: &Self) -> bool {
        self.r#type == other.r#type
            && self.project_id == other.project_id
            && self.private_key_id == other.private_key_id
            && self.private_key == other.private_key
            && self.client_email == other.client_email
            && self.client_id == other.client_id
            && self.auth_uri == other.auth_uri
            && self.token_uri == other.token_uri
            && self.auth_provider_x509_cert_url == other.auth_provider_x509_cert_url
            && self.client_x509_cert_url == other.client_x509_cert_url
            && self.universe_domain == other.universe_domain
            && extra_eq(&self.extra, &other.extra)
    }
}

#[derive(Clone, Default)]
pub struct ServiceAccount {
    pub service_account_credential: Option<ServiceAccountCredential>,
    /// omitzero.
    pub scopes: Option<Vec<String>>,
    /// Always written.
    pub use_default_credential: bool,
    /// Always written.
    pub use_id_token: bool,
    pub audience: String,
    pub extra: Extra,
}

const SERVICE_ACCOUNT_FIELDS: &[&str] = &[
    "serviceAccountCredential",
    "scopes",
    "useDefaultCredential",
    "useIdToken",
    "audience",
];

impl GoUnmarshal for ServiceAccount {
    /// Decodes a [`ServiceAccount`]: rejects neither a key nor ADC, and an ID token without
    /// an audience.
    fn go_unmarshal(raw: &RawValue) -> Result<Self, String> {
        const T: &str = "ServiceAccount";
        let mut d = decode_object(raw, T, SERVICE_ACCOUNT_FIELDS, true, &[])?;
        let sa = ServiceAccount {
            service_account_credential: d.take(
                "serviceAccountCredential",
                T,
                "*toolauth.ServiceAccountCredential",
            )?,
            scopes: d.take_string_list("scopes", T)?,
            use_default_credential: d
                .take("useDefaultCredential", T, "bool")?
                .unwrap_or_default(),
            use_id_token: d.take("useIdToken", T, "bool")?.unwrap_or_default(),
            audience: d.take("audience", T, "string")?.unwrap_or_default(),
            extra: d.extra,
        };
        if !sa.use_default_credential && sa.service_account_credential.is_none() {
            return Err("toolauth: ServiceAccount: serviceAccountCredential is required unless useDefaultCredential is set".to_owned());
        }
        if sa.use_id_token && sa.audience.is_empty() {
            return Err(
                "toolauth: ServiceAccount: audience is required with useIdToken".to_owned(),
            );
        }
        Ok(sa)
    }
}

impl GoMarshal for ServiceAccount {
    fn go_marshal(&self) -> String {
        let mut w = ObjectWriter::new();
        if let Some(key) = &self.service_account_credential {
            w.field("serviceAccountCredential", &key.go_marshal());
        }
        if let Some(scopes) = &self.scopes {
            w.field("scopes", &go_string_list(scopes));
        }
        w.field("useDefaultCredential", go_bool(self.use_default_credential));
        w.field("useIdToken", go_bool(self.use_id_token));
        non_empty(&mut w, &[("audience", &self.audience)]);
        w.finish(&self.extra, SERVICE_ACCOUNT_FIELDS, true)
    }
}

fn go_bool(b: bool) -> &'static str {
    if b { "true" } else { "false" }
}

impl PartialEq for ServiceAccount {
    fn eq(&self, other: &Self) -> bool {
        self.service_account_credential == other.service_account_credential
            && self.scopes == other.scopes
            && self.use_default_credential == other.use_default_credential
            && self.use_id_token == other.use_id_token
            && self.audience == other.audience
            && extra_eq(&self.extra, &other.extra)
    }
}

#[derive(Clone, Default)]
pub struct Credential {
    /// Required on decode.
    pub auth_type: CredentialType,
    pub resource_ref: String,
    pub api_key: String,
    pub http: Option<HttpAuth>,
    pub service_account: Option<ServiceAccount>,
    pub oauth2: Option<OAuth2Auth>,
    pub extra: Extra,
}

const CREDENTIAL_FIELDS: &[&str] = &[
    "authType",
    "resourceRef",
    "apiKey",
    "http",
    "serviceAccount",
    "oauth2",
];

impl GoUnmarshal for Credential {
    /// Decodes a [`Credential`]: rejects a missing or unknown auth type and an invalid
    /// credential in any field.
    fn go_unmarshal(raw: &RawValue) -> Result<Self, String> {
        const T: &str = "Credential";
        let mut d = decode_object(raw, T, CREDENTIAL_FIELDS, true, &["authType"])?;
        let c = Credential {
            auth_type: d
                .take("authType", T, "toolauth.CredentialType")?
                .unwrap_or_default(),
            resource_ref: d.take("resourceRef", T, "string")?.unwrap_or_default(),
            api_key: d.take("apiKey", T, "string")?.unwrap_or_default(),
            http: d.take("http", T, "*toolauth.HTTPAuth")?,
            service_account: d.take("serviceAccount", T, "*toolauth.ServiceAccount")?,
            oauth2: d.take("oauth2", T, "*toolauth.OAuth2Auth")?,
            extra: d.extra,
        };
        let known = [
            CredentialType::API_KEY,
            CredentialType::HTTP,
            CredentialType::OAUTH2,
            CredentialType::OPEN_ID_CONNECT,
            CredentialType::SERVICE_ACCOUNT,
        ];
        if !known.contains(&c.auth_type) {
            return Err("toolauth: Credential: unknown authType".to_owned());
        }
        Ok(c)
    }
}

impl GoMarshal for Credential {
    fn go_marshal(&self) -> String {
        let mut w = ObjectWriter::new();
        w.field("authType", &go_string(self.auth_type.as_str()));
        non_empty(
            &mut w,
            &[
                ("resourceRef", &self.resource_ref),
                ("apiKey", &self.api_key),
            ],
        );
        if let Some(http) = &self.http {
            w.field("http", &http.go_marshal());
        }
        if let Some(sa) = &self.service_account {
            w.field("serviceAccount", &sa.go_marshal());
        }
        if let Some(oauth2) = &self.oauth2 {
            w.field("oauth2", &oauth2.go_marshal());
        }
        w.finish(&self.extra, CREDENTIAL_FIELDS, true)
    }
}

impl PartialEq for Credential {
    fn eq(&self, other: &Self) -> bool {
        self.auth_type == other.auth_type
            && self.resource_ref == other.resource_ref
            && self.api_key == other.api_key
            && self.http == other.http
            && self.service_account == other.service_account
            && self.oauth2 == other.oauth2
            && extra_eq(&self.extra, &other.extra)
    }
}