Skip to content

Commit b166f9d

Browse files
authored
feat: optional auth token ttl (#32)
1 parent cf52aa0 commit b166f9d

File tree

1 file changed

+9
-6
lines changed

1 file changed

+9
-6
lines changed

relay_rpc/src/auth.rs

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,6 @@ pub const MULTICODEC_ED25519_HEADER: [u8; 2] = [237, 1];
3030
pub const MULTICODEC_ED25519_LENGTH: usize = 32;
3131

3232
pub const DEFAULT_TOKEN_AUD: &str = RELAY_WEBSOCKET_ADDRESS;
33-
pub const DEFAULT_TOKEN_TTL: Duration = Duration::from_secs(60 * 60);
3433

3534
#[derive(Debug, Clone, Serialize, Deserialize)]
3635
#[serde(transparent)]
@@ -83,10 +82,9 @@ impl AuthToken {
8382

8483
pub fn as_jwt(&self, key: &Keypair) -> Result<SerializedAuthToken, Error> {
8584
let iat = self.iat.unwrap_or_else(Utc::now);
86-
let ttl = self.ttl.unwrap_or(DEFAULT_TOKEN_TTL);
8785
let aud = self.aud.as_deref().unwrap_or(DEFAULT_TOKEN_AUD);
8886

89-
encode_auth_token(key, &self.sub, aud, iat, ttl)
87+
encode_auth_token(key, &self.sub, aud, iat, self.ttl)
9088
}
9189
}
9290

@@ -95,18 +93,23 @@ pub fn encode_auth_token(
9593
sub: impl Into<String>,
9694
aud: impl Into<String>,
9795
iat: DateTime<Utc>,
98-
ttl: Duration,
96+
ttl: Option<Duration>,
9997
) -> Result<SerializedAuthToken, Error> {
10098
let encoder = &data_encoding::BASE64URL_NOPAD;
101-
let exp = iat + chrono::Duration::from_std(ttl).map_err(|_| Error::InvalidDuration)?;
99+
100+
let exp = ttl
101+
.map(chrono::Duration::from_std)
102+
.transpose()
103+
.map_err(|_| Error::InvalidDuration)?
104+
.map(|ttl| (iat + ttl).timestamp());
102105

103106
let claims = {
104107
let data = JwtBasicClaims {
105108
iss: DecodedClientId::from_key(&key.public_key()).into(),
106109
sub: sub.into(),
107110
aud: aud.into(),
108111
iat: iat.timestamp(),
109-
exp: Some(exp.timestamp()),
112+
exp,
110113
};
111114

112115
encoder.encode(serde_json::to_string(&data)?.as_bytes())

0 commit comments

Comments
 (0)