1use 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#[derive(Debug, Clone, PartialEq, Eq, Hash)]
39pub struct CredentialType(Cow<'static, str>);
40
41impl CredentialType {
42 pub const API_KEY: CredentialType = CredentialType(Cow::Borrowed("apiKey"));
44 pub const HTTP: CredentialType = CredentialType(Cow::Borrowed("http"));
46 pub const OAUTH2: CredentialType = CredentialType(Cow::Borrowed("oauth2"));
48 pub const OPEN_ID_CONNECT: CredentialType = CredentialType(Cow::Borrowed("openIdConnect"));
50 pub const SERVICE_ACCOUNT: CredentialType = CredentialType(Cow::Borrowed("serviceAccount"));
52
53 pub fn new(s: impl Into<Cow<'static, str>>) -> Self {
55 CredentialType(s.into())
56 }
57
58 pub fn as_str(&self) -> &str {
60 &self.0
61 }
62}
63
64impl Default for CredentialType {
65 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
83impl 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
97macro_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
124fn 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#[derive(Clone, Default)]
136pub struct HttpCredentials {
137 pub username: String,
139 pub password: String,
141 pub token: String,
143 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#[derive(Clone, Default)]
189pub struct HttpAuth {
190 pub scheme: String,
192 pub credentials: HttpCredentials,
194 pub additional_headers: Option<BTreeMap<String, String>>,
196 pub extra: Extra,
198}
199
200const HTTP_AUTH_FIELDS: &[&str] = &["scheme", "credentials", "additionalHeaders"];
201
202impl GoUnmarshal for HttpAuth {
203 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 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#[derive(Clone, Default)]
244pub struct OAuth2Auth {
245 pub client_id: String,
247 pub client_secret: String,
249 pub auth_uri: String,
251 pub nonce: String,
253 pub state: String,
255 pub redirect_uri: String,
257 pub auth_response_uri: String,
259 pub auth_code: String,
261 pub access_token: String,
263 pub refresh_token: String,
265 pub id_token: String,
267 pub expires_at: i64,
269 pub expires_in: i64,
272 pub audience: String,
274 pub prompt: String,
276 pub code_verifier: String,
278 pub code_challenge_method: String,
280 pub token_endpoint_auth_method: String,
282 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 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 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#[derive(Clone, Default)]
442pub struct ServiceAccountCredential {
443 pub r#type: String,
445 pub project_id: String,
447 pub private_key_id: String,
449 pub private_key: String,
451 pub client_email: String,
453 pub client_id: String,
455 pub auth_uri: String,
457 pub token_uri: String,
459 pub auth_provider_x509_cert_url: String,
461 pub client_x509_cert_url: String,
463 pub universe_domain: String,
465 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 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 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#[derive(Clone, Default)]
560pub struct ServiceAccount {
561 pub service_account_credential: Option<ServiceAccountCredential>,
564 pub scopes: Option<Vec<String>>,
566 pub use_default_credential: bool,
568 pub use_id_token: bool,
570 pub audience: String,
573 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 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#[derive(Clone, Default)]
652pub struct Credential {
653 pub auth_type: CredentialType,
655 pub resource_ref: String,
657 pub api_key: String,
659 pub http: Option<HttpAuth>,
661 pub service_account: Option<ServiceAccount>,
663 pub oauth2: Option<OAuth2Auth>,
666 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 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}