chore: import MCTF services

- Added all seven issued service trees without omissions.
- Preserved the supplied runtime configuration, binaries, and assets.
This commit is contained in:
TakuyaYagam1 committed 2026-11-29 12:25:29 +03:00
commit 13f936bee9
1222 files changed
+21280

No files matched your search

+141
View File
@@ -0,0 +1,141 @@
use chrono::{Duration, Utc};
use sqlx::PgPool;
use uuid::Uuid;
use crate::{
dto::{AuthRequest, AuthResponse, ChangePasswordRequest, MeResponse, NewSession},
error::{ApiError, ApiResult},
models::{Session as SessionModel, User},
pam,
repositories::{SessionRepository, UserRepository},
};
const SESSION_TTL_DAYS: i64 = 7;
const USERNAME_MAX_LEN: usize = 30;
const TOKEN_LEN: usize = 50;
const TOKEN_CHARSET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
pub async fn register(pool: &PgPool, req: AuthRequest) -> ApiResult<AuthResponse> {
validate(&req)?;
let user = UserRepository::create(pool, req.username.trim()).await?;
pam::secrets::append(&user.username, &req.password)?;
let session = create_session(pool, user.id).await?;
Ok(AuthResponse {
token: session.cookie,
})
}
pub async fn login(pool: &PgPool, req: AuthRequest) -> ApiResult<AuthResponse> {
validate(&req)?;
let user = UserRepository::find_by_username(pool, req.username.trim())
.await?
.ok_or(ApiError::Unauthorized)?;
let service = pam::ffi::service_name(user.workspace_id);
pam::ffi::authenticate(&service, &user.username, &req.password)?;
SessionRepository::delete(pool, user.id).await?;
let session = create_session(pool, user.id).await?;
Ok(AuthResponse {
token: session.cookie,
})
}
pub async fn change_password(user: User, req: ChangePasswordRequest) -> ApiResult<()> {
validate_password(&req.new_password)?;
let service = pam::ffi::service_name(user.workspace_id);
pam::ffi::authenticate(&service, &user.username, &req.current_password)?;
pam::secrets::update(&user.username, &req.new_password)
}
fn validate_password(password: &str) -> ApiResult<()> {
if password.is_empty() {
return Err(ApiError::BadRequest(
"password must not be empty".to_string(),
));
}
if password.contains('\n') || password.contains('\0') {
return Err(ApiError::BadRequest("invalid password".to_string()));
}
Ok(())
}
pub async fn logout(pool: &PgPool, token: String) -> ApiResult<()> {
let user = SessionRepository::find_user_by_session(pool, &token).await?;
SessionRepository::delete(pool, user.id).await
}
pub async fn me(pool: &PgPool, token: String) -> ApiResult<MeResponse> {
let user = SessionRepository::find_user_by_session(pool, &token).await?;
Ok(MeResponse {
username: user.username,
workspace_id: user.workspace_id,
})
}
fn validate(req: &AuthRequest) -> ApiResult<()> {
let username = req.username.trim();
if username.is_empty() {
return Err(ApiError::BadRequest(
"username must not be empty".to_string(),
));
}
if username.len() > USERNAME_MAX_LEN {
return Err(ApiError::BadRequest(format!(
"username must be at most {USERNAME_MAX_LEN} characters"
)));
}
if username.contains(':') {
return Err(ApiError::BadRequest(
"username must not contain ':'".to_string(),
));
}
if username.contains(['\n', '\r', '\0']) {
return Err(ApiError::BadRequest(
"username must not contain line breaks".to_string(),
));
}
if req.password.is_empty() {
return Err(ApiError::BadRequest(
"password must not be empty".to_string(),
));
}
if req.password.contains('\n') || req.password.contains('\0') {
return Err(ApiError::BadRequest("invalid password".to_string()));
}
Ok(())
}
async fn create_session(pool: &PgPool, user_id: Uuid) -> ApiResult<SessionModel> {
SessionRepository::create(
pool,
NewSession {
user_id,
cookie: generate_token()?,
expires_at: Utc::now().naive_utc() + Duration::days(SESSION_TTL_DAYS),
},
)
.await
}
fn generate_token() -> ApiResult<String> {
let mut bytes = [0u8; TOKEN_LEN];
getrandom::fill(&mut bytes).map_err(|_| ApiError::Async)?;
Ok(bytes
.iter()
.map(|byte| TOKEN_CHARSET[*byte as usize % TOKEN_CHARSET.len()] as char)
.collect())
}
+48
View File
@@ -0,0 +1,48 @@
use sqlx::PgPool;
use uuid::Uuid;
use crate::{
dto::NewAuthPolicy,
error::{ApiError, ApiResult},
models::User,
pam,
repositories::AuthPolicyRepository,
};
const POLICY_NAME_MAX_LEN: usize = 100;
pub async fn create(
pool: &PgPool,
admin: User,
workspace_id: Uuid,
req: NewAuthPolicy,
) -> ApiResult<()> {
super::ensure_workspace_admin(&admin, workspace_id)?;
let name = req.name.trim();
if name.is_empty() || name.len() > POLICY_NAME_MAX_LEN {
return Err(ApiError::BadRequest(format!(
"policy name must be 1..={POLICY_NAME_MAX_LEN} characters"
)));
}
pam::validator::validate_raw(&req.content)?;
let compiled = pam::policy::compile(&req.content);
pam::deploy::stage(name, &req.content)?;
if let Ok(compiled) = &compiled {
for username in &compiled.external_rights {
pam::memberships::append(username, workspace_id)?;
}
for (username, file) in &compiled.file_rights {
pam::memberships::append_file_grant(username, workspace_id, file)?;
}
}
let stored = AuthPolicyRepository::create(pool, workspace_id, name).await;
pam::deploy::spawn_deploy(workspace_id, name.to_string());
stored
}
+285
View File
@@ -0,0 +1,285 @@
use std::fs;
use std::path::PathBuf;
use sqlx::PgPool;
use uuid::Uuid;
use crate::{
dto::FileResponse,
error::{ApiError, ApiResult},
models::{File, Role, User},
pam,
repositories::FileRepository,
};
const FILE_NAME_MAX_LEN: usize = 100;
const FILES_PER_PAGE: i64 = 10;
const MAX_UPLOAD_SIZE: usize = 1024 * 1024;
pub async fn upload(
pool: &PgPool,
user: User,
workspace_id: Uuid,
name: String,
data: Vec<u8>,
is_public: bool,
) -> ApiResult<FileResponse> {
ensure_participant(&user, workspace_id)?;
let name = sanitize_name(name)?;
let file_id = Uuid::new_v4();
let filename = format!("{workspace_id}/{file_id}");
let file = write_and_create(
pool,
&name,
&filename,
&user,
Some(workspace_id),
data,
is_public,
)
.await?;
Ok(file_response(file))
}
pub async fn upload_personal(
pool: &PgPool,
user: User,
name: String,
data: Vec<u8>,
is_public: bool,
) -> ApiResult<FileResponse> {
let name = sanitize_name(name)?;
let file_id = Uuid::new_v4();
let filename = format!("users/{}/{file_id}", user.id);
let file = write_and_create(pool, &name, &filename, &user, None, data, is_public).await?;
Ok(file_response(file))
}
pub async fn list(
pool: &PgPool,
user: User,
workspace_id: Uuid,
page: Option<u32>,
) -> ApiResult<Vec<FileResponse>> {
ensure_participant(&user, workspace_id)?;
let page = page.unwrap_or(1).max(1) as i64;
let offset = (page - 1) * FILES_PER_PAGE;
Ok(
FileRepository::list_for_workspace(pool, workspace_id, FILES_PER_PAGE, offset)
.await?
.into_iter()
.map(file_response)
.collect(),
)
}
pub async fn list_personal(
pool: &PgPool,
user: User,
page: Option<u32>,
) -> ApiResult<Vec<FileResponse>> {
let page = page.unwrap_or(1).max(1) as i64;
let offset = (page - 1) * FILES_PER_PAGE;
let mut responses: Vec<FileResponse> =
FileRepository::list_personal(pool, user.id, FILES_PER_PAGE, offset)
.await?
.into_iter()
.map(file_response)
.collect();
let mut seen: std::collections::HashSet<Uuid> = responses.iter().map(|file| file.id).collect();
for (workspace_id, granted_file) in pam::memberships::grants_for(&user.username) {
let files = match granted_file.as_deref() {
Some(name) => {
FileRepository::find_by_workspace_and_name(pool, workspace_id, name, FILES_PER_PAGE)
.await?
}
None => {
FileRepository::list_for_workspace(pool, workspace_id, FILES_PER_PAGE, 0).await?
}
};
for file in files {
if seen.insert(file.id) {
let mut response = file_response(file);
response.shared = true;
responses.push(response);
}
}
}
Ok(responses)
}
pub async fn list_public(pool: &PgPool, page: Option<u32>) -> ApiResult<Vec<FileResponse>> {
let page = page.unwrap_or(1).max(1) as i64;
let offset = (page - 1) * FILES_PER_PAGE;
Ok(FileRepository::list_public(pool, FILES_PER_PAGE, offset)
.await?
.into_iter()
.map(file_response)
.collect())
}
pub async fn download(pool: &PgPool, user: User, file_id: Uuid) -> ApiResult<(String, Vec<u8>)> {
let file = FileRepository::get(pool, file_id).await?;
ensure_access(&user, &file)?;
let path = storage_dir().join(&file.filename);
let data = fs::read(&path).map_err(|_| ApiError::NotFound)?;
Ok((file.name, data))
}
pub async fn delete(pool: &PgPool, user: User, file_id: Uuid) -> ApiResult<()> {
let file = FileRepository::get(pool, file_id).await?;
ensure_access(&user, &file)?;
let allowed = match file.workspace_id {
None => file.owner_id == user.id,
Some(workspace_id) => {
file.owner_id == user.id
|| (user.workspace_id == Some(workspace_id) && user.role == Role::WorkspaceAdmin)
}
};
if !allowed {
return Err(ApiError::Forbidden);
}
FileRepository::delete(pool, file_id).await?;
let _ = fs::remove_file(storage_dir().join(&file.filename));
Ok(())
}
fn ensure_participant(user: &User, workspace_id: Uuid) -> ApiResult<()> {
if user.workspace_id == Some(workspace_id) {
Ok(())
} else {
Err(ApiError::Forbidden)
}
}
fn ensure_access(user: &User, file: &File) -> ApiResult<()> {
if file.is_public {
return Ok(());
}
match file.workspace_id {
None => {
if file.owner_id == user.id {
Ok(())
} else {
Err(ApiError::Forbidden)
}
}
Some(workspace_id) => pam::ffi::authorize_file(&user.username, workspace_id, &file.name),
}
}
fn sanitize_name(name: String) -> ApiResult<String> {
let name = name.trim().to_string();
if name.is_empty() {
return Err(ApiError::BadRequest(
"file name must not be empty".to_string(),
));
}
if name.len() > FILE_NAME_MAX_LEN {
return Err(ApiError::BadRequest(format!(
"file name must be at most {FILE_NAME_MAX_LEN} characters"
)));
}
if name.chars().any(|c| c.is_control()) {
return Err(ApiError::BadRequest(
"file name must not contain control characters".to_string(),
));
}
Ok(name)
}
#[allow(clippy::too_many_arguments)]
async fn write_and_create(
pool: &PgPool,
name: &str,
filename: &str,
owner: &User,
workspace_id: Option<Uuid>,
data: Vec<u8>,
is_public: bool,
) -> ApiResult<File> {
if data.len() > MAX_UPLOAD_SIZE {
return Err(ApiError::BadRequest(format!(
"file must be at most {MAX_UPLOAD_SIZE} bytes"
)));
}
let path = storage_dir().join(filename);
if let Some(parent) = path.parent() {
fs::create_dir_all(parent).map_err(|err| {
println!(
"[file-upload] failed to create storage directory {}: {err}",
parent.display()
);
ApiError::Async
})?;
}
fs::write(&path, &data).map_err(|err| {
println!("[file-upload] failed to write {}: {err}", path.display());
ApiError::Async
})?;
let mut file = FileRepository::create(
pool,
name,
filename,
owner.id,
workspace_id,
data.len() as i64,
is_public,
)
.await;
match file {
Ok(ref mut created) => created.owner = owner.username.clone(),
Err(err) => {
if let Err(cleanup_err) = fs::remove_file(&path) {
println!(
"[file-upload] failed to clean up {}: {cleanup_err}",
path.display()
);
}
return Err(err);
}
}
file
}
fn storage_dir() -> PathBuf {
std::env::var("PAMSAVE_STORAGE_DIR")
.unwrap_or_else(|_| "./storage".to_string())
.into()
}
fn file_response(file: File) -> FileResponse {
FileResponse {
id: file.id,
name: file.name,
size: file.size,
is_public: file.is_public,
owner: file.owner,
created_at: file.created_at,
shared: false,
}
}
+19
View File
@@ -0,0 +1,19 @@
pub mod auth;
pub mod auth_policies;
pub mod files;
pub mod workspaces;
use uuid::Uuid;
use crate::{
error::{ApiError, ApiResult},
models::{Role, User},
};
pub(crate) fn ensure_workspace_admin(user: &User, workspace_id: Uuid) -> ApiResult<()> {
if user.workspace_id == Some(workspace_id) && user.role == Role::WorkspaceAdmin {
Ok(())
} else {
Err(ApiError::Forbidden)
}
}
+112
View File
@@ -0,0 +1,112 @@
use sqlx::PgPool;
use uuid::Uuid;
use crate::{
dto::{
AddUserRequest, MyWorkspaceResponse, NewWorkspace, WorkspaceParticipantResponse,
WorkspaceResponse,
},
error::{ApiError, ApiResult},
models::{Role, User},
pam,
repositories::{AuthPolicyRepository, UserRepository, WorkspaceRepository},
};
const WORKSPACE_NAME_MAX_LEN: usize = 100;
pub async fn create(pool: &PgPool, owner: User, req: NewWorkspace) -> ApiResult<WorkspaceResponse> {
let name = req.name.trim();
if name.is_empty() {
return Err(ApiError::BadRequest(
"workspace name must not be empty".to_string(),
));
}
if name.len() > WORKSPACE_NAME_MAX_LEN {
return Err(ApiError::BadRequest(format!(
"workspace name must be at most {WORKSPACE_NAME_MAX_LEN} characters"
)));
}
let workspace = WorkspaceRepository::create(pool, name, req.description.as_deref()).await?;
UserRepository::attach_to_workspace(pool, owner.id, workspace.id, Role::WorkspaceAdmin).await?;
pam::memberships::append(&owner.username, workspace.id)?;
Ok(WorkspaceResponse {
id: workspace.id,
name: workspace.title,
description: workspace.description,
})
}
pub async fn get_my(pool: &PgPool, user: User) -> ApiResult<MyWorkspaceResponse> {
let workspace_id = user.workspace_id.ok_or(ApiError::NotFound)?;
let workspace = WorkspaceRepository::get(pool, workspace_id).await?;
let participants = WorkspaceRepository::get_participants(pool, workspace_id).await?;
let auth_policy = AuthPolicyRepository::get(pool, workspace_id)
.await?
.map(|policy| policy.name);
Ok(MyWorkspaceResponse {
id: workspace.id,
name: workspace.title,
description: workspace.description,
participants: participants
.into_iter()
.map(|participant| WorkspaceParticipantResponse {
id: participant.id,
username: participant.username,
role: participant.role,
})
.collect(),
auth_policy,
})
}
pub async fn add_user(
pool: &PgPool,
admin: User,
workspace_id: Uuid,
req: AddUserRequest,
) -> ApiResult<()> {
super::ensure_workspace_admin(&admin, workspace_id)?;
let username = req.username.trim();
if username.is_empty() {
return Err(ApiError::BadRequest(
"username must not be empty".to_string(),
));
}
let user = UserRepository::find_by_username(pool, username)
.await?
.ok_or(ApiError::NotFound)?;
if let Some(previous) = user.workspace_id {
if previous != workspace_id {
pam::memberships::remove(&user.username, previous)?;
}
}
UserRepository::attach_to_workspace(pool, user.id, workspace_id, Role::User).await?;
pam::memberships::append(user.username.trim(), workspace_id)
}
pub async fn remove_user(
pool: &PgPool,
admin: User,
workspace_id: Uuid,
user_id: Uuid,
) -> ApiResult<()> {
super::ensure_workspace_admin(&admin, workspace_id)?;
if UserRepository::detach_member(pool, user_id, workspace_id).await? {
let user = UserRepository::get(pool, user_id).await?;
pam::memberships::remove(&user.username, workspace_id)?;
Ok(())
} else {
Err(ApiError::NotFound)
}
}