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

Default token expiry #67

Merged
merged 8 commits into from
Mar 14, 2023
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "gcp_auth"
version = "0.7.5"
version = "0.7.6"
repository = "https://github.com/hrvolapeter/gcp_auth"
description = "Google cloud platform (GCP) authentication using default and custom service accounts"
documentation = "https://docs.rs/gcp_auth/"
Expand Down
11 changes: 6 additions & 5 deletions src/gcloud_authorized_user.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,13 @@ use std::process::Command;
use std::sync::RwLock;

use async_trait::async_trait;
use time::Duration;
use which::which;

use crate::authentication_manager::ServiceAccount;
use crate::error::Error;
use crate::error::Error::{GCloudError, GCloudNotFound, GCloudParseError};
use crate::types::HyperClient;
use crate::types::{HyperClient, DEFAULT_TOKEN_DURATION};
use crate::Token;

#[derive(Debug)]
Expand All @@ -31,10 +32,10 @@ impl GCloudAuthorizedUser {
}

fn token(gcloud: &Path) -> Result<Token, Error> {
Ok(Token::from_string(run(
gcloud,
&["auth", "print-access-token", "--quiet"],
)?))
Ok(Token::from_string(
run(gcloud, &["auth", "print-access-token", "--quiet"])?,
Duration::seconds(DEFAULT_TOKEN_DURATION),
))
}
}

Expand Down
44 changes: 22 additions & 22 deletions src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,11 @@ use time::{Duration, OffsetDateTime};

use crate::Error;

/// The default number of seconds that it takes for a Google Cloud auth token to expire.
/// This appears to be the default from practical testing, but we have not found evidence
/// that this will always be the default duration.
pub(crate) const DEFAULT_TOKEN_DURATION: i64 = 3600;
MatthewHelmer marked this conversation as resolved.
Show resolved Hide resolved

/// Represents an access token. All access tokens are Bearer tokens.
///
/// Tokens should not be cached, the [`AuthenticationManager`] handles the correct caching
Expand All @@ -32,11 +37,11 @@ pub struct Token {
}

impl Token {
pub(crate) fn from_string(access_token: String) -> Self {
pub(crate) fn from_string(access_token: String, expires_in: Duration) -> Self {
Token {
inner: Arc::new(InnerToken {
access_token,
expires_at: None,
expires_at: OffsetDateTime::now_utc() + expires_in,
}),
}
}
Expand All @@ -55,11 +60,10 @@ impl fmt::Debug for Token {
struct InnerToken {
access_token: String,
#[serde(
default,
deserialize_with = "deserialize_time",
rename(deserialize = "expires_in")
)]
expires_at: Option<OffsetDateTime>,
expires_at: OffsetDateTime,
}

impl Token {
Expand All @@ -68,12 +72,7 @@ impl Token {
/// This takes an additional 30s margin to ensure the token can still be reasonably used
/// instead of expiring right after having checked.
pub fn has_expired(&self) -> bool {
self.inner
.expires_at
.map(|expiration_time| {
expiration_time - Duration::seconds(30) <= OffsetDateTime::now_utc()
})
.unwrap_or(false)
self.inner.expires_at - Duration::seconds(30) <= OffsetDateTime::now_utc()
}

/// Get str representation of the token.
Expand All @@ -82,7 +81,7 @@ impl Token {
}

/// Get expiry of token, if available
pub fn expires_at(&self) -> Option<OffsetDateTime> {
pub fn expires_at(&self) -> OffsetDateTime {
self.inner.expires_at
}
}
Expand Down Expand Up @@ -140,14 +139,12 @@ impl fmt::Debug for Signer {
}
}

fn deserialize_time<'de, D>(deserializer: D) -> Result<Option<OffsetDateTime>, D::Error>
fn deserialize_time<'de, D>(deserializer: D) -> Result<OffsetDateTime, D::Error>
where
D: Deserializer<'de>,
{
let s: Option<i64> = Deserialize::deserialize(deserializer)?;
let s =
s.map(|seconds_from_now| OffsetDateTime::now_utc() + Duration::seconds(seconds_from_now));
Ok(s)
let seconds_from_now: i64 = Deserialize::deserialize(deserializer)?;
Ok(OffsetDateTime::now_utc() + Duration::seconds(seconds_from_now))
}

pub(crate) fn client() -> HyperClient {
Expand All @@ -171,7 +168,7 @@ mod tests {
let token = Token {
inner: Arc::new(InnerToken {
access_token: "abc123".to_string(),
expires_at: Some(OffsetDateTime::from_unix_timestamp(123).unwrap()),
expires_at: OffsetDateTime::from_unix_timestamp(123).unwrap(),
}),
};
let s = serde_json::to_string(&token).unwrap();
Expand All @@ -191,17 +188,20 @@ mod tests {
assert_eq!(token.as_str(), "abc123");

// Testing time is always racy, give it 1s leeway.
let expires_at = token.expires_at().unwrap();
let expires_at = token.expires_at();
assert!(expires_at < expires + Duration::seconds(1));
assert!(expires_at > expires - Duration::seconds(1));
}

#[test]
fn test_deserialise_no_time() {
MatthewHelmer marked this conversation as resolved.
Show resolved Hide resolved
let s = r#"{"access_token":"abc123"}"#;
let token: Token = serde_json::from_str(s).unwrap();
fn test_token_from_string() {
let s = String::from("abc123");
let token = Token::from_string(s, Duration::seconds(DEFAULT_TOKEN_DURATION));
let expires = OffsetDateTime::now_utc() + Duration::seconds(DEFAULT_TOKEN_DURATION);

assert_eq!(token.as_str(), "abc123");
assert!(token.expires_at().is_none());
assert!(!token.has_expired());
assert!(token.expires_at() < expires + Duration::seconds(1));
assert!(token.expires_at() > expires - Duration::seconds(1));
}
}