Skip to content

Commit 7764d76

Browse files
committed
Switch from time to chrono
1 parent 4d2527f commit 7764d76

File tree

4 files changed

+25
-22
lines changed

4 files changed

+25
-22
lines changed

Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ webpki-roots = ["hyper-rustls/webpki-roots"]
1818
[dependencies]
1919
async-trait = "0.1"
2020
base64 = "0.21"
21+
chrono = { version = "0.4.31", features = ["serde"] }
2122
dirs-next = "2.0"
2223
hyper = { version = "0.14.2", features = ["client", "runtime", "http2"] }
2324
hyper-rustls = { version = "0.24", default-features = false, features = ["tokio-runtime", "http1", "http2"] }
@@ -27,7 +28,6 @@ rustls-pemfile = "1.0.0"
2728
serde = { version = "1.0", features = ["derive", "rc"] }
2829
serde_json = "1.0"
2930
thiserror = "1.0"
30-
time = { version = "0.3.5", features = ["serde"] }
3131
tokio = { version = "1.1", features = ["fs", "sync"] }
3232
tracing = "0.1.29"
3333
tracing-futures = "0.2.5"

src/gcloud_authorized_user.rs

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
use std::path::{Path, PathBuf};
22
use std::process::Command;
33
use std::sync::RwLock;
4+
use std::time::Duration;
45

56
use async_trait::async_trait;
6-
use time::Duration;
77
use which::which;
88

99
use crate::authentication_manager::ServiceAccount;
@@ -15,7 +15,7 @@ use crate::Token;
1515
/// The default number of seconds that it takes for a Google Cloud auth token to expire.
1616
/// This appears to be the default from practical testing, but we have not found evidence
1717
/// that this will always be the default duration.
18-
pub(crate) const DEFAULT_TOKEN_DURATION: Duration = Duration::seconds(3600);
18+
pub(crate) const DEFAULT_TOKEN_DURATION: Duration = Duration::from_secs(3600);
1919

2020
#[derive(Debug)]
2121
pub(crate) struct GCloudAuthorizedUser {
@@ -79,7 +79,8 @@ fn run(gcloud: &Path, cmd: &[&str]) -> Result<String, Error> {
7979

8080
#[cfg(test)]
8181
mod tests {
82-
use time::{Duration, OffsetDateTime};
82+
use chrono::Utc;
83+
use std::time::Duration;
8384

8485
use super::*;
8586

@@ -89,11 +90,11 @@ mod tests {
8990
let gcloud = GCloudAuthorizedUser::new().await.unwrap();
9091
println!("{:?}", gcloud.project_id);
9192
if let Some(t) = gcloud.get_token(&[""]) {
92-
let expires = OffsetDateTime::now_utc() + DEFAULT_TOKEN_DURATION;
93+
let expires = Utc::now() + DEFAULT_TOKEN_DURATION;
9394
println!("{:?}", t);
9495
assert!(!t.has_expired());
95-
assert!(t.expires_at() < expires + Duration::seconds(1));
96-
assert!(t.expires_at() > expires - Duration::seconds(1));
96+
assert!(t.expires_at() < expires + Duration::from_secs(1));
97+
assert!(t.expires_at() > expires - Duration::from_secs(1));
9798
} else {
9899
panic!("GCloud Authorized User failed to get a token");
99100
}
@@ -106,12 +107,12 @@ mod tests {
106107
fn test_token_from_string() {
107108
let s = String::from("abc123");
108109
let token = Token::from_string(s, DEFAULT_TOKEN_DURATION);
109-
let expires = OffsetDateTime::now_utc() + DEFAULT_TOKEN_DURATION;
110+
let expires = Utc::now() + DEFAULT_TOKEN_DURATION;
110111

111112
assert_eq!(token.as_str(), "abc123");
112113
assert!(!token.has_expired());
113-
assert!(token.expires_at() < expires + Duration::seconds(1));
114-
assert!(token.expires_at() > expires - Duration::seconds(1));
114+
assert!(token.expires_at() < expires + Duration::from_secs(1));
115+
assert!(token.expires_at() > expires - Duration::from_secs(1));
115116
}
116117

117118
#[test]

src/jwt.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
//! Copyright (c) 2016 Google Inc ([email protected]).
22
33
use base64::{engine::general_purpose::URL_SAFE, Engine};
4+
use chrono::Utc;
45
use serde::Serialize;
56

67
use crate::custom_service_account::ApplicationCredentials;
@@ -31,7 +32,7 @@ impl<'a> Claims<'a> {
3132
where
3233
T: std::string::ToString,
3334
{
34-
let iat = time::OffsetDateTime::now_utc().unix_timestamp();
35+
let iat = Utc::now().timestamp();
3536
let expiry = iat + 3600 - 5; // Max validity is 1h.
3637

3738
let scope: String = scopes

src/types.rs

Lines changed: 12 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,15 @@
11
use std::sync::Arc;
2+
use std::time::Duration;
23
use std::{fmt, io};
34

5+
use chrono::{DateTime, Utc};
46
use hyper::Client;
57
use hyper_rustls::HttpsConnectorBuilder;
68
use ring::{
79
rand::SystemRandom,
810
signature::{RsaKeyPair, RSA_PKCS1_SHA256},
911
};
1012
use serde::{Deserialize, Deserializer};
11-
use time::{Duration, OffsetDateTime};
1213

1314
use crate::Error;
1415
/// Represents an access token. All access tokens are Bearer tokens.
@@ -34,7 +35,7 @@ impl Token {
3435
Token {
3536
inner: Arc::new(InnerToken {
3637
access_token,
37-
expires_at: OffsetDateTime::now_utc() + expires_in,
38+
expires_at: Utc::now() + expires_in,
3839
}),
3940
}
4041
}
@@ -56,7 +57,7 @@ struct InnerToken {
5657
deserialize_with = "deserialize_time",
5758
rename(deserialize = "expires_in")
5859
)]
59-
expires_at: OffsetDateTime,
60+
expires_at: DateTime<Utc>,
6061
}
6162

6263
impl Token {
@@ -71,7 +72,7 @@ impl Token {
7172
/// The docs state, the metadata server caches tokens until 5 minutes before expiry.
7273
/// We use 20s to be on the safe side.
7374
pub fn has_expired(&self) -> bool {
74-
self.inner.expires_at - Duration::seconds(20) <= OffsetDateTime::now_utc()
75+
self.inner.expires_at - Duration::from_secs(20) <= Utc::now()
7576
}
7677

7778
/// Get str representation of the token.
@@ -80,7 +81,7 @@ impl Token {
8081
}
8182

8283
/// Get expiry of token, if available
83-
pub fn expires_at(&self) -> OffsetDateTime {
84+
pub fn expires_at(&self) -> DateTime<Utc> {
8485
self.inner.expires_at
8586
}
8687
}
@@ -138,12 +139,12 @@ impl fmt::Debug for Signer {
138139
}
139140
}
140141

141-
fn deserialize_time<'de, D>(deserializer: D) -> Result<OffsetDateTime, D::Error>
142+
fn deserialize_time<'de, D>(deserializer: D) -> Result<DateTime<Utc>, D::Error>
142143
where
143144
D: Deserializer<'de>,
144145
{
145-
let seconds_from_now: i64 = Deserialize::deserialize(deserializer)?;
146-
Ok(OffsetDateTime::now_utc() + Duration::seconds(seconds_from_now))
146+
let seconds_from_now: u64 = Deserialize::deserialize(deserializer)?;
147+
Ok(Utc::now() + Duration::from_secs(seconds_from_now))
147148
}
148149

149150
pub(crate) fn client() -> HyperClient {
@@ -166,13 +167,13 @@ mod tests {
166167
fn test_deserialize_with_time() {
167168
let s = r#"{"access_token":"abc123","expires_in":100}"#;
168169
let token: Token = serde_json::from_str(s).unwrap();
169-
let expires = OffsetDateTime::now_utc() + Duration::seconds(100);
170+
let expires = Utc::now() + Duration::from_secs(100);
170171

171172
assert_eq!(token.as_str(), "abc123");
172173

173174
// Testing time is always racy, give it 1s leeway.
174175
let expires_at = token.expires_at();
175-
assert!(expires_at < expires + Duration::seconds(1));
176-
assert!(expires_at > expires - Duration::seconds(1));
176+
assert!(expires_at < expires + Duration::from_secs(1));
177+
assert!(expires_at > expires - Duration::from_secs(1));
177178
}
178179
}

0 commit comments

Comments
 (0)