Remove PostgreSQL support: pure SQLite architecture
Test / test (push) Has been cancelled
Test / build (push) Has been cancelled

BREAKING CHANGE: Remove all PostgreSQL functionality

Changes:
- Remove dependencies: tokio-postgres, postgres from Cargo.toml
- Delete files: pg_client.rs (330 lines), sync.rs (370 lines), provider/pg.rs (300 lines)
- Remove modules from lib.rs: pg_client, sync
- Remove pg module from provider/mod.rs
- Remove PostgreSQL sync code from server.rs (lines 126-165)
- Remove auth_db field and with_sync() from auth.rs
- Simplify SSH server to use SqliteProvider only
- Convert sync API endpoints to return 410 Gone with error message
- Remove [postgresql] config section from markbase.toml

Rationale:
- Simplify architecture by using SQLite exclusively
- Remove complexity of PostgreSQL synchronization
- Reduce dependencies and maintenance burden
- SQLite is sufficient for MarkBase use case

Code removed: ~1000 lines
Files deleted: 3
Files modified: 8
This commit is contained in:
Warren
2026-10-24 19:43:22 +08:00
parent cb9810490a
commit 0802a47a5f
11 changed files with 26 additions and 1275 deletions
+16 -101
View File
@@ -211,64 +211,14 @@ pub async fn manual_sync_handler(
if let Err(resp) = verify_admin_or_401(&state, &headers) {
return resp.into_response();
}
let syncer = crate::pg_client::SftpGoSync::new(&state.auth_db_path);
match syncer {
Ok(syncer) => match syncer.full_sync().await {
Ok(result) => {
if result.status == "success" {
(
StatusCode::OK,
Json(json!({
"status": "success",
"users_synced": result.users_synced,
"groups_synced": result.groups_synced,
"mappings_synced": result.mappings_synced
})),
)
.into_response()
} else if result.status == "partial_success" {
(
StatusCode::OK,
Json(json!({
"status": "partial_success",
"users_synced": result.users_synced,
"users_failed": result.users_failed,
"groups_synced": result.groups_synced,
"groups_failed": result.groups_failed,
"errors": result.errors
})),
)
.into_response()
} else {
(
StatusCode::OK,
Json(json!({
"status": result.status,
"errors": result.errors
})),
)
.into_response()
}
}
Err(e) => (
StatusCode::INTERNAL_SERVER_ERROR,
Json(json!({
"status": "failed",
"error": e.to_string()
})),
)
.into_response(),
},
Err(e) => (
StatusCode::INTERNAL_SERVER_ERROR,
Json(json!({
"status": "failed",
"error": e.to_string()
})),
)
.into_response(),
}
(
StatusCode::GONE,
Json(json!({
"status": "error",
"message": "PostgreSQL sync functionality has been removed. MarkBase now uses SQLite exclusively."
})),
).into_response()
}
pub async fn sync_status_handler(
@@ -278,47 +228,12 @@ pub async fn sync_status_handler(
if let Err(resp) = verify_admin_or_401(&state, &headers) {
return resp.into_response();
}
let auth_db = crate::sync::AuthDb::new(&state.auth_db_path);
match auth_db {
Ok(db) => match db.open() {
Ok(conn) => {
match conn.query_row(
"SELECT sync_type, sync_time, users_synced, users_failed,
groups_synced, groups_failed, mappings_synced, status
FROM sync_log ORDER BY sync_time DESC LIMIT 5",
[],
|row| {
Ok(json!({
"sync_type": row.get::<_, String>(0)?,
"sync_time": row.get::<_, i64>(1)?,
"users_synced": row.get::<_, usize>(2)?,
"users_failed": row.get::<_, usize>(3)?,
"groups_synced": row.get::<_, usize>(4)?,
"groups_failed": row.get::<_, usize>(5)?,
"mappings_synced": row.get::<_, usize>(6)?,
"status": row.get::<_, String>(7)?,
}))
},
) {
Ok(entries) => (StatusCode::OK, Json(entries)).into_response(),
Err(e) => (
StatusCode::INTERNAL_SERVER_ERROR,
Json(json!({"error": e.to_string()})),
)
.into_response(),
}
}
Err(e) => (
StatusCode::INTERNAL_SERVER_ERROR,
Json(json!({"error": e.to_string()})),
)
.into_response(),
},
Err(e) => (
StatusCode::INTERNAL_SERVER_ERROR,
Json(json!({"error": e.to_string()})),
)
.into_response(),
}
(
StatusCode::GONE,
Json(json!({
"status": "error",
"message": "PostgreSQL sync functionality has been removed. MarkBase now uses SQLite exclusively."
})),
).into_response()
}
+5 -96
View File
@@ -66,7 +66,6 @@ pub struct AdminLoginResponse {
pub struct AuthState {
pub sessions: Arc<Mutex<HashMap<String, Session>>>,
pub users: Arc<Mutex<HashMap<String, User>>>,
pub auth_db: Option<crate::sync::AuthDb>,
pub admin_sessions: Arc<Mutex<HashMap<String, AdminSession>>>,
pub provider: Option<Arc<dyn DataProvider>>,
}
@@ -95,19 +94,6 @@ impl AuthState {
AuthState {
sessions: Arc::new(Mutex::new(HashMap::new())),
users: Arc::new(Mutex::new(users)),
auth_db: None,
admin_sessions: Arc::new(Mutex::new(HashMap::new())),
provider: None,
}
}
pub fn with_sync(auth_db_path: &str) -> Self {
let auth_db = crate::sync::AuthDb::new(auth_db_path).ok();
AuthState {
sessions: Arc::new(Mutex::new(HashMap::new())),
users: Arc::new(Mutex::new(HashMap::new())),
auth_db,
admin_sessions: Arc::new(Mutex::new(HashMap::new())),
provider: None,
}
@@ -117,7 +103,6 @@ impl AuthState {
AuthState {
sessions: Arc::new(Mutex::new(HashMap::new())),
users: Arc::new(Mutex::new(HashMap::new())),
auth_db: None,
admin_sessions: Arc::new(Mutex::new(HashMap::new())),
provider: Some(Arc::from(provider)),
}
@@ -158,30 +143,7 @@ impl AuthState {
}
pub fn admin_login(&self, username: &str, password: &str) -> Option<AdminLoginResponse> {
// Try auth_db first (legacy PostgreSQL sync)
if let Some(auth_db) = &self.auth_db {
match auth_db.get_admin(username) {
Ok(Some(admin)) if admin.status == 1 => {
if verify(password, &admin.password_hash).unwrap_or(false) {
return self.create_admin_session(username, password);
} else {
log::warn!("Invalid password for admin {}", username);
return None;
}
}
Ok(Some(_)) => {
log::warn!("Admin {} is not active", username);
return None;
}
Ok(None) => {}
Err(e) => {
log::error!("Failed to get admin {}: {}", username, e);
return None;
}
}
}
// Fallback: try provider
// Use provider if available
if let Some(provider) = &self.provider {
match provider.get_user(username) {
Ok(Some(user)) if user.status == 1 => {
@@ -204,7 +166,7 @@ impl AuthState {
}
}
log::warn!("Admin {} not found (auth_db + provider)", username);
log::warn!("Admin {} not found (provider)", username);
None
}
@@ -253,66 +215,13 @@ impl AuthState {
}
pub fn login_with_sync(&self, username: &str, password: &str) -> Option<LoginResponse> {
// Prefer provider over auth_db
// Use provider if available
if let Some(provider) = &self.provider {
return self.login_with_provider(&**provider, username, password);
}
if let Some(auth_db) = &self.auth_db {
let user = match auth_db.get_user(username) {
Ok(Some(user)) => user,
Ok(None) => {
log::warn!("User {} not found in auth database", username);
return None;
}
Err(e) => {
log::error!("Failed to get user {}: {}", username, e);
return None;
}
};
if user.status != 1 {
log::warn!("User {} is disabled", username);
return None;
}
if verify(password, &user.password_hash).unwrap_or(false) {
let groups = auth_db.get_user_groups(username).unwrap_or_default();
let permissions = user.permissions.clone();
let token = Uuid::new_v4().to_string();
let now = Utc::now();
let expires_at = now + Duration::hours(24);
let session = Session {
token: token.clone(),
user_id: username.to_string(),
username: username.to_string(),
created_at: now.format("%Y-%m-%dT%H:%M:%SZ").to_string(),
expires_at: expires_at.format("%Y-%m-%dT%H:%M:%SZ").to_string(),
groups: groups.clone(),
permissions: permissions.clone(),
};
let mut sessions = self.sessions.lock().unwrap();
sessions.insert(token.clone(), session);
log::info!("User {} logged in successfully", username);
Some(LoginResponse {
token,
expires_at: expires_at.format("%Y-%m-%dT%H:%M:%SZ").to_string(),
user_id: username.to_string(),
groups,
permissions,
})
} else {
log::warn!("Invalid password for user {}", username);
None
}
} else {
self.login(username, password)
}
// Fallback to in-memory users
self.login(username, password)
}
fn login_with_provider(
-2
View File
@@ -11,7 +11,6 @@ pub mod config;
pub mod download;
pub mod import_markdown;
pub mod myfiles;
pub mod pg_client;
pub mod provider;
pub mod render;
pub mod rsync;
@@ -24,7 +23,6 @@ pub mod scan;
pub mod smb_config;
pub mod server;
pub mod ssh_server;
pub mod sync;
pub mod vfs;
pub mod webdav;
pub mod webdav_locks;
-330
View File
@@ -1,330 +0,0 @@
use crate::sync::{PgAdmin, PgGroup, PgUser, PgUserGroupMapping};
use anyhow::Result;
use tokio_postgres::{Client, NoTls};
pub struct PgClient {
host: String,
port: u16,
user: String,
password: String,
database: String,
}
impl Default for PgClient {
fn default() -> Self {
Self::new()
}
}
impl PgClient {
pub fn new() -> Self {
Self {
host: "127.0.0.1".to_string(),
port: 5432,
user: "sftpgo".to_string(),
password: "sftpgo_pass_2026".to_string(),
database: "sftpgo".to_string(),
}
}
pub fn from_env() -> Self {
Self {
host: std::env::var("PG_HOST").unwrap_or_else(|_| "127.0.0.1".to_string()),
port: std::env::var("PG_PORT")
.unwrap_or_else(|_| "5432".to_string())
.parse()
.unwrap_or(5432),
user: std::env::var("PG_USER").unwrap_or_else(|_| "sftpgo".to_string()),
password: std::env::var("PG_PASSWORD")
.unwrap_or_else(|_| "sftpgo_pass_2026".to_string()),
database: std::env::var("PG_DATABASE").unwrap_or_else(|_| "sftpgo".to_string()),
}
}
pub async fn connect(&self) -> Result<Client> {
let config = format!(
"host={} port={} user={} password={} dbname={}",
self.host, self.port, self.user, self.password, self.database
);
let (client, connection) = tokio_postgres::connect(&config, NoTls).await?;
tokio::spawn(async move {
if let Err(e) = connection.await {
log::error!("PostgreSQL connection error: {}", e);
}
});
Ok(client)
}
pub async fn fetch_users(&self) -> Result<Vec<PgUser>> {
let client = self.connect().await?;
let rows = client
.query(
"SELECT username, password, email, status, home_dir, permissions,
uid, gid, last_login, created_at, updated_at
FROM users
WHERE status = 1 AND deleted_at = 0",
&[],
)
.await?;
let users = rows
.into_iter()
.map(|row| PgUser {
username: row.get::<_, String>(0),
password_hash: row.get::<_, String>(1),
email: row.get::<_, Option<String>>(2),
status: row.get::<_, i32>(3),
home_dir: row.get::<_, String>(4),
permissions: row.get::<_, String>(5),
uid: row.get::<_, i64>(6),
gid: row.get::<_, i64>(7),
last_login: row.get::<_, i64>(8),
created_at: row.get::<_, i64>(9),
updated_at: row.get::<_, i64>(10),
})
.collect();
Ok(users)
}
pub async fn fetch_groups(&self) -> Result<Vec<PgGroup>> {
let client = self.connect().await?;
let rows = client
.query(
"SELECT name, description, created_at, updated_at FROM groups",
&[],
)
.await?;
let groups = rows
.into_iter()
.map(|row| PgGroup {
name: row.get::<_, String>(0),
description: row.get::<_, Option<String>>(1),
created_at: row.get::<_, i64>(2),
updated_at: row.get::<_, i64>(3),
})
.collect();
Ok(groups)
}
pub async fn fetch_admins(&self) -> Result<Vec<PgAdmin>> {
let client = self.connect().await?;
let rows = client
.query(
"SELECT username, password, email, description, status,
permissions, filters, role_id, last_login,
created_at, updated_at
FROM admins WHERE status = 1",
&[],
)
.await?;
let admins = rows
.into_iter()
.map(|row| PgAdmin {
username: row.get::<_, String>(0),
password_hash: row.get::<_, String>(1),
email: row.get::<_, Option<String>>(2),
description: row.get::<_, Option<String>>(3),
status: row.get::<_, i32>(4),
permissions: row.get::<_, String>(5),
filters: row.get::<_, Option<String>>(6),
role_id: row.get::<_, Option<i32>>(7),
last_login: row.get::<_, i64>(8),
created_at: row.get::<_, i64>(9),
updated_at: row.get::<_, i64>(10),
})
.collect();
Ok(admins)
}
pub async fn fetch_mappings(&self) -> Result<Vec<PgUserGroupMapping>> {
let client = self.connect().await?;
let rows = client
.query(
"SELECT u.username, g.name
FROM users_groups_mapping ug
JOIN users u ON ug.user_id = u.id
JOIN groups g ON ug.group_id = g.id
WHERE u.status = 1",
&[],
)
.await?;
let mappings = rows
.into_iter()
.map(|row| PgUserGroupMapping {
username: row.get::<_, String>(0),
group_name: row.get::<_, String>(1),
})
.collect();
Ok(mappings)
}
}
pub struct SftpGoSync {
pg_client: PgClient,
auth_db: crate::sync::AuthDb,
}
impl SftpGoSync {
pub fn new(auth_db_path: &str) -> Result<Self> {
Ok(Self {
pg_client: PgClient::new(),
auth_db: crate::sync::AuthDb::new(auth_db_path)?,
})
}
pub async fn full_sync(&self) -> Result<crate::sync::SyncResult> {
let mut result = crate::sync::SyncResult::default();
result.sync_type = "full".to_string();
result.sync_time = chrono::Utc::now().timestamp();
log::info!("Starting full sync from SFTPGo PostgreSQL");
// 1. Sync users
match self.pg_client.fetch_users().await {
Ok(users) => {
log::info!("Fetched {} users from PostgreSQL", users.len());
for user in users {
match self.auth_db.save_user(&user) {
Ok(_) => result.users_synced += 1,
Err(e) => {
result.users_failed += 1;
result
.errors
.push(format!("User {} sync failed: {}", user.username, e));
log::error!("Failed to sync user {}: {}", user.username, e);
}
}
}
}
Err(e) => {
log::error!("Failed to fetch users from PostgreSQL: {}", e);
result.errors.push(format!("PG users fetch failed: {}", e));
result.users_failed = 1;
}
}
// 2. Sync groups
match self.pg_client.fetch_groups().await {
Ok(groups) => {
log::info!("Fetched {} groups from PostgreSQL", groups.len());
for group in groups {
match self.auth_db.save_group(&group) {
Ok(_) => result.groups_synced += 1,
Err(e) => {
result.groups_failed += 1;
result
.errors
.push(format!("Group {} sync failed: {}", group.name, e));
log::error!("Failed to sync group {}: {}", group.name, e);
}
}
}
}
Err(e) => {
log::error!("Failed to fetch groups from PostgreSQL: {}", e);
result.errors.push(format!("PG groups fetch failed: {}", e));
result.groups_failed = 1;
}
}
// 3. Sync mappings
match self.pg_client.fetch_mappings().await {
Ok(mappings) => {
log::info!("Fetched {} mappings from PostgreSQL", mappings.len());
for mapping in mappings {
match self.auth_db.save_mapping(&mapping) {
Ok(_) => result.mappings_synced += 1,
Err(e) => {
result.mappings_failed += 1;
result.errors.push(format!(
"Mapping {}->{} sync failed: {}",
mapping.username, mapping.group_name, e
));
log::error!(
"Failed to sync mapping {}->{}: {}",
mapping.username,
mapping.group_name,
e
);
}
}
}
}
Err(e) => {
log::error!("Failed to fetch mappings from PostgreSQL: {}", e);
result
.errors
.push(format!("PG mappings fetch failed: {}", e));
result.mappings_failed = 1;
}
}
// 4. Sync admins
match self.pg_client.fetch_admins().await {
Ok(admins) => {
let admins_count = admins.len();
log::info!("Fetched {} admins from PostgreSQL", admins_count);
match self.auth_db.sync_admins(admins) {
Ok(count) => result.admins_synced = count,
Err(e) => {
result.admins_failed = admins_count;
result.errors.push(format!("Admins sync failed: {}", e));
log::error!("Failed to sync admins: {}", e);
}
}
}
Err(e) => {
log::error!("Failed to fetch admins from PostgreSQL: {}", e);
result.errors.push(format!("PG admins fetch failed: {}", e));
result.admins_failed = 1;
}
}
// 5. Determine final status
if result.users_failed > 0
|| result.groups_failed > 0
|| result.mappings_failed > 0
|| result.admins_failed > 0
{
if result.users_synced > 0
|| result.groups_synced > 0
|| result.mappings_synced > 0
|| result.admins_synced > 0
{
result.status = "partial_success".to_string();
} else {
result.status = "cached".to_string();
}
} else {
result.status = "success".to_string();
}
// 6. Save sync log
self.auth_db.save_sync_log(&result)?;
log::info!(
"Sync completed: users={}, groups={}, mappings={}, admins={}, status={}",
result.users_synced,
result.groups_synced,
result.mappings_synced,
result.admins_synced,
result.status
);
Ok(result)
}
}
-3
View File
@@ -1,10 +1,7 @@
pub mod pg;
pub mod sqlite;
#[cfg(feature = "ldap")]
#[cfg(feature = "ldap")]
pub mod ldap;
pub use pg::PgProvider;
pub use sqlite::SqliteProvider;
#[cfg(feature = "ldap")]
pub use ldap::{LdapProvider, LdapConfig};
-300
View File
@@ -1,300 +0,0 @@
use super::{DataProvider, ProviderError, User};
use bcrypt::verify;
use postgres::{Client, NoTls};
use std::path::PathBuf;
/// PostgreSQL 数据提供者(兼容 SFTPGo 的 users 表)
pub struct PgProvider {
conn_str: String,
}
impl PgProvider {
/// 从连接字符串创建 PgProvider
///
/// 连接字符串格式:host=127.0.0.1 port=5432 dbname=sftpgo user=sftpgo password=sftpgo_pass_2026
pub fn new(conn_str: &str) -> Result<Self, ProviderError> {
Ok(Self {
conn_str: conn_str.to_string(),
})
}
pub fn from_params(
host: &str,
port: u16,
dbname: &str,
user: &str,
password: &str,
) -> Result<Self, ProviderError> {
let conn_str = format!(
"host={} port={} dbname={} user={} password={}",
host, port, dbname, user, password
);
Ok(Self { conn_str })
}
fn open_conn(&self) -> Result<Client, ProviderError> {
Client::connect(&self.conn_str, NoTls)
.map_err(|e| ProviderError::Internal(format!("PostgreSQL connect failed: {}", e)))
}
}
impl DataProvider for PgProvider {
fn get_user(&self, username: &str) -> Result<Option<User>, ProviderError> {
let mut conn = self.open_conn()?;
let result = conn
.query_opt(
"SELECT username, password, home_dir, permissions, uid, gid, status
FROM users WHERE username = $1 AND status = 1",
&[&username],
)
.map_err(|e| ProviderError::Internal(format!("Query error: {}", e)))?;
match result {
Some(row) => Ok(Some(User {
username: row.get(0),
password_hash: row.get::<_, Option<String>>(1).unwrap_or_default(),
home_dir: PathBuf::from(row.get::<_, String>(2)),
permissions: row
.get::<_, Option<String>>(3)
.unwrap_or_else(|| "*".to_string()),
uid: row.get::<_, i64>(4) as u32,
gid: row.get::<_, i64>(5) as u32,
status: row.get(6),
})),
None => Ok(None),
}
}
fn check_password(&self, username: &str, password: &str) -> Result<bool, ProviderError> {
let hash = match self.get_user(username)? {
Some(user) => user.password_hash,
None => return Ok(false),
};
if hash.is_empty() {
return Ok(false);
}
verify(password, &hash)
.map_err(|e| ProviderError::Internal(format!("bcrypt verify error: {}", e)))
}
fn get_home_dir(&self, username: &str) -> Result<Option<String>, ProviderError> {
Ok(self
.get_user(username)?
.map(|u| u.home_dir.to_string_lossy().to_string()))
}
fn get_public_keys(&self, username: &str) -> Result<Vec<String>, ProviderError> {
let mut conn = self.open_conn()?;
let result = conn
.query_opt(
"SELECT public_keys FROM users WHERE username = $1 AND status = 1",
&[&username],
)
.map_err(|e| ProviderError::Internal(format!("Query error: {}", e)))?;
match result {
Some(row) => {
let json_str: Option<String> = row.get(0);
match json_str {
Some(s) if !s.is_empty() => {
let keys: Vec<serde_json::Value> =
serde_json::from_str(&s).map_err(|e| {
ProviderError::Internal(format!("JSON parse error: {}", e))
})?;
Ok(keys
.iter()
.filter_map(|v| v.get("public_key")?.as_str().map(|s| s.to_string()))
.collect())
}
_ => Ok(Vec::new()),
}
}
None => Ok(Vec::new()),
}
}
fn list_users(&self) -> Result<Vec<User>, ProviderError> {
let mut conn = self.open_conn()?;
let rows = conn
.query(
"SELECT username, password, home_dir, permissions, uid, gid, status
FROM users ORDER BY username",
&[],
)
.map_err(|e| ProviderError::Internal(format!("Query error: {}", e)))?;
let users = rows
.iter()
.map(|row| User {
username: row.get(0),
password_hash: row.get::<_, Option<String>>(1).unwrap_or_default(),
home_dir: PathBuf::from(row.get::<_, String>(2)),
permissions: row
.get::<_, Option<String>>(3)
.unwrap_or_else(|| "*".to_string()),
uid: row.get::<_, i64>(4) as u32,
gid: row.get::<_, i64>(5) as u32,
status: row.get(6),
})
.collect();
Ok(users)
}
fn create_user(&self, user: &User, password: &str) -> Result<(), ProviderError> {
let mut conn = self.open_conn()?;
let hash = bcrypt::hash(password, bcrypt::DEFAULT_COST)
.map_err(|e| ProviderError::Internal(format!("bcrypt hash error: {}", e)))?;
conn.execute(
"INSERT INTO users (username, password, home_dir, permissions, uid, gid, status)
VALUES ($1, $2, $3, $4, $5, $6, $7)",
&[&user.username, &hash, &user.home_dir.to_string_lossy(), &user.permissions, &(user.uid as i64), &(user.gid as i64), &user.status],
)
.map_err(|e| ProviderError::Internal(format!("Insert error: {}", e)))?;
Ok(())
}
fn update_user(&self, user: &User, new_password: Option<&str>) -> Result<(), ProviderError> {
let mut conn = self.open_conn()?;
if let Some(pwd) = new_password {
let hash = bcrypt::hash(pwd, bcrypt::DEFAULT_COST)
.map_err(|e| ProviderError::Internal(format!("bcrypt hash error: {}", e)))?;
conn.execute(
"UPDATE users
SET password = $2, home_dir = $3, permissions = $4, uid = $5, gid = $6, status = $7
WHERE username = $1",
&[&user.username, &hash, &user.home_dir.to_string_lossy(), &user.permissions, &(user.uid as i64), &(user.gid as i64), &user.status],
)
.map_err(|e| ProviderError::Internal(format!("Update error: {}", e)))?;
} else {
conn.execute(
"UPDATE users
SET home_dir = $2, permissions = $3, uid = $4, gid = $5, status = $6
WHERE username = $1",
&[&user.username, &user.home_dir.to_string_lossy(), &user.permissions, &(user.uid as i64), &(user.gid as i64), &user.status],
)
.map_err(|e| ProviderError::Internal(format!("Update error: {}", e)))?;
}
Ok(())
}
fn delete_user(&self, username: &str) -> Result<(), ProviderError> {
let mut conn = self.open_conn()?;
conn.execute("DELETE FROM users WHERE username = $1", &[&username])
.map_err(|e| ProviderError::Internal(format!("Delete error: {}", e)))?;
Ok(())
}
fn reset_password(&self, username: &str, new_password: &str) -> Result<(), ProviderError> {
let mut conn = self.open_conn()?;
let hash = bcrypt::hash(new_password, bcrypt::DEFAULT_COST)
.map_err(|e| ProviderError::Internal(format!("bcrypt hash error: {}", e)))?;
conn.execute(
"UPDATE users SET password = $2 WHERE username = $1",
&[&username, &hash],
)
.map_err(|e| ProviderError::Internal(format!("Update error: {}", e)))?;
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_pg_provider_connection() {
// 仅当 SFTPGo PostgreSQL 可用时运行
let provider = PgProvider::new(
"host=127.0.0.1 port=5432 dbname=sftpgo user=sftpgo password=sftpgo_pass_2026",
);
assert!(provider.is_ok(), "Should connect to SFTPGo PostgreSQL");
}
#[test]
fn test_pg_get_user_demo() {
let provider = PgProvider::new(
"host=127.0.0.1 port=5432 dbname=sftpgo user=sftpgo password=sftpgo_pass_2026",
)
.unwrap();
let user = provider.get_user("demo").unwrap();
assert!(user.is_some(), "Demo user should exist");
assert_eq!(user.unwrap().username, "demo");
}
#[test]
fn test_pg_get_user_momentry() {
let provider = PgProvider::new(
"host=127.0.0.1 port=5432 dbname=sftpgo user=sftpgo password=sftpgo_pass_2026",
)
.unwrap();
let user = provider.get_user("momentry").unwrap();
assert!(user.is_some(), "Momentry user should exist");
}
#[test]
fn test_pg_get_user_warren() {
let provider = PgProvider::new(
"host=127.0.0.1 port=5432 dbname=sftpgo user=sftpgo password=sftpgo_pass_2026",
)
.unwrap();
let user = provider.get_user("warren").unwrap();
assert!(user.is_some(), "Warren user should exist");
}
#[test]
fn test_pg_check_password_demo() {
let provider = PgProvider::new(
"host=127.0.0.1 port=5432 dbname=sftpgo user=sftpgo password=sftpgo_pass_2026",
)
.unwrap();
let valid = provider.check_password("demo", "demo123").unwrap();
assert!(valid, "Password should be valid");
}
#[test]
fn test_pg_check_password_invalid() {
let provider = PgProvider::new(
"host=127.0.0.1 port=5432 dbname=sftpgo user=sftpgo password=sftpgo_pass_2026",
)
.unwrap();
let valid = provider.check_password("demo", "wrong").unwrap();
assert!(!valid, "Wrong password should fail");
}
#[test]
fn test_pg_get_home_dir() {
let provider = PgProvider::new(
"host=127.0.0.1 port=5432 dbname=sftpgo user=sftpgo password=sftpgo_pass_2026",
)
.unwrap();
let dir = provider.get_home_dir("demo").unwrap();
assert!(dir.is_some());
assert!(dir.unwrap().contains("momentry"));
}
#[test]
fn test_pg_nonexistent_user() {
let provider = PgProvider::new(
"host=127.0.0.1 port=5432 dbname=sftpgo user=sftpgo password=sftpgo_pass_2026",
)
.unwrap();
let user = provider.get_user("__nonexistent__").unwrap();
assert!(user.is_none());
}
}
+3 -52
View File
@@ -230,56 +230,8 @@ pub async fn run(port: u16, file: Option<String>, home: PathBuf) -> anyhow::Resu
}
}
// SFTPGo sync (optional fallback - default disabled)
// Set MARKBASE_ENABLE_SFTPGO_SYNC=1 to enable sync from SFTPGo PostgreSQL
let enable_sftpgo_sync = std::env::var("MARKBASE_ENABLE_SFTPGO_SYNC")
.map(|v| v == "1" || v.to_lowercase() == "true")
.unwrap_or(false);
if enable_sftpgo_sync {
log::info!("SFTPGo sync enabled - syncing from PostgreSQL to auth.sqlite");
let syncer = crate::pg_client::SftpGoSync::new(&auth_db_str)?;
tokio::spawn(async move {
match syncer.full_sync().await {
Ok(result) => {
log::info!(
"Initial sync completed: users={}, groups={}, mappings={}, status={}",
result.users_synced,
result.groups_synced,
result.mappings_synced,
result.status
);
}
Err(e) => {
log::error!("Initial sync failed: {}", e);
}
}
});
let syncer_clone = crate::pg_client::SftpGoSync::new(&auth_db_str)?;
tokio::spawn(async move {
let mut interval = tokio::time::interval(std::time::Duration::from_secs(3600));
loop {
interval.tick().await;
match syncer_clone.full_sync().await {
Ok(result) => {
log::info!(
"Hourly sync: users={}, groups={}, status={}",
result.users_synced,
result.groups_synced,
result.status
);
}
Err(e) => {
log::error!("Hourly sync failed, keeping cached data: {}", e);
}
}
}
});
} else {
log::info!("SFTPGo sync disabled - using local auth.sqlite for user management (set MARKBASE_ENABLE_SFTPGO_SYNC=1 to enable)");
}
// PostgreSQL sync removed - MarkBase now uses SQLite exclusively
log::info!("MarkBase authentication: SQLite only (PostgreSQL sync removed)");
// ===== WebDAV multi-user configuration (Phase 20 + P1) =====
let webdav_parent = std::path::PathBuf::from(&upload_path);
@@ -2033,8 +1985,7 @@ async fn get_file_probe(Path((_user_id, file_uuid)): Path<(String, String)>) ->
let (label, registered_at) = node.unwrap_or((None, None));
// Fetch probe data from 3002 PostgreSQL
let _pg_url = "postgres://accusys@localhost:5432/momentry";
// TODO: Implement data fetching from external source
let pg_conn = rusqlite::Connection::open(":memory:")?; // placeholder
drop(pg_conn);
+2 -11
View File
@@ -1,7 +1,6 @@
// SSH服务器完整实现(Phase 1-7集成版 + Phase 13端口转发)
// 参考OpenSSH sshd.c: complete SSH/SFTP flow + port forwarding
use crate::provider::pg::PgProvider;
use crate::provider::sqlite::SqliteProvider;
use crate::provider::DataProvider;
use crate::ssh_server::auth::{AuthHandler, AuthResult};
@@ -167,16 +166,8 @@ fn handle_connection_complete(
)?;
info!("Key exchange completed, encryption channel ready");
// Phase 5: SSH认证(SFTPGo兼容 — PostgreSQL或SQLite)
let provider: Box<dyn DataProvider> = if let Some(ref conn_str) = pg_conn {
info!(
"Using PostgreSQL auth provider (SFTPGo-compatible): {}",
conn_str
);
Box::new(
PgProvider::new(conn_str).map_err(|e| anyhow!("Failed to init PgProvider: {}", e))?,
)
} else {
// Phase 5: SSH认证(SQLite only)
let provider: Box<dyn DataProvider> = {
info!("Using SQLite auth provider");
Box::new(
SqliteProvider::new("data/auth.sqlite")
-370
View File
@@ -1,370 +0,0 @@
use anyhow::Result;
use chrono::Utc;
use rusqlite::{params, Connection};
use serde::{Deserialize, Serialize};
use std::path::Path;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PgUser {
pub username: String,
pub password_hash: String,
pub email: Option<String>,
pub status: i32,
pub home_dir: String,
pub permissions: String,
pub uid: i64,
pub gid: i64,
pub last_login: i64,
pub created_at: i64,
pub updated_at: i64,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PgGroup {
pub name: String,
pub description: Option<String>,
pub created_at: i64,
pub updated_at: i64,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PgUserGroupMapping {
pub username: String,
pub group_name: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PgAdmin {
pub username: String,
pub password_hash: String,
pub email: Option<String>,
pub description: Option<String>,
pub status: i32,
pub permissions: String,
pub filters: Option<String>,
pub role_id: Option<i32>,
pub last_login: i64,
pub created_at: i64,
pub updated_at: i64,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SyncResult {
pub sync_type: String,
pub sync_time: i64,
pub users_synced: usize,
pub users_failed: usize,
pub groups_synced: usize,
pub groups_failed: usize,
pub mappings_synced: usize,
pub mappings_failed: usize,
pub admins_synced: usize,
pub admins_failed: usize,
pub status: String,
pub errors: Vec<String>,
}
impl Default for SyncResult {
fn default() -> Self {
Self {
sync_type: "unknown".to_string(),
sync_time: Utc::now().timestamp(),
users_synced: 0,
users_failed: 0,
groups_synced: 0,
groups_failed: 0,
mappings_synced: 0,
mappings_failed: 0,
admins_synced: 0,
admins_failed: 0,
status: "pending".to_string(),
errors: Vec::new(),
}
}
}
impl SyncResult {
pub fn success() -> Self {
Self {
status: "success".to_string(),
..Default::default()
}
}
pub fn cached() -> Self {
Self {
status: "cached".to_string(),
..Default::default()
}
}
pub fn failed(error: String) -> Self {
Self {
status: "failed".to_string(),
errors: vec![error],
..Default::default()
}
}
pub fn merge(&mut self, other: SyncResult) {
self.users_synced += other.users_synced;
self.users_failed += other.users_failed;
self.groups_synced += other.groups_synced;
self.groups_failed += other.groups_failed;
self.mappings_synced += other.mappings_synced;
self.mappings_failed += other.mappings_failed;
self.errors.extend(other.errors);
if self.users_failed > 0 || self.groups_failed > 0 || self.mappings_failed > 0 {
if self.users_synced > 0 || self.groups_synced > 0 || self.mappings_synced > 0 {
self.status = "partial_success".to_string();
} else {
self.status = "failed".to_string();
}
}
}
}
#[derive(Clone)]
pub struct AuthDb {
pub path: String,
}
impl AuthDb {
pub fn new(path: &str) -> Result<Self> {
if !Path::new(path).exists() {
Self::init_db(path)?;
}
Ok(Self {
path: path.to_string(),
})
}
pub fn init_db(path: &str) -> Result<()> {
let conn = Connection::open(path)?;
conn.execute_batch(include_str!("../../data/init_auth_db.sql"))?;
Ok(())
}
pub fn open(&self) -> Result<Connection> {
Ok(Connection::open(&self.path)?)
}
pub fn save_user(&self, user: &PgUser) -> Result<()> {
let conn = self.open()?;
let now = Utc::now().timestamp();
conn.execute(
"INSERT OR REPLACE INTO sftpgo_users
(username, password_hash, email, status, home_dir, permissions,
uid, gid, last_login, created_at, updated_at, last_sync_at, sync_status)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13)",
params![
user.username,
user.password_hash,
user.email,
user.status,
user.home_dir,
user.permissions,
user.uid,
user.gid,
user.last_login,
user.created_at,
user.updated_at,
now,
1, // sync_status = synced
],
)?;
Ok(())
}
pub fn save_group(&self, group: &PgGroup) -> Result<()> {
let conn = self.open()?;
let now = Utc::now().timestamp();
conn.execute(
"INSERT OR REPLACE INTO sftpgo_groups
(name, description, created_at, updated_at, last_sync_at)
VALUES (?1, ?2, ?3, ?4, ?5)",
params![
group.name,
group.description,
group.created_at,
group.updated_at,
now,
],
)?;
Ok(())
}
pub fn save_mapping(&self, mapping: &PgUserGroupMapping) -> Result<()> {
let conn = self.open()?;
let now = Utc::now().timestamp();
conn.execute(
"INSERT OR REPLACE INTO users_groups_mapping
(username, group_name, created_at)
VALUES (?1, ?2, ?3)",
params![mapping.username, mapping.group_name, now,],
)?;
Ok(())
}
pub fn save_sync_log(&self, result: &SyncResult) -> Result<()> {
let conn = self.open()?;
conn.execute(
"INSERT INTO sync_log
(sync_type, sync_time, users_synced, users_failed,
groups_synced, groups_failed, mappings_synced,
mappings_failed, admins_synced, admins_failed,
status, error_message)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12)",
params![
result.sync_type,
result.sync_time,
result.users_synced,
result.users_failed,
result.groups_synced,
result.groups_failed,
result.mappings_synced,
result.mappings_failed,
result.admins_synced,
result.admins_failed,
result.status,
result.errors.join(";"),
],
)?;
log::info!(
"Sync log saved: users={}, groups={}, mappings={}, admins={}, status={}",
result.users_synced,
result.groups_synced,
result.mappings_synced,
result.admins_synced,
result.status
);
Ok(())
}
pub fn save_admin(&self, admin: &PgAdmin) -> Result<()> {
let conn = self.open()?;
conn.execute(
"INSERT OR REPLACE INTO sftpgo_admins
(username, password_hash, email, description, status,
permissions, filters, role_id, last_login,
created_at, updated_at, last_sync_at)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12)",
params![
admin.username,
admin.password_hash,
admin.email,
admin.description,
admin.status,
admin.permissions,
admin.filters,
admin.role_id,
admin.last_login,
admin.created_at,
admin.updated_at,
Utc::now().timestamp(),
],
)?;
Ok(())
}
pub fn get_admin(&self, username: &str) -> Result<Option<PgAdmin>> {
let conn = self.open()?;
let result = conn.query_row(
"SELECT username, password_hash, email, description, status,
permissions, filters, role_id, last_login,
created_at, updated_at
FROM sftpgo_admins WHERE username = ?1 AND status = 1",
params![username],
|row| {
Ok(PgAdmin {
username: row.get(0)?,
password_hash: row.get(1)?,
email: row.get(2)?,
description: row.get(3)?,
status: row.get(4)?,
permissions: row.get(5)?,
filters: row.get(6)?,
role_id: row.get(7)?,
last_login: row.get(8)?,
created_at: row.get(9)?,
updated_at: row.get(10)?,
})
},
);
match result {
Ok(admin) => Ok(Some(admin)),
Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None),
Err(e) => Err(e.into()),
}
}
pub fn sync_admins(&self, admins: Vec<PgAdmin>) -> Result<usize> {
let mut synced = 0;
for admin in admins {
match self.save_admin(&admin) {
Ok(_) => synced += 1,
Err(e) => log::warn!("Failed to sync admin {}: {}", admin.username, e),
}
}
Ok(synced)
}
pub fn get_user(&self, username: &str) -> Result<Option<PgUser>> {
let conn = self.open()?;
let result = conn.query_row(
"SELECT username, password_hash, email, status, home_dir, permissions,
uid, gid, last_login, created_at, updated_at
FROM sftpgo_users WHERE username = ?1 AND status = 1",
params![username],
|row| {
Ok(PgUser {
username: row.get(0)?,
password_hash: row.get(1)?,
email: row.get(2)?,
status: row.get(3)?,
home_dir: row.get(4)?,
permissions: row.get(5)?,
uid: row.get(6)?,
gid: row.get(7)?,
last_login: row.get(8)?,
created_at: row.get(9)?,
updated_at: row.get(10)?,
})
},
);
match result {
Ok(user) => Ok(Some(user)),
Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None),
Err(e) => Err(e.into()),
}
}
pub fn get_user_groups(&self, username: &str) -> Result<Vec<String>> {
let conn = self.open()?;
let groups: Vec<String> = conn
.prepare("SELECT group_name FROM users_groups_mapping WHERE username = ?1")?
.query_map(params![username], |row| row.get(0))?
.collect::<Result<Vec<_>, _>>()?;
Ok(groups)
}
}