Skip to content

Introduce users.is_admin column and allow admins to yank/unyank versions #7852

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 8 commits into from
Jan 4, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion app/components/version-list/row.hbs
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@
{{/if}}
</div>

{{#if this.isOwner}}
{{#if this.canYank}}
<YankButton @version={{@version}} local-class="yank-button" />
{{/if}}
</div>
4 changes: 4 additions & 0 deletions app/components/version-list/row.js
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,10 @@ export default class VersionRow extends Component {
return this.args.version.crate?.owner_user?.findBy('id', this.session.currentUser?.id);
}

get canYank() {
return this.isOwner || this.session.currentUser?.is_admin;
}

@action setFocused(value) {
this.focused = value;
}
Expand Down
1 change: 1 addition & 0 deletions app/models/user.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ export default class User extends Model {
@attr email_verified;
@attr email_verification_sent;
@attr name;
@attr is_admin;
@attr login;
@attr avatar;
@attr url;
Expand Down
1 change: 1 addition & 0 deletions migrations/2023-12-31-153126_add_admin_column/down.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
ALTER TABLE users DROP COLUMN is_admin;
1 change: 1 addition & 0 deletions migrations/2023-12-31-153126_add_admin_column/up.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
ALTER TABLE users ADD COLUMN is_admin BOOL DEFAULT false NOT NULL;
1 change: 1 addition & 0 deletions mirage/factories/user.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ export default Factory.extend({

emailVerified: null,
emailVerificationToken: null,
isAdmin: false,

afterCreate(model) {
if (model.emailVerified === null) {
Expand Down
1 change: 1 addition & 0 deletions mirage/serializers/user.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ export default BaseSerializer.extend({
if (removePrivateData) {
delete hash.email;
delete hash.email_verified;
delete hash.is_admin;
} else {
hash.email_verification_sent = hash.email_verified || Boolean(hash.email_verification_token);
}
Expand Down
7 changes: 6 additions & 1 deletion src/controllers/version/yank.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,12 @@ fn modify_yank(
let owners = krate.owners(conn)?;

if Handle::current().block_on(user.rights(state, &owners))? < Rights::Publish {
return Err(cargo_err("must already be an owner to yank or unyank"));
if user.is_admin {
let action = if yanked { "yanking" } else { "unyanking" };
warn!("Admin {} is {action} crate {}", user.gh_login, krate.name);
} else {
return Err(cargo_err("must already be an owner to yank or unyank"));
}
}

if version.yanked == yanked {
Expand Down
1 change: 1 addition & 0 deletions src/models/user.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ pub struct User {
pub gh_id: i32,
pub account_lock_reason: Option<String>,
pub account_lock_until: Option<NaiveDateTime>,
pub is_admin: bool,
}

/// Represents a new user record insertable to the `users` table
Expand Down
6 changes: 6 additions & 0 deletions src/schema.rs
Original file line number Diff line number Diff line change
Expand Up @@ -807,6 +807,12 @@ diesel::table! {
///
/// (Automatically generated by Diesel.)
account_lock_until -> Nullable<Timestamp>,
/// The `is_admin` column of the `users` table.
///
/// Its SQL type is `Bool`.
///
/// (Automatically generated by Diesel.)
is_admin -> Bool,
}
}

Expand Down
82 changes: 71 additions & 11 deletions src/tests/routes/crates/versions/yank_unyank.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,8 @@ mod auth {
use crate::util::{MockAnonymousUser, MockCookieUser};
use chrono::{Duration, Utc};
use crates_io::models::token::{CrateScope, EndpointScope};
use crates_io::schema::{crates, users, versions};
use diesel::prelude::*;

const CRATE_NAME: &str = "fyk";
const CRATE_VERSION: &str = "1.0.0";
Expand All @@ -110,74 +112,94 @@ mod auth {
(app, anon, cookie)
}

fn is_yanked(app: &TestApp) -> bool {
app.db(|conn| {
versions::table
.inner_join(crates::table)
.select(versions::yanked)
.filter(crates::name.eq(CRATE_NAME))
.filter(versions::num.eq(CRATE_VERSION))
.get_result(conn)
.unwrap()
})
}

#[test]
fn unauthenticated() {
let (_, client, _) = prepare();
let (app, client, _) = prepare();

let response = client.yank(CRATE_NAME, CRATE_VERSION);
assert_eq!(response.status(), StatusCode::FORBIDDEN);
assert_eq!(
response.into_json(),
json!({ "errors": [{ "detail": "must be logged in to perform that action" }] })
);
assert!(!is_yanked(&app));

let response = client.unyank(CRATE_NAME, CRATE_VERSION);
assert_eq!(response.status(), StatusCode::FORBIDDEN);
assert_eq!(
response.into_json(),
json!({ "errors": [{ "detail": "must be logged in to perform that action" }] })
);
assert!(!is_yanked(&app));
}

#[test]
fn cookie_user() {
let (_, _, client) = prepare();
let (app, _, client) = prepare();

let response = client.yank(CRATE_NAME, CRATE_VERSION);
assert_eq!(response.status(), StatusCode::OK);
assert_eq!(response.into_json(), json!({ "ok": true }));
assert!(is_yanked(&app));

let response = client.unyank(CRATE_NAME, CRATE_VERSION);
assert_eq!(response.status(), StatusCode::OK);
assert_eq!(response.into_json(), json!({ "ok": true }));
assert!(!is_yanked(&app));
}

#[test]
fn token_user() {
let (_, _, client) = prepare();
let (app, _, client) = prepare();
let client = client.db_new_token("test-token");

let response = client.yank(CRATE_NAME, CRATE_VERSION);
assert_eq!(response.status(), StatusCode::OK);
assert_eq!(response.into_json(), json!({ "ok": true }));
assert!(is_yanked(&app));

let response = client.unyank(CRATE_NAME, CRATE_VERSION);
assert_eq!(response.status(), StatusCode::OK);
assert_eq!(response.into_json(), json!({ "ok": true }));
assert!(!is_yanked(&app));
}

#[test]
fn token_user_not_expired() {
let expired_at = Utc::now() + Duration::days(7);

let (_, _, client) = prepare();
let (app, _, client) = prepare();
let client =
client.db_new_scoped_token("test-token", None, None, Some(expired_at.naive_utc()));

let response = client.yank(CRATE_NAME, CRATE_VERSION);
assert_eq!(response.status(), StatusCode::OK);
assert_eq!(response.into_json(), json!({ "ok": true }));
assert!(is_yanked(&app));

let response = client.unyank(CRATE_NAME, CRATE_VERSION);
assert_eq!(response.status(), StatusCode::OK);
assert_eq!(response.into_json(), json!({ "ok": true }));
assert!(!is_yanked(&app));
}

#[test]
fn token_user_expired() {
let expired_at = Utc::now() - Duration::days(7);

let (_, _, client) = prepare();
let (app, _, client) = prepare();
let client =
client.db_new_scoped_token("test-token", None, None, Some(expired_at.naive_utc()));

Expand All @@ -187,33 +209,37 @@ mod auth {
response.into_json(),
json!({ "errors": [{ "detail": "must be logged in to perform that action" }] })
);
assert!(!is_yanked(&app));

let response = client.unyank(CRATE_NAME, CRATE_VERSION);
assert_eq!(response.status(), StatusCode::FORBIDDEN);
assert_eq!(
response.into_json(),
json!({ "errors": [{ "detail": "must be logged in to perform that action" }] })
);
assert!(!is_yanked(&app));
}

#[test]
fn token_user_with_correct_endpoint_scope() {
let (_, _, client) = prepare();
let (app, _, client) = prepare();
let client =
client.db_new_scoped_token("test-token", None, Some(vec![EndpointScope::Yank]), None);

let response = client.yank(CRATE_NAME, CRATE_VERSION);
assert_eq!(response.status(), StatusCode::OK);
assert_eq!(response.into_json(), json!({ "ok": true }));
assert!(is_yanked(&app));

let response = client.unyank(CRATE_NAME, CRATE_VERSION);
assert_eq!(response.status(), StatusCode::OK);
assert_eq!(response.into_json(), json!({ "ok": true }));
assert!(!is_yanked(&app));
}

#[test]
fn token_user_with_incorrect_endpoint_scope() {
let (_, _, client) = prepare();
let (app, _, client) = prepare();
let client = client.db_new_scoped_token(
"test-token",
None,
Expand All @@ -227,18 +253,20 @@ mod auth {
response.into_json(),
json!({ "errors": [{ "detail": "must be logged in to perform that action" }] })
);
assert!(!is_yanked(&app));

let response = client.unyank(CRATE_NAME, CRATE_VERSION);
assert_eq!(response.status(), StatusCode::FORBIDDEN);
assert_eq!(
response.into_json(),
json!({ "errors": [{ "detail": "must be logged in to perform that action" }] })
);
assert!(!is_yanked(&app));
}

#[test]
fn token_user_with_correct_crate_scope() {
let (_, _, client) = prepare();
let (app, _, client) = prepare();
let client = client.db_new_scoped_token(
"test-token",
Some(vec![CrateScope::try_from(CRATE_NAME).unwrap()]),
Expand All @@ -249,15 +277,17 @@ mod auth {
let response = client.yank(CRATE_NAME, CRATE_VERSION);
assert_eq!(response.status(), StatusCode::OK);
assert_eq!(response.into_json(), json!({ "ok": true }));
assert!(is_yanked(&app));

let response = client.unyank(CRATE_NAME, CRATE_VERSION);
assert_eq!(response.status(), StatusCode::OK);
assert_eq!(response.into_json(), json!({ "ok": true }));
assert!(!is_yanked(&app));
}

#[test]
fn token_user_with_correct_wildcard_crate_scope() {
let (_, _, client) = prepare();
let (app, _, client) = prepare();
let wildcard = format!("{}*", CRATE_NAME.chars().next().unwrap());
let client = client.db_new_scoped_token(
"test-token",
Expand All @@ -269,15 +299,17 @@ mod auth {
let response = client.yank(CRATE_NAME, CRATE_VERSION);
assert_eq!(response.status(), StatusCode::OK);
assert_eq!(response.into_json(), json!({ "ok": true }));
assert!(is_yanked(&app));

let response = client.unyank(CRATE_NAME, CRATE_VERSION);
assert_eq!(response.status(), StatusCode::OK);
assert_eq!(response.into_json(), json!({ "ok": true }));
assert!(!is_yanked(&app));
}

#[test]
fn token_user_with_incorrect_crate_scope() {
let (_, _, client) = prepare();
let (app, _, client) = prepare();
let client = client.db_new_scoped_token(
"test-token",
Some(vec![CrateScope::try_from("foo").unwrap()]),
Expand All @@ -291,18 +323,20 @@ mod auth {
response.into_json(),
json!({ "errors": [{ "detail": "must be logged in to perform that action" }] })
);
assert!(!is_yanked(&app));

let response = client.unyank(CRATE_NAME, CRATE_VERSION);
assert_eq!(response.status(), StatusCode::FORBIDDEN);
assert_eq!(
response.into_json(),
json!({ "errors": [{ "detail": "must be logged in to perform that action" }] })
);
assert!(!is_yanked(&app));
}

#[test]
fn token_user_with_incorrect_wildcard_crate_scope() {
let (_, _, client) = prepare();
let (app, _, client) = prepare();
let client = client.db_new_scoped_token(
"test-token",
Some(vec![CrateScope::try_from("foo*").unwrap()]),
Expand All @@ -316,12 +350,38 @@ mod auth {
response.into_json(),
json!({ "errors": [{ "detail": "must be logged in to perform that action" }] })
);
assert!(!is_yanked(&app));

let response = client.unyank(CRATE_NAME, CRATE_VERSION);
assert_eq!(response.status(), StatusCode::FORBIDDEN);
assert_eq!(
response.into_json(),
json!({ "errors": [{ "detail": "must be logged in to perform that action" }] })
);
assert!(!is_yanked(&app));
}

#[test]
fn admin() {
let (app, _, _) = prepare();

let admin = app.db_new_user("admin");

app.db(|conn| {
diesel::update(admin.as_model())
.set(users::is_admin.eq(true))
.execute(conn)
.unwrap();
});

let response = admin.yank(CRATE_NAME, CRATE_VERSION);
assert_eq!(response.status(), StatusCode::OK);
assert_eq!(response.into_json(), json!({ "ok": true }));
assert!(is_yanked(&app));

let response = admin.unyank(CRATE_NAME, CRATE_VERSION);
assert_eq!(response.status(), StatusCode::OK);
assert_eq!(response.into_json(), json!({ "ok": true }));
assert!(!is_yanked(&app));
}
}
21 changes: 12 additions & 9 deletions src/tests/routes/me/get.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
use crate::builders::CrateBuilder;
use crate::util::{RequestHelper, TestApp};
use crates_io::views::{EncodablePrivateUser, OwnedCrate};
use http::StatusCode;
use insta::{assert_display_snapshot, assert_json_snapshot};

impl crate::util::MockCookieUser {
pub fn show_me(&self) -> UserShowPrivateResponse {
Expand All @@ -17,22 +19,23 @@ pub struct UserShowPrivateResponse {

#[test]
fn me() {
let url = "/api/v1/me";
let (app, anon) = TestApp::init().empty();
anon.get(url).assert_forbidden();
let (app, anon, user) = TestApp::init().with_user();

let user = app.db_new_user("foo");
let json = user.show_me();
let response = anon.get::<()>("/api/v1/me");
assert_eq!(response.status(), StatusCode::FORBIDDEN);
assert_display_snapshot!(response.into_text(), @r###"{"errors":[{"detail":"must be logged in to perform that action"}]}"###);

assert_eq!(json.owned_crates.len(), 0);
let response = user.get::<()>("/api/v1/me");
assert_eq!(response.status(), StatusCode::OK);
assert_json_snapshot!(response.into_json());

app.db(|conn| {
CrateBuilder::new("foo_my_packages", user.as_model().id).expect_build(conn);
assert_eq!(json.user.email, user.as_model().email(conn).unwrap());
});
let updated_json = user.show_me();

assert_eq!(updated_json.owned_crates.len(), 1);
let response = user.get::<()>("/api/v1/me");
assert_eq!(response.status(), StatusCode::OK);
assert_json_snapshot!(response.into_json());
}

#[test]
Expand Down
Loading