this repo has no description
1use axum::{
2 extract::FromRequestParts,
3 http::{StatusCode, request::Parts},
4 response::{IntoResponse, Response},
5 Json,
6};
7use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
8use hmac::{Hmac, Mac};
9use serde_json::json;
10use sha2::Sha256;
11use sqlx::PgPool;
12use subtle::ConstantTimeEq;
13
14use crate::config::AuthConfig;
15use crate::state::AppState;
16use super::db;
17use super::dpop::DPoPVerifier;
18use super::OAuthError;
19
20pub struct OAuthTokenInfo {
21 pub did: String,
22 pub token_id: String,
23 pub client_id: String,
24 pub scope: Option<String>,
25 pub dpop_jkt: Option<String>,
26}
27
28pub struct VerifyResult {
29 pub did: String,
30 pub token_id: String,
31 pub client_id: String,
32 pub scope: Option<String>,
33}
34
35pub async fn verify_oauth_access_token(
36 pool: &PgPool,
37 access_token: &str,
38 dpop_proof: Option<&str>,
39 http_method: &str,
40 http_uri: &str,
41) -> Result<VerifyResult, OAuthError> {
42 let token_info = extract_oauth_token_info(access_token)?;
43 let token_data = db::get_token_by_id(pool, &token_info.token_id)
44 .await?
45 .ok_or_else(|| OAuthError::InvalidToken("Token not found or revoked".to_string()))?;
46 let now = chrono::Utc::now();
47 if token_data.expires_at < now {
48 return Err(OAuthError::InvalidToken("Token has expired".to_string()));
49 }
50 if let Some(expected_jkt) = &token_data.parameters.dpop_jkt {
51 let proof = dpop_proof.ok_or_else(|| {
52 OAuthError::UseDpopNonce("DPoP proof required".to_string())
53 })?;
54 let config = AuthConfig::get();
55 let verifier = DPoPVerifier::new(config.dpop_secret().as_bytes());
56 let access_token_hash = compute_ath(access_token);
57 let result = verifier.verify_proof(proof, http_method, http_uri, Some(&access_token_hash))?;
58 if !db::check_and_record_dpop_jti(pool, &result.jti).await? {
59 return Err(OAuthError::InvalidDpopProof(
60 "DPoP proof has already been used".to_string(),
61 ));
62 }
63 if &result.jkt != expected_jkt {
64 return Err(OAuthError::InvalidDpopProof(
65 "DPoP key binding mismatch".to_string(),
66 ));
67 }
68 }
69 Ok(VerifyResult {
70 did: token_data.did,
71 token_id: token_info.token_id,
72 client_id: token_data.client_id,
73 scope: token_data.scope,
74 })
75}
76
77pub fn extract_oauth_token_info(token: &str) -> Result<OAuthTokenInfo, OAuthError> {
78 let parts: Vec<&str> = token.split('.').collect();
79 if parts.len() != 3 {
80 return Err(OAuthError::InvalidToken("Invalid token format".to_string()));
81 }
82 let header_bytes = URL_SAFE_NO_PAD
83 .decode(parts[0])
84 .map_err(|_| OAuthError::InvalidToken("Invalid token encoding".to_string()))?;
85 let header: serde_json::Value = serde_json::from_slice(&header_bytes)
86 .map_err(|_| OAuthError::InvalidToken("Invalid token header".to_string()))?;
87 if header.get("typ").and_then(|t| t.as_str()) != Some("at+jwt") {
88 return Err(OAuthError::InvalidToken("Not an OAuth access token".to_string()));
89 }
90 if header.get("alg").and_then(|a| a.as_str()) != Some("HS256") {
91 return Err(OAuthError::InvalidToken("Unsupported algorithm".to_string()));
92 }
93 let config = AuthConfig::get();
94 let secret = config.jwt_secret();
95 let signing_input = format!("{}.{}", parts[0], parts[1]);
96 let provided_sig = URL_SAFE_NO_PAD
97 .decode(parts[2])
98 .map_err(|_| OAuthError::InvalidToken("Invalid signature encoding".to_string()))?;
99 type HmacSha256 = Hmac<Sha256>;
100 let mut mac = HmacSha256::new_from_slice(secret.as_bytes())
101 .map_err(|_| OAuthError::ServerError("HMAC initialization failed".to_string()))?;
102 mac.update(signing_input.as_bytes());
103 let expected_sig = mac.finalize().into_bytes();
104 if !bool::from(expected_sig.ct_eq(&provided_sig)) {
105 return Err(OAuthError::InvalidToken("Invalid token signature".to_string()));
106 }
107 let payload_bytes = URL_SAFE_NO_PAD
108 .decode(parts[1])
109 .map_err(|_| OAuthError::InvalidToken("Invalid payload encoding".to_string()))?;
110 let payload: serde_json::Value = serde_json::from_slice(&payload_bytes)
111 .map_err(|_| OAuthError::InvalidToken("Invalid token payload".to_string()))?;
112 let exp = payload
113 .get("exp")
114 .and_then(|e| e.as_i64())
115 .ok_or_else(|| OAuthError::InvalidToken("Missing exp claim".to_string()))?;
116 let now = chrono::Utc::now().timestamp();
117 if exp < now {
118 return Err(OAuthError::InvalidToken("Token has expired".to_string()));
119 }
120 let token_id = payload
121 .get("jti")
122 .and_then(|j| j.as_str())
123 .ok_or_else(|| OAuthError::InvalidToken("Missing jti claim".to_string()))?
124 .to_string();
125 let did = payload
126 .get("sub")
127 .and_then(|s| s.as_str())
128 .ok_or_else(|| OAuthError::InvalidToken("Missing sub claim".to_string()))?
129 .to_string();
130 let scope = payload.get("scope").and_then(|s| s.as_str()).map(|s| s.to_string());
131 let dpop_jkt = payload
132 .get("cnf")
133 .and_then(|c| c.get("jkt"))
134 .and_then(|j| j.as_str())
135 .map(|s| s.to_string());
136 let client_id = payload
137 .get("client_id")
138 .and_then(|c| c.as_str())
139 .map(|s| s.to_string())
140 .unwrap_or_default();
141 Ok(OAuthTokenInfo {
142 did,
143 token_id,
144 client_id,
145 scope,
146 dpop_jkt,
147 })
148}
149
150fn compute_ath(access_token: &str) -> String {
151 use sha2::Digest;
152 let mut hasher = Sha256::new();
153 hasher.update(access_token.as_bytes());
154 let hash = hasher.finalize();
155 URL_SAFE_NO_PAD.encode(&hash)
156}
157
158pub fn generate_dpop_nonce() -> String {
159 let config = AuthConfig::get();
160 let verifier = DPoPVerifier::new(config.dpop_secret().as_bytes());
161 verifier.generate_nonce()
162}
163
164pub struct OAuthUser {
165 pub did: String,
166 pub client_id: Option<String>,
167 pub scope: Option<String>,
168 pub is_oauth: bool,
169}
170
171pub struct OAuthAuthError {
172 pub status: StatusCode,
173 pub error: String,
174 pub message: String,
175 pub dpop_nonce: Option<String>,
176}
177
178impl IntoResponse for OAuthAuthError {
179 fn into_response(self) -> Response {
180 let mut response = (
181 self.status,
182 Json(json!({
183 "error": self.error,
184 "message": self.message
185 })),
186 )
187 .into_response();
188 if let Some(nonce) = self.dpop_nonce {
189 response.headers_mut().insert(
190 "DPoP-Nonce",
191 nonce.parse().unwrap(),
192 );
193 }
194 response
195 }
196}
197
198impl FromRequestParts<AppState> for OAuthUser {
199 type Rejection = OAuthAuthError;
200
201 async fn from_request_parts(parts: &mut Parts, state: &AppState) -> Result<Self, Self::Rejection> {
202 let auth_header = parts
203 .headers
204 .get("Authorization")
205 .and_then(|v| v.to_str().ok())
206 .ok_or_else(|| OAuthAuthError {
207 status: StatusCode::UNAUTHORIZED,
208 error: "AuthenticationRequired".to_string(),
209 message: "Authorization header required".to_string(),
210 dpop_nonce: None,
211 })?;
212 let auth_header_trimmed = auth_header.trim();
213 let (token, is_dpop_token) = if auth_header_trimmed.len() >= 7 && auth_header_trimmed[..7].eq_ignore_ascii_case("bearer ") {
214 (auth_header_trimmed[7..].trim(), false)
215 } else if auth_header_trimmed.len() >= 5 && auth_header_trimmed[..5].eq_ignore_ascii_case("dpop ") {
216 (auth_header_trimmed[5..].trim(), true)
217 } else {
218 return Err(OAuthAuthError {
219 status: StatusCode::UNAUTHORIZED,
220 error: "InvalidRequest".to_string(),
221 message: "Invalid authorization scheme".to_string(),
222 dpop_nonce: None,
223 });
224 };
225 let dpop_proof = parts
226 .headers
227 .get("DPoP")
228 .and_then(|v| v.to_str().ok());
229 if let Ok(result) = try_legacy_auth(&state.db, token).await {
230 return Ok(OAuthUser {
231 did: result.did,
232 client_id: None,
233 scope: None,
234 is_oauth: false,
235 });
236 }
237 let http_method = parts.method.as_str();
238 let http_uri = parts.uri.to_string();
239 match verify_oauth_access_token(&state.db, token, dpop_proof, http_method, &http_uri).await {
240 Ok(result) => Ok(OAuthUser {
241 did: result.did,
242 client_id: Some(result.client_id),
243 scope: result.scope,
244 is_oauth: true,
245 }),
246 Err(OAuthError::UseDpopNonce(nonce)) => Err(OAuthAuthError {
247 status: StatusCode::UNAUTHORIZED,
248 error: "use_dpop_nonce".to_string(),
249 message: "DPoP nonce required".to_string(),
250 dpop_nonce: Some(nonce),
251 }),
252 Err(OAuthError::InvalidDpopProof(msg)) => {
253 let nonce = generate_dpop_nonce();
254 Err(OAuthAuthError {
255 status: StatusCode::UNAUTHORIZED,
256 error: "invalid_dpop_proof".to_string(),
257 message: msg,
258 dpop_nonce: Some(nonce),
259 })
260 }
261 Err(e) => {
262 let nonce = if is_dpop_token { Some(generate_dpop_nonce()) } else { None };
263 Err(OAuthAuthError {
264 status: StatusCode::UNAUTHORIZED,
265 error: "AuthenticationFailed".to_string(),
266 message: format!("{:?}", e),
267 dpop_nonce: nonce,
268 })
269 }
270 }
271 }
272}
273
274struct LegacyAuthResult {
275 did: String,
276}
277
278async fn try_legacy_auth(pool: &PgPool, token: &str) -> Result<LegacyAuthResult, ()> {
279 match crate::auth::validate_bearer_token(pool, token).await {
280 Ok(user) if !user.is_oauth => Ok(LegacyAuthResult { did: user.did }),
281 _ => Err(()),
282 }
283}