Skip to content

Add Crate Owner Auditing #2025

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

Closed
wants to merge 1 commit into from
Closed
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
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
DROP TABLE crate_owner_actions;
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
CREATE TABLE crate_owner_actions (
id SERIAL PRIMARY KEY,
crate_id INTEGER NOT NULL REFERENCES crates(id) ON DELETE CASCADE,
user_id INTEGER NOT NULL REFERENCES users(id),
api_token_id INTEGER REFERENCES api_tokens(id),
action INTEGER NOT NULL,
time TIMESTAMP NOT NULL DEFAULT now()
);
6 changes: 4 additions & 2 deletions src/controllers/krate/metadata.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@
use crate::controllers::frontend_prelude::*;

use crate::models::{
Category, Crate, CrateCategory, CrateKeyword, CrateVersions, Keyword, RecentCrateDownloads,
User, Version, VersionOwnerAction,
Category, Crate, CrateCategory, CrateKeyword, CrateOwnerAction, CrateVersions, Keyword,
RecentCrateDownloads, User, Version, VersionOwnerAction,
};
use crate::schema::*;
use crate::views::{
Expand Down Expand Up @@ -106,6 +106,7 @@ pub fn show(req: &mut dyn Request) -> AppResult<Response> {
let conn = req.db_conn()?;
let krate = Crate::by_name(name).first::<Crate>(&*conn)?;

let krate_owner_actions = CrateOwnerAction::by_crate(&*conn, &krate)?;
let mut versions_and_publishers = krate
.all_versions()
.left_outer_join(users::table)
Expand Down Expand Up @@ -162,6 +163,7 @@ pub fn show(req: &mut dyn Request) -> AppResult<Response> {
Some(badges),
false,
recent_downloads,
krate_owner_actions,
),
versions: versions_publishers_and_audit_actions
.into_iter()
Expand Down
21 changes: 20 additions & 1 deletion src/controllers/krate/owners.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
use serde_json;

use crate::controllers::prelude::*;
use crate::models::{Crate, Owner, Rights, Team, User};
use crate::models::{insert_crate_owner_action, Crate, CrateAction, Owner, Rights, Team, User};
use crate::views::EncodableOwner;

/// Handles the `GET /crates/:crate_id/owners` route.
Expand Down Expand Up @@ -95,6 +95,7 @@ fn modify_owners(req: &mut dyn Request, add: bool) -> AppResult<Response> {
let user = req.user()?;
let crate_name = &req.params()["crate_id"];
let conn = req.db_conn()?;
let authentication_source = req.authentication_source()?;

conn.transaction(|| {
let krate = Crate::by_name(crate_name).first::<Crate>(&*conn)?;
Expand Down Expand Up @@ -124,6 +125,15 @@ fn modify_owners(req: &mut dyn Request, add: bool) -> AppResult<Response> {
let msg = krate.owner_add(app, &conn, user, login)?;
msgs.push(msg);
}

insert_crate_owner_action(
&conn,
krate.id,
user.id,
authentication_source.api_token_id(),
CrateAction::InviteUser,
)?;

msgs.join(",")
} else {
for login in &logins {
Expand All @@ -136,6 +146,15 @@ fn modify_owners(req: &mut dyn Request, add: bool) -> AppResult<Response> {
at least one individual owner is required.",
));
}

insert_crate_owner_action(
&conn,
krate.id,
user.id,
authentication_source.api_token_id(),
CrateAction::RemoveUser,
)?;

"owners successfully removed".to_owned()
};

Expand Down
2 changes: 2 additions & 0 deletions src/models.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ pub use self::email::{Email, NewEmail};
pub use self::follow::Follow;
pub use self::keyword::{CrateKeyword, Keyword};
pub use self::krate::{Crate, CrateVersions, NewCrate, RecentCrateDownloads};
pub use self::krate_owner_actions::{insert_crate_owner_action, CrateAction, CrateOwnerAction};
pub use self::owner::{CrateOwner, Owner, OwnerKind};
pub use self::rights::Rights;
pub use self::team::{NewTeam, Team};
Expand All @@ -27,6 +28,7 @@ mod email;
mod follow;
mod keyword;
pub mod krate;
mod krate_owner_actions;
mod owner;
mod rights;
mod team;
Expand Down
17 changes: 14 additions & 3 deletions src/models/krate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,11 @@ use crate::app::App;
use crate::email;
use crate::models::version::TopVersions;
use crate::models::{
Badge, Category, CrateOwner, CrateOwnerInvitation, Keyword, NewCrateOwnerInvitation, Owner,
OwnerKind, ReverseDependency, User, Version,
Badge, Category, CrateOwner, CrateOwnerAction, CrateOwnerInvitation, Keyword,
NewCrateOwnerInvitation, Owner, OwnerKind, ReverseDependency, User, Version,
};
use crate::util::{cargo_err, AppResult};
use crate::views::{EncodableCrate, EncodableCrateLinks};
use crate::views::{EncodableAuditAction, EncodableCrate, EncodableCrateLinks};

use crate::models::helpers::with_count::*;
use crate::publish_rate_limit::PublishRateLimit;
Expand Down Expand Up @@ -294,6 +294,7 @@ impl Crate {
badges,
exact_match,
recent_downloads,
vec![],
)
}

Expand All @@ -307,6 +308,7 @@ impl Crate {
badges: Option<Vec<Badge>>,
exact_match: bool,
recent_downloads: Option<i64>,
audit_actions: Vec<(CrateOwnerAction, User)>,
) -> EncodableCrate {
let Crate {
name,
Expand All @@ -327,6 +329,14 @@ impl Crate {
let category_ids = categories.map(|cats| cats.iter().map(|cat| cat.slug.clone()).collect());
let badges = badges.map(|bs| bs.into_iter().map(Badge::encodable).collect());
let documentation = Crate::remove_blocked_documentation_urls(documentation);
let audit_actions = audit_actions
.into_iter()
.map(|(audit_action, user)| EncodableAuditAction {
action: audit_action.action.into(),
user: User::encodable_public(user),
time: audit_action.time,
})
.collect();

EncodableCrate {
id: name.clone(),
Expand Down Expand Up @@ -354,6 +364,7 @@ impl Crate {
owner_user: Some(format!("/api/v1/crates/{}/owner_user", name)),
reverse_dependencies: format!("/api/v1/crates/{}/reverse_dependencies", name),
},
audit_actions,
}
}

Expand Down
101 changes: 101 additions & 0 deletions src/models/krate_owner_actions.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
use chrono::NaiveDateTime;
use diesel::prelude::*;
use diesel::{
deserialize::{self, FromSql},
pg::Pg,
serialize::{self, Output, ToSql},
sql_types::Integer,
};
use std::io::Write;

use crate::models::{ApiToken, Crate, User};
use crate::schema::*;

#[derive(Debug, Clone, Copy, PartialEq, FromSqlRow, AsExpression)]
#[repr(i32)]
#[sql_type = "Integer"]
pub enum CrateAction {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd prefer a name like ActionKind or ActionType here, or even CrateOwnerActionKind, though this is kind of unwieldy.

We have the CrateOwnerAction and CrateAction types in this module, and while these types have quite different nature, the nature of their difference isn't reflected in the current naming.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I like the suggestion. I'll have a look.

InviteUser = 0,
RemoveUser = 1,
}

impl Into<&'static str> for CrateAction {
fn into(self) -> &'static str {
match self {
CrateAction::InviteUser => "invite_user",
CrateAction::RemoveUser => "remove_user",
}
}
}

impl Into<String> for CrateAction {
fn into(self) -> String {
let string: &'static str = self.into();

string.into()
}
}

impl FromSql<Integer, Pg> for CrateAction {
fn from_sql(bytes: Option<&[u8]>) -> deserialize::Result<Self> {
match <i32 as FromSql<Integer, Pg>>::from_sql(bytes)? {
0 => Ok(CrateAction::InviteUser),
1 => Ok(CrateAction::RemoveUser),
n => Err(format!("unknown crate action: {}", n).into()),
}
}
}

impl ToSql<Integer, Pg> for CrateAction {
fn to_sql<W: Write>(&self, out: &mut Output<'_, W, Pg>) -> serialize::Result {
ToSql::<Integer, Pg>::to_sql(&(*self as i32), out)
}
}

#[derive(Debug, Clone, Copy, Queryable, Identifiable, Associations)]
#[belongs_to(Crate)]
#[belongs_to(User)]
#[belongs_to(ApiToken)]
pub struct CrateOwnerAction {
pub id: i32,
pub crate_id: i32,
pub user_id: i32,
pub api_token_id: Option<i32>,
pub action: CrateAction,
pub time: NaiveDateTime,
}

impl CrateOwnerAction {
pub fn all(conn: &PgConnection) -> QueryResult<Vec<Self>> {
crate_owner_actions::table.load(conn)
}

pub fn by_crate(conn: &PgConnection, krate: &Crate) -> QueryResult<Vec<(Self, User)>> {
use crate_owner_actions::dsl::crate_id;

crate_owner_actions::table
.filter(crate_id.eq(krate.id))
.inner_join(users::table)
.order(crate_owner_actions::dsl::id)
.load(conn)
}
}

pub fn insert_crate_owner_action(
conn: &PgConnection,
crate_id_: i32,
user_id_: i32,
api_token_id_: Option<i32>,
action_: CrateAction,
) -> QueryResult<CrateOwnerAction> {
use crate_owner_actions::dsl::{action, api_token_id, crate_id, user_id};

diesel::insert_into(crate_owner_actions::table)
.values((
crate_id.eq(crate_id_),
user_id.eq(user_id_),
api_token_id.eq(api_token_id_),
action.eq(action_),
))
.get_result(conn)
}
27 changes: 12 additions & 15 deletions src/schema.patch
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@ index df884e4..18e08cd 100644
use diesel_full_text_search::{TsVector as Tsvector};

/// Representation of the `api_tokens` table.
@@ -125,14 +125,8 @@ table! {
@@ -169,16 +171,10 @@
///
/// Its SQL type is `Timestamp`.
///
/// (Automatically generated by Diesel.)
Expand All @@ -25,8 +26,8 @@ index df884e4..18e08cd 100644
}

table! {
@@ -608,11 +610,29 @@ table! {
/// (Automatically generated by Diesel.)
use diesel::sql_types::*;
@@ -711,10 +707,28 @@
rendered_at -> Timestamp,
}
}
Expand Down Expand Up @@ -55,10 +56,10 @@ index df884e4..18e08cd 100644

/// Representation of the `reserved_crate_names` table.
///
@@ -881,23 +901,25 @@ table! {

joinable!(api_tokens -> users (user_id));
joinable!(badges -> crates (crate_id));
@@ -1045,11 +1059,12 @@
joinable!(crate_owner_actions -> api_tokens (api_token_id));
joinable!(crate_owner_actions -> crates (crate_id));
joinable!(crate_owner_actions -> users (user_id));
joinable!(crate_owner_invitations -> crates (crate_id));
joinable!(crate_owners -> crates (crate_id));
-joinable!(crate_owners -> users (created_by));
Expand All @@ -69,8 +70,7 @@ index df884e4..18e08cd 100644
joinable!(crates_keywords -> crates (crate_id));
joinable!(crates_keywords -> keywords (keyword_id));
joinable!(dependencies -> crates (crate_id));
joinable!(dependencies -> versions (version_id));
joinable!(emails -> users (user_id));
@@ -1058,10 +1073,11 @@
joinable!(follows -> crates (crate_id));
joinable!(follows -> users (user_id));
joinable!(publish_limit_buckets -> users (user_id));
Expand All @@ -80,11 +80,9 @@ index df884e4..18e08cd 100644
joinable!(version_authors -> users (user_id));
joinable!(version_authors -> versions (version_id));
joinable!(version_downloads -> versions (version_id));
joinable!(version_owner_actions -> api_tokens (owner_token_id));

@@ -913,13 +935,14 @@ allow_tables_to_appear_in_same_query!(
emails,
follows,
joinable!(version_owner_actions -> api_tokens (api_token_id));
joinable!(version_owner_actions -> users (user_id));
@@ -1087,10 +1103,11 @@
keywords,
metadata,
publish_limit_buckets,
Expand All @@ -96,4 +94,3 @@ index df884e4..18e08cd 100644
users,
version_authors,
version_downloads,
versions,
51 changes: 51 additions & 0 deletions src/schema.rs
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,53 @@ table! {
}
}

table! {
use diesel::sql_types::*;
use diesel_full_text_search::{TsVector as Tsvector};

/// Representation of the `crate_owner_actions` table.
///
/// (Automatically generated by Diesel.)
crate_owner_actions (id) {
/// The `id` column of the `crate_owner_actions` table.
///
/// Its SQL type is `Int4`.
///
/// (Automatically generated by Diesel.)
id -> Int4,
/// The `crate_id` column of the `crate_owner_actions` table.
///
/// Its SQL type is `Int4`.
///
/// (Automatically generated by Diesel.)
crate_id -> Int4,
/// The `user_id` column of the `crate_owner_actions` table.
///
/// Its SQL type is `Int4`.
///
/// (Automatically generated by Diesel.)
user_id -> Int4,
/// The `api_token_id` column of the `crate_owner_actions` table.
///
/// Its SQL type is `Nullable<Int4>`.
///
/// (Automatically generated by Diesel.)
api_token_id -> Nullable<Int4>,
/// The `action` column of the `crate_owner_actions` table.
///
/// Its SQL type is `Int4`.
///
/// (Automatically generated by Diesel.)
action -> Int4,
/// The `time` column of the `crate_owner_actions` table.
///
/// Its SQL type is `Timestamp`.
///
/// (Automatically generated by Diesel.)
time -> Timestamp,
}
}

table! {
use diesel::sql_types::*;
use diesel_full_text_search::{TsVector as Tsvector};
Expand Down Expand Up @@ -1009,6 +1056,9 @@ table! {

joinable!(api_tokens -> users (user_id));
joinable!(badges -> crates (crate_id));
joinable!(crate_owner_actions -> api_tokens (api_token_id));
joinable!(crate_owner_actions -> crates (crate_id));
joinable!(crate_owner_actions -> users (user_id));
joinable!(crate_owner_invitations -> crates (crate_id));
joinable!(crate_owners -> crates (crate_id));
joinable!(crate_owners -> teams (owner_id));
Expand Down Expand Up @@ -1041,6 +1091,7 @@ allow_tables_to_appear_in_same_query!(
background_jobs,
badges,
categories,
crate_owner_actions,
crate_owner_invitations,
crate_owners,
crates,
Expand Down
Loading