Skip to content

Commit

Permalink
wip: beat it
Browse files Browse the repository at this point in the history
  • Loading branch information
ElaBosak233 committed Nov 22, 2024
1 parent f6667c4 commit 70abb0c
Show file tree
Hide file tree
Showing 35 changed files with 169 additions and 90 deletions.
3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ description = "The CdsCTF project is an open-source, high-performance, Jeopardy-
async-trait = { version = "0.1" }
tokio = { version = "1.41", features = ["full"] }
tokio-util = { version = "0.7.12" }
tokio-rustls = { version = "0.26.0", features = ["ring"] }
futures = { version = "^0.3" }
futures-util = { version = "^0.3" }
tower = { version = "0.5" }
Expand Down Expand Up @@ -92,7 +93,7 @@ fred = { version = "9.4", features = [
] }

# Containerization & Orchestration
kube = { version = "0.96", features = ["client", "config", "runtime", "derive", "rustls-tls", "ws"] }
kube = { version = "0.97", features = ["client", "config", "runtime", "derive", "rustls-tls", "ws"] }
k8s-openapi = { version = "0.23", features = ["latest"] }

# Miscellaneous
Expand Down
2 changes: 1 addition & 1 deletion src/cluster/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ pub async fn init() {
}

pub async fn create(
name: String, challenge: crate::shared::Challenge,
name: String, challenge: crate::db::entity::challenge::Model,
injected_flag: crate::db::entity::challenge::Flag,
) -> Result<Vec<crate::db::entity::pod::Nat>, anyhow::Error> {
let client = get_k8s_client().clone();
Expand Down
1 change: 1 addition & 0 deletions src/db/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
pub mod entity;
mod migration;
pub mod transfer;

use std::time::Duration;

Expand Down
24 changes: 24 additions & 0 deletions src/shared/challenge.rs → src/db/transfer/challenge.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,30 @@ impl From<entity::challenge::Model> for Challenge {
}
}

impl From<Challenge> for entity::challenge::Model {
fn from(challenge: Challenge) -> Self {
Self {
id: challenge.id,
title: challenge.title,
description: challenge.description,
category: challenge.category,
tags: challenge.tags,
is_dynamic: challenge.is_dynamic,
has_attachment: challenge.has_attachment,
is_practicable: challenge.is_practicable,
image_name: challenge.image_name,
cpu_limit: challenge.cpu_limit,
memory_limit: challenge.memory_limit,
duration: challenge.duration,
ports: challenge.ports,
envs: challenge.envs,
flags: challenge.flags,
created_at: challenge.created_at,
updated_at: challenge.updated_at,
}
}
}

impl Challenge {
pub fn desensitize(&mut self) {
self.envs.clear();
Expand Down
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
2 changes: 0 additions & 2 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,6 @@ mod logger;
mod media;
mod metric;
mod queue;
mod shared;
mod util;
mod web;

use std::net::SocketAddr;
Expand Down
3 changes: 0 additions & 3 deletions src/util/mod.rs

This file was deleted.

42 changes: 42 additions & 0 deletions src/web/extract/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
use async_trait::async_trait;
use axum::{
extract::{path::ErrorKind, rejection::PathRejection, FromRequest, FromRequestParts},
http::request::Parts,
};
use serde::de::DeserializeOwned;

use crate::web::traits::WebError;

pub mod validate;

pub struct Path<T>(T);

#[async_trait]
impl<S, T> FromRequestParts<S> for Path<T>
where
T: DeserializeOwned + Send,
S: Send + Sync,
{
type Rejection = WebError;

async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
match axum::extract::Path::<T>::from_request_parts(parts, state).await {
Ok(value) => Ok(Self(value.0)),
Err(rejection) => match rejection {
PathRejection::FailedToDeserializePathParams(inner) => {
let kind = inner.kind();
match &kind {
ErrorKind::UnsupportedType { .. } => {
Err(WebError::InternalServerError(kind.to_string()))
}
_ => Err(WebError::BadRequest(kind.to_string())),
}
}
PathRejection::MissingPathParams(error) => {
Err(WebError::InternalServerError(error.to_string()))
}
_ => Err(WebError::InternalServerError(rejection.to_string())),
},
}
}
}
File renamed without changes.
10 changes: 6 additions & 4 deletions src/web/middleware/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use sea_orm::EntityTrait;

use crate::{
db::{entity::user::Group, get_db},
util,
web,
web::traits::{Ext, WebError},
};

Expand All @@ -37,12 +37,12 @@ pub async fn jwt(mut req: Request<Body>, next: Next) -> Result<Response, WebErro

let token = jar.get("token").map(|cookie| cookie.value()).unwrap_or("");

let decoding_key = DecodingKey::from_secret(util::jwt::get_secret().await.as_bytes());
let decoding_key = DecodingKey::from_secret(web::util::jwt::get_secret().await.as_bytes());
let validation = Validation::default();

let mut user: Option<crate::shared::User> = None;
let mut user: Option<crate::db::transfer::User> = None;

let result = decode::<util::jwt::Claims>(token, &decoding_key, &validation);
let result = decode::<web::util::jwt::Claims>(token, &decoding_key, &validation);

if let Ok(data) = result {
user = crate::db::entity::user::Entity::find_by_id(data.claims.id)
Expand All @@ -59,6 +59,8 @@ pub async fn jwt(mut req: Request<Body>, next: Next) -> Result<Response, WebErro
if user.group == Group::Banned {
return Err(WebError::Forbidden(String::from("forbidden")));
}
} else {
return Ok(next.run(req).await);
}

let ConnectInfo(addr) = req.extensions().get::<ConnectInfo<SocketAddr>>().unwrap();
Expand Down
9 changes: 9 additions & 0 deletions src/web/middleware/error.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
use axum::response::IntoResponse;

use crate::web::traits::WebError;

pub async fn validation_error(err: validator::ValidationError) -> impl IntoResponse {}

pub async fn box_error(err: axum::BoxError) -> WebError {
WebError::InternalServerError(format!("{:?}", err))
}
2 changes: 1 addition & 1 deletion src/web/middleware/mod.rs
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
pub mod auth;
mod validate;
pub mod error;
3 changes: 0 additions & 3 deletions src/web/middleware/validate.rs

This file was deleted.

1 change: 1 addition & 0 deletions src/web/mod.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
pub mod extract;
pub mod middleware;
pub mod model;
pub mod router;
Expand Down
20 changes: 10 additions & 10 deletions src/web/router/api/challenge/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@ use crate::{
entity::{submission::Status, user::Group},
get_db,
},
util::validate,
web::{
extract::validate,
model::Metadata,
traits::{Ext, WebError, WebResult},
},
Expand Down Expand Up @@ -58,13 +58,13 @@ pub struct GetRequest {

pub async fn get(
Extension(ext): Extension<Ext>, Query(params): Query<GetRequest>,
) -> Result<WebResult<Vec<crate::shared::Challenge>>, WebError> {
) -> Result<WebResult<Vec<crate::db::transfer::Challenge>>, WebError> {
let operator = ext.operator.ok_or(WebError::Unauthorized(String::new()))?;
if operator.group != Group::Admin && params.is_detailed.unwrap_or(false) {
return Err(WebError::Forbidden(String::new()));
}

let (mut challenges, total) = crate::shared::challenge::find(
let (mut challenges, total) = crate::db::transfer::challenge::find(
params.id,
params.title,
params.category,
Expand Down Expand Up @@ -103,7 +103,7 @@ pub struct StatusResult {
pub is_solved: bool,
pub solved_times: i64,
pub pts: i64,
pub bloods: Vec<crate::shared::Submission>,
pub bloods: Vec<crate::db::transfer::Submission>,
}

pub async fn get_status(
Expand All @@ -112,7 +112,7 @@ pub async fn get_status(
let _ = ext.operator.ok_or(WebError::Unauthorized(String::new()))?;

let mut submissions =
crate::shared::submission::get_by_challenge_ids(body.cids.clone()).await?;
crate::db::transfer::submission::get_by_challenge_ids(body.cids.clone()).await?;

let mut result: HashMap<i64, StatusResult> = HashMap::new();

Expand Down Expand Up @@ -164,7 +164,7 @@ pub async fn get_status(

if let Some(game_id) = body.game_id {
let (game_challenges, _) =
crate::shared::game_challenge::find(Some(game_id), None, None).await?;
crate::db::transfer::game_challenge::find(Some(game_id), None, None).await?;

for game_challenge in game_challenges {
let status_response = result.get_mut(&game_challenge.challenge_id).unwrap();
Expand Down Expand Up @@ -200,7 +200,7 @@ pub struct CreateRequest {

pub async fn create(
Extension(ext): Extension<Ext>, Json(body): Json<CreateRequest>,
) -> Result<WebResult<crate::shared::Challenge>, WebError> {
) -> Result<WebResult<crate::db::transfer::Challenge>, WebError> {
let operator = ext.operator.ok_or(WebError::Unauthorized(String::new()))?;
if operator.group != Group::Admin {
return Err(WebError::Forbidden(String::new()));
Expand All @@ -225,7 +225,7 @@ pub async fn create(
}
.insert(get_db())
.await?;
let challenge = crate::shared::Challenge::from(challenge);
let challenge = crate::db::transfer::Challenge::from(challenge);

Ok(WebResult {
code: StatusCode::OK.as_u16(),
Expand Down Expand Up @@ -257,7 +257,7 @@ pub struct UpdateRequest {
pub async fn update(
Extension(ext): Extension<Ext>, Path(id): Path<i64>,
validate::Json(mut body): validate::Json<UpdateRequest>,
) -> Result<WebResult<crate::shared::Challenge>, WebError> {
) -> Result<WebResult<crate::db::transfer::Challenge>, WebError> {
let operator = ext.operator.ok_or(WebError::Unauthorized(String::new()))?;
if operator.group != Group::Admin {
return Err(WebError::Forbidden(String::new()));
Expand Down Expand Up @@ -285,7 +285,7 @@ pub async fn update(
}
.update(get_db())
.await?;
let challenge = crate::shared::Challenge::from(challenge);
let challenge = crate::db::transfer::Challenge::from(challenge);

Ok(WebResult {
code: StatusCode::OK.as_u16(),
Expand Down
2 changes: 1 addition & 1 deletion src/web/router/api/game/calculator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ pub async fn calculate(game_id: i64) {
// sort submissions by created_at
submissions.sort_by_key(|s| s.created_at);

let base_pts = crate::util::math::curve(
let base_pts = crate::web::util::math::curve(
game_challenge.max_pts,
game_challenge.min_pts,
game_challenge.difficulty,
Expand Down
Loading

0 comments on commit 70abb0c

Please sign in to comment.