Skip to content

Commit a1c4691

Browse files
committed
Add PATCH /crates/:crate/:version route
Signed-off-by: Rustin170506 <[email protected]>
1 parent 3678583 commit a1c4691

File tree

3 files changed

+161
-67
lines changed

3 files changed

+161
-67
lines changed

src/controllers/version/metadata.rs

Lines changed: 156 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,17 +6,39 @@
66
77
use axum::extract::Path;
88
use axum::Json;
9+
use crates_io_worker::BackgroundJob;
10+
use diesel::{
11+
BoolExpressionMethods, ExpressionMethods, PgExpressionMethods, QueryDsl, RunQueryDsl,
12+
};
913
use diesel_async::async_connection_wrapper::AsyncConnectionWrapper;
14+
use http::request::Parts;
15+
use http::StatusCode;
16+
use serde::Deserialize;
1017
use serde_json::Value;
18+
use tokio::runtime::Handle;
1119

1220
use crate::app::AppState;
13-
use crate::models::VersionOwnerAction;
21+
use crate::auth::AuthCheck;
22+
use crate::models::token::EndpointScope;
23+
use crate::models::{
24+
insert_version_owner_action, Crate, Rights, Version, VersionAction, VersionOwnerAction,
25+
};
26+
use crate::rate_limiter::LimitedAction;
27+
use crate::schema::versions;
1428
use crate::tasks::spawn_blocking;
15-
use crate::util::errors::{version_not_found, AppResult};
29+
use crate::util::diesel::Conn;
30+
use crate::util::errors::{bad_request, custom, version_not_found, AppResult};
1631
use crate::views::{EncodableDependency, EncodableVersion};
32+
use crate::worker::jobs::{self, UpdateDefaultVersion};
1733

1834
use super::version_and_crate;
1935

36+
#[derive(Deserialize)]
37+
pub struct VersionUpdate {
38+
yanked: Option<bool>,
39+
yank_message: Option<String>,
40+
}
41+
2042
/// Handles the `GET /crates/:crate_id/:version/dependencies` route.
2143
///
2244
/// This information can be obtained directly from the index.
@@ -84,3 +106,135 @@ pub async fn show(
84106
})
85107
.await
86108
}
109+
110+
/// Handles the `PATCH /crates/:crate/:version` route.
111+
///
112+
/// This endpoint allows updating the yanked state of a version, including a yank message.
113+
pub async fn update(
114+
state: AppState,
115+
Path((crate_name, version)): Path<(String, String)>,
116+
req: Parts,
117+
Json(update_data): Json<VersionUpdate>,
118+
) -> AppResult<Json<Value>> {
119+
if semver::Version::parse(&version).is_err() {
120+
return Err(version_not_found(&crate_name, &version));
121+
}
122+
123+
let conn = state.db_write().await?;
124+
spawn_blocking(move || {
125+
let conn: &mut AsyncConnectionWrapper<_> = &mut conn.into();
126+
let (mut version, krate) = version_and_crate(conn, &crate_name, &version)?;
127+
128+
validate_yank_update(&update_data, &version)?;
129+
perform_version_yank_update(
130+
&state,
131+
&req,
132+
conn,
133+
&mut version,
134+
&krate,
135+
update_data.yanked,
136+
update_data.yank_message,
137+
)?;
138+
139+
let published_by = version.published_by(conn);
140+
let actions = VersionOwnerAction::by_version(conn, &version)?;
141+
let updated_version = EncodableVersion::from(version, &krate.name, published_by, actions);
142+
Ok(Json(json!({ "version": updated_version })))
143+
})
144+
.await
145+
}
146+
147+
fn validate_yank_update(update_data: &VersionUpdate, version: &Version) -> AppResult<()> {
148+
match (update_data.yanked, &update_data.yank_message) {
149+
(Some(false), Some(_)) => {
150+
return Err(bad_request("Cannot set yank message when unyanking"));
151+
}
152+
(None, Some(_)) => {
153+
if !version.yanked {
154+
return Err(bad_request(
155+
"Cannot update yank message for a version that is not yanked",
156+
));
157+
}
158+
}
159+
_ => {}
160+
}
161+
Ok(())
162+
}
163+
164+
pub fn perform_version_yank_update(
165+
state: &AppState,
166+
req: &Parts,
167+
conn: &mut impl Conn,
168+
version: &mut Version,
169+
krate: &Crate,
170+
yanked: Option<bool>,
171+
yank_message: Option<String>,
172+
) -> AppResult<()> {
173+
let auth = AuthCheck::default()
174+
.with_endpoint_scope(EndpointScope::Yank)
175+
.for_crate(&krate.name)
176+
.check(req, conn)?;
177+
178+
state
179+
.rate_limiter
180+
.check_rate_limit(auth.user_id(), LimitedAction::YankUnyank, conn)?;
181+
182+
let api_token_id = auth.api_token_id();
183+
let user = auth.user();
184+
let owners = krate.owners(conn)?;
185+
186+
if Handle::current().block_on(user.rights(state, &owners))? < Rights::Publish {
187+
if user.is_admin {
188+
let action = if version.yanked {
189+
"yanking"
190+
} else {
191+
"unyanking"
192+
};
193+
warn!(
194+
"Admin {} is {action} {}@{}",
195+
user.gh_login, krate.name, version.num
196+
);
197+
} else {
198+
return Err(custom(
199+
StatusCode::FORBIDDEN,
200+
"must already be an owner to yank or unyank",
201+
));
202+
}
203+
}
204+
205+
let yanked = yanked.unwrap_or(version.yanked);
206+
// Check if the yanked state or yank message has changed and update if necessary
207+
let updated_cnt = diesel::update(
208+
versions::table.find(version.id).filter(
209+
versions::yanked
210+
.is_distinct_from(yanked)
211+
.or(versions::yank_message.is_distinct_from(&yank_message)),
212+
),
213+
)
214+
.set((
215+
versions::yanked.eq(yanked),
216+
versions::yank_message.eq(&yank_message),
217+
))
218+
.execute(conn)?;
219+
220+
// If no rows were updated, return early
221+
if updated_cnt == 0 {
222+
return Ok(());
223+
}
224+
225+
// Apply the update to the version
226+
version.yanked = yanked;
227+
version.yank_message = yank_message;
228+
229+
let action = if version.yanked {
230+
VersionAction::Yank
231+
} else {
232+
VersionAction::Unyank
233+
};
234+
insert_version_owner_action(conn, version.id, user.id, api_token_id, action)?;
235+
236+
jobs::enqueue_sync_to_index(&krate.name, conn)?;
237+
UpdateDefaultVersion::new(krate.id).enqueue(conn)?;
238+
239+
Ok(())
240+
}

src/controllers/version/yank.rs

Lines changed: 4 additions & 64 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,15 @@
11
//! Endpoints for yanking and unyanking specific versions of crates
22
3+
use super::metadata::perform_version_yank_update;
34
use super::version_and_crate;
45
use crate::app::AppState;
5-
use crate::auth::AuthCheck;
66
use crate::controllers::helpers::ok_true;
7-
use crate::models::token::EndpointScope;
8-
use crate::models::Rights;
9-
use crate::models::{insert_version_owner_action, VersionAction};
10-
use crate::rate_limiter::LimitedAction;
11-
use crate::schema::versions;
127
use crate::tasks::spawn_blocking;
13-
use crate::util::errors::{custom, version_not_found, AppResult};
14-
use crate::worker::jobs;
15-
use crate::worker::jobs::UpdateDefaultVersion;
8+
use crate::util::errors::{version_not_found, AppResult};
169
use axum::extract::Path;
1710
use axum::response::Response;
18-
use crates_io_worker::BackgroundJob;
19-
use diesel::prelude::*;
2011
use diesel_async::async_connection_wrapper::AsyncConnectionWrapper;
2112
use http::request::Parts;
22-
use http::StatusCode;
23-
use tokio::runtime::Handle;
2413

2514
/// Handles the `DELETE /crates/:crate_id/:version/yank` route.
2615
/// This does not delete a crate version, it makes the crate
@@ -66,57 +55,8 @@ async fn modify_yank(
6655
let conn = state.db_write().await?;
6756
spawn_blocking(move || {
6857
let conn: &mut AsyncConnectionWrapper<_> = &mut conn.into();
69-
70-
let auth = AuthCheck::default()
71-
.with_endpoint_scope(EndpointScope::Yank)
72-
.for_crate(&crate_name)
73-
.check(&req, conn)?;
74-
75-
state
76-
.rate_limiter
77-
.check_rate_limit(auth.user_id(), LimitedAction::YankUnyank, conn)?;
78-
79-
let (version, krate) = version_and_crate(conn, &crate_name, &version)?;
80-
let api_token_id = auth.api_token_id();
81-
let user = auth.user();
82-
let owners = krate.owners(conn)?;
83-
84-
if Handle::current().block_on(user.rights(&state, &owners))? < Rights::Publish {
85-
if user.is_admin {
86-
let action = if yanked { "yanking" } else { "unyanking" };
87-
warn!(
88-
"Admin {} is {action} {}@{}",
89-
user.gh_login, krate.name, version.num
90-
);
91-
} else {
92-
return Err(custom(
93-
StatusCode::FORBIDDEN,
94-
"must already be an owner to yank or unyank",
95-
));
96-
}
97-
}
98-
99-
if version.yanked == yanked {
100-
// The crate is already in the state requested, nothing to do
101-
return ok_true();
102-
}
103-
104-
diesel::update(&version)
105-
.set(versions::yanked.eq(yanked))
106-
.execute(conn)?;
107-
108-
let action = if yanked {
109-
VersionAction::Yank
110-
} else {
111-
VersionAction::Unyank
112-
};
113-
114-
insert_version_owner_action(conn, version.id, user.id, api_token_id, action)?;
115-
116-
jobs::enqueue_sync_to_index(&krate.name, conn)?;
117-
118-
UpdateDefaultVersion::new(krate.id).enqueue(conn)?;
119-
58+
let (mut version, krate) = version_and_crate(conn, &crate_name, &version)?;
59+
perform_version_yank_update(&state, &req, conn, &mut version, &krate, Some(yanked), None)?;
12060
ok_true()
12161
})
12262
.await

src/router.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ pub fn build_axum_router(state: AppState) -> Router<()> {
4545
.route("/api/v1/crates/:crate_id", get(krate::metadata::show))
4646
.route(
4747
"/api/v1/crates/:crate_id/:version",
48-
get(version::metadata::show),
48+
get(version::metadata::show).patch(version::metadata::update),
4949
)
5050
.route(
5151
"/api/v1/crates/:crate_id/:version/readme",

0 commit comments

Comments
 (0)