yoshidan / google-cloud-rust

Google Cloud Client Libraries for Rust.
MIT License
241 stars 86 forks source link

Can not generate ID Token #248

Closed h-michael closed 5 months ago

h-michael commented 6 months ago

I tried to generate ID Token from service account for accessing the endpoint protected by IAP with following codes.

let audience = "AUDIENCE";
let creds = CredentialsFile::new_from_file("PATH TO SERVICE ACCOUNT JSON").await?;
let ts = google_cloud_auth::idtoken::IdTokenSourceConfig::new()
    .with_credentials(creds)
    .build(audience)
    .await?;

match ts.token().await {
    Ok(token) => Ok(token),
    Err(err) => Err(err.into()),
}

But I got JwtError(Error(InvalidAudience)).

I generated ID token with this bash script and I can pass IAP with that ID token. Two ID token generated from Rust script and bash script were the same token.

I found the cause. That error happens this line. https://github.com/yoshidan/google-cloud-rust/blob/0ab379e04857fbc1e09086d7f703a5806759fa7a/foundation/auth/src/token_source/mod.rs#L74

This get_exp function calls jsonwebtoken::Validation::default(). https://github.com/yoshidan/google-cloud-rust/blob/0ab379e04857fbc1e09086d7f703a5806759fa7a/foundation/auth/src/token_source/mod.rs#L70

jsonwebtoken::Validation::default funciton calls jsonwebtoken::Validation::new function. https://github.com/Keats/jsonwebtoken/blob/08601f727bea94b61e8d98901b63e43ae1bce350/src/validation.rs#L141

jsonwebtoken::Validation::new function sets jsonwebtoken::Validation.validate_aud trueandjsonwebtoken::Validation.aud`None. https://github.com/Keats/jsonwebtoken/blob/08601f727bea94b61e8d98901b63e43ae1bce350/src/validation.rs#L98-L104

So get_exp function always passes this branch. https://github.com/Keats/jsonwebtoken/blob/08601f727bea94b61e8d98901b63e43ae1bce350/src/validation.rs#L289-L291

I think there are two options to resolve this issue.

  1. set jsonwebtoken::Validation.aud to expected audience
  2. set jsonwebtoken::Validation.validate_aud as false

Which do you think is better?

Thank you.

yoshidan commented 5 months ago

Thanks for your report!

  1. set jsonwebtoken::Validation.aud to expected audience

Since the expected Audience should be a valid one, we think this is the better choice.