Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

fix(auth): refresh access tokens issued without macro claims (#8420)

teod9e95c87c6c4
diff --git a/apps/web/src/lib/service-clients/service-auth/openapi.json b/apps/web/src/lib/service-clients/service-auth/openapi.json
index 53b5a2db7d..9ffcbb275d 100644
--- a/apps/web/src/lib/service-clients/service-auth/openapi.json
+++ b/apps/web/src/lib/service-clients/service-auth/openapi.json
@@ -1969,7 +1969,7 @@
}
},
"429": {
- "description": "Refresh already in progress for this user",
+ "description": "Refresh already in progress for this user, or the access token lacks the Macro claims and was issued too recently to refresh",
"content": {
"text/plain": {
"schema": {
diff --git a/crates/macro_auth/src/middleware/decode_jwt.rs b/crates/macro_auth/src/middleware/decode_jwt.rs
index db1f441617..5257fe615a 100644
--- a/crates/macro_auth/src/middleware/decode_jwt.rs
+++ b/crates/macro_auth/src/middleware/decode_jwt.rs
@@ -1,7 +1,12 @@
#[cfg(test)]
mod agent_test;
+#[cfg(test)]
+mod fusionauth_access_token_test;
-use std::sync::OnceLock;
+use std::{
+ sync::OnceLock,
+ time::{Duration, SystemTime, UNIX_EPOCH},
+};
use anyhow::Context;
use jsonwebtoken::{Algorithm, DecodingKey, Validation, decode};
@@ -166,6 +171,42 @@ pub fn decode_macro_access_token_allow_expired(
Ok(macro_user_id)
}
+#[derive(serde::Deserialize)]
+struct FusionAuthAccessToken {
+ iat: u64,
+}
+
+/// Checks that a token was issued by FusionAuth for this application (signature, audience and
+/// issuer) without checking expiry or the Macro claims, and returns when it was issued.
+/// FusionAuth still issues an access token when the JWT populate lambda fails, just without
+/// those claims.
+pub fn validate_fusionauth_access_token_allow_expired(
+ access_token: &str,
+ args: &JwtValidationArgs,
+) -> Result<SystemTime, MacroAuthError> {
+ let mut validation = Validation::new(Algorithm::HS256);
+ validation.set_audience(&[args.audience.as_ref()]);
+ validation.set_issuer(&[args.issuer.as_ref()]);
+ validation.set_required_spec_claims(&["exp", "aud", "iss"]);
+ validation.validate_exp = false;
+
+ let token = decode::<FusionAuthAccessToken>(
+ access_token,
+ &DecodingKey::from_secret(args.jwt_secret.as_ref().as_bytes()),
+ &validation,
+ )
+ .map_err(|e| MacroAuthError::JwtValidationFailed {
+ details: e.to_string(),
+ })?
+ .claims;
+
+ UNIX_EPOCH
+ .checked_add(Duration::from_secs(token.iat))
+ .ok_or_else(|| MacroAuthError::JwtValidationFailed {
+ details: "iat is out of range".to_string(),
+ })
+}
+
fn validate_macro_access_token_inner(
macro_access_token: &str,
jwt_secret: &LocalOrRemoteSecret<JwtSecretKey>,
diff --git a/crates/macro_auth/src/middleware/decode_jwt/fusionauth_access_token_test.rs b/crates/macro_auth/src/middleware/decode_jwt/fusionauth_access_token_test.rs
new file mode 100644
index 0000000000..0c53a9d7e4
--- /dev/null
+++ b/crates/macro_auth/src/middleware/decode_jwt/fusionauth_access_token_test.rs
@@ -0,0 +1,151 @@
+use super::*;
+use crate::macro_api_token::{EncodeMacroApiTokenArgs, encode_macro_api_token};
+
+const FUSIONAUTH_SECRET: &str = "fusionauth-secret";
+const ISSUED_AT: u64 = 1_700_000_000;
+/// Base64url of `{"alg":"none","typ":"JWT"}`.
+const NONE_ALGORITHM_HEADER: &str = "eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0";
+
+fn args() -> JwtValidationArgs {
+ JwtValidationArgs {
+ audience: Audience::new_testing("macro-app"),
+ issuer: Issuer::new_testing("auth.macro.test"),
+ jwt_secret: LocalOrRemoteSecret::Local(JwtSecretKey::new_testing(FUSIONAUTH_SECRET)),
+ macro_api_token_issuer: MacroApiTokenIssuer::new_testing("macro-api.test"),
+ macro_api_token_public_key: LocalOrRemoteSecret::Local(
+ MacroApiTokenPublicKey::new_testing(tests::PUBLIC_KEY),
+ ),
+ }
+}
+
+/// An expired access token FusionAuth issued for this application without the Macro claims.
+fn claims_without_macro_claims() -> serde_json::Value {
+ serde_json::json!({
+ "aud": "macro-app", "exp": ISSUED_AT + 3600, "iat": ISSUED_AT, "iss": "auth.macro.test",
+ "sub": "fusion-user", "tid": "tenant", "email": "[email protected]",
+ "applicationId": "macro-app", "roles": [],
+ })
+}
+
+fn with(claim: &str, value: serde_json::Value) -> serde_json::Value {
+ let mut claims = claims_without_macro_claims();
+ claims[claim] = value;
+ claims
+}
+
+fn without(claim: &str) -> serde_json::Value {
+ let mut claims = claims_without_macro_claims();
+ claims.as_object_mut().unwrap().remove(claim);
+ claims
+}
+
+fn sign(algorithm: Algorithm, secret: &str, claims: &serde_json::Value) -> String {
+ let mut header = jsonwebtoken::Header::new(algorithm);
+ header.kid = Some("fusionauth-key".into());
+ jsonwebtoken::encode(
+ &header,
+ claims,
+ &jsonwebtoken::EncodingKey::from_secret(secret.as_bytes()),
+ )
+ .unwrap()
+}
+
+#[test]
+fn token_without_macro_claims_is_recognized_as_issued_for_this_application() {
+ let expired = sign(
+ Algorithm::HS256,
+ FUSIONAUTH_SECRET,
+ &claims_without_macro_claims(),
+ );
+ let unexpired = sign(
+ Algorithm::HS256,
+ FUSIONAUTH_SECRET,
+ &with("exp", 4_102_444_800_u64.into()),
+ );
+
+ for token in [&expired, &unexpired] {
+ assert!(matches!(
+ validate_macro_access_token(token, &args()),
+ Err(MacroAuthError::JwtValidationFailed { .. })
+ ));
+ assert_eq!(
+ validate_fusionauth_access_token_allow_expired(token, &args()).unwrap(),
+ UNIX_EPOCH + Duration::from_secs(ISSUED_AT)
+ );
+ }
+}
+
+#[test]
+fn tokens_not_issued_by_fusionauth_for_this_application_are_rejected() {
+ let valid = sign(
+ Algorithm::HS256,
+ FUSIONAUTH_SECRET,
+ &claims_without_macro_claims(),
+ );
+ assert!(validate_fusionauth_access_token_allow_expired(&valid, &args()).is_ok());
+ let [header, payload, signature]: [&str; 3] =
+ valid.split('.').collect::<Vec<_>>().try_into().unwrap();
+ let other_user = sign(
+ Algorithm::HS256,
+ FUSIONAUTH_SECRET,
+ &with("sub", "other-fusion-user".into()),
+ );
+ let other_payload = other_user.split('.').nth(1).unwrap();
+ let macro_api_token = encode_macro_api_token(EncodeMacroApiTokenArgs {
+ fusionauth_id: "fusion-user".into(),
+ macro_user_id: "macro|[email protected]".into(),
+ organization_id: None,
+ issuer: "macro-api.test".into(),
+ private_key: tests::PRIVATE_KEY.into(),
+ expiry_seconds: 60,
+ agent_id: None,
+ })
+ .unwrap();
+
+ let hs256 = |claims: serde_json::Value| sign(Algorithm::HS256, FUSIONAUTH_SECRET, &claims);
+ let cases = [
+ (
+ "signed with another secret",
+ sign(
+ Algorithm::HS256,
+ "other-secret",
+ &claims_without_macro_claims(),
+ ),
+ ),
+ (
+ "signed with HS512",
+ sign(
+ Algorithm::HS512,
+ FUSIONAUTH_SECRET,
+ &claims_without_macro_claims(),
+ ),
+ ),
+ ("unsigned", format!("{NONE_ALGORITHM_HEADER}.{payload}.")),
+ (
+ "payload swapped under a valid signature",
+ format!("{header}.{other_payload}.{signature}"),
+ ),
+ ("another audience", hs256(with("aud", "other-app".into()))),
+ (
+ "another issuer",
+ hs256(with("iss", "other.issuer.test".into())),
+ ),
+ ("no audience", hs256(without("aud"))),
+ ("no issuer", hs256(without("iss"))),
+ ("no expiry", hs256(without("exp"))),
+ ("no issued-at", hs256(without("iat"))),
+ (
+ "issued-at out of range",
+ hs256(with("iat", u64::MAX.into())),
+ ),
+ ("Macro API token", macro_api_token),
+ ("not a JWT", "not-a-jwt".into()),
+ ];
+
+ for (case, token) in cases {
+ assert!(
+ validate_fusionauth_access_token_allow_expired(&token, &args()).is_err(),
+ "{case}"
+ );
+ }
+}
diff --git a/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/RefreshErrors.md b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/RefreshErrors.md
index ac3ce7afc5..e6283b0de6 100644
--- a/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/RefreshErrors.md
+++ b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/RefreshErrors.md
@@ -8,5 +8,5 @@
| ------ | ------ | ------ |
| <a id="property-400"></a> `400` | `string` | - |
| <a id="property-401"></a> `401` | `string` | - |
-| <a id="property-429"></a> `429` | `string` | Refresh already in progress for this user |
+| <a id="property-429"></a> `429` | `string` | Refresh already in progress for this user, or the access token lacks the Macro claims and was issued too recently to refresh |
| <a id="property-500"></a> `500` | `string` | - |
diff --git a/packages/sdk/generated/auth/types.gen.ts b/packages/sdk/generated/auth/types.gen.ts
index 36c8db251d..1ed646fe0a 100644
--- a/packages/sdk/generated/auth/types.gen.ts
+++ b/packages/sdk/generated/auth/types.gen.ts
@@ -2952,7 +2952,7 @@ export type RefreshErrors = {
400: string;
401: string;
/**
- * Refresh already in progress for this user
+ * Refresh already in progress for this user, or the access token lacks the Macro claims and was issued too recently to refresh
*/
429: string;
500: string;
diff --git a/packages/sdk/specs/auth.json b/packages/sdk/specs/auth.json
index 53b5a2db7d..9ffcbb275d 100644
--- a/packages/sdk/specs/auth.json
+++ b/packages/sdk/specs/auth.json
@@ -1969,7 +1969,7 @@
}
},
"429": {
- "description": "Refresh already in progress for this user",
+ "description": "Refresh already in progress for this user, or the access token lacks the Macro claims and was issued too recently to refresh",
"content": {
"text/plain": {
"schema": {
diff --git a/services/authentication_service/AGENTS.md b/services/authentication_service/AGENTS.md
index 9b5d2384da..60c14df9d8 100644
--- a/services/authentication_service/AGENTS.md
+++ b/services/authentication_service/AGENTS.md
@@ -119,6 +119,13 @@ inputs cannot select an agent, and ordinary user credentials remain unattributed
("Invalid origin uri <origin>") means the page that sent the browser to
FusionAuth is missing from `infra/stacks/fusionauth-instance/origins.ts`;
these failures carry no user id.
+- When the FusionAuth JWT populate lambda fails (its `fetch` to
+ `/webhooks/user/jwt` times out after 2 s or gets a non-200), FusionAuth still
+ issues the access token, just without the Macro claims. `/jwt/refresh`
+ refreshes such tokens instead of rejecting them, and warns when FusionAuth
+ returns one. It answers 429 for one issued under 30 s ago, so client retries
+ (websocket reconnects refresh on every attempt) can't turn a lambda outage
+ into a FusionAuth refresh per retry.
## Related
diff --git a/services/authentication_service/Cargo.toml b/services/authentication_service/Cargo.toml
index 075b0e4b9a..a07bdbcadb 100644
--- a/services/authentication_service/Cargo.toml
+++ b/services/authentication_service/Cargo.toml
@@ -191,6 +191,7 @@ database_env_vars = { path = "../../crates/database_env_vars" }
[dev-dependencies]
cool_asserts = "2"
+macro_auth = { path = "../../crates/macro_auth", features = ["testing"] }
macro_db_migrator = { path = "../../crates/macro_db_migrator" }
serde_urlencoded = { workspace = true }
wiremock = { workspace = true }
diff --git a/services/authentication_service/src/api/jwt/refresh.rs b/services/authentication_service/src/api/jwt/refresh.rs
index 645bedfa2d..f44304e75b 100644
--- a/services/authentication_service/src/api/jwt/refresh.rs
+++ b/services/authentication_service/src/api/jwt/refresh.rs
@@ -1,3 +1,6 @@
+#[cfg(test)]
+mod test;
+
use crate::api::{
context::TokenContext,
utils::{create_access_token_cookie, create_refresh_token_cookie},
@@ -9,11 +12,23 @@ use axum::{
response::{IntoResponse, Response},
};
use fusionauth::{FusionAuthClient, error::FusionAuthClientError};
-use macro_auth::{error::MacroAuthError, middleware::decode_jwt::JwtValidationArgs};
+use macro_auth::{
+ error::MacroAuthError,
+ middleware::decode_jwt::{
+ JwtValidationArgs, validate_fusionauth_access_token_allow_expired,
+ validate_macro_access_token,
+ },
+};
use model::response::UserTokensResponse;
-use std::sync::Arc;
+use std::{sync::Arc, time::Duration};
use tower_cookies::Cookies;
+/// Minimum age of a token without the Macro claims before it is refreshed. A newer one most
+/// likely came from a refresh whose populate lambda just failed, and while the lambda keeps
+/// failing, every client retry (websocket reconnects refresh on each attempt) would otherwise be
+/// another FusionAuth refresh and lambda run.
+const MISSING_MACRO_CLAIMS_REFRESH_COOLDOWN: Duration = Duration::from_secs(30);
+
#[derive(Debug, thiserror::Error)]
pub enum RefreshError {
#[error("internal server error")]
@@ -21,6 +36,8 @@ pub enum RefreshError {
#[error("refresh in progress")]
#[allow(dead_code)]
RefreshInProgress,
+ #[error("access token without macro claims was issued too recently to refresh")]
+ MissingMacroClaimsCooldown,
#[error("invalid refresh token")]
InvalidRefreshToken,
#[error("unauthorized")]
@@ -32,7 +49,9 @@ impl IntoResponse for RefreshError {
let status_code = match self {
RefreshError::InternalServerError => StatusCode::INTERNAL_SERVER_ERROR,
RefreshError::InvalidRefreshToken => StatusCode::BAD_REQUEST,
- RefreshError::RefreshInProgress => StatusCode::TOO_MANY_REQUESTS,
+ RefreshError::RefreshInProgress | RefreshError::MissingMacroClaimsCooldown => {
+ StatusCode::TOO_MANY_REQUESTS
+ }
RefreshError::Unauthorized => StatusCode::UNAUTHORIZED,
};
@@ -54,7 +73,7 @@ impl IntoResponse for RefreshError {
(status = 200, body = UserTokensResponse),
(status = 400, body=String),
(status = 401, body=String),
- (status = 429, body=String, description = "Refresh already in progress for this user"),
+ (status = 429, body=String, description = "Refresh already in progress for this user, or the access token lacks the Macro claims and was issued too recently to refresh"),
(status = 500, body=String),
)
)]
@@ -65,10 +84,7 @@ pub async fn handler(
token_context: Extension<TokenContext>,
cookies: Cookies,
) -> Result<Json<UserTokensResponse>, RefreshError> {
- match macro_auth::middleware::decode_jwt::validate_macro_access_token(
- &token_context.access_token,
- &jwt,
- ) {
+ match validate_macro_access_token(&token_context.access_token, &jwt) {
Ok(_) => {
// jwt is valid, return back original tokens
tracing::trace!("jwt still valid");
@@ -77,14 +93,28 @@ pub async fn handler(
refresh_token: token_context.refresh_token.clone(),
}));
}
- Err(e) => match e {
- // We only want to refresh the token if it's expired
- MacroAuthError::JwtExpired => {}
- _ => {
- tracing::error!(error=?e, "unable to decode jwt");
- return Err(RefreshError::Unauthorized);
+ Err(MacroAuthError::JwtExpired) => {}
+ // FusionAuth issues the token without the Macro claims when the JWT populate lambda
+ // fails; refreshing runs the lambda again.
+ Err(e) => {
+ match validate_fusionauth_access_token_allow_expired(&token_context.access_token, &jwt)
+ {
+ Ok(issued_at)
+ if issued_at.elapsed().unwrap_or_default()
+ < MISSING_MACRO_CLAIMS_REFRESH_COOLDOWN =>
+ {
+ tracing::info!(error=?e, "access token without macro claims is too new to refresh");
+ return Err(RefreshError::MissingMacroClaimsCooldown);
+ }
+ Ok(_) => {
+ tracing::info!(error=?e, "refreshing access token without macro claims");
+ }
+ Err(_) => {
+ tracing::error!(error=?e, "unable to decode jwt");
+ return Err(RefreshError::Unauthorized);
+ }
}
- },
+ }
}
// NOTE: Disabled until we fix FE auth setup.
@@ -127,6 +157,12 @@ pub async fn handler(
tracing::info!(time_taken=?start_time.elapsed(), "refresh token time");
+ validate_macro_access_token(&access_token, &jwt)
+ .inspect_err(|e| {
+ tracing::warn!(error=?e, "fusionauth issued an access token that fails validation");
+ })
+ .ok();
+
// Add in cookies to response
cookies.add(create_access_token_cookie(&access_token));
cookies.add(create_refresh_token_cookie(&refresh_token));
diff --git a/services/authentication_service/src/api/jwt/refresh/test.rs b/services/authentication_service/src/api/jwt/refresh/test.rs
new file mode 100644
index 0000000000..2754d602bf
--- /dev/null
+++ b/services/authentication_service/src/api/jwt/refresh/test.rs
@@ -0,0 +1,244 @@
+use std::{
+ sync::Arc,
+ time::{SystemTime, UNIX_EPOCH},
+};
+
+use axum::{
+ Router,
+ body::{Body, to_bytes},
+ extract::FromRef,
+ http::{Request, StatusCode, header::AUTHORIZATION},
+ routing::post,
+};
+use fusionauth::FusionAuthClient;
+use jsonwebtoken::{Algorithm, EncodingKey, Header, encode};
+use macro_auth::{constant::MACRO_REFRESH_TOKEN_HEADER, middleware::decode_jwt::JwtValidationArgs};
+use model::response::UserTokensResponse;
+use tower::{ServiceBuilder, ServiceExt};
+use tower_cookies::CookieManagerLayer;
+use wiremock::{
+ Mock, MockServer, ResponseTemplate,
+ matchers::{method, path},
+};
+
+use super::handler;
+use crate::api::middleware::extract_tokens;
+
+const REFRESH_TOKEN: &str = "refresh-token";
+const TEN_MINUTES: u64 = 600;
+const TWO_HOURS: u64 = 7200;
+
+#[derive(Clone, FromRef)]
+struct RefreshState {
+ auth_client: Arc<FusionAuthClient>,
+ jwt: JwtValidationArgs,
+}
+
+fn now() -> u64 {
+ SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .unwrap()
+ .as_secs()
+}
+
+/// What FusionAuth issues for `JwtValidationArgs::new_testing()` when the JWT populate lambda
+/// fails.
+fn claims_without_macro_claims(issued_at: u64) -> serde_json::Value {
+ serde_json::json!({
+ "aud": "", "exp": issued_at + 3600, "iat": issued_at, "iss": "", "sub": "fusion-user",
+ "tid": "tenant", "applicationId": "", "roles": [],
+ })
+}
+
+fn claims_with_macro_claims(issued_at: u64) -> serde_json::Value {
+ let mut claims = claims_without_macro_claims(issued_at);
+ claims["email"] = "[email protected]".into();
+ claims["fusion_user_id"] = "fusion-user".into();
+ claims["macro_user_id"] = "macro|[email protected]".into();
+ claims
+}
+
+fn sign(secret: &[u8], claims: &serde_json::Value) -> String {
+ let mut header = Header::new(Algorithm::HS256);
+ header.kid = Some("fusionauth-key".into());
+ encode(&header, claims, &EncodingKey::from_secret(secret)).unwrap()
+}
+
+fn refreshed() -> ResponseTemplate {
+ ResponseTemplate::new(200).set_body_json(serde_json::json!({
+ "token": "new-access-token",
+ "refreshToken": "new-refresh-token",
+ "refreshTokenId": "refresh-token-id",
+ }))
+}
+
+/// FusionAuth's `/api/jwt/refresh`, which must be called exactly `calls` times.
+async fn fusionauth(response: ResponseTemplate, calls: u64) -> MockServer {
+ let server = MockServer::start().await;
+ Mock::given(method("POST"))
+ .and(path("/api/jwt/refresh"))
+ .respond_with(response)
+ .expect(calls)
+ .mount(&server)
+ .await;
+ server
+}
+
+async fn post_refresh(fusionauth: &MockServer, access_token: &str) -> (StatusCode, String) {
+ let auth_client = FusionAuthClient::new(
+ "api-key".into(),
+ "client-id".into(),
+ "client-secret".into(),
+ fusionauth.uri(),
+ "http://localhost/oauth/redirect".into(),
+ "google-client-id".into(),
+ "google-client-secret".into(),
+ );
+ let response = Router::new()
+ .route(
+ "/jwt/refresh",
+ post(handler).layer(
+ ServiceBuilder::new()
+ .layer(axum::middleware::from_fn(extract_tokens::handler))
+ .layer(CookieManagerLayer::new()),
+ ),
+ )
+ .with_state(RefreshState {
+ auth_client: Arc::new(auth_client),
+ jwt: JwtValidationArgs::new_testing(),
+ })
+ .oneshot(
+ Request::builder()
+ .method("POST")
+ .uri("/jwt/refresh")
+ .header(AUTHORIZATION, format!("Bearer {access_token}"))
+ .header(MACRO_REFRESH_TOKEN_HEADER, REFRESH_TOKEN)
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ let status = response.status();
+ let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();
+ (status, String::from_utf8(body.to_vec()).unwrap())
+}
+
+#[tokio::test]
+async fn token_without_macro_claims_is_refreshed() {
+ let fusionauth = fusionauth(refreshed(), 3).await;
+ let issued_ats = [now() - 45, now() - TEN_MINUTES, now() - TWO_HOURS];
+
+ for issued_at in issued_ats {
+ let access_token = sign(b"", &claims_without_macro_claims(issued_at));
+ let (status, body) = post_refresh(&fusionauth, &access_token).await;
+
+ assert_eq!(status, StatusCode::OK, "issued at {issued_at}");
+ let tokens: UserTokensResponse = serde_json::from_str(&body).unwrap();
+ assert_eq!(tokens.access_token, "new-access-token");
+ assert_eq!(tokens.refresh_token, "new-refresh-token");
+ }
+}
+
+#[tokio::test]
+async fn token_without_macro_claims_is_not_refreshed_within_the_cooldown() {
+ let fusionauth = fusionauth(refreshed(), 0).await;
+ // The last one was issued by a FusionAuth whose clock is ahead of ours.
+ let issued_ats = [now(), now() - 15, now() + 60];
+
+ for issued_at in issued_ats {
+ let access_token = sign(b"", &claims_without_macro_claims(issued_at));
+
+ assert_eq!(
+ post_refresh(&fusionauth, &access_token).await,
+ (
+ StatusCode::TOO_MANY_REQUESTS,
+ "access token without macro claims was issued too recently to refresh".into()
+ ),
+ "issued at {issued_at}"
+ );
+ }
+}
+
+#[tokio::test]
+async fn token_not_issued_for_this_application_is_rejected_without_calling_fusionauth() {
+ let fusionauth = fusionauth(refreshed(), 0).await;
+ let issued_at = now() - TEN_MINUTES;
+ let mut other_audience = claims_without_macro_claims(issued_at);
+ other_audience["aud"] = "other-app".into();
+ let mut other_issuer = claims_without_macro_claims(issued_at);
+ other_issuer["iss"] = "other.issuer.test".into();
+ let cases = [
+ (
+ "signed with another secret",
+ sign(b"other-secret", &claims_without_macro_claims(issued_at)),
+ ),
+ (
+ "signed with another secret within the cooldown",
+ sign(b"other-secret", &claims_without_macro_claims(now())),
+ ),
+ (
+ "signed with another secret with the macro claims",
+ sign(b"other-secret", &claims_with_macro_claims(issued_at)),
+ ),
+ ("another audience", sign(b"", &other_audience)),
+ ("another issuer", sign(b"", &other_issuer)),
+ ("not a JWT", "not-a-jwt".into()),
+ ];
+
+ for (case, access_token) in cases {
+ assert_eq!(
+ post_refresh(&fusionauth, &access_token).await,
+ (StatusCode::UNAUTHORIZED, "unauthorized".into()),
+ "{case}"
+ );
+ }
+}
+
+#[tokio::test]
+async fn valid_token_is_returned_without_calling_fusionauth() {
+ let fusionauth = fusionauth(refreshed(), 0).await;
+ let access_token = sign(b"", &claims_with_macro_claims(now() - TEN_MINUTES));
+
+ let (status, body) = post_refresh(&fusionauth, &access_token).await;
+
+ assert_eq!(status, StatusCode::OK);
+ let tokens: UserTokensResponse = serde_json::from_str(&body).unwrap();
+ assert_eq!(tokens.access_token, access_token);
+ assert_eq!(tokens.refresh_token, REFRESH_TOKEN);
+}
+
+#[tokio::test]
+async fn expired_token_is_refreshed() {
+ let fusionauth = fusionauth(refreshed(), 1).await;
+ let access_token = sign(b"", &claims_with_macro_claims(now() - TWO_HOURS));
+
+ let (status, body) = post_refresh(&fusionauth, &access_token).await;
+
+ assert_eq!(status, StatusCode::OK);
+ let tokens: UserTokensResponse = serde_json::from_str(&body).unwrap();
+ assert_eq!(tokens.access_token, "new-access-token");
+}
+
+#[tokio::test]
+async fn fusionauth_failures_on_refreshing_a_token_without_macro_claims_are_reported() {
+ let access_token = sign(b"", &claims_without_macro_claims(now() - TEN_MINUTES));
+ let refresh_token_rejected = fusionauth(
+ ResponseTemplate::new(400)
+ .set_body_string("The refresh token was not found or has expired."),
+ 1,
+ )
+ .await;
+ let unavailable = fusionauth(ResponseTemplate::new(500), 1).await;
+
+ assert_eq!(
+ post_refresh(&refresh_token_rejected, &access_token).await,
+ (StatusCode::BAD_REQUEST, "invalid refresh token".into())
+ );
+ assert_eq!(
+ post_refresh(&unavailable, &access_token).await,
+ (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ "internal server error".into()
+ )
+ );
+}