-
Notifications
You must be signed in to change notification settings - Fork 646
Add DELETE /api/v1/trusted_publishing/tokens
API endpoint
#11234
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,2 +1,3 @@ | ||
pub mod exchange; | ||
pub mod json; | ||
pub mod revoke; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,48 @@ | ||
use crate::app::AppState; | ||
use crate::util::errors::{AppResult, custom}; | ||
use crates_io_database::schema::trustpub_tokens; | ||
use crates_io_trustpub::access_token::AccessToken; | ||
use diesel::prelude::*; | ||
use diesel_async::RunQueryDsl; | ||
use http::{HeaderMap, StatusCode, header}; | ||
|
||
#[cfg(test)] | ||
mod tests; | ||
|
||
/// Revoke a temporary access token. | ||
/// | ||
/// The access token is expected to be passed in the `Authorization` header | ||
/// as a `Bearer` token, similar to how it is used in the publish endpoint. | ||
#[utoipa::path( | ||
delete, | ||
path = "/api/v1/trusted_publishing/tokens", | ||
tag = "trusted_publishing", | ||
responses((status = 204, description = "Successful Response")), | ||
)] | ||
pub async fn revoke_trustpub_token(app: AppState, headers: HeaderMap) -> AppResult<StatusCode> { | ||
let Some(auth_header) = headers.get(header::AUTHORIZATION) else { | ||
let message = "Missing authorization header"; | ||
return Err(custom(StatusCode::UNAUTHORIZED, message)); | ||
}; | ||
|
||
let Some(bearer) = auth_header.as_bytes().strip_prefix(b"Bearer ") else { | ||
let message = "Invalid authorization header"; | ||
return Err(custom(StatusCode::UNAUTHORIZED, message)); | ||
}; | ||
|
||
let Ok(token) = AccessToken::from_byte_str(bearer) else { | ||
let message = "Invalid authorization header"; | ||
return Err(custom(StatusCode::UNAUTHORIZED, message)); | ||
}; | ||
|
||
let hashed_token = token.sha256(); | ||
|
||
let mut conn = app.db_write().await?; | ||
|
||
diesel::delete(trustpub_tokens::table) | ||
.filter(trustpub_tokens::hashed_token.eq(hashed_token.as_slice())) | ||
.execute(&mut conn) | ||
.await?; | ||
|
||
Ok(StatusCode::NO_CONTENT) | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,121 @@ | ||
use crate::tests::util::{MockTokenUser, RequestHelper, TestApp}; | ||
use chrono::{TimeDelta, Utc}; | ||
use crates_io_database::models::trustpub::NewToken; | ||
use crates_io_database::schema::trustpub_tokens; | ||
use crates_io_trustpub::access_token::AccessToken; | ||
use diesel::prelude::*; | ||
use diesel_async::{AsyncPgConnection, RunQueryDsl}; | ||
use http::StatusCode; | ||
use insta::assert_compact_debug_snapshot; | ||
use insta::assert_snapshot; | ||
use secrecy::ExposeSecret; | ||
use sha2::Sha256; | ||
use sha2::digest::Output; | ||
|
||
const URL: &str = "/api/v1/trusted_publishing/tokens"; | ||
|
||
fn generate_token() -> (String, Output<Sha256>) { | ||
let token = AccessToken::generate(); | ||
(token.finalize().expose_secret().to_string(), token.sha256()) | ||
} | ||
|
||
async fn new_token(conn: &mut AsyncPgConnection, crate_id: i32) -> QueryResult<String> { | ||
let (token, hashed_token) = generate_token(); | ||
|
||
let new_token = NewToken { | ||
expires_at: Utc::now() + TimeDelta::minutes(30), | ||
hashed_token: hashed_token.as_slice(), | ||
crate_ids: &[crate_id], | ||
}; | ||
|
||
new_token.insert(conn).await?; | ||
|
||
Ok(token) | ||
} | ||
|
||
async fn all_crate_ids(conn: &mut AsyncPgConnection) -> QueryResult<Vec<Vec<Option<i32>>>> { | ||
trustpub_tokens::table | ||
.select(trustpub_tokens::crate_ids) | ||
.load(conn) | ||
.await | ||
} | ||
|
||
#[tokio::test(flavor = "multi_thread")] | ||
async fn test_happy_path() -> anyhow::Result<()> { | ||
let (app, _client) = TestApp::full().empty().await; | ||
let mut conn = app.db_conn().await; | ||
|
||
let token1 = new_token(&mut conn, 1).await?; | ||
let _token2 = new_token(&mut conn, 2).await?; | ||
assert_compact_debug_snapshot!(all_crate_ids(&mut conn).await?, @"[[Some(1)], [Some(2)]]"); | ||
|
||
let header = format!("Bearer {}", token1); | ||
let token_client = MockTokenUser::with_auth_header(header, app.clone()); | ||
|
||
let response = token_client.delete::<()>(URL).await; | ||
assert_eq!(response.status(), StatusCode::NO_CONTENT); | ||
assert_eq!(response.text(), ""); | ||
|
||
// Check that the token is deleted | ||
assert_compact_debug_snapshot!(all_crate_ids(&mut conn).await?, @"[[Some(2)]]"); | ||
|
||
Ok(()) | ||
} | ||
|
||
#[tokio::test(flavor = "multi_thread")] | ||
async fn test_missing_authorization_header() -> anyhow::Result<()> { | ||
let (_app, client) = TestApp::full().empty().await; | ||
|
||
let response = client.delete::<()>(URL).await; | ||
assert_eq!(response.status(), StatusCode::UNAUTHORIZED); | ||
assert_snapshot!(response.text(), @r#"{"errors":[{"detail":"Missing authorization header"}]}"#); | ||
|
||
Ok(()) | ||
} | ||
|
||
#[tokio::test(flavor = "multi_thread")] | ||
async fn test_invalid_authorization_header_format() -> anyhow::Result<()> { | ||
let (app, _client) = TestApp::full().empty().await; | ||
|
||
// Create a client with an invalid authorization header (missing "Bearer " prefix) | ||
let header = "invalid-format".to_string(); | ||
let token_client = MockTokenUser::with_auth_header(header, app.clone()); | ||
|
||
let response = token_client.delete::<()>(URL).await; | ||
assert_eq!(response.status(), StatusCode::UNAUTHORIZED); | ||
assert_snapshot!(response.text(), @r#"{"errors":[{"detail":"Invalid authorization header"}]}"#); | ||
|
||
Ok(()) | ||
} | ||
|
||
#[tokio::test(flavor = "multi_thread")] | ||
async fn test_invalid_token_format() -> anyhow::Result<()> { | ||
let (app, _client) = TestApp::full().empty().await; | ||
|
||
// Create a client with an invalid token format | ||
let header = "Bearer invalid-token".to_string(); | ||
let token_client = MockTokenUser::with_auth_header(header, app.clone()); | ||
|
||
let response = token_client.delete::<()>(URL).await; | ||
assert_eq!(response.status(), StatusCode::UNAUTHORIZED); | ||
assert_snapshot!(response.text(), @r#"{"errors":[{"detail":"Invalid authorization header"}]}"#); | ||
|
||
Ok(()) | ||
} | ||
|
||
#[tokio::test(flavor = "multi_thread")] | ||
async fn test_non_existent_token() -> anyhow::Result<()> { | ||
let (app, _client) = TestApp::full().empty().await; | ||
|
||
// Generate a valid token format, but it doesn't exist in the database | ||
let (token, _) = generate_token(); | ||
let header = format!("Bearer {}", token); | ||
let token_client = MockTokenUser::with_auth_header(header, app.clone()); | ||
|
||
// The request should succeed with 204 No Content even though the token doesn't exist | ||
let response = token_client.delete::<()>(URL).await; | ||
assert_eq!(response.status(), StatusCode::NO_CONTENT); | ||
assert_eq!(response.text(), ""); | ||
|
||
Ok(()) | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.