Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add audience to custom_service_account #119

Merged
merged 3 commits into from
Oct 14, 2024
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 16 additions & 3 deletions src/custom_service_account.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ pub struct CustomServiceAccount {
signer: Signer,
tokens: RwLock<HashMap<Vec<String>, Arc<Token>>>,
subject: Option<String>,
audience: Option<String>,
}

impl CustomServiceAccount {
Expand Down Expand Up @@ -59,6 +60,12 @@ impl CustomServiceAccount {
self
}

/// Set the `Audience` to impersonate a user
pub fn with_audience(mut self, audience: String) -> Self {
self.audience = Some(audience);
self
}

fn new(credentials: ServiceAccountKey, client: HttpClient) -> Result<Self, Error> {
debug!(project = ?credentials.project_id, email = credentials.client_email, "found credentials");
Ok(Self {
Expand All @@ -67,13 +74,14 @@ impl CustomServiceAccount {
credentials,
tokens: RwLock::new(HashMap::new()),
subject: None,
audience: None,
})
}

#[instrument(level = Level::DEBUG, skip(self))]
async fn fetch_token(&self, scopes: &[&str]) -> Result<Arc<Token>, Error> {
let jwt =
Claims::new(&self.credentials, scopes, self.subject.as_deref()).to_jwt(&self.signer)?;
Claims::new(&self.credentials, scopes, self.subject.as_deref(), self.audience.as_deref()).to_jwt(&self.signer)?;
let body = Bytes::from(
form_urlencoded::Serializer::new(String::new())
.extend_pairs(&[("grant_type", GRANT_TYPE), ("assertion", jwt.as_str())])
Expand Down Expand Up @@ -156,7 +164,7 @@ pub(crate) struct Claims<'a> {
}

impl<'a> Claims<'a> {
pub(crate) fn new(key: &'a ServiceAccountKey, scopes: &[&str], sub: Option<&'a str>) -> Self {
pub(crate) fn new(key: &'a ServiceAccountKey, scopes: &[&str], sub: Option<&'a str>, aud: Option<&'a str>) -> Self {
let mut scope = String::with_capacity(16);
for (i, s) in scopes.iter().enumerate() {
if i != 0 {
Expand All @@ -167,9 +175,14 @@ impl<'a> Claims<'a> {
}

let iat = Utc::now().timestamp();
let aud = if let Some(aud_str) = aud {
aud_str
} else {
&key.token_uri
};
Claims {
iss: &key.client_email,
aud: &key.token_uri,
aud,
dacozai marked this conversation as resolved.
Show resolved Hide resolved
exp: iat + 3600 - 5, // Max validity is 1h
iat,
sub,
Expand Down
Loading