Compare commits
3 Commits
secrets-mc
...
secrets-mc
| Author | SHA1 | Date | |
|---|---|---|---|
| 87a29af82d | |||
| 1b11f7e976 | |||
| 08e81363c9 |
@@ -118,7 +118,7 @@ oauth_accounts (
|
|||||||
|
|
||||||
### PEM 共享(`key_ref`)
|
### PEM 共享(`key_ref`)
|
||||||
|
|
||||||
将共享 PEM 存为 **`type=key`** 的 entry;其它记录在 `metadata.key_ref` 指向该 key 的 `name`。更新 key 记录后,引用方通过服务层解析合并逻辑即可使用新密钥(实现见 `secrets_core::service`)。
|
将共享 PEM 存为 **`type=key`** 的 entry;其它记录在 `metadata.key_ref` 指向该 key 的 `name`(支持 `folder/name` 格式消歧)。更新 key 记录后,引用方通过服务层解析合并逻辑即可使用新密钥(实现见 `secrets_core::service::env_map`)。
|
||||||
|
|
||||||
## 代码规范
|
## 代码规范
|
||||||
|
|
||||||
|
|||||||
2
Cargo.lock
generated
2
Cargo.lock
generated
@@ -1968,7 +1968,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "secrets-mcp"
|
name = "secrets-mcp"
|
||||||
version = "0.3.1"
|
version = "0.3.4"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"anyhow",
|
"anyhow",
|
||||||
"askama",
|
"askama",
|
||||||
|
|||||||
24
README.md
24
README.md
@@ -17,7 +17,10 @@ cargo build --release -p secrets-mcp
|
|||||||
|
|
||||||
| 变量 | 说明 |
|
| 变量 | 说明 |
|
||||||
|------|------|
|
|------|------|
|
||||||
| `SECRETS_DATABASE_URL` | **必填**。PostgreSQL 连接串(建议专用库,如 `secrets-mcp`)。 |
|
| `SECRETS_DATABASE_URL` | **必填**。PostgreSQL 连接串(推荐使用域名,例如 `db.refining.ltd`,避免直连 IP)。 |
|
||||||
|
| `SECRETS_DATABASE_SSL_MODE` | 可选但强烈建议生产必填。推荐 `verify-full`(至少 `verify-ca`),避免回退到弱 TLS 模式。 |
|
||||||
|
| `SECRETS_DATABASE_SSL_ROOT_CERT` | 可选。私有 CA 或自签链路时指定 CA 根证书路径(如 `/etc/secrets/pg-ca.crt`)。 |
|
||||||
|
| `SECRETS_ENV` | 可选。设为 `prod` / `production` 时会拒绝弱 PostgreSQL TLS 模式(`prefer`、`disable`、`allow`、`require`)。 |
|
||||||
| `BASE_URL` | 对外访问基址;OAuth 回调为 `{BASE_URL}/auth/google/callback`。默认 `http://localhost:9315`。 |
|
| `BASE_URL` | 对外访问基址;OAuth 回调为 `{BASE_URL}/auth/google/callback`。默认 `http://localhost:9315`。 |
|
||||||
| `SECRETS_MCP_BIND` | 监听地址,默认 `127.0.0.1:9315`。容器内或直接对外暴露端口时请改为 `0.0.0.0:9315`;反代时常为 `127.0.0.1:9315`。 |
|
| `SECRETS_MCP_BIND` | 监听地址,默认 `127.0.0.1:9315`。容器内或直接对外暴露端口时请改为 `0.0.0.0:9315`;反代时常为 `127.0.0.1:9315`。 |
|
||||||
| `GOOGLE_CLIENT_ID` / `GOOGLE_CLIENT_SECRET` | 可选;不配置则无 Google 登录入口。运行时从环境读取,勿写入 CI、勿打入二进制。 |
|
| `GOOGLE_CLIENT_ID` / `GOOGLE_CLIENT_SECRET` | 可选;不配置则无 Google 登录入口。运行时从环境读取,勿写入 CI、勿打入二进制。 |
|
||||||
@@ -27,9 +30,26 @@ cargo build --release -p secrets-mcp
|
|||||||
cargo run -p secrets-mcp
|
cargo run -p secrets-mcp
|
||||||
```
|
```
|
||||||
|
|
||||||
|
生产推荐示例(PostgreSQL TLS):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
SECRETS_DATABASE_URL=postgres://postgres:***@db.refining.ltd:5432/secrets-mcp
|
||||||
|
SECRETS_DATABASE_SSL_MODE=verify-full
|
||||||
|
SECRETS_DATABASE_SSL_ROOT_CERT=/etc/secrets/pg-ca.crt
|
||||||
|
SECRETS_ENV=production
|
||||||
|
```
|
||||||
|
|
||||||
- **Web**:`BASE_URL`(登录、Dashboard、设置密码短语、创建 API Key)。
|
- **Web**:`BASE_URL`(登录、Dashboard、设置密码短语、创建 API Key)。
|
||||||
- **MCP**:Streamable HTTP 基址 `{BASE_URL}/mcp`,需 `Authorization: Bearer <api_key>` + `X-Encryption-Key: <hex>` 请求头(读密文工具须带密钥)。
|
- **MCP**:Streamable HTTP 基址 `{BASE_URL}/mcp`,需 `Authorization: Bearer <api_key>` + `X-Encryption-Key: <hex>` 请求头(读密文工具须带密钥)。
|
||||||
|
|
||||||
|
## PostgreSQL TLS 加固
|
||||||
|
|
||||||
|
- 推荐将数据库域名单独设置为 `db.refining.ltd`,服务域名保持 `secrets.refining.app`。
|
||||||
|
- 数据库证书建议使用可校验链路(如 Let's Encrypt 或私有 CA),并保证证书 `SAN` 包含 `db.refining.ltd`。
|
||||||
|
- PostgreSQL 侧建议使用 `hostssl` 规则限制应用来源(如 `47.238.146.244/32`),逐步移除公网明文 `host` 访问。
|
||||||
|
- 应用端推荐 `SECRETS_DATABASE_SSL_MODE=verify-full`;仅在过渡阶段可临时用 `verify-ca`。
|
||||||
|
- 可执行运维步骤见 [`deploy/postgres-tls-hardening.md`](deploy/postgres-tls-hardening.md)。
|
||||||
|
|
||||||
## MCP 与 AI 工作流(v0.3+)
|
## MCP 与 AI 工作流(v0.3+)
|
||||||
|
|
||||||
条目在逻辑上以 **`(folder, name)`** 在用户内唯一(数据库唯一索引:`user_id + folder + name`)。同名可在不同 folder 下各存一条(例如 `refining/aliyun` 与 `ricnsmart/aliyun`)。
|
条目在逻辑上以 **`(folder, name)`** 在用户内唯一(数据库唯一索引:`user_id + folder + name`)。同名可在不同 folder 下各存一条(例如 `refining/aliyun` 与 `ricnsmart/aliyun`)。
|
||||||
@@ -147,7 +167,7 @@ flowchart LR
|
|||||||
|
|
||||||
### PEM 共享(`key_ref`)
|
### PEM 共享(`key_ref`)
|
||||||
|
|
||||||
同一 PEM 可被多条 `server` 等记录引用:将 PEM 存为 **`type=key`** 的 entry,在其它条目的 `metadata.key_ref` 中写该 key 条目的 `name`;轮换时只更新 key 对应记录即可。
|
同一 PEM 可被多条 `server` 等记录引用:将 PEM 存为 **`type=key`** 的 entry,在其它条目的 `metadata.key_ref` 中写该 key 条目的 `name`(支持 `folder/name` 格式消歧);轮换时只更新 key 记录即可。
|
||||||
|
|
||||||
## 审计日志
|
## 审计日志
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,15 @@
|
|||||||
use anyhow::Result;
|
use std::path::PathBuf;
|
||||||
|
|
||||||
|
use anyhow::{Context, Result};
|
||||||
|
use sqlx::postgres::PgSslMode;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct DatabaseConfig {
|
||||||
|
pub url: String,
|
||||||
|
pub ssl_mode: Option<PgSslMode>,
|
||||||
|
pub ssl_root_cert: Option<PathBuf>,
|
||||||
|
pub enforce_strict_tls: bool,
|
||||||
|
}
|
||||||
|
|
||||||
/// Resolve database URL from environment.
|
/// Resolve database URL from environment.
|
||||||
/// Priority: `SECRETS_DATABASE_URL` env var → error.
|
/// Priority: `SECRETS_DATABASE_URL` env var → error.
|
||||||
@@ -18,3 +29,54 @@ pub fn resolve_db_url(override_url: &str) -> Result<String> {
|
|||||||
Example: SECRETS_DATABASE_URL=postgres://user:pass@host:port/dbname"
|
Example: SECRETS_DATABASE_URL=postgres://user:pass@host:port/dbname"
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn env_var_non_empty(name: &str) -> Option<String> {
|
||||||
|
std::env::var(name)
|
||||||
|
.ok()
|
||||||
|
.filter(|value| !value.trim().is_empty())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse_ssl_mode_from_env() -> Result<Option<PgSslMode>> {
|
||||||
|
let Some(mode) = env_var_non_empty("SECRETS_DATABASE_SSL_MODE") else {
|
||||||
|
return Ok(None);
|
||||||
|
};
|
||||||
|
|
||||||
|
let parsed = mode.parse::<PgSslMode>().with_context(|| {
|
||||||
|
format!(
|
||||||
|
"Invalid SECRETS_DATABASE_SSL_MODE='{mode}'. Use one of: disable, allow, prefer, require, verify-ca, verify-full."
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
Ok(Some(parsed))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn resolve_ssl_root_cert_from_env() -> Result<Option<PathBuf>> {
|
||||||
|
let Some(path) = env_var_non_empty("SECRETS_DATABASE_SSL_ROOT_CERT") else {
|
||||||
|
return Ok(None);
|
||||||
|
};
|
||||||
|
let path = PathBuf::from(path);
|
||||||
|
if !path.exists() {
|
||||||
|
anyhow::bail!(
|
||||||
|
"SECRETS_DATABASE_SSL_ROOT_CERT points to a missing file: {}",
|
||||||
|
path.display()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
Ok(Some(path))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_production_env() -> bool {
|
||||||
|
matches!(
|
||||||
|
env_var_non_empty("SECRETS_ENV")
|
||||||
|
.as_deref()
|
||||||
|
.map(|value| value.to_ascii_lowercase()),
|
||||||
|
Some(value) if value == "prod" || value == "production"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn resolve_db_config(override_url: &str) -> Result<DatabaseConfig> {
|
||||||
|
Ok(DatabaseConfig {
|
||||||
|
url: resolve_db_url(override_url)?,
|
||||||
|
ssl_mode: parse_ssl_mode_from_env()?,
|
||||||
|
ssl_root_cert: resolve_ssl_root_cert_from_env()?,
|
||||||
|
enforce_strict_tls: is_production_env(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,14 +1,45 @@
|
|||||||
use anyhow::Result;
|
use std::str::FromStr;
|
||||||
|
|
||||||
|
use anyhow::{Context, Result};
|
||||||
use serde_json::Value;
|
use serde_json::Value;
|
||||||
use sqlx::PgPool;
|
use sqlx::PgPool;
|
||||||
use sqlx::postgres::PgPoolOptions;
|
use sqlx::postgres::{PgConnectOptions, PgPoolOptions, PgSslMode};
|
||||||
|
|
||||||
pub async fn create_pool(database_url: &str) -> Result<PgPool> {
|
use crate::config::DatabaseConfig;
|
||||||
|
|
||||||
|
fn build_connect_options(config: &DatabaseConfig) -> Result<PgConnectOptions> {
|
||||||
|
let mut options = PgConnectOptions::from_str(&config.url)
|
||||||
|
.with_context(|| "failed to parse SECRETS_DATABASE_URL".to_string())?;
|
||||||
|
|
||||||
|
if let Some(mode) = config.ssl_mode {
|
||||||
|
options = options.ssl_mode(mode);
|
||||||
|
}
|
||||||
|
if let Some(path) = &config.ssl_root_cert {
|
||||||
|
options = options.ssl_root_cert(path);
|
||||||
|
}
|
||||||
|
|
||||||
|
if config.enforce_strict_tls
|
||||||
|
&& !matches!(
|
||||||
|
options.get_ssl_mode(),
|
||||||
|
PgSslMode::VerifyCa | PgSslMode::VerifyFull
|
||||||
|
)
|
||||||
|
{
|
||||||
|
anyhow::bail!(
|
||||||
|
"Refusing to start in production with weak PostgreSQL TLS mode. \
|
||||||
|
Set SECRETS_DATABASE_SSL_MODE=verify-ca or verify-full."
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(options)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn create_pool(config: &DatabaseConfig) -> Result<PgPool> {
|
||||||
tracing::debug!("connecting to database");
|
tracing::debug!("connecting to database");
|
||||||
|
let connect_options = build_connect_options(config)?;
|
||||||
let pool = PgPoolOptions::new()
|
let pool = PgPoolOptions::new()
|
||||||
.max_connections(10)
|
.max_connections(10)
|
||||||
.acquire_timeout(std::time::Duration::from_secs(5))
|
.acquire_timeout(std::time::Duration::from_secs(5))
|
||||||
.connect(database_url)
|
.connect_with(connect_options)
|
||||||
.await?;
|
.await?;
|
||||||
tracing::debug!("database connection established");
|
tracing::debug!("database connection established");
|
||||||
Ok(pool)
|
Ok(pool)
|
||||||
|
|||||||
@@ -26,7 +26,8 @@ pub async fn build_env_map(
|
|||||||
let mut combined: HashMap<String, String> = HashMap::new();
|
let mut combined: HashMap<String, String> = HashMap::new();
|
||||||
|
|
||||||
for entry in &entries {
|
for entry in &entries {
|
||||||
let entry_map = build_entry_env_map(pool, entry, only_fields, prefix, master_key).await?;
|
let entry_map =
|
||||||
|
build_entry_env_map(pool, entry, only_fields, prefix, master_key, user_id).await?;
|
||||||
combined.extend(entry_map);
|
combined.extend(entry_map);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -39,6 +40,7 @@ async fn build_entry_env_map(
|
|||||||
only_fields: &[String],
|
only_fields: &[String],
|
||||||
prefix: &str,
|
prefix: &str,
|
||||||
master_key: &[u8; 32],
|
master_key: &[u8; 32],
|
||||||
|
user_id: Option<Uuid>,
|
||||||
) -> Result<HashMap<String, String>> {
|
) -> Result<HashMap<String, String>> {
|
||||||
let entry_ids = vec![entry.id];
|
let entry_ids = vec![entry.id];
|
||||||
let secrets_map = fetch_secrets_for_entries(pool, &entry_ids).await?;
|
let secrets_map = fetch_secrets_for_entries(pool, &entry_ids).await?;
|
||||||
@@ -66,10 +68,31 @@ async fn build_entry_env_map(
|
|||||||
map.insert(key, json_to_env_string(&decrypted));
|
map.insert(key, json_to_env_string(&decrypted));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Resolve key_ref
|
// Resolve key_ref. Supported formats: "name" or "folder/name".
|
||||||
if let Some(key_ref) = entry.metadata.get("key_ref").and_then(|v| v.as_str()) {
|
if let Some(key_ref) = entry.metadata.get("key_ref").and_then(|v| v.as_str()) {
|
||||||
let key_entries =
|
let (ref_folder, ref_name) = if let Some((f, n)) = key_ref.split_once('/') {
|
||||||
fetch_entries(pool, None, Some("key"), Some(key_ref), &[], None, None).await?;
|
(Some(f), n)
|
||||||
|
} else {
|
||||||
|
(None, key_ref)
|
||||||
|
};
|
||||||
|
let key_entries = fetch_entries(
|
||||||
|
pool,
|
||||||
|
ref_folder,
|
||||||
|
Some("key"),
|
||||||
|
Some(ref_name),
|
||||||
|
&[],
|
||||||
|
None,
|
||||||
|
user_id,
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
if key_entries.len() > 1 {
|
||||||
|
anyhow::bail!(
|
||||||
|
"key_ref '{}' matched {} entries; qualify with folder/name to resolve the ambiguity",
|
||||||
|
key_ref,
|
||||||
|
key_entries.len()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
if let Some(key_entry) = key_entries.first() {
|
if let Some(key_entry) = key_entries.first() {
|
||||||
let key_ids = vec![key_entry.id];
|
let key_ids = vec![key_entry.id];
|
||||||
@@ -87,7 +110,7 @@ async fn build_entry_env_map(
|
|||||||
map.insert(key_var, json_to_env_string(&decrypted));
|
map.insert(key_var, json_to_env_string(&decrypted));
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
tracing::warn!(key_ref, "key_ref target not found");
|
tracing::warn!(key_ref, ?user_id, "key_ref target not found");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -27,49 +27,46 @@ pub struct SearchResult {
|
|||||||
pub secret_schemas: HashMap<Uuid, Vec<SecretField>>,
|
pub secret_schemas: HashMap<Uuid, Vec<SecretField>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn run(pool: &PgPool, params: SearchParams<'_>) -> Result<SearchResult> {
|
/// List `entries` rows matching params (paged, ordered per `params.sort`).
|
||||||
let entries = fetch_entries_paged(pool, ¶ms).await?;
|
/// Does not read the `secrets` table.
|
||||||
let entry_ids: Vec<Uuid> = entries.iter().map(|e| e.id).collect();
|
pub async fn list_entries(pool: &PgPool, params: SearchParams<'_>) -> Result<Vec<Entry>> {
|
||||||
let secret_schemas = if !entry_ids.is_empty() {
|
|
||||||
fetch_secret_schemas(pool, &entry_ids).await?
|
|
||||||
} else {
|
|
||||||
HashMap::new()
|
|
||||||
};
|
|
||||||
Ok(SearchResult {
|
|
||||||
entries,
|
|
||||||
secret_schemas,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Fetch entries matching the given filters — returns all matching entries up to FETCH_ALL_LIMIT.
|
|
||||||
pub async fn fetch_entries(
|
|
||||||
pool: &PgPool,
|
|
||||||
folder: Option<&str>,
|
|
||||||
entry_type: Option<&str>,
|
|
||||||
name: Option<&str>,
|
|
||||||
tags: &[String],
|
|
||||||
query: Option<&str>,
|
|
||||||
user_id: Option<Uuid>,
|
|
||||||
) -> Result<Vec<Entry>> {
|
|
||||||
let params = SearchParams {
|
|
||||||
folder,
|
|
||||||
entry_type,
|
|
||||||
name,
|
|
||||||
tags,
|
|
||||||
query,
|
|
||||||
sort: "name",
|
|
||||||
limit: FETCH_ALL_LIMIT,
|
|
||||||
offset: 0,
|
|
||||||
user_id,
|
|
||||||
};
|
|
||||||
fetch_entries_paged(pool, ¶ms).await
|
fetch_entries_paged(pool, ¶ms).await
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn fetch_entries_paged(pool: &PgPool, a: &SearchParams<'_>) -> Result<Vec<Entry>> {
|
/// Count `entries` rows matching the same filters as [`list_entries`] (ignores `sort` / `limit` / `offset`).
|
||||||
|
/// Does not read the `secrets` table.
|
||||||
|
pub async fn count_entries(pool: &PgPool, a: &SearchParams<'_>) -> Result<i64> {
|
||||||
|
let (where_clause, _) = entry_where_clause_and_next_idx(a);
|
||||||
|
let sql = format!("SELECT COUNT(*)::bigint FROM entries {where_clause}");
|
||||||
|
let mut q = sqlx::query_scalar::<_, i64>(&sql);
|
||||||
|
if let Some(uid) = a.user_id {
|
||||||
|
q = q.bind(uid);
|
||||||
|
}
|
||||||
|
if let Some(v) = a.folder {
|
||||||
|
q = q.bind(v);
|
||||||
|
}
|
||||||
|
if let Some(v) = a.entry_type {
|
||||||
|
q = q.bind(v);
|
||||||
|
}
|
||||||
|
if let Some(v) = a.name {
|
||||||
|
q = q.bind(v);
|
||||||
|
}
|
||||||
|
for tag in a.tags {
|
||||||
|
q = q.bind(tag);
|
||||||
|
}
|
||||||
|
if let Some(v) = a.query {
|
||||||
|
let pattern = format!("%{}%", v.replace('%', "\\%").replace('_', "\\_"));
|
||||||
|
q = q.bind(pattern);
|
||||||
|
}
|
||||||
|
let n = q.fetch_one(pool).await?;
|
||||||
|
Ok(n)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Shared WHERE clause and the next `$n` index (for LIMIT/OFFSET in paged queries).
|
||||||
|
fn entry_where_clause_and_next_idx(a: &SearchParams<'_>) -> (String, i32) {
|
||||||
let mut conditions: Vec<String> = Vec::new();
|
let mut conditions: Vec<String> = Vec::new();
|
||||||
let mut idx: i32 = 1;
|
let mut idx: i32 = 1;
|
||||||
|
|
||||||
// user_id filtering — always comes first when present
|
|
||||||
if a.user_id.is_some() {
|
if a.user_id.is_some() {
|
||||||
conditions.push(format!("user_id = ${}", idx));
|
conditions.push(format!("user_id = ${}", idx));
|
||||||
idx += 1;
|
idx += 1;
|
||||||
@@ -115,6 +112,55 @@ async fn fetch_entries_paged(pool: &PgPool, a: &SearchParams<'_>) -> Result<Vec<
|
|||||||
idx += 1;
|
idx += 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let where_clause = if conditions.is_empty() {
|
||||||
|
String::new()
|
||||||
|
} else {
|
||||||
|
format!("WHERE {}", conditions.join(" AND "))
|
||||||
|
};
|
||||||
|
(where_clause, idx)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn run(pool: &PgPool, params: SearchParams<'_>) -> Result<SearchResult> {
|
||||||
|
let entries = fetch_entries_paged(pool, ¶ms).await?;
|
||||||
|
let entry_ids: Vec<Uuid> = entries.iter().map(|e| e.id).collect();
|
||||||
|
let secret_schemas = if !entry_ids.is_empty() {
|
||||||
|
fetch_secret_schemas(pool, &entry_ids).await?
|
||||||
|
} else {
|
||||||
|
HashMap::new()
|
||||||
|
};
|
||||||
|
Ok(SearchResult {
|
||||||
|
entries,
|
||||||
|
secret_schemas,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Fetch entries matching the given filters — returns all matching entries up to FETCH_ALL_LIMIT.
|
||||||
|
pub async fn fetch_entries(
|
||||||
|
pool: &PgPool,
|
||||||
|
folder: Option<&str>,
|
||||||
|
entry_type: Option<&str>,
|
||||||
|
name: Option<&str>,
|
||||||
|
tags: &[String],
|
||||||
|
query: Option<&str>,
|
||||||
|
user_id: Option<Uuid>,
|
||||||
|
) -> Result<Vec<Entry>> {
|
||||||
|
let params = SearchParams {
|
||||||
|
folder,
|
||||||
|
entry_type,
|
||||||
|
name,
|
||||||
|
tags,
|
||||||
|
query,
|
||||||
|
sort: "name",
|
||||||
|
limit: FETCH_ALL_LIMIT,
|
||||||
|
offset: 0,
|
||||||
|
user_id,
|
||||||
|
};
|
||||||
|
list_entries(pool, params).await
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn fetch_entries_paged(pool: &PgPool, a: &SearchParams<'_>) -> Result<Vec<Entry>> {
|
||||||
|
let (where_clause, idx) = entry_where_clause_and_next_idx(a);
|
||||||
|
|
||||||
let order = match a.sort {
|
let order = match a.sort {
|
||||||
"updated" => "updated_at DESC",
|
"updated" => "updated_at DESC",
|
||||||
"created" => "created_at DESC",
|
"created" => "created_at DESC",
|
||||||
@@ -122,14 +168,7 @@ async fn fetch_entries_paged(pool: &PgPool, a: &SearchParams<'_>) -> Result<Vec<
|
|||||||
};
|
};
|
||||||
|
|
||||||
let limit_idx = idx;
|
let limit_idx = idx;
|
||||||
idx += 1;
|
let offset_idx = idx + 1;
|
||||||
let offset_idx = idx;
|
|
||||||
|
|
||||||
let where_clause = if conditions.is_empty() {
|
|
||||||
String::new()
|
|
||||||
} else {
|
|
||||||
format!("WHERE {}", conditions.join(" AND "))
|
|
||||||
};
|
|
||||||
|
|
||||||
let sql = format!(
|
let sql = format!(
|
||||||
"SELECT id, user_id, folder, type, name, notes, tags, metadata, version, \
|
"SELECT id, user_id, folder, type, name, notes, tags, metadata, version, \
|
||||||
@@ -138,7 +177,6 @@ async fn fetch_entries_paged(pool: &PgPool, a: &SearchParams<'_>) -> Result<Vec<
|
|||||||
);
|
);
|
||||||
|
|
||||||
let mut q = sqlx::query_as::<_, EntryRaw>(&sql);
|
let mut q = sqlx::query_as::<_, EntryRaw>(&sql);
|
||||||
|
|
||||||
if let Some(uid) = a.user_id {
|
if let Some(uid) = a.user_id {
|
||||||
q = q.bind(uid);
|
q = q.bind(uid);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "secrets-mcp"
|
name = "secrets-mcp"
|
||||||
version = "0.3.1"
|
version = "0.3.4"
|
||||||
edition.workspace = true
|
edition.workspace = true
|
||||||
|
|
||||||
[[bin]]
|
[[bin]]
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ use tower_sessions_sqlx_store_chrono::PostgresStore;
|
|||||||
use tracing_subscriber::EnvFilter;
|
use tracing_subscriber::EnvFilter;
|
||||||
use tracing_subscriber::fmt::time::FormatTime;
|
use tracing_subscriber::fmt::time::FormatTime;
|
||||||
|
|
||||||
use secrets_core::config::resolve_db_url;
|
use secrets_core::config::resolve_db_config;
|
||||||
use secrets_core::db::{create_pool, migrate};
|
use secrets_core::db::{create_pool, migrate};
|
||||||
|
|
||||||
use crate::oauth::OAuthConfig;
|
use crate::oauth::OAuthConfig;
|
||||||
@@ -78,9 +78,9 @@ async fn main() -> Result<()> {
|
|||||||
.init();
|
.init();
|
||||||
|
|
||||||
// ── Database ──────────────────────────────────────────────────────────────
|
// ── Database ──────────────────────────────────────────────────────────────
|
||||||
let db_url = resolve_db_url("")
|
let db_config = resolve_db_config("")
|
||||||
.context("Database not configured. Set SECRETS_DATABASE_URL environment variable.")?;
|
.context("Database not configured. Set SECRETS_DATABASE_URL environment variable.")?;
|
||||||
let pool = create_pool(&db_url)
|
let pool = create_pool(&db_config)
|
||||||
.await
|
.await
|
||||||
.context("failed to connect to database")?;
|
.context("failed to connect to database")?;
|
||||||
migrate(&pool)
|
migrate(&pool)
|
||||||
|
|||||||
@@ -19,6 +19,7 @@ use secrets_core::crypto::hex;
|
|||||||
use secrets_core::service::{
|
use secrets_core::service::{
|
||||||
api_key::{ensure_api_key, regenerate_api_key},
|
api_key::{ensure_api_key, regenerate_api_key},
|
||||||
audit_log::list_for_user,
|
audit_log::list_for_user,
|
||||||
|
search::{SearchParams, count_entries, list_entries},
|
||||||
user::{
|
user::{
|
||||||
OAuthProfile, bind_oauth_account, find_or_create_user, get_user_by_id,
|
OAuthProfile, bind_oauth_account, find_or_create_user, get_user_by_id,
|
||||||
unbind_oauth_account, update_user_key_setup,
|
unbind_oauth_account, update_user_key_setup,
|
||||||
@@ -78,6 +79,33 @@ struct AuditEntryView {
|
|||||||
detail: String,
|
detail: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Template)]
|
||||||
|
#[template(path = "entries.html")]
|
||||||
|
struct EntriesPageTemplate {
|
||||||
|
user_name: String,
|
||||||
|
user_email: String,
|
||||||
|
entries: Vec<EntryListItemView>,
|
||||||
|
total_count: i64,
|
||||||
|
shown_count: usize,
|
||||||
|
limit: u32,
|
||||||
|
version: &'static str,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Non-sensitive fields only (no `secrets` / ciphertext).
|
||||||
|
struct EntryListItemView {
|
||||||
|
folder: String,
|
||||||
|
entry_type: String,
|
||||||
|
name: String,
|
||||||
|
notes: String,
|
||||||
|
tags: String,
|
||||||
|
metadata: String,
|
||||||
|
/// RFC3339 UTC for `<time datetime>`; localized in entries.html.
|
||||||
|
updated_at_iso: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Cap for HTML list (avoids loading unbounded rows into memory).
|
||||||
|
const ENTRIES_PAGE_LIMIT: u32 = 5_000;
|
||||||
|
|
||||||
// ── App state helpers ─────────────────────────────────────────────────────────
|
// ── App state helpers ─────────────────────────────────────────────────────────
|
||||||
|
|
||||||
fn google_cfg(state: &AppState) -> Option<&OAuthConfig> {
|
fn google_cfg(state: &AppState) -> Option<&OAuthConfig> {
|
||||||
@@ -149,6 +177,7 @@ pub fn web_router() -> Router<AppState> {
|
|||||||
.route("/auth/google/callback", get(auth_google_callback))
|
.route("/auth/google/callback", get(auth_google_callback))
|
||||||
.route("/auth/logout", post(auth_logout))
|
.route("/auth/logout", post(auth_logout))
|
||||||
.route("/dashboard", get(dashboard))
|
.route("/dashboard", get(dashboard))
|
||||||
|
.route("/entries", get(entries_page))
|
||||||
.route("/audit", get(audit_page))
|
.route("/audit", get(audit_page))
|
||||||
.route("/account/bind/google", get(account_bind_google))
|
.route("/account/bind/google", get(account_bind_google))
|
||||||
.route(
|
.route(
|
||||||
@@ -478,6 +507,72 @@ async fn dashboard(
|
|||||||
render_template(tmpl)
|
render_template(tmpl)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async fn entries_page(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
session: Session,
|
||||||
|
) -> Result<Response, StatusCode> {
|
||||||
|
let Some(user_id) = current_user_id(&session).await else {
|
||||||
|
return Ok(Redirect::to("/login").into_response());
|
||||||
|
};
|
||||||
|
|
||||||
|
let user = match get_user_by_id(&state.pool, user_id).await.map_err(|e| {
|
||||||
|
tracing::error!(error = %e, %user_id, "failed to load user for entries page");
|
||||||
|
StatusCode::INTERNAL_SERVER_ERROR
|
||||||
|
})? {
|
||||||
|
Some(u) => u,
|
||||||
|
None => return Ok(Redirect::to("/login").into_response()),
|
||||||
|
};
|
||||||
|
|
||||||
|
let params = SearchParams {
|
||||||
|
folder: None,
|
||||||
|
entry_type: None,
|
||||||
|
name: None,
|
||||||
|
tags: &[],
|
||||||
|
query: None,
|
||||||
|
sort: "updated",
|
||||||
|
limit: ENTRIES_PAGE_LIMIT,
|
||||||
|
offset: 0,
|
||||||
|
user_id: Some(user_id),
|
||||||
|
};
|
||||||
|
|
||||||
|
let total_count = count_entries(&state.pool, ¶ms).await.map_err(|e| {
|
||||||
|
tracing::error!(error = %e, "failed to count entries for web");
|
||||||
|
StatusCode::INTERNAL_SERVER_ERROR
|
||||||
|
})?;
|
||||||
|
|
||||||
|
let rows = list_entries(&state.pool, params).await.map_err(|e| {
|
||||||
|
tracing::error!(error = %e, "failed to load entries list for web");
|
||||||
|
StatusCode::INTERNAL_SERVER_ERROR
|
||||||
|
})?;
|
||||||
|
let shown_count = rows.len();
|
||||||
|
|
||||||
|
let entries = rows
|
||||||
|
.into_iter()
|
||||||
|
.map(|e| EntryListItemView {
|
||||||
|
folder: e.folder,
|
||||||
|
entry_type: e.entry_type,
|
||||||
|
name: e.name,
|
||||||
|
notes: e.notes,
|
||||||
|
tags: e.tags.join(", "),
|
||||||
|
metadata: serde_json::to_string_pretty(&e.metadata)
|
||||||
|
.unwrap_or_else(|_| "{}".to_string()),
|
||||||
|
updated_at_iso: e.updated_at.to_rfc3339_opts(SecondsFormat::Secs, true),
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
let tmpl = EntriesPageTemplate {
|
||||||
|
user_name: user.name.clone(),
|
||||||
|
user_email: user.email.clone().unwrap_or_default(),
|
||||||
|
entries,
|
||||||
|
total_count,
|
||||||
|
shown_count,
|
||||||
|
limit: ENTRIES_PAGE_LIMIT,
|
||||||
|
version: env!("CARGO_PKG_VERSION"),
|
||||||
|
};
|
||||||
|
|
||||||
|
render_template(tmpl)
|
||||||
|
}
|
||||||
|
|
||||||
async fn audit_page(
|
async fn audit_page(
|
||||||
State(state): State<AppState>,
|
State(state): State<AppState>,
|
||||||
session: Session,
|
session: Session,
|
||||||
|
|||||||
@@ -92,6 +92,7 @@
|
|||||||
<a href="/dashboard" class="sidebar-logo"><span>secrets</span></a>
|
<a href="/dashboard" class="sidebar-logo"><span>secrets</span></a>
|
||||||
<nav class="sidebar-menu">
|
<nav class="sidebar-menu">
|
||||||
<a href="/dashboard" class="sidebar-link">MCP</a>
|
<a href="/dashboard" class="sidebar-link">MCP</a>
|
||||||
|
<a href="/entries" class="sidebar-link">条目</a>
|
||||||
<a href="/audit" class="sidebar-link active">审计</a>
|
<a href="/audit" class="sidebar-link active">审计</a>
|
||||||
</nav>
|
</nav>
|
||||||
</aside>
|
</aside>
|
||||||
|
|||||||
@@ -174,6 +174,7 @@
|
|||||||
<a href="/dashboard" class="sidebar-logo"><span>secrets</span></a>
|
<a href="/dashboard" class="sidebar-logo"><span>secrets</span></a>
|
||||||
<nav class="sidebar-menu">
|
<nav class="sidebar-menu">
|
||||||
<a href="/dashboard" class="sidebar-link active">MCP</a>
|
<a href="/dashboard" class="sidebar-link active">MCP</a>
|
||||||
|
<a href="/entries" class="sidebar-link">条目</a>
|
||||||
<a href="/audit" class="sidebar-link">审计</a>
|
<a href="/audit" class="sidebar-link">审计</a>
|
||||||
</nav>
|
</nav>
|
||||||
</aside>
|
</aside>
|
||||||
|
|||||||
170
crates/secrets-mcp/templates/entries.html
Normal file
170
crates/secrets-mcp/templates/entries.html
Normal file
@@ -0,0 +1,170 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="zh-CN">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<link rel="icon" href="/favicon.svg?v={{ version }}" type="image/svg+xml">
|
||||||
|
<title>Secrets — 条目</title>
|
||||||
|
<style>
|
||||||
|
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
|
||||||
|
@import url('https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;600&family=Inter:wght@400;500;600&display=swap');
|
||||||
|
:root {
|
||||||
|
--bg: #0d1117; --surface: #161b22; --surface2: #21262d;
|
||||||
|
--border: #30363d; --text: #e6edf3; --text-muted: #8b949e;
|
||||||
|
--accent: #58a6ff; --accent-hover: #79b8ff;
|
||||||
|
}
|
||||||
|
body { background: var(--bg); color: var(--text); font-family: 'Inter', sans-serif; min-height: 100vh; }
|
||||||
|
.layout { display: flex; min-height: 100vh; }
|
||||||
|
.sidebar {
|
||||||
|
width: 220px; flex-shrink: 0; background: var(--surface); border-right: 1px solid var(--border);
|
||||||
|
padding: 24px 16px; display: flex; flex-direction: column; gap: 20px;
|
||||||
|
}
|
||||||
|
.sidebar-logo { font-family: 'JetBrains Mono', monospace; font-size: 16px; font-weight: 600;
|
||||||
|
color: var(--text); text-decoration: none; padding: 0 10px; }
|
||||||
|
.sidebar-logo span { color: var(--accent); }
|
||||||
|
.sidebar-menu { display: flex; flex-direction: column; gap: 6px; }
|
||||||
|
.sidebar-link {
|
||||||
|
padding: 10px 12px; border-radius: 8px; color: var(--text-muted); text-decoration: none;
|
||||||
|
border: 1px solid transparent; font-size: 13px; font-weight: 500;
|
||||||
|
}
|
||||||
|
.sidebar-link:hover { background: var(--surface2); color: var(--text); }
|
||||||
|
.sidebar-link.active {
|
||||||
|
background: rgba(88,166,255,0.12); color: var(--text); border-color: rgba(88,166,255,0.35);
|
||||||
|
}
|
||||||
|
.content-shell { flex: 1; min-width: 0; display: flex; flex-direction: column; }
|
||||||
|
.topbar {
|
||||||
|
background: var(--surface); border-bottom: 1px solid var(--border); padding: 0 24px;
|
||||||
|
display: flex; align-items: center; gap: 12px; min-height: 52px;
|
||||||
|
}
|
||||||
|
.topbar-spacer { flex: 1; }
|
||||||
|
.nav-user { font-size: 13px; color: var(--text-muted); }
|
||||||
|
.btn-sign-out {
|
||||||
|
padding: 5px 12px; border-radius: 6px; border: 1px solid var(--border);
|
||||||
|
background: none; color: var(--text); font-size: 12px; text-decoration: none; cursor: pointer;
|
||||||
|
}
|
||||||
|
.btn-sign-out:hover { background: var(--surface2); }
|
||||||
|
.main { padding: 32px 24px 40px; flex: 1; }
|
||||||
|
.card { background: var(--surface); border: 1px solid var(--border); border-radius: 12px;
|
||||||
|
padding: 24px; width: 100%; max-width: 1280px; margin: 0 auto; }
|
||||||
|
.card-title { font-size: 20px; font-weight: 600; margin-bottom: 8px; }
|
||||||
|
.card-subtitle { color: var(--text-muted); font-size: 13px; margin-bottom: 20px; }
|
||||||
|
.empty { color: var(--text-muted); font-size: 14px; padding: 20px 0; }
|
||||||
|
.table-wrap { overflow-x: auto; }
|
||||||
|
table { width: 100%; border-collapse: collapse; min-width: 720px; }
|
||||||
|
th, td { text-align: left; vertical-align: top; padding: 12px 10px; border-top: 1px solid var(--border); }
|
||||||
|
th { color: var(--text-muted); font-size: 12px; font-weight: 600; white-space: nowrap; }
|
||||||
|
td { font-size: 13px; }
|
||||||
|
.mono { font-family: 'JetBrains Mono', monospace; }
|
||||||
|
.cell-notes, .cell-meta {
|
||||||
|
max-width: 280px; word-break: break-word;
|
||||||
|
}
|
||||||
|
.detail {
|
||||||
|
background: var(--bg); border: 1px solid var(--border); border-radius: 8px;
|
||||||
|
padding: 10px; white-space: pre-wrap; word-break: break-word; font-size: 12px;
|
||||||
|
max-width: 320px; max-height: 160px; overflow: auto;
|
||||||
|
}
|
||||||
|
@media (max-width: 900px) {
|
||||||
|
.layout { flex-direction: column; }
|
||||||
|
.sidebar {
|
||||||
|
width: 100%; border-right: none; border-bottom: 1px solid var(--border);
|
||||||
|
padding: 16px; gap: 14px;
|
||||||
|
}
|
||||||
|
.sidebar-menu { flex-direction: row; flex-wrap: wrap; }
|
||||||
|
.sidebar-link { flex: 1; text-align: center; min-width: 72px; }
|
||||||
|
.main { padding: 20px 12px 28px; }
|
||||||
|
.card { padding: 16px; }
|
||||||
|
.topbar { padding: 12px 16px; flex-wrap: wrap; }
|
||||||
|
table, thead, tbody, th, td, tr { display: block; }
|
||||||
|
thead { display: none; }
|
||||||
|
tr { border-top: 1px solid var(--border); padding: 12px 0; }
|
||||||
|
td { border-top: none; padding: 6px 0; max-width: none; }
|
||||||
|
td::before {
|
||||||
|
display: block; color: var(--text-muted); font-size: 11px;
|
||||||
|
margin-bottom: 4px; text-transform: uppercase;
|
||||||
|
}
|
||||||
|
td.col-updated::before { content: "更新"; }
|
||||||
|
td.col-folder::before { content: "Folder"; }
|
||||||
|
td.col-type::before { content: "Type"; }
|
||||||
|
td.col-name::before { content: "Name"; }
|
||||||
|
td.col-notes::before { content: "Notes"; }
|
||||||
|
td.col-tags::before { content: "Tags"; }
|
||||||
|
td.col-meta::before { content: "Metadata"; }
|
||||||
|
.detail { max-width: none; }
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div class="layout">
|
||||||
|
<aside class="sidebar">
|
||||||
|
<a href="/dashboard" class="sidebar-logo"><span>secrets</span></a>
|
||||||
|
<nav class="sidebar-menu">
|
||||||
|
<a href="/dashboard" class="sidebar-link">MCP</a>
|
||||||
|
<a href="/entries" class="sidebar-link active">条目</a>
|
||||||
|
<a href="/audit" class="sidebar-link">审计</a>
|
||||||
|
</nav>
|
||||||
|
</aside>
|
||||||
|
|
||||||
|
<div class="content-shell">
|
||||||
|
<div class="topbar">
|
||||||
|
<span class="topbar-spacer"></span>
|
||||||
|
<span class="nav-user">{{ user_name }}{% if !user_email.is_empty() %} · {{ user_email }}{% endif %}</span>
|
||||||
|
<form action="/auth/logout" method="post" style="display:inline">
|
||||||
|
<button type="submit" class="btn-sign-out">退出</button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<main class="main">
|
||||||
|
<section class="card">
|
||||||
|
<div class="card-title">我的条目</div>
|
||||||
|
<div class="card-subtitle">共 <strong>{{ total_count }}</strong> 条记录;当前列表显示 <strong>{{ shown_count }}</strong> 条(按更新时间降序,单页最多 {{ limit }} 条)。不含密文字段。时间为浏览器本地时区。</div>
|
||||||
|
|
||||||
|
{% if entries.is_empty() %}
|
||||||
|
<div class="empty">暂无条目。</div>
|
||||||
|
{% else %}
|
||||||
|
<div class="table-wrap">
|
||||||
|
<table>
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>更新</th>
|
||||||
|
<th>Folder</th>
|
||||||
|
<th>Type</th>
|
||||||
|
<th>Name</th>
|
||||||
|
<th>Notes</th>
|
||||||
|
<th>Tags</th>
|
||||||
|
<th>Metadata</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{% for entry in entries %}
|
||||||
|
<tr>
|
||||||
|
<td class="col-updated mono"><time class="entry-local-time" datetime="{{ entry.updated_at_iso }}">{{ entry.updated_at_iso }}</time></td>
|
||||||
|
<td class="col-folder mono">{{ entry.folder }}</td>
|
||||||
|
<td class="col-type mono">{{ entry.entry_type }}</td>
|
||||||
|
<td class="col-name mono">{{ entry.name }}</td>
|
||||||
|
<td class="col-notes cell-notes">{{ entry.notes }}</td>
|
||||||
|
<td class="col-tags mono">{{ entry.tags }}</td>
|
||||||
|
<td class="col-meta cell-meta"><pre class="detail">{{ entry.metadata }}</pre></td>
|
||||||
|
</tr>
|
||||||
|
{% endfor %}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
|
</section>
|
||||||
|
</main>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<script>
|
||||||
|
(function () {
|
||||||
|
document.querySelectorAll('time.entry-local-time[datetime]').forEach(function (el) {
|
||||||
|
var raw = el.getAttribute('datetime');
|
||||||
|
var d = raw ? new Date(raw) : null;
|
||||||
|
if (d && !isNaN(d.getTime())) {
|
||||||
|
el.textContent = d.toLocaleString(undefined, { dateStyle: 'medium', timeStyle: 'medium' });
|
||||||
|
el.title = raw + ' (UTC)';
|
||||||
|
}
|
||||||
|
});
|
||||||
|
})();
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -3,7 +3,13 @@
|
|||||||
|
|
||||||
# ─── 数据库 ───────────────────────────────────────────────────────────
|
# ─── 数据库 ───────────────────────────────────────────────────────────
|
||||||
# Web 会话(tower-sessions)与业务数据共用此库;启动时会自动 migrate 会话表,无需额外环境变量。
|
# Web 会话(tower-sessions)与业务数据共用此库;启动时会自动 migrate 会话表,无需额外环境变量。
|
||||||
SECRETS_DATABASE_URL=postgres://postgres:PASSWORD@HOST:PORT/secrets-mcp
|
SECRETS_DATABASE_URL=postgres://postgres:PASSWORD@db.refining.ltd:5432/secrets-mcp
|
||||||
|
# 强烈建议生产使用 verify-full(至少 verify-ca)
|
||||||
|
SECRETS_DATABASE_SSL_MODE=verify-full
|
||||||
|
# 私有 CA 或自建链路时填写 CA 根证书路径;使用公共受信 CA 可留空
|
||||||
|
# SECRETS_DATABASE_SSL_ROOT_CERT=/etc/secrets/pg-ca.crt
|
||||||
|
# 当设为 prod/production 时,服务会拒绝弱 TLS 模式(prefer/disable/allow/require)
|
||||||
|
SECRETS_ENV=production
|
||||||
|
|
||||||
# ─── 服务地址 ─────────────────────────────────────────────────────────
|
# ─── 服务地址 ─────────────────────────────────────────────────────────
|
||||||
# 内网监听地址(Cloudflare / Nginx 反代时填内网端口)
|
# 内网监听地址(Cloudflare / Nginx 反代时填内网端口)
|
||||||
|
|||||||
92
deploy/postgres-tls-hardening.md
Normal file
92
deploy/postgres-tls-hardening.md
Normal file
@@ -0,0 +1,92 @@
|
|||||||
|
# PostgreSQL TLS Hardening Runbook
|
||||||
|
|
||||||
|
This runbook applies to:
|
||||||
|
|
||||||
|
- PostgreSQL server: `47.117.131.22` (`db.refining.ltd`)
|
||||||
|
- `secrets-mcp` app server: `47.238.146.244` (`secrets.refining.app`)
|
||||||
|
|
||||||
|
## 1) Issue certificate for `db.refining.ltd` (Let's Encrypt + Cloudflare DNS-01)
|
||||||
|
|
||||||
|
Install `acme.sh` on the PostgreSQL server and use a Cloudflare API token with DNS edit permission for the target zone.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl https://get.acme.sh | sh -s email=ops@refining.ltd
|
||||||
|
export CF_Token="your_cloudflare_dns_token"
|
||||||
|
export CF_Zone_ID="your_zone_id"
|
||||||
|
~/.acme.sh/acme.sh --issue --dns dns_cf -d db.refining.ltd --keylength ec-256
|
||||||
|
```
|
||||||
|
|
||||||
|
Install cert/key into a PostgreSQL-readable path:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
sudo mkdir -p /etc/postgresql/tls
|
||||||
|
sudo ~/.acme.sh/acme.sh --install-cert -d db.refining.ltd --ecc \
|
||||||
|
--fullchain-file /etc/postgresql/tls/fullchain.pem \
|
||||||
|
--key-file /etc/postgresql/tls/privkey.pem \
|
||||||
|
--reloadcmd "systemctl reload postgresql || systemctl restart postgresql"
|
||||||
|
sudo chown -R postgres:postgres /etc/postgresql/tls
|
||||||
|
sudo chmod 600 /etc/postgresql/tls/privkey.pem
|
||||||
|
sudo chmod 644 /etc/postgresql/tls/fullchain.pem
|
||||||
|
```
|
||||||
|
|
||||||
|
## 2) Configure PostgreSQL TLS and access rules
|
||||||
|
|
||||||
|
In `postgresql.conf`:
|
||||||
|
|
||||||
|
```conf
|
||||||
|
ssl = on
|
||||||
|
ssl_cert_file = '/etc/postgresql/tls/fullchain.pem'
|
||||||
|
ssl_key_file = '/etc/postgresql/tls/privkey.pem'
|
||||||
|
```
|
||||||
|
|
||||||
|
In `pg_hba.conf`, allow app traffic via TLS only (example):
|
||||||
|
|
||||||
|
```conf
|
||||||
|
hostssl secrets-mcp postgres 47.238.146.244/32 scram-sha-256
|
||||||
|
```
|
||||||
|
|
||||||
|
Keep a safe admin path (`local` socket or restricted source CIDR) before removing old plaintext `host` rules.
|
||||||
|
|
||||||
|
Reload PostgreSQL:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
sudo systemctl reload postgresql
|
||||||
|
```
|
||||||
|
|
||||||
|
## 3) Verify server-side TLS
|
||||||
|
|
||||||
|
```bash
|
||||||
|
openssl s_client -starttls postgres -connect db.refining.ltd:5432 -servername db.refining.ltd
|
||||||
|
```
|
||||||
|
|
||||||
|
The handshake should succeed and the certificate should match `db.refining.ltd`.
|
||||||
|
|
||||||
|
## 4) Update `secrets-mcp` app server env
|
||||||
|
|
||||||
|
Use environment values like:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
SECRETS_DATABASE_URL=postgres://postgres:***@db.refining.ltd:5432/secrets-mcp
|
||||||
|
SECRETS_DATABASE_SSL_MODE=verify-full
|
||||||
|
SECRETS_ENV=production
|
||||||
|
```
|
||||||
|
|
||||||
|
If you use private CA instead of public CA, also set:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
SECRETS_DATABASE_SSL_ROOT_CERT=/etc/secrets/pg-ca.crt
|
||||||
|
```
|
||||||
|
|
||||||
|
Restart `secrets-mcp` after updating env.
|
||||||
|
|
||||||
|
## 5) Verify from app server
|
||||||
|
|
||||||
|
Run positive and negative checks:
|
||||||
|
|
||||||
|
- Positive: app starts, migrations pass, dashboard + MCP API work.
|
||||||
|
- Negative:
|
||||||
|
- wrong hostname -> connection fails
|
||||||
|
- wrong CA file -> connection fails
|
||||||
|
- disable TLS on DB -> connection fails
|
||||||
|
|
||||||
|
This ensures no silent downgrade to weak TLS in production.
|
||||||
Reference in New Issue
Block a user