Skip to content

Commit

Permalink
Cleaned up routes and namings
Browse files Browse the repository at this point in the history
  • Loading branch information
ko1N committed Mar 22, 2024
1 parent c616447 commit e385bd2
Show file tree
Hide file tree
Showing 4 changed files with 86 additions and 46 deletions.
75 changes: 46 additions & 29 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ mod storage;

use error::ResponseResult;
use storage::{
database::{PluginDatabaseFindParams, PluginEntry},
database::{PluginDatabaseFindParams, PluginEntry, PluginName},
pki::SignatureVerifier,
plugin_analyzer, Storage,
};
Expand Down Expand Up @@ -69,19 +69,57 @@ async fn main() {

fn app(storage: Storage) -> Router {
Router::new()
.route("/", post(plugin_push))
.route("/find", get(plugin_find))
.route("/:digest", get(plugin_pull))
.route("/plugins", get(get_plugins))
.route("/plugins/:plugin_name", get(find_plugin_variants))
.route("/files/", post(upload_file))
.route("/files/:digest", get(find_file_by_digest))
.layer(DefaultBodyLimit::max(20 * 1024 * 1024)) // 20 mb
.with_state(storage)
}

async fn plugin_push(
#[derive(Clone, Serialize)]
struct PluginsAllResponse {
plugins: Vec<PluginName>,
}

/// Returns a list of all available plugins
async fn get_plugins(State(storage): State<Storage>) -> ResponseResult<Json<PluginsAllResponse>> {
let plugins = storage.database().plugins();
Ok(PluginsAllResponse { plugins }.into())
}

#[derive(Clone, Serialize)]
struct PluginsFindResponse {
plugins: Vec<PluginEntry>,
skip: usize,
}

/// Returns a list of plugins based on the given filter parameters
async fn find_plugin_variants(
State(storage): State<Storage>,
params: Query<PluginDatabaseFindParams>,
Path(plugin_name): Path<String>,
) -> ResponseResult<Json<PluginsFindResponse>> {
// find entries in database
let params: PluginDatabaseFindParams = params.0;
let entries = storage
.database()
.plugin_variants(&plugin_name, params.clone());

Ok(PluginsFindResponse {
plugins: entries,
skip: params.skip.unwrap_or(0),
}
.into())
}

/// Posts a file to the backend and analyzes it.
async fn upload_file(
State(storage): State<Storage>,
TypedHeader(authorization): TypedHeader<Authorization<Bearer>>,
mut multipart: Multipart,
) -> ResponseResult<()> {
// TODO: move to state?
// TODO: move to state? + move to middleware
if let Ok(token) = std::env::var("MEMFLOW_BEARER_TOKEN") {
if authorization.0.token() != token {
warn!(
Expand Down Expand Up @@ -165,29 +203,8 @@ async fn plugin_push(
}
}

#[derive(Clone, Serialize)]
struct PluginListResponse {
plugins: Vec<PluginEntry>,
skip: usize,
}

async fn plugin_find(
State(storage): State<Storage>,
params: Query<PluginDatabaseFindParams>,
) -> ResponseResult<Json<PluginListResponse>> {
let params: PluginDatabaseFindParams = params.0;

// find entries in database
let entries = storage.database().find(params.clone());

Ok(PluginListResponse {
plugins: entries,
skip: params.skip.unwrap_or(0),
}
.into())
}

async fn plugin_pull(
/// Retrieves a file by it's digest.
async fn find_file_by_digest(
State(storage): State<Storage>,
Path(digest): Path<String>,
) -> ResponseResult<impl IntoResponse> {
Expand Down
42 changes: 34 additions & 8 deletions src/storage/database.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,14 @@ pub struct PluginEntry {
pub descriptor: PluginDescriptor,
}

#[derive(Clone, Serialize)]
pub struct PluginName {
name: String,
description: String,
}

#[derive(Debug, Default, Clone, Deserialize)]
pub struct PluginDatabaseFindParams {
pub name: Option<String>,
pub version: Option<String>,
pub memflow_plugin_version: Option<i32>,
pub file_type: Option<PluginFileType>,
Expand Down Expand Up @@ -72,17 +77,38 @@ impl PluginDatabase {
Ok(())
}

pub fn find(&self, params: PluginDatabaseFindParams) -> Vec<PluginEntry> {
/// Returns a list of all plugin names and their descriptions.
pub fn plugins(&self) -> Vec<PluginName> {
let mut plugins = self
.plugins
.iter()
.map(|entry| PluginName {
name: entry.descriptor.name.clone(),
description: entry.descriptor.description.clone(),
})
.collect::<Vec<_>>();
plugins.sort_by(|a, b| a.name.cmp(&b.name));
plugins.dedup_by(|a, b| a.name == b.name);
plugins
}

/// Retrieves a specific digest
pub fn find_by_digest(&self, digest: &str) -> Option<PluginEntry> {
self.plugins.iter().find(|p| p.digest == digest).cloned()
}

/// Retrieves a list of variants for a specific plugin.
/// Additional search parameters can be specified.
pub fn plugin_variants(
&self,
plugin_name: &str,
params: PluginDatabaseFindParams,
) -> Vec<PluginEntry> {
self.plugins
.iter()
.skip(params.skip.unwrap_or(0))
.filter(|p| p.descriptor.name == plugin_name)
.filter(|p| {
if let Some(name) = &params.name {
if *name != p.descriptor.name {
return false;
}
}

if let Some(version) = &params.version {
if *version != p.descriptor.version {
return false;
Expand Down
13 changes: 4 additions & 9 deletions src/storage/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ pub mod plugin_analyzer;
use plugin_analyzer::PluginDescriptor;

pub mod database;
use database::{PluginDatabase, PluginDatabaseFindParams};
use database::PluginDatabase;

pub mod pki;
use pki::SignatureVerifier;
Expand Down Expand Up @@ -124,14 +124,9 @@ impl Storage {
pub async fn download(&self, digest: &str) -> Result<File> {
let plugin_info = {
let lock = self.database.read();
lock.find(PluginDatabaseFindParams {
digest: Some(digest.to_owned()),
limit: Some(1),
..Default::default()
})
.first()
.ok_or_else(|| Error::NotFound("plugin not found".to_owned()))?
.to_owned()
lock.find_by_digest(digest)
.ok_or_else(|| Error::NotFound("plugin not found".to_owned()))?
.to_owned()
};

let mut file_name = self.root.clone().join(&plugin_info.digest);
Expand Down
2 changes: 2 additions & 0 deletions src/storage/plugin_analyzer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ const _: [(); std::mem::size_of::<PluginDescriptor64>()] = [(); 0x60];
unsafe impl Pod for PluginDescriptor64 {}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
#[serde(rename_all = "snake_case")]
pub enum PluginArchitecture {
Unknown(u32),
X86,
Expand All @@ -68,6 +69,7 @@ pub enum PluginArchitecture {
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
#[serde(rename_all = "snake_case")]
pub enum PluginFileType {
Pe,
Elf,
Expand Down

0 comments on commit e385bd2

Please sign in to comment.