Skip to main content

hyprstream_core/services/oauth/
revocation.rs

1//! OAuth 2.0 Token Revocation (RFC 7009).
2//!
3//! `POST /oauth/revoke` — revokes refresh tokens and access tokens.
4
5use 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    /// The token to revoke.
18    pub token: String,
19    /// Optional hint: "refresh_token" or "access_token".
20    #[serde(default)]
21    pub token_type_hint: Option<String>,
22}
23
24/// POST /oauth/revoke (RFC 7009)
25///
26/// Revokes a refresh token or access token. Access tokens with a `jti` claim
27/// are published to the credential-revocation store (checked by
28/// `verify_claims` on every request). Per RFC 7009 Section 2.1, the server
29/// responds with 200 OK even if the token is invalid or already revoked.
30/// Publication failure is different: an absent store or a publication the
31/// revocation authority did not durably accept is a 503 — a revocation that
32/// did not happen must never look like success.
33pub 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(&params.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        // Verify the token using the single verification stack
49        // (typ, signature, local-issuer) with the relaxed audience
50        // policy appropriate for revocation: any locally-issued
51        // resource-audience token may be revoked. An unverified
52        // token's iss/jti/exp are attacker-controlled; a forged
53        // token must not revoke another credential. If verification
54        // fails, return 200 per RFC 7009 but do not modify the store.
55        match super::auth::verify_access_token(
56            state.as_ref(),
57            &params.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                // Token verification failed — may be expired, wrong key,
69                // or not a JWT. RFC 7009: still 200.
70            }
71        }
72    }
73
74    StatusCode::OK.into_response()
75}
76
77/// Publish a verified access token's credential ID to the process-global
78/// revocation store. Fail-closed: an absent store or a rejected publication
79/// yields `503 Service Unavailable`.
80async 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
96/// Publish one credential revocation to `store`. A publication the authority
97/// did not durably accept is a 503, not a success.
98async 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    /// Build a minimal OAuthState with a known Ed25519 signing key.
121    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    /// Ensure the global credential-revocation store is published. If it's
151    /// already set (from another test), use the existing one.
152    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    /// A valid locally-signed RFC 9068 access token with a resource audience
160    /// (not the OAuth issuer URL) is successfully revoked: its exact
161    /// CredentialId appears in the global store after the handler returns.
162    #[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"; // MCP/xet resource audience
169
170        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        // Call the actual revocation handler.
186        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    /// A forged (wrong-key-signed) token returns 200 (RFC 7009) but does NOT
203    /// publish to the store — attacker-controlled claims cannot revoke
204    /// another credential.
205    #[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        // Sign with the WRONG key — the state expects signing_key's VK.
220        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    /// A revocation store whose authority rejects the publication surfaces as
247    /// 503 — a revocation that was not durably accepted must never look like
248    /// success.
249    #[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}