Skip to content

WIP: Admin interface #5376

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 3 commits 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
1 change: 1 addition & 0 deletions app/models/user.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ export default class User extends Model {
@attr avatar;
@attr url;
@attr kind;
@attr admin;

async stats() {
return await customAction(this, { method: 'GET', path: 'stats' });
Expand Down
3 changes: 3 additions & 0 deletions app/router.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,9 @@ Router.map(function () {
this.route('following');
this.route('pending-invites');
});
this.route('admin', function () {
this.route('rate-limits');
});
this.route('settings', function () {
this.route('appearance');
this.route('email-notifications');
Expand Down
34 changes: 34 additions & 0 deletions app/routes/admin/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { inject as service } from '@ember/service';

import AuthenticatedRoute from './../-authenticated-route';

export default class AdminRoute extends AuthenticatedRoute {
@service router;
@service session;

async beforeModel(transition) {
// wait for the `loadUserTask.perform()` of either the `application` route,
// or the `session.login()` call
let result = await this.session.loadUserTask.last;

if (!result.currentUser) {
this.session.savedTransition = transition;
this.router.replaceWith('catch-all', {
transition,
loginNeeded: true,
title: 'This page requires admin authentication',
});
} else if (!result.currentUser.admin) {
this.session.savedTransition = transition;
this.router.replaceWith('catch-all', {
transition,
loginNeeded: false,
title: 'This page requires admin authentication',
});
}
}

redirect() {
this.router.replaceWith('admin.rate-limits');
}
}
30 changes: 30 additions & 0 deletions app/routes/admin/rate-limits.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { inject as service } from '@ember/service';

import AuthenticatedRoute from './../-authenticated-route';

export default class RateLimitsAdminRoute extends AuthenticatedRoute {
@service router;
@service session;

async beforeModel(transition) {
// wait for the `loadUserTask.perform()` of either the `application` route,
// or the `session.login()` call
let result = await this.session.loadUserTask.last;

if (!result.currentUser) {
this.session.savedTransition = transition;
this.router.replaceWith('catch-all', {
transition,
loginNeeded: true,
title: 'This page requires admin authentication',
});
} else if (!result.currentUser.admin) {
this.session.savedTransition = transition;
this.router.replaceWith('catch-all', {
transition,
loginNeeded: false,
title: 'This page requires admin authentication',
});
}
}
}
18 changes: 18 additions & 0 deletions app/styles/admin/rate-limits.module.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
.rate-limit {}

.page {
display: grid;
gap: 16px;

@media (--min-m) {
grid-template:
"menu content" auto /
200px auto;
}
}

.content {
h2:first-child {
margin-top: 4px;
}
}
18 changes: 18 additions & 0 deletions app/templates/admin/rate-limits.hbs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{{page-title 'Admin Actions'}}

<PageHeader @title="Admin Actions" data-test-heading />

<div local-class="page" ...attributes>
<SideMenu as |menu|>
<menu.Item @link={{link "admin.rate-limits"}}>Increase Rate Limit</menu.Item>
<menu.Item>More actions coming soon</menu.Item>
</SideMenu>

<div local-class="content">
<div local-class='rate-limit'>
<h2>Increase Rate Limit</h2>
<label>email address:</label>
</div>
</div>

</div>
1 change: 1 addition & 0 deletions src/controllers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ mod prelude {
pub mod helpers;
mod util;

pub mod admin;
pub mod category;
pub mod crate_owner_invitation;
pub mod keyword;
Expand Down
48 changes: 48 additions & 0 deletions src/controllers/admin.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
use super::frontend_prelude::*;
use crate::{
models::{AdminUser, User},
schema::{publish_limit_buckets, publish_rate_overrides},
};
use diesel::dsl::*;

#[derive(Deserialize)]
struct RateLimitIncrease {
email: String,
rate_limit: i32,
}

/// Increases the rate limit for the user with the specified verified email address.
pub fn publish_rate_override(req: &mut dyn RequestExt) -> EndpointResult {
let admin = req.authenticate()?.forbid_api_token_auth()?.admin_user()?;
increase_rate_limit(admin, req)
}

/// Increasing the rate limit requires that you are an admin user, but no information from the
/// admin user is currently needed. Someday having an audit log of which admin user took the action
/// would be nice.
fn increase_rate_limit(_admin: AdminUser, req: &mut dyn RequestExt) -> EndpointResult {
let mut body = String::new();
req.body().read_to_string(&mut body)?;

let rate_limit_increase: RateLimitIncrease = serde_json::from_str(&body)
.map_err(|e| bad_request(&format!("invalid json request: {e}")))?;

let conn = req.db_write()?;
let user = User::find_by_verified_email(&conn, &rate_limit_increase.email)?;

conn.transaction(|| {
diesel::insert_into(publish_rate_overrides::table)
.values((
publish_rate_overrides::user_id.eq(user.id),
publish_rate_overrides::burst.eq(rate_limit_increase.rate_limit),
publish_rate_overrides::expires_at.eq((now + 30.days()).nullable()),
))
.execute(&*conn)?;

diesel::delete(publish_limit_buckets::table)
.filter(publish_limit_buckets::user_id.eq(user.id))
.execute(&*conn)
})?;

ok_true()
}
6 changes: 5 additions & 1 deletion src/controllers/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use conduit_cookie::RequestSession;
use super::prelude::*;

use crate::middleware::log_request;
use crate::models::{ApiToken, User};
use crate::models::{AdminUser, ApiToken, User};
use crate::util::errors::{
account_locked, forbidden, internal, AppError, AppResult, InsecurelyGeneratedTokenRevoked,
};
Expand All @@ -28,6 +28,10 @@ impl AuthenticatedUser {
self.user
}

pub fn admin_user(self) -> AppResult<AdminUser> {
AdminUser::new(&self.user)
}

/// Disallows token authenticated users
pub fn forbid_api_token_auth(self) -> AppResult<Self> {
if self.token_id.is_none() {
Expand Down
2 changes: 1 addition & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ pub mod email;
pub mod github;
pub mod metrics;
pub mod middleware;
mod publish_rate_limit;
pub mod publish_rate_limit;
pub mod schema;
pub mod sql;
mod test_util;
Expand Down
2 changes: 1 addition & 1 deletion src/models.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ pub use self::owner::{CrateOwner, Owner, OwnerKind};
pub use self::rights::Rights;
pub use self::team::{NewTeam, Team};
pub use self::token::{ApiToken, CreatedApiToken};
pub use self::user::{NewUser, User};
pub use self::user::{AdminUser, NewUser, User};
pub use self::version::{NewVersion, TopVersions, Version};

pub mod helpers;
Expand Down
60 changes: 59 additions & 1 deletion src/models/user.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use std::borrow::Cow;

use crate::app::App;
use crate::email::Emails;
use crate::util::errors::AppResult;
use crate::util::errors::{forbidden, AppResult};

use crate::models::{ApiToken, Crate, CrateOwner, Email, NewEmail, Owner, OwnerKind, Rights};
use crate::schema::{crate_owners, emails, users};
Expand Down Expand Up @@ -121,6 +121,16 @@ impl User {
Ok(Self::find(conn, api_token.user_id)?)
}

/// Queries the database for a user with the specified verified email address.
pub fn find_by_verified_email(conn: &PgConnection, email: &str) -> AppResult<User> {
let email: Email = emails::table
.filter(emails::email.eq(email))
.filter(emails::verified.eq(true))
.first(conn)?;

Ok(Self::find(conn, email.user_id)?)
}

pub fn owning(krate: &Crate, conn: &PgConnection) -> QueryResult<Vec<Owner>> {
let users = CrateOwner::by_owner_kind(OwnerKind::User)
.inner_join(users::table)
Expand Down Expand Up @@ -177,4 +187,52 @@ impl User {
.first(conn)
.optional()?)
}

/// Attempt to turn this user into an AdminUser
pub fn admin(&self) -> AppResult<AdminUser> {
AdminUser::new(self)
}
}

pub struct AdminUser(User);

impl AdminUser {
pub fn new(user: &User) -> AppResult<Self> {
match user.gh_login.as_str() {
"carols10cents" | "jtgeibel" | "Turbo87" => Ok(Self(user.clone())),
_ => Err(forbidden()),
}
}
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn hardcoded_admins() {
let user = User {
id: 3,
gh_access_token: "arbitrary".into(),
gh_login: "literally_anything".into(),
name: None,
gh_avatar: None,
gh_id: 7,
account_lock_reason: None,
account_lock_until: None,
};
assert!(user.admin().is_err());

let sneaky_user = User {
gh_login: "carols10cents_plus_extra_stuff".into(),
..user
};
assert!(sneaky_user.admin().is_err());

let real_real_real = User {
gh_login: "carols10cents".into(),
..sneaky_user
};
assert!(real_real_real.admin().is_ok());
}
}
6 changes: 6 additions & 0 deletions src/router.rs
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,12 @@ pub fn build_router(app: &App) -> RouteBuilder {
C(crate_owner_invitation::private_list),
);

// Admin actions
router.put(
"/api/private/admin/rate-limits",
C(admin::publish_rate_override),
);

// Only serve the local checkout of the git index in development mode.
// In production, for crates.io, cargo gets the index from
// https://github.com/rust-lang/crates.io-index directly.
Expand Down
Loading