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:
commit
13f936bee9
1222 files changed
+21280
No files matched your search
Generated
Executable
+86
@@ -0,0 +1,86 @@
|
||||
{
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "SELECT id, username, org_id, role AS \"role: Role\", created_at\n FROM users WHERE id = $1",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"ordinal": 0,
|
||||
"name": "id",
|
||||
"type_info": "Uuid",
|
||||
"origin": {
|
||||
"Table": {
|
||||
"table": "users",
|
||||
"name": "id"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"ordinal": 1,
|
||||
"name": "username",
|
||||
"type_info": "Varchar",
|
||||
"origin": {
|
||||
"Table": {
|
||||
"table": "users",
|
||||
"name": "username"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"ordinal": 2,
|
||||
"name": "org_id",
|
||||
"type_info": "Uuid",
|
||||
"origin": {
|
||||
"Table": {
|
||||
"table": "users",
|
||||
"name": "org_id"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"ordinal": 3,
|
||||
"name": "role: Role",
|
||||
"type_info": {
|
||||
"Custom": {
|
||||
"name": "role",
|
||||
"kind": {
|
||||
"Enum": [
|
||||
"user",
|
||||
"org_adm"
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
"origin": {
|
||||
"Table": {
|
||||
"table": "users",
|
||||
"name": "role"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"ordinal": 4,
|
||||
"name": "created_at",
|
||||
"type_info": "Timestamp",
|
||||
"origin": {
|
||||
"Table": {
|
||||
"table": "users",
|
||||
"name": "created_at"
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Left": [
|
||||
"Uuid"
|
||||
]
|
||||
},
|
||||
"nullable": [
|
||||
false,
|
||||
false,
|
||||
true,
|
||||
false,
|
||||
false
|
||||
]
|
||||
},
|
||||
"hash": "15d692cec3cdbfa5be75baacd1c62f196cc78c2a3689a9c218f16460320355c8"
|
||||
}
|
||||
Generated
Executable
+54
@@ -0,0 +1,54 @@
|
||||
{
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "\n INSERT INTO sessions (user_id, cookie, expires_at)\n VALUES ($1, $2, $3)\n RETURNING *\n ",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"ordinal": 0,
|
||||
"name": "user_id",
|
||||
"type_info": "Uuid",
|
||||
"origin": {
|
||||
"Table": {
|
||||
"table": "sessions",
|
||||
"name": "user_id"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"ordinal": 1,
|
||||
"name": "cookie",
|
||||
"type_info": "Varchar",
|
||||
"origin": {
|
||||
"Table": {
|
||||
"table": "sessions",
|
||||
"name": "cookie"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"ordinal": 2,
|
||||
"name": "expires_at",
|
||||
"type_info": "Timestamp",
|
||||
"origin": {
|
||||
"Table": {
|
||||
"table": "sessions",
|
||||
"name": "expires_at"
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Left": [
|
||||
"Uuid",
|
||||
"Varchar",
|
||||
"Timestamp"
|
||||
]
|
||||
},
|
||||
"nullable": [
|
||||
false,
|
||||
false,
|
||||
false
|
||||
]
|
||||
},
|
||||
"hash": "3d390f6fd58cc4711ca50a751466392e17f503f0af26c8247ad2b35b76115f6e"
|
||||
}
|
||||
Generated
Executable
+86
@@ -0,0 +1,86 @@
|
||||
{
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "\n SELECT id, username, org_id, role AS \"role: Role\", created_at\n FROM users WHERE id = $1\n ",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"ordinal": 0,
|
||||
"name": "id",
|
||||
"type_info": "Uuid",
|
||||
"origin": {
|
||||
"Table": {
|
||||
"table": "users",
|
||||
"name": "id"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"ordinal": 1,
|
||||
"name": "username",
|
||||
"type_info": "Varchar",
|
||||
"origin": {
|
||||
"Table": {
|
||||
"table": "users",
|
||||
"name": "username"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"ordinal": 2,
|
||||
"name": "org_id",
|
||||
"type_info": "Uuid",
|
||||
"origin": {
|
||||
"Table": {
|
||||
"table": "users",
|
||||
"name": "org_id"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"ordinal": 3,
|
||||
"name": "role: Role",
|
||||
"type_info": {
|
||||
"Custom": {
|
||||
"name": "role",
|
||||
"kind": {
|
||||
"Enum": [
|
||||
"user",
|
||||
"org_adm"
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
"origin": {
|
||||
"Table": {
|
||||
"table": "users",
|
||||
"name": "role"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"ordinal": 4,
|
||||
"name": "created_at",
|
||||
"type_info": "Timestamp",
|
||||
"origin": {
|
||||
"Table": {
|
||||
"table": "users",
|
||||
"name": "created_at"
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Left": [
|
||||
"Uuid"
|
||||
]
|
||||
},
|
||||
"nullable": [
|
||||
false,
|
||||
false,
|
||||
true,
|
||||
false,
|
||||
false
|
||||
]
|
||||
},
|
||||
"hash": "e36812c14843dcd272a1fb487a5065407085dc2952635c948f3134cd6a105025"
|
||||
}
|
||||
Executable
+22
@@ -0,0 +1,22 @@
|
||||
[package]
|
||||
name = "api"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
[dependencies]
|
||||
dioxus = { workspace = true, features = ["fullstack"] }
|
||||
sqlx = { version = "0.9.0", features = ["postgres", "runtime-tokio", "uuid", "chrono"], optional = true }
|
||||
chrono = { version = "0.4", features = ["serde"] }
|
||||
thiserror = "2.0.21"
|
||||
uuid = { workspace = true }
|
||||
serde = { version = "1.0.229", features = ["derive"] }
|
||||
toml = "0.8"
|
||||
tracing = "0.1"
|
||||
tokio = { version = "1", features = ["full"], optional = true }
|
||||
axum = { version = "0.8.9", optional = true, features = ["multipart"] }
|
||||
getrandom = { version = "0.3", optional = true }
|
||||
libc = { version = "0.2", optional = true }
|
||||
sha-crypt = { version = "0.6", optional = true, features = ["getrandom"] }
|
||||
|
||||
[features]
|
||||
server = ["dioxus/server", "dep:sqlx", "dep:tokio", "dep:axum", "dep:getrandom", "dep:libc", "dep:sha-crypt", "uuid/v4"]
|
||||
Executable
+5
@@ -0,0 +1,5 @@
|
||||
fn main() {
|
||||
if std::env::var_os("CARGO_FEATURE_SERVER").is_some() {
|
||||
println!("cargo:rustc-link-lib=dylib=pam");
|
||||
}
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
CREATE TABLE workspaces (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
title VARCHAR(100) NOT NULL UNIQUE,
|
||||
description TEXT,
|
||||
created_at TIMESTAMP NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE TYPE role AS ENUM (
|
||||
'user',
|
||||
'workspace_admin'
|
||||
);
|
||||
|
||||
CREATE TABLE users (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
username VARCHAR(30) NOT NULL UNIQUE,
|
||||
workspace_id UUID REFERENCES workspaces(id),
|
||||
role role NOT NULL DEFAULT 'user',
|
||||
created_at TIMESTAMP NOT NULL DEFAULT now(),
|
||||
UNIQUE (workspace_id, username)
|
||||
);
|
||||
|
||||
CREATE TABLE sessions (
|
||||
user_id UUID PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE,
|
||||
cookie VARCHAR(50) NOT NULL UNIQUE,
|
||||
expires_at TIMESTAMP NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE files (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
name VARCHAR(100) NOT NULL,
|
||||
filename VARCHAR(100) NOT NULL,
|
||||
owner_id UUID NOT NULL REFERENCES users(id),
|
||||
size BIGINT NOT NULL,
|
||||
created_at TIMESTAMP NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE TABLE auth_policies (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
name VARCHAR(100) NOT NULL DEFAULT 'policy.conf',
|
||||
filename VARCHAR(100) NOT NULL,
|
||||
workspace_id UUID NOT NULL REFERENCES workspaces(id) ON DELETE CASCADE,
|
||||
UNIQUE (workspace_id, filename)
|
||||
);
|
||||
@@ -0,0 +1,7 @@
|
||||
ALTER TABLE files
|
||||
ADD COLUMN workspace_id UUID NULL REFERENCES workspaces(id) ON DELETE CASCADE;
|
||||
|
||||
UPDATE files
|
||||
SET workspace_id = users.workspace_id
|
||||
FROM users
|
||||
WHERE users.id = files.owner_id;
|
||||
@@ -0,0 +1,2 @@
|
||||
ALTER TABLE files
|
||||
ADD COLUMN is_public BOOLEAN NOT NULL DEFAULT FALSE;
|
||||
Executable
+13
@@ -0,0 +1,13 @@
|
||||
use sqlx::postgres::{PgPool, PgPoolOptions};
|
||||
|
||||
use crate::error::{ApiError, ApiResult};
|
||||
|
||||
pub async fn establish_connection(db_url: &str) -> ApiResult<PgPool> {
|
||||
let pool = PgPoolOptions::new()
|
||||
.max_connections(50)
|
||||
.connect(db_url)
|
||||
.await
|
||||
.map_err(|_| ApiError::Async)?;
|
||||
|
||||
Ok(pool)
|
||||
}
|
||||
Executable
+99
@@ -0,0 +1,99 @@
|
||||
use chrono::NaiveDateTime;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::models::Role;
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Serialize)]
|
||||
pub struct AuthRequest {
|
||||
pub username: String,
|
||||
pub password: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Serialize)]
|
||||
pub struct AuthResponse {
|
||||
pub token: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Serialize)]
|
||||
pub struct CheckAuthRequest {
|
||||
pub token: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Serialize)]
|
||||
pub struct MeResponse {
|
||||
pub username: String,
|
||||
pub workspace_id: Option<Uuid>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Serialize)]
|
||||
pub struct NewAuthPolicy {
|
||||
pub name: String,
|
||||
pub content: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Serialize)]
|
||||
pub struct ChangePasswordRequest {
|
||||
pub current_password: String,
|
||||
pub new_password: String,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize)]
|
||||
pub struct NewFile {
|
||||
name: String,
|
||||
content: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
|
||||
pub struct FileResponse {
|
||||
pub id: Uuid,
|
||||
pub name: String,
|
||||
pub size: i64,
|
||||
pub is_public: bool,
|
||||
pub owner: String,
|
||||
pub created_at: NaiveDateTime,
|
||||
#[serde(default)]
|
||||
pub shared: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Serialize)]
|
||||
pub struct WorkspaceParticipantResponse {
|
||||
pub id: Uuid,
|
||||
pub username: String,
|
||||
pub role: Role,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Serialize)]
|
||||
pub struct MyWorkspaceResponse {
|
||||
pub id: Uuid,
|
||||
pub name: String,
|
||||
pub description: Option<String>,
|
||||
pub participants: Vec<WorkspaceParticipantResponse>,
|
||||
|
||||
pub auth_policy: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Serialize)]
|
||||
pub struct NewWorkspace {
|
||||
pub name: String,
|
||||
pub description: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Serialize)]
|
||||
pub struct WorkspaceResponse {
|
||||
pub id: Uuid,
|
||||
pub name: String,
|
||||
pub description: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Serialize)]
|
||||
pub struct AddUserRequest {
|
||||
pub username: String,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize)]
|
||||
pub struct NewSession {
|
||||
pub user_id: Uuid,
|
||||
pub cookie: String,
|
||||
pub expires_at: NaiveDateTime,
|
||||
}
|
||||
Executable
+49
@@ -0,0 +1,49 @@
|
||||
use dioxus::fullstack::ServerFnError;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
pub type ApiResult<T> = Result<T, ApiError>;
|
||||
pub type DioxusApiResult<T> = Result<T, ServerFnError>;
|
||||
|
||||
#[derive(Debug, thiserror::Error, Serialize, Deserialize)]
|
||||
pub enum ApiError {
|
||||
#[error("unauthorized")]
|
||||
Unauthorized,
|
||||
#[error("forbidden")]
|
||||
Forbidden,
|
||||
#[error("not found")]
|
||||
NotFound,
|
||||
#[error("bad request: {0}")]
|
||||
BadRequest(String),
|
||||
#[error("database error")]
|
||||
Database,
|
||||
#[error("async error")]
|
||||
Async,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct ErrorResponse {
|
||||
pub error: String,
|
||||
}
|
||||
|
||||
#[cfg(feature = "server")]
|
||||
impl axum::response::IntoResponse for ApiError {
|
||||
fn into_response(self) -> axum::response::Response {
|
||||
use axum::http::StatusCode;
|
||||
use axum::response::IntoResponse;
|
||||
|
||||
let (status, message) = match &self {
|
||||
Self::Unauthorized => (StatusCode::UNAUTHORIZED, "unauthorized".to_string()),
|
||||
Self::Forbidden => (StatusCode::FORBIDDEN, "forbidden".to_string()),
|
||||
Self::NotFound => (StatusCode::NOT_FOUND, "not found".to_string()),
|
||||
Self::BadRequest(message) => (StatusCode::BAD_REQUEST, message.clone()),
|
||||
Self::Database | Self::Async => (
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
"internal error".to_string(),
|
||||
),
|
||||
};
|
||||
|
||||
tracing::warn!(status = status.as_u16(), message, "request failed");
|
||||
|
||||
(status, axum::Json(ErrorResponse { error: message })).into_response()
|
||||
}
|
||||
}
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
use axum::{
|
||||
extract::FromRequestParts,
|
||||
http::{header::AUTHORIZATION, request::Parts},
|
||||
};
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct AuthHeader {
|
||||
pub token: Option<String>,
|
||||
}
|
||||
|
||||
impl<S> FromRequestParts<S> for AuthHeader
|
||||
where
|
||||
S: Send + Sync,
|
||||
{
|
||||
type Rejection = ();
|
||||
|
||||
async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
|
||||
let token = parts
|
||||
.headers
|
||||
.get(AUTHORIZATION)
|
||||
.and_then(|value| value.to_str().ok())
|
||||
.and_then(parse_bearer_token);
|
||||
|
||||
Ok(Self { token })
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn parse_bearer_token(value: &str) -> Option<String> {
|
||||
value
|
||||
.strip_prefix("Bearer ")
|
||||
.map(str::trim)
|
||||
.filter(|token| !token.is_empty())
|
||||
.map(str::to_string)
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
use axum::{
|
||||
extract::FromRequestParts,
|
||||
http::{header::AUTHORIZATION, request::Parts, StatusCode},
|
||||
};
|
||||
use sqlx::PgPool;
|
||||
|
||||
use super::auth_header::parse_bearer_token;
|
||||
use crate::{models::User, repositories::SessionRepository};
|
||||
|
||||
pub struct CurrentUser(pub User);
|
||||
|
||||
impl FromRequestParts<PgPool> for CurrentUser {
|
||||
type Rejection = StatusCode;
|
||||
|
||||
async fn from_request_parts(
|
||||
parts: &mut Parts,
|
||||
state: &PgPool,
|
||||
) -> Result<Self, Self::Rejection> {
|
||||
let token = parts
|
||||
.headers
|
||||
.get(AUTHORIZATION)
|
||||
.and_then(|value| value.to_str().ok())
|
||||
.and_then(parse_bearer_token)
|
||||
.ok_or(StatusCode::UNAUTHORIZED)?;
|
||||
|
||||
let user = SessionRepository::find_user_by_session(state, &token)
|
||||
.await
|
||||
.map_err(|_| StatusCode::UNAUTHORIZED)?;
|
||||
|
||||
Ok(Self(user))
|
||||
}
|
||||
}
|
||||
Executable
+5
@@ -0,0 +1,5 @@
|
||||
pub mod auth_header;
|
||||
pub mod current_user;
|
||||
|
||||
pub use auth_header::AuthHeader;
|
||||
pub use current_user::CurrentUser;
|
||||
Executable
+50
@@ -0,0 +1,50 @@
|
||||
use crate::{
|
||||
dto::{AuthRequest, AuthResponse, ChangePasswordRequest, MeResponse},
|
||||
error::ApiError,
|
||||
extractors::{AuthHeader, CurrentUser},
|
||||
services,
|
||||
};
|
||||
use axum::{extract::State, Json};
|
||||
use sqlx::PgPool;
|
||||
|
||||
pub async fn login(
|
||||
State(pool): State<PgPool>,
|
||||
Json(req): Json<AuthRequest>,
|
||||
) -> Result<Json<AuthResponse>, ApiError> {
|
||||
let response = services::auth::login(&pool, req).await?;
|
||||
|
||||
Ok(Json(response))
|
||||
}
|
||||
|
||||
pub async fn register(
|
||||
State(pool): State<PgPool>,
|
||||
Json(req): Json<AuthRequest>,
|
||||
) -> Result<Json<AuthResponse>, ApiError> {
|
||||
let response = services::auth::register(&pool, req).await?;
|
||||
|
||||
Ok(Json(response))
|
||||
}
|
||||
|
||||
pub async fn change_password(
|
||||
user: CurrentUser,
|
||||
Json(req): Json<ChangePasswordRequest>,
|
||||
) -> Result<(), ApiError> {
|
||||
services::auth::change_password(user.0, req).await
|
||||
}
|
||||
|
||||
pub async fn logout(State(pool): State<PgPool>, auth: AuthHeader) -> Result<(), ApiError> {
|
||||
let token = auth.token.ok_or(ApiError::Unauthorized)?;
|
||||
|
||||
services::auth::logout(&pool, token).await
|
||||
}
|
||||
|
||||
pub async fn me(
|
||||
State(pool): State<PgPool>,
|
||||
auth: AuthHeader,
|
||||
) -> Result<Json<MeResponse>, ApiError> {
|
||||
let token = auth.token.ok_or(ApiError::Unauthorized)?;
|
||||
|
||||
let me = services::auth::me(&pool, token).await?;
|
||||
|
||||
Ok(Json(me))
|
||||
}
|
||||
Executable
+192
@@ -0,0 +1,192 @@
|
||||
use crate::{dto::FileResponse, error::ApiError, extractors::CurrentUser, services};
|
||||
use axum::{
|
||||
body::Body,
|
||||
extract::{Multipart, Path, Query, State},
|
||||
http::header,
|
||||
response::Response,
|
||||
Json,
|
||||
};
|
||||
use serde::Deserialize;
|
||||
use sqlx::PgPool;
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct ListFilesQuery {
|
||||
pub page: Option<u32>,
|
||||
}
|
||||
|
||||
struct UploadedFile {
|
||||
name: String,
|
||||
data: Vec<u8>,
|
||||
is_public: bool,
|
||||
}
|
||||
|
||||
async fn read_multipart(multipart: &mut Multipart) -> Result<UploadedFile, ApiError> {
|
||||
let mut file: Option<(String, Vec<u8>)> = None;
|
||||
let mut is_public = false;
|
||||
|
||||
while let Some(field) = multipart
|
||||
.next_field()
|
||||
.await
|
||||
.map_err(|_| ApiError::BadRequest("invalid multipart body".to_string()))?
|
||||
{
|
||||
match field.name() {
|
||||
Some("file") => {
|
||||
if file.is_none() {
|
||||
let name = field.file_name().map(str::to_string).unwrap_or_default();
|
||||
let data = field
|
||||
.bytes()
|
||||
.await
|
||||
.map_err(|_| ApiError::BadRequest("failed to read file".to_string()))?;
|
||||
file = Some((name, data.to_vec()));
|
||||
}
|
||||
}
|
||||
Some("public") => {
|
||||
let value = field
|
||||
.text()
|
||||
.await
|
||||
.map_err(|_| ApiError::BadRequest("failed to read field".to_string()))?;
|
||||
is_public = matches!(value.trim(), "true" | "1" | "yes" | "on");
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
let (name, data) =
|
||||
file.ok_or_else(|| ApiError::BadRequest("missing file field".to_string()))?;
|
||||
|
||||
Ok(UploadedFile {
|
||||
name,
|
||||
data,
|
||||
is_public,
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn upload(
|
||||
State(pool): State<PgPool>,
|
||||
user: CurrentUser,
|
||||
Path(workspace_id): Path<Uuid>,
|
||||
mut multipart: Multipart,
|
||||
) -> Result<Json<FileResponse>, ApiError> {
|
||||
let uploaded = read_multipart(&mut multipart).await?;
|
||||
let user_id = user.0.id;
|
||||
println!(
|
||||
"[file-upload] started scope=workspace workspace_id={workspace_id} user_id={user_id} size={} public={}",
|
||||
uploaded.data.len(),
|
||||
uploaded.is_public
|
||||
);
|
||||
|
||||
let file = services::files::upload(
|
||||
&pool,
|
||||
user.0,
|
||||
workspace_id,
|
||||
uploaded.name,
|
||||
uploaded.data,
|
||||
uploaded.is_public,
|
||||
)
|
||||
.await
|
||||
.map_err(|err| {
|
||||
println!(
|
||||
"[file-upload] failed scope=workspace workspace_id={workspace_id} user_id={user_id} error={err:?}"
|
||||
);
|
||||
err
|
||||
})?;
|
||||
|
||||
println!(
|
||||
"[file-upload] completed scope=workspace workspace_id={workspace_id} file_id={}",
|
||||
file.id
|
||||
);
|
||||
|
||||
Ok(Json(file))
|
||||
}
|
||||
|
||||
pub async fn upload_personal(
|
||||
State(pool): State<PgPool>,
|
||||
user: CurrentUser,
|
||||
mut multipart: Multipart,
|
||||
) -> Result<Json<FileResponse>, ApiError> {
|
||||
let uploaded = read_multipart(&mut multipart).await?;
|
||||
let user_id = user.0.id;
|
||||
println!(
|
||||
"[file-upload] started scope=personal user_id={user_id} size={} public={}",
|
||||
uploaded.data.len(),
|
||||
uploaded.is_public
|
||||
);
|
||||
|
||||
let file = services::files::upload_personal(
|
||||
&pool,
|
||||
user.0,
|
||||
uploaded.name,
|
||||
uploaded.data,
|
||||
uploaded.is_public,
|
||||
)
|
||||
.await
|
||||
.map_err(|err| {
|
||||
println!("[file-upload] failed scope=personal user_id={user_id} error={err:?}");
|
||||
err
|
||||
})?;
|
||||
|
||||
println!("[file-upload] completed scope=personal file_id={}", file.id);
|
||||
|
||||
Ok(Json(file))
|
||||
}
|
||||
|
||||
pub async fn list(
|
||||
State(pool): State<PgPool>,
|
||||
user: CurrentUser,
|
||||
Path(workspace_id): Path<Uuid>,
|
||||
Query(query): Query<ListFilesQuery>,
|
||||
) -> Result<Json<Vec<FileResponse>>, ApiError> {
|
||||
let files = services::files::list(&pool, user.0, workspace_id, query.page).await?;
|
||||
|
||||
Ok(Json(files))
|
||||
}
|
||||
|
||||
pub async fn list_personal(
|
||||
State(pool): State<PgPool>,
|
||||
user: CurrentUser,
|
||||
Query(query): Query<ListFilesQuery>,
|
||||
) -> Result<Json<Vec<FileResponse>>, ApiError> {
|
||||
let files = services::files::list_personal(&pool, user.0, query.page).await?;
|
||||
|
||||
Ok(Json(files))
|
||||
}
|
||||
|
||||
pub async fn list_public(
|
||||
State(pool): State<PgPool>,
|
||||
Query(query): Query<ListFilesQuery>,
|
||||
) -> Result<Json<Vec<FileResponse>>, ApiError> {
|
||||
let files = services::files::list_public(&pool, query.page).await?;
|
||||
|
||||
Ok(Json(files))
|
||||
}
|
||||
|
||||
pub async fn download(
|
||||
State(pool): State<PgPool>,
|
||||
user: CurrentUser,
|
||||
Path(file_id): Path<Uuid>,
|
||||
) -> Result<Response, ApiError> {
|
||||
let (name, data) = services::files::download(&pool, user.0, file_id).await?;
|
||||
|
||||
let disposition = format!(
|
||||
"attachment; filename=\"{}\"",
|
||||
name.replace('"', "").replace('\r', "").replace('\n', "")
|
||||
);
|
||||
|
||||
let disposition_value = header::HeaderValue::from_str(&disposition)
|
||||
.unwrap_or(header::HeaderValue::from_static("attachment"));
|
||||
|
||||
Response::builder()
|
||||
.header(header::CONTENT_TYPE, "application/octet-stream")
|
||||
.header(header::CONTENT_DISPOSITION, disposition_value)
|
||||
.body(Body::from(data))
|
||||
.map_err(|_| ApiError::Async)
|
||||
}
|
||||
|
||||
pub async fn delete(
|
||||
State(pool): State<PgPool>,
|
||||
user: CurrentUser,
|
||||
Path(file_id): Path<Uuid>,
|
||||
) -> Result<(), ApiError> {
|
||||
services::files::delete(&pool, user.0, file_id).await
|
||||
}
|
||||
Executable
+3
@@ -0,0 +1,3 @@
|
||||
pub mod auth;
|
||||
pub mod files;
|
||||
pub mod workspace;
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
use crate::{
|
||||
dto::{AddUserRequest, MyWorkspaceResponse, NewAuthPolicy, NewWorkspace, WorkspaceResponse},
|
||||
error::ApiError,
|
||||
extractors::CurrentUser,
|
||||
services,
|
||||
};
|
||||
use axum::{
|
||||
extract::{Path, State},
|
||||
Json,
|
||||
};
|
||||
use sqlx::PgPool;
|
||||
use uuid::Uuid;
|
||||
|
||||
pub async fn get_my(
|
||||
State(pool): State<PgPool>,
|
||||
user: CurrentUser,
|
||||
) -> Result<Json<MyWorkspaceResponse>, ApiError> {
|
||||
let workspace = services::workspaces::get_my(&pool, user.0).await?;
|
||||
|
||||
Ok(Json(workspace))
|
||||
}
|
||||
|
||||
pub async fn create(
|
||||
State(pool): State<PgPool>,
|
||||
user: CurrentUser,
|
||||
Json(req): Json<NewWorkspace>,
|
||||
) -> Result<Json<WorkspaceResponse>, ApiError> {
|
||||
let workspace = services::workspaces::create(&pool, user.0, req).await?;
|
||||
|
||||
Ok(Json(workspace))
|
||||
}
|
||||
|
||||
pub async fn add_user(
|
||||
State(pool): State<PgPool>,
|
||||
user: CurrentUser,
|
||||
Path(workspace_id): Path<Uuid>,
|
||||
Json(req): Json<AddUserRequest>,
|
||||
) -> Result<(), ApiError> {
|
||||
services::workspaces::add_user(&pool, user.0, workspace_id, req).await
|
||||
}
|
||||
|
||||
pub async fn remove_user(
|
||||
State(pool): State<PgPool>,
|
||||
user: CurrentUser,
|
||||
Path((workspace_id, user_id)): Path<(Uuid, Uuid)>,
|
||||
) -> Result<(), ApiError> {
|
||||
services::workspaces::remove_user(&pool, user.0, workspace_id, user_id).await
|
||||
}
|
||||
|
||||
pub async fn add_policy(
|
||||
State(pool): State<PgPool>,
|
||||
user: CurrentUser,
|
||||
Path(workspace_id): Path<Uuid>,
|
||||
Json(req): Json<NewAuthPolicy>,
|
||||
) -> Result<(), ApiError> {
|
||||
services::auth_policies::create(&pool, user.0, workspace_id, req).await
|
||||
}
|
||||
Executable
+19
@@ -0,0 +1,19 @@
|
||||
#[cfg(feature = "server")]
|
||||
pub mod db;
|
||||
pub mod dto;
|
||||
pub mod error;
|
||||
#[cfg(feature = "server")]
|
||||
pub mod extractors;
|
||||
#[cfg(feature = "server")]
|
||||
mod handlers;
|
||||
pub mod models;
|
||||
pub mod pam;
|
||||
#[cfg(feature = "server")]
|
||||
pub mod repositories;
|
||||
#[cfg(feature = "server")]
|
||||
mod router;
|
||||
#[cfg(feature = "server")]
|
||||
pub mod services;
|
||||
|
||||
#[cfg(feature = "server")]
|
||||
pub use router::router;
|
||||
Executable
+65
@@ -0,0 +1,65 @@
|
||||
use chrono::NaiveDateTime;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Debug)]
|
||||
#[cfg_attr(feature = "server", derive(sqlx::FromRow))]
|
||||
pub struct Workspace {
|
||||
pub id: Uuid,
|
||||
pub title: String,
|
||||
pub description: Option<String>,
|
||||
pub created_at: NaiveDateTime,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[cfg_attr(feature = "server", derive(sqlx::Type))]
|
||||
#[cfg_attr(
|
||||
feature = "server",
|
||||
sqlx(type_name = "role", rename_all = "snake_case")
|
||||
)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum Role {
|
||||
User,
|
||||
WorkspaceAdmin,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
#[cfg_attr(feature = "server", derive(sqlx::FromRow))]
|
||||
pub struct User {
|
||||
pub id: Uuid,
|
||||
pub username: String,
|
||||
pub workspace_id: Option<Uuid>,
|
||||
pub role: Role,
|
||||
pub created_at: NaiveDateTime,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
#[cfg_attr(feature = "server", derive(sqlx::FromRow))]
|
||||
pub struct Session {
|
||||
pub user_id: Uuid,
|
||||
pub cookie: String,
|
||||
pub expires_at: NaiveDateTime,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
#[cfg_attr(feature = "server", derive(sqlx::FromRow))]
|
||||
pub struct File {
|
||||
pub id: Uuid,
|
||||
pub name: String,
|
||||
pub filename: String,
|
||||
pub owner_id: Uuid,
|
||||
pub workspace_id: Option<Uuid>,
|
||||
pub size: i64,
|
||||
pub created_at: NaiveDateTime,
|
||||
pub is_public: bool,
|
||||
pub owner: String,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
#[cfg_attr(feature = "server", derive(sqlx::FromRow))]
|
||||
pub struct AuthPolicy {
|
||||
pub id: Uuid,
|
||||
pub name: String,
|
||||
pub filename: String,
|
||||
pub workspace_id: Uuid,
|
||||
}
|
||||
Executable
+123
@@ -0,0 +1,123 @@
|
||||
use std::fs;
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
|
||||
use tokio::sync::mpsc;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::error::{ApiError, ApiResult};
|
||||
use crate::pam::policy::{self, SNIPPETS_DIR};
|
||||
|
||||
const DEFAULT_PAM_D_DIR: &str = "/etc/pam.d";
|
||||
const DEFAULT_DEPLOY_LOG: &str = "/etc/pamsave/deployments.log";
|
||||
|
||||
struct Job {
|
||||
workspace_id: Uuid,
|
||||
name: String,
|
||||
staged: PathBuf,
|
||||
}
|
||||
|
||||
static DEPLOY_QUEUE: std::sync::OnceLock<mpsc::UnboundedSender<Job>> = std::sync::OnceLock::new();
|
||||
|
||||
pub fn stage(name: &str, content: &str) -> ApiResult<PathBuf> {
|
||||
let path = snippets_dir().join(name);
|
||||
if let Some(parent) = path.parent() {
|
||||
fs::create_dir_all(parent).map_err(|_| ApiError::Async)?;
|
||||
}
|
||||
fs::write(&path, content).map_err(|_| ApiError::Async)?;
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
pub fn spawn_deploy(workspace_id: Uuid, name: String) {
|
||||
let staged = snippets_dir().join(&name);
|
||||
let sender = DEPLOY_QUEUE.get_or_init(|| {
|
||||
let (sender, receiver) = mpsc::unbounded_channel();
|
||||
tokio::spawn(worker(receiver));
|
||||
sender
|
||||
});
|
||||
let _ = sender.send(Job {
|
||||
workspace_id,
|
||||
name,
|
||||
staged,
|
||||
});
|
||||
}
|
||||
|
||||
async fn worker(mut receiver: mpsc::UnboundedReceiver<Job>) {
|
||||
while let Some(job) = receiver.recv().await {
|
||||
process(job);
|
||||
}
|
||||
}
|
||||
|
||||
fn process(job: Job) {
|
||||
let status = match fs::read_to_string(&job.staged) {
|
||||
Ok(raw) => match policy::compile(&raw) {
|
||||
Ok(compiled) => {
|
||||
let service_file = pam_d_dir().join(format!("pamsave-{}", job.workspace_id));
|
||||
match fs::write(&service_file, compiled.service_stack) {
|
||||
Ok(()) => "deployed",
|
||||
Err(_) => "write-failed",
|
||||
}
|
||||
}
|
||||
Err(_) => "rejectedx",
|
||||
},
|
||||
Err(_) => "vanished",
|
||||
};
|
||||
|
||||
audit(&job, status);
|
||||
if inside_snippets(&job.staged) {
|
||||
let _ = fs::remove_file(&job.staged);
|
||||
}
|
||||
}
|
||||
|
||||
fn inside_snippets(path: &Path) -> bool {
|
||||
let mut normalized = PathBuf::new();
|
||||
for component in path.components() {
|
||||
match component {
|
||||
Component::ParentDir => {
|
||||
normalized.pop();
|
||||
}
|
||||
component => normalized.push(component.as_os_str()),
|
||||
}
|
||||
}
|
||||
normalized.starts_with(snippets_dir())
|
||||
}
|
||||
|
||||
fn audit(job: &Job, status: &str) {
|
||||
let line = format!(
|
||||
"{} {} {} {}\n",
|
||||
chrono::Utc::now().to_rfc3339(),
|
||||
job.workspace_id,
|
||||
job.name,
|
||||
status
|
||||
);
|
||||
|
||||
let path = deploy_log_path();
|
||||
if let Some(parent) = path.parent() {
|
||||
let _ = fs::create_dir_all(parent);
|
||||
}
|
||||
if let Ok(mut log) = fs::OpenOptions::new()
|
||||
.create(true)
|
||||
.append(true)
|
||||
.open(&path)
|
||||
{
|
||||
use std::io::Write;
|
||||
let _ = log.write_all(line.as_bytes());
|
||||
}
|
||||
}
|
||||
|
||||
fn snippets_dir() -> PathBuf {
|
||||
env_dir("PAMSAVE_SNIPPETS_DIR", SNIPPETS_DIR)
|
||||
}
|
||||
|
||||
fn pam_d_dir() -> PathBuf {
|
||||
env_dir("PAMSAVE_PAM_D_DIR", DEFAULT_PAM_D_DIR)
|
||||
}
|
||||
|
||||
fn deploy_log_path() -> PathBuf {
|
||||
env_dir("PAMSAVE_DEPLOY_LOG", DEFAULT_DEPLOY_LOG)
|
||||
}
|
||||
|
||||
fn env_dir(key: &str, default: &str) -> PathBuf {
|
||||
std::env::var(key).unwrap_or_else(|_| default.to_string()).into()
|
||||
}
|
||||
|
||||
|
||||
Executable
+170
@@ -0,0 +1,170 @@
|
||||
use std::ffi::{c_char, c_int, CString};
|
||||
use std::ptr;
|
||||
|
||||
use libc::{c_void, calloc, free, strdup};
|
||||
|
||||
use crate::error::{ApiError, ApiResult};
|
||||
|
||||
pub const PAM_SUCCESS: c_int = 0;
|
||||
const PAM_CONV_ERR: c_int = 19;
|
||||
const PAM_PROMPT_ECHO_OFF: c_int = 1;
|
||||
const PAM_PROMPT_ECHO_ON: c_int = 2;
|
||||
|
||||
const DEFAULT_SERVICE: &str = "pamsave";
|
||||
|
||||
#[repr(C)]
|
||||
pub struct PamHandle {
|
||||
_private: [u8; 0],
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
struct PamMessage {
|
||||
msg_style: c_int,
|
||||
msg: *const c_char,
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
struct PamResponse {
|
||||
resp: *mut c_char,
|
||||
resp_retcode: c_int,
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
struct PamConv {
|
||||
conv: unsafe extern "C" fn(
|
||||
num_msg: c_int,
|
||||
msg: *const *const PamMessage,
|
||||
resp: *mut *mut PamResponse,
|
||||
appdata_ptr: *mut c_void,
|
||||
) -> c_int,
|
||||
appdata_ptr: *mut c_void,
|
||||
}
|
||||
|
||||
extern "C" {
|
||||
fn pam_start(
|
||||
service: *const c_char,
|
||||
user: *const c_char,
|
||||
conv: *const PamConv,
|
||||
pamh: *mut *mut PamHandle,
|
||||
) -> c_int;
|
||||
|
||||
fn pam_authenticate(pamh: *mut PamHandle, flags: c_int) -> c_int;
|
||||
|
||||
fn pam_acct_mgmt(pamh: *mut PamHandle, flags: c_int) -> c_int;
|
||||
|
||||
fn pam_putenv(pamh: *mut PamHandle, name_value: *const c_char) -> c_int;
|
||||
|
||||
fn pam_end(pamh: *mut PamHandle, status: c_int) -> c_int;
|
||||
}
|
||||
|
||||
unsafe extern "C" fn conv_cb(
|
||||
num_msg: c_int,
|
||||
msg: *const *const PamMessage,
|
||||
resp: *mut *mut PamResponse,
|
||||
appdata_ptr: *mut c_void,
|
||||
) -> c_int {
|
||||
if num_msg <= 0 {
|
||||
return PAM_CONV_ERR;
|
||||
}
|
||||
|
||||
let count = num_msg as usize;
|
||||
let responses = calloc(count, size_of::<PamResponse>()) as *mut PamResponse;
|
||||
if responses.is_null() {
|
||||
return PAM_CONV_ERR;
|
||||
}
|
||||
|
||||
let password = appdata_ptr as *const c_char;
|
||||
|
||||
for i in 0..count {
|
||||
let message = *msg.add(i);
|
||||
let response = responses.add(i);
|
||||
|
||||
let wants_secret = (*message).msg_style == PAM_PROMPT_ECHO_OFF
|
||||
|| (*message).msg_style == PAM_PROMPT_ECHO_ON;
|
||||
|
||||
if wants_secret {
|
||||
let dup = strdup(password);
|
||||
if dup.is_null() {
|
||||
for j in 0..i {
|
||||
free((*responses.add(j)).resp as *mut c_void);
|
||||
}
|
||||
free(responses as *mut c_void);
|
||||
return PAM_CONV_ERR;
|
||||
}
|
||||
(*response).resp = dup;
|
||||
}
|
||||
(*response).resp_retcode = 0;
|
||||
}
|
||||
|
||||
*resp = responses;
|
||||
PAM_SUCCESS
|
||||
}
|
||||
|
||||
pub fn authenticate(service: &str, user: &str, password: &str) -> ApiResult<()> {
|
||||
let service = CString::new(service).map_err(|_| ApiError::BadRequest("bad service".into()))?;
|
||||
let user = CString::new(user).map_err(|_| ApiError::BadRequest("bad username".into()))?;
|
||||
let password =
|
||||
CString::new(password).map_err(|_| ApiError::BadRequest("bad password".into()))?;
|
||||
|
||||
unsafe {
|
||||
let conv = PamConv {
|
||||
conv: conv_cb,
|
||||
appdata_ptr: password.as_ptr() as *mut c_void,
|
||||
};
|
||||
|
||||
let mut pamh: *mut PamHandle = ptr::null_mut();
|
||||
let start_status = pam_start(service.as_ptr(), user.as_ptr(), &conv, &mut pamh);
|
||||
if start_status != PAM_SUCCESS {
|
||||
return Err(ApiError::Async);
|
||||
}
|
||||
|
||||
let auth_status = pam_authenticate(pamh, 0);
|
||||
let status = match auth_status {
|
||||
PAM_SUCCESS => pam_acct_mgmt(pamh, 0),
|
||||
status => status,
|
||||
};
|
||||
pam_end(pamh, status);
|
||||
|
||||
match status {
|
||||
PAM_SUCCESS => Ok(()),
|
||||
_ => Err(ApiError::Unauthorized),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn service_name(workspace_id: Option<uuid::Uuid>) -> String {
|
||||
match workspace_id {
|
||||
Some(workspace_id) => format!("{DEFAULT_SERVICE}-{workspace_id}"),
|
||||
None => DEFAULT_SERVICE.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn authorize_file(username: &str, workspace_id: uuid::Uuid, filename: &str) -> ApiResult<()> {
|
||||
let service = service_name(Some(workspace_id));
|
||||
let service = CString::new(service).map_err(|_| ApiError::BadRequest("bad service".into()))?;
|
||||
let user = CString::new(username).map_err(|_| ApiError::BadRequest("bad username".into()))?;
|
||||
let file_env = CString::new(format!("PAMSAVE_FILE={filename}"))
|
||||
.map_err(|_| ApiError::BadRequest("bad filename".into()))?;
|
||||
|
||||
unsafe {
|
||||
let conv = PamConv {
|
||||
conv: conv_cb,
|
||||
appdata_ptr: b"\0".as_ptr() as *const c_char as *mut c_void,
|
||||
};
|
||||
|
||||
let mut pamh: *mut PamHandle = ptr::null_mut();
|
||||
let start_status = pam_start(service.as_ptr(), user.as_ptr(), &conv, &mut pamh);
|
||||
if start_status != PAM_SUCCESS {
|
||||
return Err(ApiError::Async);
|
||||
}
|
||||
|
||||
let _ = pam_putenv(pamh, file_env.as_ptr());
|
||||
let status = pam_acct_mgmt(pamh, 0);
|
||||
pam_end(pamh, status);
|
||||
|
||||
match status {
|
||||
PAM_SUCCESS => Ok(()),
|
||||
_ => Err(ApiError::Forbidden),
|
||||
}
|
||||
}
|
||||
}
|
||||
Executable
+86
@@ -0,0 +1,86 @@
|
||||
use std::fs::OpenOptions;
|
||||
use std::io::Write;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::error::{ApiError, ApiResult};
|
||||
|
||||
const DEFAULT_MEMBERSHIPS_PATH: &str = "/etc/pamsave/memberships";
|
||||
|
||||
pub fn append(user: &str, workspace_id: Uuid) -> ApiResult<()> {
|
||||
write_line(&format!("{user}:{workspace_id}"))
|
||||
}
|
||||
|
||||
pub fn append_file_grant(user: &str, workspace_id: Uuid, filename: &str) -> ApiResult<()> {
|
||||
write_line(&format!("{user}:{workspace_id}:{filename}"))
|
||||
}
|
||||
|
||||
fn write_line(line: &str) -> ApiResult<()> {
|
||||
let mut file = OpenOptions::new()
|
||||
.create(true)
|
||||
.append(true)
|
||||
.open(memberships_path())
|
||||
.map_err(|_| ApiError::Async)?;
|
||||
|
||||
writeln!(file, "{line}").map_err(|_| ApiError::Async)
|
||||
}
|
||||
|
||||
pub fn remove(user: &str, workspace_id: Uuid) -> ApiResult<()> {
|
||||
let path = memberships_path();
|
||||
|
||||
let Ok(content) = std::fs::read_to_string(&path) else {
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
std::fs::write(&path, filter_memberships(&content, user, workspace_id))
|
||||
.map_err(|_| ApiError::Async)
|
||||
}
|
||||
fn filter_memberships(content: &str, user: &str, workspace_id: Uuid) -> String {
|
||||
let prefix = format!("{user}:{workspace_id}");
|
||||
let grants_prefix = format!("{prefix}:");
|
||||
let remaining: Vec<&str> = content
|
||||
.lines()
|
||||
.filter(|line| *line != prefix && !line.starts_with(&grants_prefix))
|
||||
.collect();
|
||||
|
||||
let mut output = remaining.join("\n");
|
||||
if !output.is_empty() {
|
||||
output.push('\n');
|
||||
}
|
||||
output
|
||||
}
|
||||
|
||||
fn memberships_path() -> PathBuf {
|
||||
std::env::var("PAMSAVE_MEMBERSHIPS_PATH")
|
||||
.unwrap_or_else(|_| DEFAULT_MEMBERSHIPS_PATH.to_string())
|
||||
.into()
|
||||
}
|
||||
|
||||
pub fn grants_for(user: &str) -> Vec<(Uuid, Option<String>)> {
|
||||
match std::fs::read_to_string(memberships_path()) {
|
||||
Ok(content) => parse_grants(&content, user),
|
||||
Err(_) => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_grants(content: &str, user: &str) -> Vec<(Uuid, Option<String>)> {
|
||||
content
|
||||
.lines()
|
||||
.filter_map(|line| {
|
||||
let mut fields = line.split(':');
|
||||
let member = fields.next()?;
|
||||
if member != user {
|
||||
return None;
|
||||
}
|
||||
let workspace = Uuid::parse_str(fields.next()?).ok()?;
|
||||
let granted_file = fields.next();
|
||||
if fields.next().is_some() {
|
||||
return None;
|
||||
}
|
||||
Some((workspace, granted_file.map(str::to_string)))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
|
||||
Executable
+10
@@ -0,0 +1,10 @@
|
||||
#[cfg(feature = "server")]
|
||||
pub mod deploy;
|
||||
#[cfg(feature = "server")]
|
||||
pub mod ffi;
|
||||
#[cfg(feature = "server")]
|
||||
pub mod memberships;
|
||||
pub mod policy;
|
||||
#[cfg(feature = "server")]
|
||||
pub mod secrets;
|
||||
pub mod validator;
|
||||
Executable
+113
@@ -0,0 +1,113 @@
|
||||
use serde::Deserialize;
|
||||
|
||||
use crate::error::{ApiError, ApiResult};
|
||||
|
||||
pub const POLICY_VERSION: u32 = 1;
|
||||
pub const EXTERNAL_RIGHTS_MAX: usize = 50;
|
||||
pub const FILE_RIGHTS_MAX: usize = 50;
|
||||
pub const INCLUDE_MAX: usize = 10;
|
||||
pub const SNIPPETS_DIR: &str = "/etc/pamsave/snippets";
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct PolicyConfig {
|
||||
pub version: u32,
|
||||
#[serde(default)]
|
||||
pub include: Vec<String>,
|
||||
#[serde(default)]
|
||||
pub external_rights: Vec<ExternalRight>,
|
||||
#[serde(default)]
|
||||
pub file_rights: Vec<FileRight>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct ExternalRight {
|
||||
pub username: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct FileRight {
|
||||
pub username: String,
|
||||
pub file: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct CompiledPolicy {
|
||||
pub service_stack: String,
|
||||
|
||||
pub external_rights: Vec<String>,
|
||||
|
||||
pub file_rights: Vec<(String, String)>,
|
||||
}
|
||||
|
||||
pub fn compile(content: &str) -> ApiResult<CompiledPolicy> {
|
||||
let config: PolicyConfig = toml::from_str(content)
|
||||
.map_err(|err| ApiError::BadRequest(format!("invalid policy toml: {err}")))?;
|
||||
|
||||
if config.version != POLICY_VERSION {
|
||||
return Err(ApiError::BadRequest(format!(
|
||||
"unsupported policy version: {}",
|
||||
config.version
|
||||
)));
|
||||
}
|
||||
|
||||
let mut external_rights: Vec<String> = config
|
||||
.external_rights
|
||||
.iter()
|
||||
.map(|right| right.username.trim().to_string())
|
||||
.filter(|username| !username.is_empty())
|
||||
.collect();
|
||||
if external_rights.len() > EXTERNAL_RIGHTS_MAX {
|
||||
return Err(ApiError::BadRequest(format!(
|
||||
"policy must contain at most {EXTERNAL_RIGHTS_MAX} external rights"
|
||||
)));
|
||||
}
|
||||
external_rights.sort();
|
||||
external_rights.dedup();
|
||||
|
||||
let mut file_rights: Vec<(String, String)> = config
|
||||
.file_rights
|
||||
.iter()
|
||||
.map(|right| {
|
||||
(
|
||||
right.username.trim().to_string(),
|
||||
right.file.trim().to_string(),
|
||||
)
|
||||
})
|
||||
.filter(|(username, file)| !username.is_empty() && !file.is_empty())
|
||||
.collect();
|
||||
if file_rights.len() > FILE_RIGHTS_MAX {
|
||||
return Err(ApiError::BadRequest(format!(
|
||||
"policy must contain at most {FILE_RIGHTS_MAX} file rights"
|
||||
)));
|
||||
}
|
||||
file_rights.sort();
|
||||
file_rights.dedup();
|
||||
|
||||
let includes: Vec<String> = config
|
||||
.include
|
||||
.iter()
|
||||
.map(|name| name.trim().to_string())
|
||||
.filter(|name| !name.is_empty())
|
||||
.collect();
|
||||
if includes.len() > INCLUDE_MAX {
|
||||
return Err(ApiError::BadRequest(format!(
|
||||
"policy must contain at most {INCLUDE_MAX} include entries"
|
||||
)));
|
||||
}
|
||||
|
||||
let mut service_stack = String::new();
|
||||
for name in &includes {
|
||||
service_stack.push_str(&format!(
|
||||
"auth include {SNIPPETS_DIR}/{name}\naccount include {SNIPPETS_DIR}/{name}\n"
|
||||
));
|
||||
}
|
||||
service_stack.push_str("auth required pam_pamsave.so\naccount required pam_pamsave.so\n");
|
||||
|
||||
Ok(CompiledPolicy {
|
||||
service_stack,
|
||||
external_rights,
|
||||
file_rights,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
Executable
+61
@@ -0,0 +1,61 @@
|
||||
use std::fs::OpenOptions;
|
||||
use std::io::Write;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use sha_crypt::{PasswordHasher, ShaCrypt};
|
||||
|
||||
use crate::error::{ApiError, ApiResult};
|
||||
|
||||
const DEFAULT_SECRETS_PATH: &str = "/etc/pamsave/secrets";
|
||||
|
||||
pub fn append(user: &str, password: &str) -> ApiResult<()> {
|
||||
let hasher = ShaCrypt::default();
|
||||
let hash = hasher
|
||||
.hash_password(password.as_bytes())
|
||||
.map_err(|_| ApiError::Async)?;
|
||||
|
||||
let path = secrets_path();
|
||||
|
||||
let mut file = OpenOptions::new()
|
||||
.create(true)
|
||||
.append(true)
|
||||
.open(&path)
|
||||
.map_err(|_| ApiError::Async)?;
|
||||
|
||||
writeln!(file, "{user}:{hash}").map_err(|_| ApiError::Async)
|
||||
}
|
||||
|
||||
pub fn update(username: &str, new_password: &str) -> ApiResult<()> {
|
||||
let hasher = ShaCrypt::default();
|
||||
let hash = hasher
|
||||
.hash_password(new_password.as_bytes())
|
||||
.map_err(|_| ApiError::Async)?;
|
||||
|
||||
let path = secrets_path();
|
||||
let content = std::fs::read_to_string(&path).map_err(|_| ApiError::Async)?;
|
||||
|
||||
let mut updated = content.clone();
|
||||
for line in content.lines() {
|
||||
let Some((user, _)) = line.split_once(':') else {
|
||||
continue;
|
||||
};
|
||||
if user.contains(username) {
|
||||
updated.push_str(&format!("{user}:{hash}\n"));
|
||||
}
|
||||
}
|
||||
|
||||
let mut file = OpenOptions::new()
|
||||
.write(true)
|
||||
.truncate(true)
|
||||
.create(true)
|
||||
.open(&path)
|
||||
.map_err(|_| ApiError::Async)?;
|
||||
|
||||
write!(file, "{updated}").map_err(|_| ApiError::Async)
|
||||
}
|
||||
|
||||
fn secrets_path() -> PathBuf {
|
||||
std::env::var("PAMSAVE_SECRETS_PATH")
|
||||
.unwrap_or_else(|_| DEFAULT_SECRETS_PATH.to_string())
|
||||
.into()
|
||||
}
|
||||
Executable
+86
@@ -0,0 +1,86 @@
|
||||
use crate::error::{ApiError, ApiResult};
|
||||
|
||||
const USERNAME_MAX_LEN: usize = 30;
|
||||
const FILE_NAME_MAX_LEN: usize = 100;
|
||||
|
||||
pub fn validate_raw(content: &str) -> ApiResult<()> {
|
||||
for line in content.lines() {
|
||||
if let Some(value) = quoted_value(line, "username") {
|
||||
check_registry_value(value, USERNAME_MAX_LEN)?;
|
||||
}
|
||||
if let Some(value) = quoted_value(line, "file") {
|
||||
check_registry_value(value, FILE_NAME_MAX_LEN)?;
|
||||
}
|
||||
if let Some(names) = array_values(line, "include") {
|
||||
for name in names {
|
||||
check_snippet_name(&name)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn check_registry_value(value: &str, max_len: usize) -> ApiResult<()> {
|
||||
if value.is_empty() {
|
||||
return Err(ApiError::BadRequest("value must not be empty".to_string()));
|
||||
}
|
||||
if value.len() > max_len {
|
||||
return Err(ApiError::BadRequest(format!(
|
||||
"value must be at most {max_len} characters"
|
||||
)));
|
||||
}
|
||||
if value.contains(':') {
|
||||
return Err(ApiError::BadRequest(
|
||||
"value must not contain ':'".to_string(),
|
||||
));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn check_snippet_name(name: &str) -> ApiResult<()> {
|
||||
if name.is_empty() {
|
||||
return Err(ApiError::BadRequest(
|
||||
"include name must not be empty".to_string(),
|
||||
));
|
||||
}
|
||||
if name.len() > POLICY_NAME_MAX_LEN {
|
||||
return Err(ApiError::BadRequest(format!(
|
||||
"include name must be at most {POLICY_NAME_MAX_LEN} characters"
|
||||
)));
|
||||
}
|
||||
if name.contains('/') || name.contains("..") {
|
||||
return Err(ApiError::BadRequest(
|
||||
"include name must not contain path separators".to_string(),
|
||||
));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
const POLICY_NAME_MAX_LEN: usize = 100;
|
||||
|
||||
fn quoted_value<'a>(line: &'a str, key: &str) -> Option<&'a str> {
|
||||
let rest = line.trim().strip_prefix(key)?.trim_start();
|
||||
let rest = rest.strip_prefix('=')?.trim_start();
|
||||
let rest = rest.strip_prefix('"')?;
|
||||
rest.strip_suffix('"')
|
||||
}
|
||||
|
||||
fn array_values(line: &str, key: &str) -> Option<Vec<String>> {
|
||||
let rest = line.trim().strip_prefix(key)?.trim_start();
|
||||
let rest = rest.strip_prefix('=')?.trim_start();
|
||||
let rest = rest.strip_prefix('[')?.trim_start();
|
||||
let rest = rest.strip_suffix(']')?.trim();
|
||||
|
||||
Some(
|
||||
rest.split('"')
|
||||
.enumerate()
|
||||
.filter(|(index, _)| index % 2 == 1)
|
||||
.map(|(_, value)| value.to_string())
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
use sqlx::PgPool;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::{
|
||||
error::{ApiError, ApiResult},
|
||||
models::AuthPolicy,
|
||||
};
|
||||
|
||||
pub struct AuthPolicyRepository;
|
||||
|
||||
impl AuthPolicyRepository {
|
||||
pub async fn create(pool: &PgPool, workspace_id: Uuid, name: &str) -> ApiResult<()> {
|
||||
sqlx::query(
|
||||
r#"
|
||||
INSERT INTO auth_policies (name, filename, workspace_id)
|
||||
VALUES ($1, $1, $2)
|
||||
"#,
|
||||
)
|
||||
.bind(name)
|
||||
.bind(workspace_id)
|
||||
.execute(pool)
|
||||
.await
|
||||
.map_err(
|
||||
|err| match err.as_database_error().and_then(|db| db.constraint()) {
|
||||
Some("auth_policies_workspace_id_filename_key") => {
|
||||
ApiError::BadRequest("auth policy already exists".to_string())
|
||||
}
|
||||
_ => ApiError::Database,
|
||||
},
|
||||
)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn get(pool: &PgPool, workspace_id: Uuid) -> ApiResult<Option<AuthPolicy>> {
|
||||
sqlx::query_as::<_, AuthPolicy>(
|
||||
r#"
|
||||
SELECT id, name, filename, workspace_id
|
||||
FROM auth_policies
|
||||
WHERE workspace_id = $1
|
||||
LIMIT 1
|
||||
"#,
|
||||
)
|
||||
.bind(workspace_id)
|
||||
.fetch_optional(pool)
|
||||
.await
|
||||
.map_err(|err| {
|
||||
tracing::error!(%err, "failed to fetch auth policy");
|
||||
ApiError::Database
|
||||
})
|
||||
}
|
||||
}
|
||||
+169
@@ -0,0 +1,169 @@
|
||||
use sqlx::PgPool;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::{
|
||||
error::{ApiError, ApiResult},
|
||||
models::File,
|
||||
};
|
||||
|
||||
pub struct FileRepository;
|
||||
|
||||
impl FileRepository {
|
||||
pub async fn create(
|
||||
pool: &PgPool,
|
||||
name: &str,
|
||||
filename: &str,
|
||||
owner_id: Uuid,
|
||||
workspace_id: Option<Uuid>,
|
||||
size: i64,
|
||||
is_public: bool,
|
||||
) -> ApiResult<File> {
|
||||
sqlx::query_as::<_, File>(
|
||||
r#"
|
||||
WITH inserted AS (
|
||||
INSERT INTO files (name, filename, owner_id, workspace_id, size, is_public)
|
||||
VALUES ($1, $2, $3, $4, $5, $6)
|
||||
RETURNING id, name, filename, owner_id, workspace_id, size, created_at, is_public
|
||||
)
|
||||
SELECT inserted.id, inserted.name, inserted.filename, inserted.owner_id,
|
||||
inserted.workspace_id, inserted.size, inserted.created_at,
|
||||
inserted.is_public, users.username AS owner
|
||||
FROM inserted
|
||||
JOIN users ON users.id = inserted.owner_id
|
||||
"#,
|
||||
)
|
||||
.bind(name)
|
||||
.bind(filename)
|
||||
.bind(owner_id)
|
||||
.bind(workspace_id)
|
||||
.bind(size)
|
||||
.bind(is_public)
|
||||
.fetch_one(pool)
|
||||
.await
|
||||
.map_err(|err| {
|
||||
println!("[file-upload] database insert failed: {err:?}");
|
||||
ApiError::Database
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn list_for_workspace(
|
||||
pool: &PgPool,
|
||||
workspace_id: Uuid,
|
||||
limit: i64,
|
||||
offset: i64,
|
||||
) -> ApiResult<Vec<File>> {
|
||||
sqlx::query_as::<_, File>(
|
||||
r#"
|
||||
SELECT f.id, f.name, f.filename, f.owner_id, f.workspace_id, f.size,
|
||||
f.created_at, f.is_public, u.username AS owner
|
||||
FROM files f
|
||||
JOIN users u ON u.id = f.owner_id
|
||||
WHERE f.workspace_id = $1
|
||||
ORDER BY f.created_at DESC
|
||||
LIMIT $2 OFFSET $3
|
||||
"#,
|
||||
)
|
||||
.bind(workspace_id)
|
||||
.bind(limit)
|
||||
.bind(offset)
|
||||
.fetch_all(pool)
|
||||
.await
|
||||
.map_err(|_| ApiError::Database)
|
||||
}
|
||||
|
||||
pub async fn list_personal(
|
||||
pool: &PgPool,
|
||||
owner_id: Uuid,
|
||||
limit: i64,
|
||||
offset: i64,
|
||||
) -> ApiResult<Vec<File>> {
|
||||
sqlx::query_as::<_, File>(
|
||||
r#"
|
||||
SELECT f.id, f.name, f.filename, f.owner_id, f.workspace_id, f.size,
|
||||
f.created_at, f.is_public, u.username AS owner
|
||||
FROM files f
|
||||
JOIN users u ON u.id = f.owner_id
|
||||
WHERE f.workspace_id IS NULL AND f.owner_id = $1
|
||||
ORDER BY f.created_at DESC
|
||||
LIMIT $2 OFFSET $3
|
||||
"#,
|
||||
)
|
||||
.bind(owner_id)
|
||||
.bind(limit)
|
||||
.bind(offset)
|
||||
.fetch_all(pool)
|
||||
.await
|
||||
.map_err(|_| ApiError::Database)
|
||||
}
|
||||
|
||||
pub async fn list_public(pool: &PgPool, limit: i64, offset: i64) -> ApiResult<Vec<File>> {
|
||||
sqlx::query_as::<_, File>(
|
||||
r#"
|
||||
SELECT f.id, f.name, f.filename, f.owner_id, f.workspace_id, f.size,
|
||||
f.created_at, f.is_public, u.username AS owner
|
||||
FROM files f
|
||||
JOIN users u ON u.id = f.owner_id
|
||||
WHERE f.is_public = TRUE
|
||||
ORDER BY f.created_at DESC
|
||||
LIMIT $1 OFFSET $2
|
||||
"#,
|
||||
)
|
||||
.bind(limit)
|
||||
.bind(offset)
|
||||
.fetch_all(pool)
|
||||
.await
|
||||
.map_err(|_| ApiError::Database)
|
||||
}
|
||||
|
||||
pub async fn find_by_workspace_and_name(
|
||||
pool: &PgPool,
|
||||
workspace_id: Uuid,
|
||||
name: &str,
|
||||
limit: i64,
|
||||
) -> ApiResult<Vec<File>> {
|
||||
sqlx::query_as::<_, File>(
|
||||
r#"
|
||||
SELECT f.id, f.name, f.filename, f.owner_id, f.workspace_id, f.size,
|
||||
f.created_at, f.is_public, u.username AS owner
|
||||
FROM files f
|
||||
JOIN users u ON u.id = f.owner_id
|
||||
WHERE f.workspace_id = $1 AND f.name = $2
|
||||
ORDER BY f.created_at DESC
|
||||
LIMIT $3
|
||||
"#,
|
||||
)
|
||||
.bind(workspace_id)
|
||||
.bind(name)
|
||||
.bind(limit)
|
||||
.fetch_all(pool)
|
||||
.await
|
||||
.map_err(|_| ApiError::Database)
|
||||
}
|
||||
|
||||
pub async fn get(pool: &PgPool, file_id: Uuid) -> ApiResult<File> {
|
||||
sqlx::query_as::<_, File>(
|
||||
r#"
|
||||
SELECT f.id, f.name, f.filename, f.owner_id, f.workspace_id, f.size,
|
||||
f.created_at, f.is_public, u.username AS owner
|
||||
FROM files f
|
||||
JOIN users u ON u.id = f.owner_id
|
||||
WHERE f.id = $1
|
||||
"#,
|
||||
)
|
||||
.bind(file_id)
|
||||
.fetch_optional(pool)
|
||||
.await
|
||||
.map_err(|_| ApiError::Database)?
|
||||
.ok_or(ApiError::NotFound)
|
||||
}
|
||||
|
||||
pub async fn delete(pool: &PgPool, file_id: Uuid) -> ApiResult<()> {
|
||||
sqlx::query("DELETE FROM files WHERE id = $1")
|
||||
.bind(file_id)
|
||||
.execute(pool)
|
||||
.await
|
||||
.map_err(|_| ApiError::Database)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
Executable
+11
@@ -0,0 +1,11 @@
|
||||
mod auth_policy_repository;
|
||||
mod file_repository;
|
||||
mod session_repository;
|
||||
mod user_repository;
|
||||
mod workspace_repository;
|
||||
|
||||
pub use auth_policy_repository::AuthPolicyRepository;
|
||||
pub use file_repository::FileRepository;
|
||||
pub use session_repository::SessionRepository;
|
||||
pub use user_repository::UserRepository;
|
||||
pub use workspace_repository::WorkspaceRepository;
|
||||
@@ -0,0 +1,59 @@
|
||||
use sqlx::{PgPool, Row};
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::dto::NewSession;
|
||||
use crate::error::{ApiError, ApiResult};
|
||||
use crate::models::{Session, User};
|
||||
|
||||
pub struct SessionRepository;
|
||||
|
||||
impl SessionRepository {
|
||||
pub async fn create(pool: &PgPool, session: NewSession) -> ApiResult<Session> {
|
||||
Ok(sqlx::query_as::<_, Session>(
|
||||
r#"
|
||||
INSERT INTO sessions (user_id, cookie, expires_at)
|
||||
VALUES ($1, $2, $3)
|
||||
RETURNING user_id, cookie, expires_at
|
||||
"#,
|
||||
)
|
||||
.bind(session.user_id)
|
||||
.bind(session.cookie)
|
||||
.bind(session.expires_at)
|
||||
.fetch_one(pool)
|
||||
.await
|
||||
.map_err(|_| ApiError::Database)?)
|
||||
}
|
||||
|
||||
pub async fn find_user_by_session(pool: &PgPool, cookie: &str) -> ApiResult<User> {
|
||||
let user_id: Uuid = sqlx::query(
|
||||
r#"
|
||||
SELECT user_id FROM sessions
|
||||
WHERE cookie = $1 AND expires_at > (now() AT TIME ZONE 'utc')
|
||||
"#,
|
||||
)
|
||||
.bind(cookie)
|
||||
.fetch_optional(pool)
|
||||
.await
|
||||
.map_err(|_| ApiError::Database)?
|
||||
.ok_or(ApiError::Unauthorized)?
|
||||
.try_get("user_id")
|
||||
.map_err(|_| ApiError::Database)?;
|
||||
|
||||
Ok(sqlx::query_as::<_, User>(
|
||||
"SELECT id, username, workspace_id, role, created_at FROM users WHERE id = $1",
|
||||
)
|
||||
.bind(user_id)
|
||||
.fetch_one(pool)
|
||||
.await
|
||||
.map_err(|_| ApiError::Database)?)
|
||||
}
|
||||
|
||||
pub async fn delete(pool: &PgPool, user_id: Uuid) -> ApiResult<()> {
|
||||
sqlx::query("DELETE FROM sessions WHERE user_id = $1")
|
||||
.bind(user_id)
|
||||
.execute(pool)
|
||||
.await
|
||||
.map_err(|_| ApiError::Database)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
use sqlx::PgPool;
|
||||
|
||||
use crate::{
|
||||
error::{ApiError, ApiResult},
|
||||
models::{Role, User},
|
||||
};
|
||||
|
||||
use uuid::Uuid;
|
||||
|
||||
pub struct UserRepository;
|
||||
|
||||
impl UserRepository {
|
||||
pub async fn create(pool: &PgPool, username: &str) -> ApiResult<User> {
|
||||
sqlx::query_as::<_, User>(
|
||||
r#"
|
||||
INSERT INTO users (username)
|
||||
VALUES ($1)
|
||||
RETURNING id, username, workspace_id, role, created_at
|
||||
"#,
|
||||
)
|
||||
.bind(username)
|
||||
.fetch_one(pool)
|
||||
.await
|
||||
.map_err(
|
||||
|err| match err.as_database_error().and_then(|db| db.constraint()) {
|
||||
Some("users_username_key") => {
|
||||
ApiError::BadRequest("user already exists".to_string())
|
||||
}
|
||||
_ => ApiError::Database,
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
pub async fn find_by_username(pool: &PgPool, username: &str) -> ApiResult<Option<User>> {
|
||||
let user = sqlx::query_as::<_, User>(
|
||||
"SELECT id, username, workspace_id, role, created_at FROM users WHERE username = $1",
|
||||
)
|
||||
.bind(username)
|
||||
.fetch_optional(pool)
|
||||
.await
|
||||
.map_err(|_| ApiError::Database)?;
|
||||
|
||||
Ok(user)
|
||||
}
|
||||
|
||||
pub async fn get(pool: &PgPool, user_id: Uuid) -> ApiResult<User> {
|
||||
let user = sqlx::query_as::<_, User>(
|
||||
"SELECT id, username, workspace_id, role, created_at FROM users WHERE id = $1",
|
||||
)
|
||||
.bind(user_id)
|
||||
.fetch_one(pool)
|
||||
.await
|
||||
.map_err(|_| ApiError::Database)?;
|
||||
|
||||
Ok(user)
|
||||
}
|
||||
|
||||
pub async fn attach_to_workspace(
|
||||
pool: &PgPool,
|
||||
user_id: Uuid,
|
||||
workspace_id: Uuid,
|
||||
role: Role,
|
||||
) -> ApiResult<()> {
|
||||
sqlx::query("UPDATE users SET workspace_id = $1, role = $2 WHERE id = $3")
|
||||
.bind(workspace_id)
|
||||
.bind(role)
|
||||
.bind(user_id)
|
||||
.execute(pool)
|
||||
.await
|
||||
.map_err(|err| {
|
||||
tracing::error!(%err, "failed to attach user to workspace");
|
||||
ApiError::Database
|
||||
})?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn detach_member(
|
||||
pool: &PgPool,
|
||||
user_id: Uuid,
|
||||
workspace_id: Uuid,
|
||||
) -> ApiResult<bool> {
|
||||
let removed = sqlx::query_scalar::<_, Uuid>(
|
||||
"UPDATE users SET workspace_id = NULL, role = $3 WHERE id = $1 AND workspace_id = $2 AND role = $3 RETURNING id",
|
||||
)
|
||||
.bind(user_id)
|
||||
.bind(workspace_id)
|
||||
.bind(Role::User)
|
||||
.fetch_optional(pool)
|
||||
.await
|
||||
.map_err(|err| {
|
||||
tracing::error!(%err, "failed to remove workspace member");
|
||||
ApiError::Database
|
||||
})?;
|
||||
|
||||
Ok(removed.is_some())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
use sqlx::PgPool;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::{
|
||||
error::{ApiError, ApiResult},
|
||||
models::{User, Workspace},
|
||||
};
|
||||
|
||||
pub struct WorkspaceRepository;
|
||||
|
||||
impl WorkspaceRepository {
|
||||
pub async fn create(
|
||||
pool: &PgPool,
|
||||
title: &str,
|
||||
description: Option<&str>,
|
||||
) -> ApiResult<Workspace> {
|
||||
sqlx::query_as::<_, Workspace>(
|
||||
r#"
|
||||
INSERT INTO workspaces (title, description)
|
||||
VALUES ($1, $2)
|
||||
RETURNING id, title, description, created_at
|
||||
"#,
|
||||
)
|
||||
.bind(title)
|
||||
.bind(description)
|
||||
.fetch_one(pool)
|
||||
.await
|
||||
.map_err(|err| {
|
||||
tracing::error!(%err, "failed to create workspace");
|
||||
match err.as_database_error().and_then(|db| db.constraint()) {
|
||||
Some("workspaces_title_key") => {
|
||||
ApiError::BadRequest("workspace name is already taken".to_string())
|
||||
}
|
||||
_ => ApiError::Database,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn get(pool: &PgPool, workspace_id: Uuid) -> ApiResult<Workspace> {
|
||||
sqlx::query_as::<_, Workspace>(
|
||||
"SELECT id, title, description, created_at FROM workspaces WHERE id = $1",
|
||||
)
|
||||
.bind(workspace_id)
|
||||
.fetch_optional(pool)
|
||||
.await
|
||||
.map_err(|_| ApiError::Database)?
|
||||
.ok_or(ApiError::NotFound)
|
||||
}
|
||||
|
||||
pub async fn get_participants(pool: &PgPool, workspace_id: Uuid) -> ApiResult<Vec<User>> {
|
||||
sqlx::query_as::<_, User>(
|
||||
"SELECT id, username, workspace_id, role, created_at FROM users WHERE workspace_id = $1 ORDER BY created_at",
|
||||
)
|
||||
.bind(workspace_id)
|
||||
.fetch_all(pool)
|
||||
.await
|
||||
.map_err(|_| ApiError::Database)
|
||||
}
|
||||
}
|
||||
Executable
+45
@@ -0,0 +1,45 @@
|
||||
use axum::{
|
||||
extract::DefaultBodyLimit,
|
||||
routing::{delete, get, post},
|
||||
Router,
|
||||
};
|
||||
use sqlx::PgPool;
|
||||
|
||||
use crate::handlers;
|
||||
|
||||
pub fn router(pool: PgPool) -> Router {
|
||||
Router::new()
|
||||
.route("/auth/login", post(handlers::auth::login))
|
||||
.route("/auth/register", post(handlers::auth::register))
|
||||
.route("/auth/logout", post(handlers::auth::logout))
|
||||
.route("/auth/me", get(handlers::auth::me))
|
||||
.route("/auth/password", post(handlers::auth::change_password))
|
||||
.route(
|
||||
"/workspace",
|
||||
get(handlers::workspace::get_my).post(handlers::workspace::create),
|
||||
)
|
||||
.route("/workspace/{id}/users", post(handlers::workspace::add_user))
|
||||
.route(
|
||||
"/workspace/{id}/users/{user_id}",
|
||||
delete(handlers::workspace::remove_user),
|
||||
)
|
||||
.route(
|
||||
"/workspace/{id}/auth_policy",
|
||||
post(handlers::workspace::add_policy),
|
||||
)
|
||||
.route(
|
||||
"/workspace/{id}/files",
|
||||
post(handlers::files::upload).get(handlers::files::list),
|
||||
)
|
||||
.route(
|
||||
"/files",
|
||||
post(handlers::files::upload_personal).get(handlers::files::list_public),
|
||||
)
|
||||
.route("/my-files", get(handlers::files::list_personal))
|
||||
.route(
|
||||
"/files/{id}",
|
||||
get(handlers::files::download).delete(handlers::files::delete),
|
||||
)
|
||||
.layer(DefaultBodyLimit::max(10 * 1024 * 1024))
|
||||
.with_state(pool)
|
||||
}
|
||||
Executable
+141
@@ -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
@@ -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
|
||||
}
|
||||
Executable
+285
@@ -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,
|
||||
}
|
||||
}
|
||||
Executable
+19
@@ -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
@@ -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)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user