hyprstream_core/services/oauth/
revocation.rs1use std::sync::Arc;
6
7use axum::extract::State;
8use axum::http::StatusCode;
9use axum::response::{IntoResponse, Response};
10use axum::Form;
11use serde::Deserialize;
12
13use super::state::OAuthState;
14
15#[derive(Deserialize)]
16pub struct RevocationRequest {
17 pub token: String,
19 #[serde(default)]
21 pub token_type_hint: Option<String>,
22}
23
24pub async fn revoke_token(
34 State(state): State<Arc<OAuthState>>,
35 Form(params): Form<RevocationRequest>,
36) -> Response {
37 let is_access_hint = params.token_type_hint.as_deref() == Some("access_token");
38
39 if !is_access_hint {
40 if let Err(e) = state.delete_refresh_token(¶ms.token).await {
41 tracing::warn!(error = %e, "Refresh token store delete failed during revocation");
42 } else {
43 tracing::info!("Revoked refresh token");
44 }
45 }
46
47 if is_access_hint || params.token_type_hint.is_none() {
48 match super::auth::verify_access_token(
56 state.as_ref(),
57 ¶ms.token,
58 super::auth::AudiencePolicy::AnyLocalIssuer,
59 )
60 .await
61 {
62 Ok(claims) => {
63 if let Err(response) = publish_access_token_revocation(&claims).await {
64 return response;
65 }
66 }
67 Err(_) => {
68 }
71 }
72 }
73
74 StatusCode::OK.into_response()
75}
76
77async fn publish_access_token_revocation(
81 claims: &hyprstream_rpc::auth::Claims,
82) -> Result<(), Response> {
83 let Some(ref jti) = claims.jti else {
84 return Ok(());
85 };
86 let cred_id = hyprstream_rpc::auth::CredentialId::jwt(&claims.iss, jti);
87 let Some(store) = hyprstream_rpc::auth::global_credential_revocation_store() else {
88 tracing::error!(sub = %claims.sub, "Revocation store unavailable — cannot publish revocation");
89 return Err(StatusCode::SERVICE_UNAVAILABLE.into_response());
90 };
91 publish_credential_revocation(store.as_ref(), cred_id, claims.exp).await?;
92 tracing::info!(sub = %claims.sub, "Revoked access token via credential revocation store");
93 Ok(())
94}
95
96async fn publish_credential_revocation(
99 store: &dyn hyprstream_rpc::auth::CredentialRevocationStore,
100 cred_id: hyprstream_rpc::auth::CredentialId,
101 expires_at: i64,
102) -> Result<(), Response> {
103 store
104 .revoke_credential(cred_id.clone(), expires_at)
105 .await
106 .map_err(|e| {
107 tracing::error!(credential = %cred_id, error = %e, "Revocation publication failed");
108 StatusCode::SERVICE_UNAVAILABLE.into_response()
109 })
110}
111
112#[cfg(test)]
113#[allow(clippy::unwrap_used, clippy::expect_used)]
114mod tests {
115 use super::*;
116 use crate::config::OAuthConfig;
117 use hyprstream_rpc_std::discovery_client::DiscoveryClient;
118 use hyprstream_rpc_std::policy_client::PolicyClient;
119
120 fn make_test_state(signing_key: &ed25519_dalek::SigningKey) -> (Arc<OAuthState>, String) {
122 use hyprstream_rpc::crypto::CryptoPolicy;
123 use hyprstream_rpc::rpc_client::RpcClientImpl;
124 use hyprstream_rpc::signer::LocalSigner;
125 use hyprstream_rpc::transport::lazy_uds::LazyUdsTransport;
126
127 let remote_key = ed25519_dalek::SigningKey::from_bytes(&[0x99; 32]).verifying_key();
128 let make_client = || {
129 Arc::new(
130 RpcClientImpl::new(
131 LocalSigner::new(signing_key.clone()),
132 LazyUdsTransport::new("/dev/null/revocation-test.sock".into()),
133 Some(remote_key),
134 )
135 .with_response_verify_policy(CryptoPolicy::Classical),
136 )
137 };
138 let mut config = OAuthConfig::default();
139 config.external_url = Some("https://idp.test.example".to_owned());
140 let issuer = config.issuer_url();
141 let state = Arc::new(OAuthState::new(
142 &config,
143 PolicyClient::new(make_client()),
144 DiscoveryClient::new(make_client()),
145 signing_key.verifying_key().to_bytes(),
146 ));
147 (state, issuer)
148 }
149
150 fn ensure_global_store() {
153 if hyprstream_rpc::auth::global_credential_revocation_store().is_none() {
154 let store = Arc::new(hyprstream_rpc::auth::InMemoryCredentialRevocationStore::new());
155 let _ = hyprstream_rpc::auth::set_global_credential_revocation_store(store);
156 }
157 }
158
159 #[tokio::test]
163 async fn resource_audience_token_is_revoked() {
164 ensure_global_store();
165
166 let signing_key = ed25519_dalek::SigningKey::from_bytes(&[0x55; 32]);
167 let (state, issuer) = make_test_state(&signing_key);
168 let resource_aud = "http://localhost:6792"; let now = chrono::Utc::now().timestamp();
171 let claims = hyprstream_rpc::auth::Claims::new("alice".to_owned(), now, now + 3600)
172 .with_issuer(issuer.clone())
173 .with_audience(Some(resource_aud.to_owned()))
174 .with_jti();
175 let token = hyprstream_rpc::auth::jwt::encode(&claims, &signing_key);
176 let actual_jti = claims.jti.as_deref().unwrap();
177
178 let cred_id = hyprstream_rpc::auth::CredentialId::jwt(&issuer, actual_jti);
179 let store = hyprstream_rpc::auth::global_credential_revocation_store().unwrap();
180 assert!(
181 !store.is_revoked(&cred_id).await,
182 "precondition: credential not yet revoked"
183 );
184
185 let response = revoke_token(
187 State(state),
188 Form(RevocationRequest {
189 token,
190 token_type_hint: Some("access_token".to_owned()),
191 }),
192 )
193 .await;
194
195 assert_eq!(response.status(), StatusCode::OK, "RFC 7009: always 200");
196 assert!(
197 store.is_revoked(&cred_id).await,
198 "resource-audience token must be revoked in the store"
199 );
200 }
201
202 #[tokio::test]
206 async fn forged_token_is_not_revoked() {
207 ensure_global_store();
208
209 let signing_key = ed25519_dalek::SigningKey::from_bytes(&[0x66; 32]);
210 let wrong_key = ed25519_dalek::SigningKey::from_bytes(&[0x77; 32]);
211 let (state, issuer) = make_test_state(&signing_key);
212 let resource_aud = "http://localhost:6792";
213
214 let now = chrono::Utc::now().timestamp();
215 let claims = hyprstream_rpc::auth::Claims::new("mallory".to_owned(), now, now + 3600)
216 .with_issuer(issuer.clone())
217 .with_audience(Some(resource_aud.to_owned()))
218 .with_jti();
219 let forged_token = hyprstream_rpc::auth::jwt::encode(&claims, &wrong_key);
221 let actual_jti = claims.jti.as_deref().unwrap();
222
223 let cred_id = hyprstream_rpc::auth::CredentialId::jwt(&issuer, actual_jti);
224 let store = hyprstream_rpc::auth::global_credential_revocation_store().unwrap();
225 assert!(
226 !store.is_revoked(&cred_id).await,
227 "precondition: not revoked"
228 );
229
230 let response = revoke_token(
231 State(state),
232 Form(RevocationRequest {
233 token: forged_token,
234 token_type_hint: Some("access_token".to_owned()),
235 }),
236 )
237 .await;
238
239 assert_eq!(response.status(), StatusCode::OK, "RFC 7009: always 200");
240 assert!(
241 !store.is_revoked(&cred_id).await,
242 "forged token must NOT publish a revocation"
243 );
244 }
245
246 #[tokio::test]
250 async fn publication_failure_is_service_unavailable() {
251 use hyprstream_rpc::auth::{
252 CredentialId, CredentialRevocationStore, RevocationPublishError,
253 };
254
255 struct FailingStore;
256
257 #[async_trait::async_trait]
258 impl CredentialRevocationStore for FailingStore {
259 async fn is_revoked_checked(&self, _id: &CredentialId) -> bool {
260 false
261 }
262
263 async fn revoke_credential(
264 &self,
265 _id: CredentialId,
266 _expires_at: i64,
267 ) -> Result<(), RevocationPublishError> {
268 Err(RevocationPublishError::new("stub: authority unavailable"))
269 }
270 }
271
272 let result = publish_credential_revocation(
273 &FailingStore,
274 CredentialId::jwt("https://a.example", "jti-1"),
275 9_999_999_999,
276 )
277 .await;
278 let response = result.expect_err("failed publication must surface as an error response");
279 assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
280 }
281}