Compare commits
10 Commits
secrets-mc
...
secrets-mc
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
409fd78a35 | ||
|
|
f7afd7f819 | ||
|
|
719bdd7e08 | ||
|
|
1e597559a2 | ||
|
|
e3ca43ca3f | ||
|
|
0b57605103 | ||
|
|
8b191937cd | ||
|
|
11c936a5b8 | ||
|
|
b6349dd1c8 | ||
|
|
f720983328 |
64
AGENTS.md
64
AGENTS.md
@@ -2,12 +2,13 @@
|
|||||||
|
|
||||||
本仓库为 **MCP SaaS**:`secrets-core`(业务与持久化)+ `secrets-mcp`(Streamable HTTP MCP、Web、OAuth、API Key)。对外入口见 `crates/secrets-mcp`。
|
本仓库为 **MCP SaaS**:`secrets-core`(业务与持久化)+ `secrets-mcp`(Streamable HTTP MCP、Web、OAuth、API Key)。对外入口见 `crates/secrets-mcp`。
|
||||||
|
|
||||||
## 提交 / 发版硬规则(优先于下文)
|
## 提交 / 推送硬规则(优先于下文)
|
||||||
|
|
||||||
|
**每次提交和推送前必须执行以下检查,无论是否明确「发版」:**
|
||||||
|
|
||||||
1. 涉及 `crates/**`、根目录 `Cargo.toml`/`Cargo.lock`、`secrets-mcp` 行为变更的提交,默认视为**需要发版**,除非明确说明「本次不发版」。
|
1. 涉及 `crates/**`、根目录 `Cargo.toml`/`Cargo.lock`、`secrets-mcp` 行为变更的提交,默认视为**需要发版**,除非明确说明「本次不发版」。
|
||||||
2. 发版前检查 `crates/secrets-mcp/Cargo.toml` 的 `version`,再查 tag:`git tag -l 'secrets-mcp-*'`。
|
2. 提交前检查 `crates/secrets-mcp/Cargo.toml` 的 `version`,再查 tag:`git tag -l 'secrets-mcp-*'`。若当前版本对应 tag 已存在且有代码变更,**必须 bump 版本号**并 `cargo build` 同步 `Cargo.lock`。
|
||||||
3. 若当前版本对应 tag 已存在,默认允许复用现有 tag 继续构建;仅在需要新的发布版本时再 bump `version` 并 `cargo build` 同步 `Cargo.lock`。
|
3. 提交前运行 `./scripts/release-check.sh`(版本/tag + `fmt` + `clippy --locked` + `test --locked`)。若脚本不存在或不可用,至少运行 `cargo fmt -- --check && cargo clippy --locked -- -D warnings && cargo test --locked`。
|
||||||
4. 提交前优先运行 `./scripts/release-check.sh`(版本/tag + `fmt` + `clippy --locked` + `test --locked`)。
|
|
||||||
|
|
||||||
## 项目结构
|
## 项目结构
|
||||||
|
|
||||||
@@ -28,7 +29,8 @@ secrets/
|
|||||||
|
|
||||||
- **建议库名**:`secrets-mcp`(专用实例,与历史库名区分)。
|
- **建议库名**:`secrets-mcp`(专用实例,与历史库名区分)。
|
||||||
- **连接**:环境变量 **`SECRETS_DATABASE_URL`**(本分支无本地配置文件路径)。
|
- **连接**:环境变量 **`SECRETS_DATABASE_URL`**(本分支无本地配置文件路径)。
|
||||||
- **表**:`entries`(含 `user_id`)、`secrets`、`entries_history`、`secrets_history`、`audit_log`、`users`、`oauth_accounts`、`api_keys`,首次连接 **auto-migrate**。
|
- **表**:`entries`(含 `user_id`)、`secrets`、`entries_history`、`secrets_history`、`audit_log`、`users`、`oauth_accounts`,首次连接 **auto-migrate**(`secrets-core` 的 `migrate`)。
|
||||||
|
- **Web 会话**:与上项 **同一数据库 URL**;`secrets-mcp` 启动时对 tower-sessions 的 PostgreSQL 存储 **auto-migrate**(会话表与业务表共存于该实例,无需第二套连接串)。
|
||||||
|
|
||||||
### 表结构(摘录)
|
### 表结构(摘录)
|
||||||
|
|
||||||
@@ -36,15 +38,18 @@ secrets/
|
|||||||
entries (
|
entries (
|
||||||
id UUID PRIMARY KEY DEFAULT uuidv7(),
|
id UUID PRIMARY KEY DEFAULT uuidv7(),
|
||||||
user_id UUID, -- 多租户:NULL=遗留行;非空=归属用户
|
user_id UUID, -- 多租户:NULL=遗留行;非空=归属用户
|
||||||
namespace VARCHAR(64) NOT NULL,
|
folder VARCHAR(128) NOT NULL DEFAULT '',
|
||||||
kind VARCHAR(64) NOT NULL,
|
type VARCHAR(64) NOT NULL DEFAULT '',
|
||||||
name VARCHAR(256) NOT NULL,
|
name VARCHAR(256) NOT NULL,
|
||||||
|
notes TEXT NOT NULL DEFAULT '',
|
||||||
tags TEXT[] NOT NULL DEFAULT '{}',
|
tags TEXT[] NOT NULL DEFAULT '{}',
|
||||||
metadata JSONB NOT NULL DEFAULT '{}',
|
metadata JSONB NOT NULL DEFAULT '{}',
|
||||||
version BIGINT NOT NULL DEFAULT 1,
|
version BIGINT NOT NULL DEFAULT 1,
|
||||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||||
)
|
)
|
||||||
|
-- 唯一:UNIQUE(user_id, folder, name) WHERE user_id IS NOT NULL;
|
||||||
|
-- UNIQUE(folder, name) WHERE user_id IS NULL(单租户遗留)
|
||||||
```
|
```
|
||||||
|
|
||||||
```sql
|
```sql
|
||||||
@@ -60,7 +65,7 @@ secrets (
|
|||||||
)
|
)
|
||||||
```
|
```
|
||||||
|
|
||||||
### users / oauth_accounts / api_keys
|
### users / oauth_accounts
|
||||||
|
|
||||||
```sql
|
```sql
|
||||||
users (
|
users (
|
||||||
@@ -71,6 +76,7 @@ users (
|
|||||||
key_salt BYTEA, -- PBKDF2 salt(32B),首次设置密码短语时写入
|
key_salt BYTEA, -- PBKDF2 salt(32B),首次设置密码短语时写入
|
||||||
key_check BYTEA, -- 派生密钥加密已知常量,用于验证密码短语
|
key_check BYTEA, -- 派生密钥加密已知常量,用于验证密码短语
|
||||||
key_params JSONB, -- 算法参数,如 {"alg":"pbkdf2-sha256","iterations":600000}
|
key_params JSONB, -- 算法参数,如 {"alg":"pbkdf2-sha256","iterations":600000}
|
||||||
|
api_key TEXT UNIQUE, -- MCP Bearer token(当前实现为明文存储)
|
||||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||||
)
|
)
|
||||||
@@ -80,32 +86,31 @@ oauth_accounts (
|
|||||||
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||||
provider VARCHAR(32) NOT NULL,
|
provider VARCHAR(32) NOT NULL,
|
||||||
provider_id VARCHAR(256) NOT NULL,
|
provider_id VARCHAR(256) NOT NULL,
|
||||||
...
|
email VARCHAR(256),
|
||||||
|
name VARCHAR(256),
|
||||||
|
avatar_url TEXT,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
UNIQUE(provider, provider_id)
|
UNIQUE(provider, provider_id)
|
||||||
)
|
)
|
||||||
|
-- 另有唯一索引 UNIQUE(user_id, provider)(迁移中 idx_oauth_accounts_user_provider):同一用户每种 provider 至多一条关联。
|
||||||
api_keys (
|
|
||||||
id UUID PRIMARY KEY DEFAULT uuidv7(),
|
|
||||||
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
|
||||||
name VARCHAR(256) NOT NULL,
|
|
||||||
key_hash VARCHAR(64) NOT NULL UNIQUE,
|
|
||||||
key_prefix VARCHAR(12) NOT NULL,
|
|
||||||
last_used_at TIMESTAMPTZ,
|
|
||||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
|
||||||
)
|
|
||||||
```
|
```
|
||||||
|
|
||||||
### audit_log / history
|
### audit_log / history
|
||||||
|
|
||||||
与迁移脚本一致:`audit_log`、`entries_history`、`secrets_history` 用于审计与时间旅行恢复;字段定义见 `crates/secrets-core/src/db.rs` 内 `migrate` SQL。
|
与迁移脚本一致:`audit_log`、`entries_history`、`secrets_history` 用于审计与时间旅行恢复;字段定义见 `crates/secrets-core/src/db.rs` 内 `migrate` SQL。`audit_log` 含可选 **`user_id`**(多租户下标识操作者;可空以兼容遗留数据)。`audit_log` 中普通业务事件使用 **`folder` / `type` / `name`** 对应 entry 坐标;登录类事件固定使用 **`folder='auth'`**,此时 `type`/`name` 表示认证目标而非 entry 身份。
|
||||||
|
|
||||||
|
### MCP 消歧(AI 调用)
|
||||||
|
|
||||||
|
按 `name` 定位条目的工具(`get` / `update` / 单条 `delete` / `history` / `rollback`):若该用户下仅一条匹配则直接执行;若多条(同 `name`、不同 `folder`)则返回错误并提示补全 `folder`。`secrets_delete` 的 `dry_run=true` 与真实删除使用相同消歧规则。
|
||||||
|
|
||||||
### 字段职责
|
### 字段职责
|
||||||
|
|
||||||
| 字段 | 含义 | 示例 |
|
| 字段 | 含义 | 示例 |
|
||||||
|------|------|------|
|
|------|------|------|
|
||||||
| `namespace` | 隔离空间 | `refining` |
|
| `folder` | 隔离空间(参与唯一键) | `refining` |
|
||||||
| `kind` | 记录类型 | `server`, `service`, `key` |
|
| `type` | 软分类(不参与唯一键) | `server`, `service`, `key`, `person` |
|
||||||
| `name` | 标识名 | `gitea`, `i-example0…` |
|
| `name` | 标识名 | `gitea`, `aliyun` |
|
||||||
|
| `notes` | 非敏感说明 | 自由文本 |
|
||||||
| `tags` | 标签 | `["aliyun","prod"]` |
|
| `tags` | 标签 | `["aliyun","prod"]` |
|
||||||
| `metadata` | 明文描述 | `ip`、`url`、`key_ref` |
|
| `metadata` | 明文描述 | `ip`、`url`、`key_ref` |
|
||||||
| `secrets.field_name` | 加密字段名(明文) | `token`, `ssh_key` |
|
| `secrets.field_name` | 加密字段名(明文) | `token`, `ssh_key` |
|
||||||
@@ -113,14 +118,14 @@ api_keys (
|
|||||||
|
|
||||||
### PEM 共享(`key_ref`)
|
### PEM 共享(`key_ref`)
|
||||||
|
|
||||||
将共享 PEM 存为 `kind=key` 的 entry;其它记录在 `metadata.key_ref` 指向该 key 的 `name`。更新 key 记录后,引用方通过服务层解析合并逻辑即可使用新密钥(实现见 `secrets_core::service`)。
|
将共享 PEM 存为 **`type=key`** 的 entry;其它记录在 `metadata.key_ref` 指向该 key 的 `name`。更新 key 记录后,引用方通过服务层解析合并逻辑即可使用新密钥(实现见 `secrets_core::service`)。
|
||||||
|
|
||||||
## 代码规范
|
## 代码规范
|
||||||
|
|
||||||
- 错误:业务层 `anyhow::Result`,避免生产路径 `unwrap()`。
|
- 错误:业务层 `anyhow::Result`,避免生产路径 `unwrap()`。
|
||||||
- 异步:`tokio` + `sqlx` async。
|
- 异步:`tokio` + `sqlx` async。
|
||||||
- SQL:`sqlx::query` / `query_as` 参数绑定;动态 WHERE 仍须用占位符绑定。
|
- SQL:`sqlx::query` / `query_as` 参数绑定;动态 WHERE 仍须用占位符绑定。
|
||||||
- 日志:运维用 `tracing`;面向用户的 Web 响应走 axum handler。
|
- 日志:运维用 `tracing`;面向用户的 Web 响应走 axum handler。tracing 字段风格:变量名即字段名时用简写(`%var`、`?var`、`var`),否则用显式形式(`field = %expr`)。
|
||||||
- 审计:写操作成功后尽量 `audit::log_tx`;失败可 `warn`,不掩盖主错误。
|
- 审计:写操作成功后尽量 `audit::log_tx`;失败可 `warn`,不掩盖主错误。
|
||||||
- 加密:密钥由用户密码短语通过 **PBKDF2-SHA256(600k 次)** 在客户端派生,服务端只存 `key_salt`/`key_check`/`key_params`,不持有原始密钥。Web 客户端在浏览器本地完成加解密;MCP 客户端通过 `X-Encryption-Key` 请求头传递密钥,服务端临时解密后返回明文。
|
- 加密:密钥由用户密码短语通过 **PBKDF2-SHA256(600k 次)** 在客户端派生,服务端只存 `key_salt`/`key_check`/`key_params`,不持有原始密钥。Web 客户端在浏览器本地完成加解密;MCP 客户端通过 `X-Encryption-Key` 请求头传递密钥,服务端临时解密后返回明文。
|
||||||
- MCP:tools 参数与 JSON Schema(`schemars`)保持同步,鉴权以请求扩展中的用户上下文为准。
|
- MCP:tools 参数与 JSON Schema(`schemars`)保持同步,鉴权以请求扩展中的用户上下文为准。
|
||||||
@@ -148,10 +153,10 @@ git tag -l 'secrets-mcp-*'
|
|||||||
|
|
||||||
## CI/CD
|
## CI/CD
|
||||||
|
|
||||||
- **触发**:任意分支 `push`,且路径含 `crates/**`、`deploy/**`、根目录 `Cargo.toml`、`Cargo.lock`(见 `.gitea/workflows/secrets.yml`)。
|
- **触发**:任意分支 `push`,且路径含 `crates/**`、`deploy/**`、根目录 `Cargo.toml`、`Cargo.lock`、`.gitea/workflows/**`(见 `.gitea/workflows/secrets.yml`)。
|
||||||
- **版本与 tag**:从 `crates/secrets-mcp/Cargo.toml` 读版本;若远程已存在同名 `secrets-mcp-<version>` tag,则复用现有 tag 继续构建;否则由 CI 创建并推送该 tag。
|
- **版本与 tag**:从 `crates/secrets-mcp/Cargo.toml` 读版本;构建成功后打 `secrets-mcp-<version>`:若远端已存在同名 tag,CI 会先删后于**当前提交**重建并推送(覆盖式发版)。
|
||||||
- **质量与构建**:`fmt` / `clippy --locked` / `test --locked` → `x86_64-unknown-linux-musl` 发布构建 `secrets-mcp`。
|
- **质量与构建**:`fmt` / `clippy --locked` / `test --locked` → `x86_64-unknown-linux-musl` 发布构建 `secrets-mcp`。
|
||||||
- **Release(可选)**:`secrets.RELEASE_TOKEN`(Gitea PAT)用于创建草稿 Release、上传 `tar.gz` + `.sha256`、构建成功后发布;未配置则跳过 API Release,仅 tag + 构建。
|
- **Release(可选)**:`secrets.RELEASE_TOKEN`(Gitea PAT)用于通过 API **创建或更新**该 tag 的 Release(非 draft)、上传 `tar.gz` + `.sha256`;未配置则跳过 API Release,仅 tag + 构建。
|
||||||
- **部署(可选)**:仅 `main`、`feat/mcp`、`mcp` 分支在构建成功时跑 `deploy-mcp`;需 `vars.DEPLOY_HOST`、`vars.DEPLOY_USER`、`secrets.DEPLOY_SSH_KEY`。勿把 OAuth/DB 等写进 workflow,用 `deploy/.env.example` 在目标机配置。
|
- **部署(可选)**:仅 `main`、`feat/mcp`、`mcp` 分支在构建成功时跑 `deploy-mcp`;需 `vars.DEPLOY_HOST`、`vars.DEPLOY_USER`、`secrets.DEPLOY_SSH_KEY`。勿把 OAuth/DB 等写进 workflow,用 `deploy/.env.example` 在目标机配置。
|
||||||
- **Secrets 写法**:Actions **secrets 须为原始值**(PEM、PAT 明文),**勿** base64;否则 SSH/Release 会失败。**勿**在 CI 中保存 `GOOGLE_CLIENT_SECRET`、DB 密码。
|
- **Secrets 写法**:Actions **secrets 须为原始值**(PEM、PAT 明文),**勿** base64;否则 SSH/Release 会失败。**勿**在 CI 中保存 `GOOGLE_CLIENT_SECRET`、DB 密码。
|
||||||
- **通知**:`vars.WEBHOOK_URL`(可选,飞书)。
|
- **通知**:`vars.WEBHOOK_URL`(可选,飞书)。
|
||||||
@@ -162,9 +167,8 @@ git tag -l 'secrets-mcp-*'
|
|||||||
|------|------|
|
|------|------|
|
||||||
| `SECRETS_DATABASE_URL` | **必填**。PostgreSQL URL。 |
|
| `SECRETS_DATABASE_URL` | **必填**。PostgreSQL URL。 |
|
||||||
| `BASE_URL` | 对外基址;OAuth 回调 `${BASE_URL}/auth/google/callback`。 |
|
| `BASE_URL` | 对外基址;OAuth 回调 `${BASE_URL}/auth/google/callback`。 |
|
||||||
| `SECRETS_MCP_BIND` | 监听地址,默认 `0.0.0.0:9315`。 |
|
| `SECRETS_MCP_BIND` | 监听地址,默认 `127.0.0.1:9315`(容器/远程直接暴露时需改为 `0.0.0.0:9315`)。 |
|
||||||
| `GOOGLE_CLIENT_ID` / `GOOGLE_CLIENT_SECRET` | 可选;仅运行时配置。 |
|
| `GOOGLE_CLIENT_ID` / `GOOGLE_CLIENT_SECRET` | 可选;仅运行时配置。 |
|
||||||
| `RUST_LOG` | 如 `secrets_mcp=debug`。 |
|
| `RUST_LOG` | 如 `secrets_mcp=debug`。 |
|
||||||
| `USER` | 若写入审计 `actor`,由运行环境提供。 |
|
|
||||||
|
|
||||||
> `SERVER_MASTER_KEY` 已不再需要。新架构下密钥由用户密码短语在客户端派生,服务端不持有。
|
> `SERVER_MASTER_KEY` 已不再需要。新架构下密钥由用户密码短语在客户端派生,服务端不持有。
|
||||||
|
|||||||
40
Cargo.lock
generated
40
Cargo.lock
generated
@@ -1809,6 +1809,25 @@ dependencies = [
|
|||||||
"syn",
|
"syn",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "rmp"
|
||||||
|
version = "0.8.15"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "4ba8be72d372b2c9b35542551678538b562e7cf86c3315773cae48dfbfe7790c"
|
||||||
|
dependencies = [
|
||||||
|
"num-traits",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "rmp-serde"
|
||||||
|
version = "1.3.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "72f81bee8c8ef9b577d1681a70ebbc962c232461e397b22c208c43c04b67a155"
|
||||||
|
dependencies = [
|
||||||
|
"rmp",
|
||||||
|
"serde",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "rsa"
|
name = "rsa"
|
||||||
version = "0.9.10"
|
version = "0.9.10"
|
||||||
@@ -1949,7 +1968,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "secrets-mcp"
|
name = "secrets-mcp"
|
||||||
version = "0.1.9"
|
version = "0.3.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"anyhow",
|
"anyhow",
|
||||||
"askama",
|
"askama",
|
||||||
@@ -1967,10 +1986,12 @@ dependencies = [
|
|||||||
"serde_json",
|
"serde_json",
|
||||||
"sha2",
|
"sha2",
|
||||||
"sqlx",
|
"sqlx",
|
||||||
|
"time",
|
||||||
"tokio",
|
"tokio",
|
||||||
"tower",
|
"tower",
|
||||||
"tower-http",
|
"tower-http",
|
||||||
"tower-sessions",
|
"tower-sessions",
|
||||||
|
"tower-sessions-sqlx-store-chrono",
|
||||||
"tracing",
|
"tracing",
|
||||||
"tracing-subscriber",
|
"tracing-subscriber",
|
||||||
"urlencoding",
|
"urlencoding",
|
||||||
@@ -2700,6 +2721,7 @@ dependencies = [
|
|||||||
"tower",
|
"tower",
|
||||||
"tower-layer",
|
"tower-layer",
|
||||||
"tower-service",
|
"tower-service",
|
||||||
|
"tracing",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -2765,6 +2787,22 @@ dependencies = [
|
|||||||
"tower-sessions-core",
|
"tower-sessions-core",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "tower-sessions-sqlx-store-chrono"
|
||||||
|
version = "0.14.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "b295c8fc08db03246e92773c5e10119b72db6bc4240112135bebb0e49670804f"
|
||||||
|
dependencies = [
|
||||||
|
"async-trait",
|
||||||
|
"axum",
|
||||||
|
"chrono",
|
||||||
|
"rmp-serde",
|
||||||
|
"sqlx",
|
||||||
|
"thiserror",
|
||||||
|
"time",
|
||||||
|
"tower-sessions-core",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "tracing"
|
name = "tracing"
|
||||||
version = "0.1.44"
|
version = "0.1.44"
|
||||||
|
|||||||
38
README.md
38
README.md
@@ -19,15 +19,24 @@ cargo build --release -p secrets-mcp
|
|||||||
|------|------|
|
|------|------|
|
||||||
| `SECRETS_DATABASE_URL` | **必填**。PostgreSQL 连接串(建议专用库,如 `secrets-mcp`)。 |
|
| `SECRETS_DATABASE_URL` | **必填**。PostgreSQL 连接串(建议专用库,如 `secrets-mcp`)。 |
|
||||||
| `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` | 监听地址,默认 `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、勿打入二进制。 |
|
||||||
|
| `RUST_LOG` | 可选;日志级别,如 `secrets_mcp=debug`。 |
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
cargo run -p secrets-mcp
|
cargo run -p secrets-mcp
|
||||||
```
|
```
|
||||||
|
|
||||||
- **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>` 请求头(读密文工具须带密钥)。
|
||||||
|
|
||||||
|
## MCP 与 AI 工作流(v0.3+)
|
||||||
|
|
||||||
|
条目在逻辑上以 **`(folder, name)`** 在用户内唯一(数据库唯一索引:`user_id + folder + name`)。同名可在不同 folder 下各存一条(例如 `refining/aliyun` 与 `ricnsmart/aliyun`)。
|
||||||
|
|
||||||
|
- **`secrets_search`**:发现条目(可按 query / folder / type / name 过滤);不要求加密头。
|
||||||
|
- **`secrets_get` / `secrets_update` / `secrets_delete`(按 name)/ `secrets_history` / `secrets_rollback`**:仅 `name` 且全局唯一则直接命中;若多条同名,返回消歧错误,需在参数中补 **`folder`**。
|
||||||
|
- **`secrets_delete`**:`dry_run=true` 时与真实删除相同的消歧规则——唯一则预览一条,多条则报错并要求 `folder`。
|
||||||
|
|
||||||
## 加密架构(混合 E2EE)
|
## 加密架构(混合 E2EE)
|
||||||
|
|
||||||
@@ -77,7 +86,7 @@ flowchart LR
|
|||||||
### 敏感数据传输
|
### 敏感数据传输
|
||||||
|
|
||||||
- **OAuth `client_secret`** 只存服务端环境变量,不发给浏览器
|
- **OAuth `client_secret`** 只存服务端环境变量,不发给浏览器
|
||||||
- **API Key** 创建时原始 key 仅展示一次,库中只存 SHA-256 哈希
|
- **API Key** 当前存放在 `users.api_key`,Dashboard 会明文展示并可重置
|
||||||
- **X-Encryption-Key** 随 MCP 请求经 TLS 传输,服务端仅在请求处理期间持有(不持久化)
|
- **X-Encryption-Key** 随 MCP 请求经 TLS 传输,服务端仅在请求处理期间持有(不持久化)
|
||||||
- **生产环境必须走 HTTPS/TLS**
|
- **生产环境必须走 HTTPS/TLS**
|
||||||
|
|
||||||
@@ -121,13 +130,14 @@ flowchart LR
|
|||||||
|
|
||||||
## 数据模型
|
## 数据模型
|
||||||
|
|
||||||
主表 **`entries`**(`namespace`、`kind`、`name`、`tags`、`metadata`,多租户时带 `user_id`)+ 子表 **`secrets`**(每行一个加密字段:`field_name`、`encrypted`)。另有 `entries_history`、`secrets_history`、`audit_log`,以及 **`users`**(含 `key_salt`、`key_check`、`key_params`)、**`oauth_accounts`**、**`api_keys`**。首次连库自动迁移建表。
|
主表 **`entries`**(`folder`、`type`、`name`、`notes`、`tags`、`metadata`,多租户时带 `user_id`)+ 子表 **`secrets`**(每行一个加密字段:`field_name`、`encrypted`)。**唯一性**:`UNIQUE(user_id, folder, name)`(`user_id` 为空时为遗留行唯一 `(folder, name)`)。另有 `entries_history`、`secrets_history`、`audit_log`,以及 **`users`**(含 `key_salt`、`key_check`、`key_params`、`api_key`)、**`oauth_accounts`**。首次连库自动迁移建表(`secrets-core` 的 `migrate`);已有库可对照 [`scripts/migrate-v0.3.0.sql`](scripts/migrate-v0.3.0.sql) 做列重命名与索引重建。**Web 登录会话**(tower-sessions)使用同一 `SECRETS_DATABASE_URL`,进程启动时对会话存储执行迁移(见 `secrets-mcp` 中 `PostgresStore::migrate`),无需额外环境变量。
|
||||||
|
|
||||||
| 位置 | 字段 | 说明 |
|
| 位置 | 字段 | 说明 |
|
||||||
|------|------|------|
|
|------|------|------|
|
||||||
| entries | namespace | 一级隔离,如 `refining`、`ricnsmart` |
|
| entries | folder | 组织/隔离空间,如 `refining`、`ricnsmart`;参与唯一键 |
|
||||||
| entries | kind | `server`、`service`、`key` 等(可扩展) |
|
| entries | type | 软分类,如 `server`、`service`、`key`、`person`(可扩展,不参与唯一键) |
|
||||||
| entries | name | 人类可读标识 |
|
| entries | name | 人类可读标识;与 `folder` 一起在用户内唯一 |
|
||||||
|
| entries | notes | 非敏感说明文本 |
|
||||||
| entries | metadata | 明文 JSON(ip、url、`key_ref` 等) |
|
| entries | metadata | 明文 JSON(ip、url、`key_ref` 等) |
|
||||||
| secrets | field_name | 明文字段名,便于 schema 展示 |
|
| secrets | field_name | 明文字段名,便于 schema 展示 |
|
||||||
| secrets | encrypted | AES-GCM 密文(含 nonce) |
|
| secrets | encrypted | AES-GCM 密文(含 nonce) |
|
||||||
@@ -137,14 +147,15 @@ flowchart LR
|
|||||||
|
|
||||||
### PEM 共享(`key_ref`)
|
### PEM 共享(`key_ref`)
|
||||||
|
|
||||||
同一 PEM 可被多条 `server` 记录引用:将 PEM 存为 `kind=key` 的 entry,在服务器条目的 `metadata.key_ref` 中写 key 的名称;轮换时只更新 key 对应记录即可。
|
同一 PEM 可被多条 `server` 等记录引用:将 PEM 存为 **`type=key`** 的 entry,在其它条目的 `metadata.key_ref` 中写该 key 条目的 `name`;轮换时只更新 key 对应记录即可。
|
||||||
|
|
||||||
## 审计日志
|
## 审计日志
|
||||||
|
|
||||||
`add`、`update`、`delete` 等写操作写入 **`audit_log`**(操作类型、对象、摘要,不含 secret 明文)。
|
`add`、`update`、`delete` 等写操作写入 **`audit_log`**(操作类型、对象、摘要,不含 secret 明文)。多租户场景下可写 **`user_id`**(可空,兼容遗留行)。
|
||||||
|
业务条目事件使用 **`folder` / `type` / `name`**;登录类事件使用 **`folder='auth'`**,此时 `type`/`name` 表示认证目标(例如 `oauth` / `google`),不表示某条 secrets entry。
|
||||||
|
|
||||||
```sql
|
```sql
|
||||||
SELECT action, namespace, kind, name, actor, detail, created_at
|
SELECT action, folder, type, name, detail, user_id, created_at
|
||||||
FROM audit_log
|
FROM audit_log
|
||||||
ORDER BY created_at DESC
|
ORDER BY created_at DESC
|
||||||
LIMIT 20;
|
LIMIT 20;
|
||||||
@@ -157,6 +168,7 @@ Cargo.toml
|
|||||||
crates/secrets-core/ # db / crypto / models / audit / service
|
crates/secrets-core/ # db / crypto / models / audit / service
|
||||||
crates/secrets-mcp/ # MCP HTTP、Web、OAuth、API Key
|
crates/secrets-mcp/ # MCP HTTP、Web、OAuth、API Key
|
||||||
scripts/
|
scripts/
|
||||||
|
migrate-v0.3.0.sql # 可选:手动 SQL 迁移(namespace/kind → folder/type、唯一键含 folder)
|
||||||
deploy/ # systemd、.env 示例
|
deploy/ # systemd、.env 示例
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -164,9 +176,9 @@ deploy/ # systemd、.env 示例
|
|||||||
|
|
||||||
见 [`.gitea/workflows/secrets.yml`](.gitea/workflows/secrets.yml)。
|
见 [`.gitea/workflows/secrets.yml`](.gitea/workflows/secrets.yml)。
|
||||||
|
|
||||||
- **触发**:任意分支 `push`,且变更路径包含 `crates/**`、`deploy/**`、根目录 `Cargo.toml` / `Cargo.lock`。
|
- **触发**:任意分支 `push`,且变更路径包含 `crates/**`、`deploy/**`、根目录 `Cargo.toml` / `Cargo.lock`、`.gitea/workflows/**`。
|
||||||
- **流水线**:解析 `crates/secrets-mcp/Cargo.toml` 版本 → 若 `secrets-mcp-<version>` 的 tag 已存在则**复用现有 tag 继续构建**,否则自动打 tag → `cargo fmt` / `clippy --locked` / `test --locked` → 交叉编译 `x86_64-unknown-linux-musl` 的 `secrets-mcp`。
|
- **流水线**:解析 `crates/secrets-mcp/Cargo.toml` 版本 → `cargo fmt` / `clippy --locked` / `test --locked` → 交叉编译 `x86_64-unknown-linux-musl` 的 `secrets-mcp` → 构建成功后打 tag `secrets-mcp-<version>`(若远端已存在同名 tag,会先删除再于**当前提交**重建并推送,覆盖式发版)。
|
||||||
- **Release(可选)**:配置仓库 Secret `RELEASE_TOKEN`(Gitea PAT,明文勿 base64)时,会通过 API 创建**草稿** Release、在 Linux 构建成功后上传 `tar.gz` 与 `.sha256`,再自动将草稿**正式发布**;未配置则跳过创建 Release 与产物上传,仅保留 tag 与构建结果。
|
- **Release(可选)**:配置仓库 Secret `RELEASE_TOKEN`(Gitea PAT,明文勿 base64)时,会通过 API **创建或更新**已指向该 tag 的 Release(非 draft)、上传 `tar.gz` 与 `.sha256`;未配置则跳过 API Release,仅 tag + 构建结果。
|
||||||
- **部署(可选)**:仅在 `main`、`feat/mcp` 或 `mcp` 分支且构建成功时,若已配置 `vars.DEPLOY_HOST`、`vars.DEPLOY_USER` 与 `secrets.DEPLOY_SSH_KEY`,则 `deploy-mcp` 通过 SCP/SSH 更新目标机二进制并 `systemctl restart secrets-mcp`。
|
- **部署(可选)**:仅在 `main`、`feat/mcp` 或 `mcp` 分支且构建成功时,若已配置 `vars.DEPLOY_HOST`、`vars.DEPLOY_USER` 与 `secrets.DEPLOY_SSH_KEY`,则 `deploy-mcp` 通过 SCP/SSH 更新目标机二进制并 `systemctl restart secrets-mcp`。
|
||||||
- **通知(可选)**:`vars.WEBHOOK_URL` 为飞书 Webhook 时,构建/部署/发布节点会推送简要状态。
|
- **通知(可选)**:`vars.WEBHOOK_URL` 为飞书 Webhook 时,构建/部署/发布节点会推送简要状态。
|
||||||
|
|
||||||
|
|||||||
@@ -3,12 +3,7 @@ use sqlx::{PgPool, Postgres, Transaction};
|
|||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
|
|
||||||
pub const ACTION_LOGIN: &str = "login";
|
pub const ACTION_LOGIN: &str = "login";
|
||||||
pub const NAMESPACE_AUTH: &str = "auth";
|
pub const FOLDER_AUTH: &str = "auth";
|
||||||
|
|
||||||
/// Return the current OS user as the audit actor (falls back to empty string).
|
|
||||||
pub fn current_actor() -> String {
|
|
||||||
std::env::var("USER").unwrap_or_default()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn login_detail(provider: &str, client_ip: Option<&str>, user_agent: Option<&str>) -> Value {
|
fn login_detail(provider: &str, client_ip: Option<&str>, user_agent: Option<&str>) -> Value {
|
||||||
json!({
|
json!({
|
||||||
@@ -21,32 +16,30 @@ fn login_detail(provider: &str, client_ip: Option<&str>, user_agent: Option<&str
|
|||||||
/// Write a login audit entry without requiring an explicit transaction.
|
/// Write a login audit entry without requiring an explicit transaction.
|
||||||
pub async fn log_login(
|
pub async fn log_login(
|
||||||
pool: &PgPool,
|
pool: &PgPool,
|
||||||
kind: &str,
|
entry_type: &str,
|
||||||
provider: &str,
|
provider: &str,
|
||||||
user_id: Uuid,
|
user_id: Uuid,
|
||||||
client_ip: Option<&str>,
|
client_ip: Option<&str>,
|
||||||
user_agent: Option<&str>,
|
user_agent: Option<&str>,
|
||||||
) {
|
) {
|
||||||
let actor = current_actor();
|
|
||||||
let detail = login_detail(provider, client_ip, user_agent);
|
let detail = login_detail(provider, client_ip, user_agent);
|
||||||
let result: Result<_, sqlx::Error> = sqlx::query(
|
let result: Result<_, sqlx::Error> = sqlx::query(
|
||||||
"INSERT INTO audit_log (user_id, action, namespace, kind, name, detail, actor) \
|
"INSERT INTO audit_log (user_id, action, folder, type, name, detail) \
|
||||||
VALUES ($1, $2, $3, $4, $5, $6, $7)",
|
VALUES ($1, $2, $3, $4, $5, $6)",
|
||||||
)
|
)
|
||||||
.bind(user_id)
|
.bind(user_id)
|
||||||
.bind(ACTION_LOGIN)
|
.bind(ACTION_LOGIN)
|
||||||
.bind(NAMESPACE_AUTH)
|
.bind(FOLDER_AUTH)
|
||||||
.bind(kind)
|
.bind(entry_type)
|
||||||
.bind(provider)
|
.bind(provider)
|
||||||
.bind(&detail)
|
.bind(&detail)
|
||||||
.bind(&actor)
|
|
||||||
.execute(pool)
|
.execute(pool)
|
||||||
.await;
|
.await;
|
||||||
|
|
||||||
if let Err(e) = result {
|
if let Err(e) = result {
|
||||||
tracing::warn!(error = %e, kind, provider, "failed to write login audit log");
|
tracing::warn!(error = %e, entry_type, provider, "failed to write login audit log");
|
||||||
} else {
|
} else {
|
||||||
tracing::debug!(kind, provider, ?user_id, actor, "login audit logged");
|
tracing::debug!(entry_type, provider, ?user_id, "login audit logged");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -55,30 +48,28 @@ pub async fn log_tx(
|
|||||||
tx: &mut Transaction<'_, Postgres>,
|
tx: &mut Transaction<'_, Postgres>,
|
||||||
user_id: Option<Uuid>,
|
user_id: Option<Uuid>,
|
||||||
action: &str,
|
action: &str,
|
||||||
namespace: &str,
|
folder: &str,
|
||||||
kind: &str,
|
entry_type: &str,
|
||||||
name: &str,
|
name: &str,
|
||||||
detail: Value,
|
detail: Value,
|
||||||
) {
|
) {
|
||||||
let actor = current_actor();
|
|
||||||
let result: Result<_, sqlx::Error> = sqlx::query(
|
let result: Result<_, sqlx::Error> = sqlx::query(
|
||||||
"INSERT INTO audit_log (user_id, action, namespace, kind, name, detail, actor) \
|
"INSERT INTO audit_log (user_id, action, folder, type, name, detail) \
|
||||||
VALUES ($1, $2, $3, $4, $5, $6, $7)",
|
VALUES ($1, $2, $3, $4, $5, $6)",
|
||||||
)
|
)
|
||||||
.bind(user_id)
|
.bind(user_id)
|
||||||
.bind(action)
|
.bind(action)
|
||||||
.bind(namespace)
|
.bind(folder)
|
||||||
.bind(kind)
|
.bind(entry_type)
|
||||||
.bind(name)
|
.bind(name)
|
||||||
.bind(&detail)
|
.bind(&detail)
|
||||||
.bind(&actor)
|
|
||||||
.execute(&mut **tx)
|
.execute(&mut **tx)
|
||||||
.await;
|
.await;
|
||||||
|
|
||||||
if let Err(e) = result {
|
if let Err(e) = result {
|
||||||
tracing::warn!(error = %e, "failed to write audit log");
|
tracing::warn!(error = %e, "failed to write audit log");
|
||||||
} else {
|
} else {
|
||||||
tracing::debug!(action, namespace, kind, name, actor, "audit logged");
|
tracing::debug!(action, folder, entry_type, name, "audit logged");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -55,35 +55,6 @@ pub fn decrypt_json(master_key: &[u8; 32], data: &[u8]) -> Result<Value> {
|
|||||||
serde_json::from_slice(&bytes).context("deserialize decrypted JSON")
|
serde_json::from_slice(&bytes).context("deserialize decrypted JSON")
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─── Per-user key management (DEPRECATED — kept only for migration) ───────────
|
|
||||||
|
|
||||||
/// Generate a new random 32-byte per-user encryption key.
|
|
||||||
#[allow(dead_code)]
|
|
||||||
pub fn generate_user_key() -> [u8; 32] {
|
|
||||||
use aes_gcm::aead::rand_core::RngCore;
|
|
||||||
let mut key = [0u8; 32];
|
|
||||||
OsRng.fill_bytes(&mut key);
|
|
||||||
key
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Wrap a per-user key with the server master key using AES-256-GCM.
|
|
||||||
#[allow(dead_code)]
|
|
||||||
pub fn wrap_user_key(server_master_key: &[u8; 32], user_key: &[u8; 32]) -> Result<Vec<u8>> {
|
|
||||||
encrypt(server_master_key, user_key.as_ref())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Unwrap a per-user key using the server master key.
|
|
||||||
#[allow(dead_code)]
|
|
||||||
pub fn unwrap_user_key(server_master_key: &[u8; 32], wrapped: &[u8]) -> Result<[u8; 32]> {
|
|
||||||
let bytes = decrypt(server_master_key, wrapped)?;
|
|
||||||
if bytes.len() != 32 {
|
|
||||||
bail!("unwrapped user key has unexpected length {}", bytes.len());
|
|
||||||
}
|
|
||||||
let mut key = [0u8; 32];
|
|
||||||
key.copy_from_slice(&bytes);
|
|
||||||
Ok(key)
|
|
||||||
}
|
|
||||||
|
|
||||||
// ─── Client-supplied key extraction ──────────────────────────────────────────
|
// ─── Client-supplied key extraction ──────────────────────────────────────────
|
||||||
|
|
||||||
/// Parse a 64-char hex string (from X-Encryption-Key header) into a 32-byte key.
|
/// Parse a 64-char hex string (from X-Encryption-Key header) into a 32-byte key.
|
||||||
@@ -100,33 +71,6 @@ pub fn extract_key_from_hex(hex_str: &str) -> Result<[u8; 32]> {
|
|||||||
Ok(key)
|
Ok(key)
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─── Server master key ────────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
/// Load the server master key from `SERVER_MASTER_KEY` environment variable (64 hex chars).
|
|
||||||
pub fn load_master_key_auto() -> Result<[u8; 32]> {
|
|
||||||
let hex_str = std::env::var("SERVER_MASTER_KEY").map_err(|_| {
|
|
||||||
anyhow::anyhow!(
|
|
||||||
"SERVER_MASTER_KEY is not set. \
|
|
||||||
Generate one with: openssl rand -hex 32"
|
|
||||||
)
|
|
||||||
})?;
|
|
||||||
|
|
||||||
if hex_str.is_empty() {
|
|
||||||
bail!("SERVER_MASTER_KEY is set but empty");
|
|
||||||
}
|
|
||||||
|
|
||||||
let bytes = hex::decode_hex(hex_str.trim())?;
|
|
||||||
if bytes.len() != 32 {
|
|
||||||
bail!(
|
|
||||||
"SERVER_MASTER_KEY must be 64 hex chars (32 bytes), got {} bytes",
|
|
||||||
bytes.len()
|
|
||||||
);
|
|
||||||
}
|
|
||||||
let mut key = [0u8; 32];
|
|
||||||
key.copy_from_slice(&bytes);
|
|
||||||
Ok(key)
|
|
||||||
}
|
|
||||||
|
|
||||||
// ─── Public hex helpers ───────────────────────────────────────────────────────
|
// ─── Public hex helpers ───────────────────────────────────────────────────────
|
||||||
|
|
||||||
pub mod hex {
|
pub mod hex {
|
||||||
@@ -186,22 +130,4 @@ mod tests {
|
|||||||
let dec = decrypt_json(&key, &enc).unwrap();
|
let dec = decrypt_json(&key, &enc).unwrap();
|
||||||
assert_eq!(dec, value);
|
assert_eq!(dec, value);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn user_key_wrap_unwrap_roundtrip() {
|
|
||||||
let server_key = [0xABu8; 32];
|
|
||||||
let user_key = [0xCDu8; 32];
|
|
||||||
let wrapped = wrap_user_key(&server_key, &user_key).unwrap();
|
|
||||||
let unwrapped = unwrap_user_key(&server_key, &wrapped).unwrap();
|
|
||||||
assert_eq!(unwrapped, user_key);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn user_key_wrap_wrong_server_key_fails() {
|
|
||||||
let server_key1 = [0xABu8; 32];
|
|
||||||
let server_key2 = [0xEFu8; 32];
|
|
||||||
let user_key = [0xCDu8; 32];
|
|
||||||
let wrapped = wrap_user_key(&server_key1, &user_key).unwrap();
|
|
||||||
assert!(unwrap_user_key(&server_key2, &wrapped).is_err());
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,8 +3,6 @@ use serde_json::Value;
|
|||||||
use sqlx::PgPool;
|
use sqlx::PgPool;
|
||||||
use sqlx::postgres::PgPoolOptions;
|
use sqlx::postgres::PgPoolOptions;
|
||||||
|
|
||||||
use crate::audit::current_actor;
|
|
||||||
|
|
||||||
pub async fn create_pool(database_url: &str) -> Result<PgPool> {
|
pub async fn create_pool(database_url: &str) -> Result<PgPool> {
|
||||||
tracing::debug!("connecting to database");
|
tracing::debug!("connecting to database");
|
||||||
let pool = PgPoolOptions::new()
|
let pool = PgPoolOptions::new()
|
||||||
@@ -24,9 +22,10 @@ pub async fn migrate(pool: &PgPool) -> Result<()> {
|
|||||||
CREATE TABLE IF NOT EXISTS entries (
|
CREATE TABLE IF NOT EXISTS entries (
|
||||||
id UUID PRIMARY KEY DEFAULT uuidv7(),
|
id UUID PRIMARY KEY DEFAULT uuidv7(),
|
||||||
user_id UUID,
|
user_id UUID,
|
||||||
namespace VARCHAR(64) NOT NULL,
|
folder VARCHAR(128) NOT NULL DEFAULT '',
|
||||||
kind VARCHAR(64) NOT NULL,
|
type VARCHAR(64) NOT NULL DEFAULT '',
|
||||||
name VARCHAR(256) NOT NULL,
|
name VARCHAR(256) NOT NULL,
|
||||||
|
notes TEXT NOT NULL DEFAULT '',
|
||||||
tags TEXT[] NOT NULL DEFAULT '{}',
|
tags TEXT[] NOT NULL DEFAULT '{}',
|
||||||
metadata JSONB NOT NULL DEFAULT '{}',
|
metadata JSONB NOT NULL DEFAULT '{}',
|
||||||
version BIGINT NOT NULL DEFAULT 1,
|
version BIGINT NOT NULL DEFAULT 1,
|
||||||
@@ -36,19 +35,19 @@ pub async fn migrate(pool: &PgPool) -> Result<()> {
|
|||||||
|
|
||||||
-- Legacy unique constraint without user_id (single-user mode)
|
-- Legacy unique constraint without user_id (single-user mode)
|
||||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_entries_unique_legacy
|
CREATE UNIQUE INDEX IF NOT EXISTS idx_entries_unique_legacy
|
||||||
ON entries(namespace, kind, name)
|
ON entries(folder, name)
|
||||||
WHERE user_id IS NULL;
|
WHERE user_id IS NULL;
|
||||||
|
|
||||||
-- Multi-user unique constraint
|
-- Multi-user unique constraint
|
||||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_entries_unique_user
|
CREATE UNIQUE INDEX IF NOT EXISTS idx_entries_unique_user
|
||||||
ON entries(user_id, namespace, kind, name)
|
ON entries(user_id, folder, name)
|
||||||
WHERE user_id IS NOT NULL;
|
WHERE user_id IS NOT NULL;
|
||||||
|
|
||||||
CREATE INDEX IF NOT EXISTS idx_entries_namespace ON entries(namespace);
|
CREATE INDEX IF NOT EXISTS idx_entries_folder ON entries(folder) WHERE folder <> '';
|
||||||
CREATE INDEX IF NOT EXISTS idx_entries_kind ON entries(kind);
|
CREATE INDEX IF NOT EXISTS idx_entries_type ON entries(type) WHERE type <> '';
|
||||||
CREATE INDEX IF NOT EXISTS idx_entries_user_id ON entries(user_id) WHERE user_id IS NOT NULL;
|
CREATE INDEX IF NOT EXISTS idx_entries_user_id ON entries(user_id) WHERE user_id IS NOT NULL;
|
||||||
CREATE INDEX IF NOT EXISTS idx_entries_tags ON entries USING GIN(tags);
|
CREATE INDEX IF NOT EXISTS idx_entries_tags ON entries USING GIN(tags);
|
||||||
CREATE INDEX IF NOT EXISTS idx_entries_metadata ON entries USING GIN(metadata jsonb_path_ops);
|
CREATE INDEX IF NOT EXISTS idx_entries_metadata ON entries USING GIN(metadata jsonb_path_ops);
|
||||||
|
|
||||||
-- ── secrets: one row per encrypted field ─────────────────────────────────
|
-- ── secrets: one row per encrypted field ─────────────────────────────────
|
||||||
CREATE TABLE IF NOT EXISTS secrets (
|
CREATE TABLE IF NOT EXISTS secrets (
|
||||||
@@ -69,42 +68,44 @@ pub async fn migrate(pool: &PgPool) -> Result<()> {
|
|||||||
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
||||||
user_id UUID,
|
user_id UUID,
|
||||||
action VARCHAR(32) NOT NULL,
|
action VARCHAR(32) NOT NULL,
|
||||||
namespace VARCHAR(64) NOT NULL,
|
folder VARCHAR(128) NOT NULL DEFAULT '',
|
||||||
kind VARCHAR(64) NOT NULL,
|
type VARCHAR(64) NOT NULL DEFAULT '',
|
||||||
name VARCHAR(256) NOT NULL,
|
name VARCHAR(256) NOT NULL,
|
||||||
detail JSONB NOT NULL DEFAULT '{}',
|
detail JSONB NOT NULL DEFAULT '{}',
|
||||||
actor VARCHAR(128) NOT NULL DEFAULT '',
|
|
||||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||||
);
|
);
|
||||||
|
|
||||||
CREATE INDEX IF NOT EXISTS idx_audit_log_created ON audit_log(created_at DESC);
|
CREATE INDEX IF NOT EXISTS idx_audit_log_created ON audit_log(created_at DESC);
|
||||||
CREATE INDEX IF NOT EXISTS idx_audit_log_ns_kind ON audit_log(namespace, kind);
|
CREATE INDEX IF NOT EXISTS idx_audit_log_folder_type ON audit_log(folder, type);
|
||||||
CREATE INDEX IF NOT EXISTS idx_audit_log_user_id ON audit_log(user_id) WHERE user_id IS NOT NULL;
|
CREATE INDEX IF NOT EXISTS idx_audit_log_user_id ON audit_log(user_id) WHERE user_id IS NOT NULL;
|
||||||
|
|
||||||
-- ── entries_history ───────────────────────────────────────────────────────
|
-- ── entries_history ───────────────────────────────────────────────────────
|
||||||
CREATE TABLE IF NOT EXISTS entries_history (
|
CREATE TABLE IF NOT EXISTS entries_history (
|
||||||
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
||||||
entry_id UUID NOT NULL,
|
entry_id UUID NOT NULL,
|
||||||
namespace VARCHAR(64) NOT NULL,
|
folder VARCHAR(128) NOT NULL DEFAULT '',
|
||||||
kind VARCHAR(64) NOT NULL,
|
type VARCHAR(64) NOT NULL DEFAULT '',
|
||||||
name VARCHAR(256) NOT NULL,
|
name VARCHAR(256) NOT NULL,
|
||||||
version BIGINT NOT NULL,
|
version BIGINT NOT NULL,
|
||||||
action VARCHAR(16) NOT NULL,
|
action VARCHAR(16) NOT NULL,
|
||||||
tags TEXT[] NOT NULL DEFAULT '{}',
|
tags TEXT[] NOT NULL DEFAULT '{}',
|
||||||
metadata JSONB NOT NULL DEFAULT '{}',
|
metadata JSONB NOT NULL DEFAULT '{}',
|
||||||
actor VARCHAR(128) NOT NULL DEFAULT '',
|
|
||||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||||
);
|
);
|
||||||
|
|
||||||
CREATE INDEX IF NOT EXISTS idx_entries_history_entry_id
|
CREATE INDEX IF NOT EXISTS idx_entries_history_entry_id
|
||||||
ON entries_history(entry_id, version DESC);
|
ON entries_history(entry_id, version DESC);
|
||||||
CREATE INDEX IF NOT EXISTS idx_entries_history_ns_kind_name
|
CREATE INDEX IF NOT EXISTS idx_entries_history_folder_type_name
|
||||||
ON entries_history(namespace, kind, name, version DESC);
|
ON entries_history(folder, type, name, version DESC);
|
||||||
|
|
||||||
-- Backfill: add user_id to entries_history for multi-tenant isolation
|
-- Backfill: add user_id to entries_history for multi-tenant isolation
|
||||||
ALTER TABLE entries_history ADD COLUMN IF NOT EXISTS user_id UUID;
|
ALTER TABLE entries_history ADD COLUMN IF NOT EXISTS user_id UUID;
|
||||||
CREATE INDEX IF NOT EXISTS idx_entries_history_user_id
|
CREATE INDEX IF NOT EXISTS idx_entries_history_user_id
|
||||||
ON entries_history(user_id) WHERE user_id IS NOT NULL;
|
ON entries_history(user_id) WHERE user_id IS NOT NULL;
|
||||||
|
ALTER TABLE entries_history DROP COLUMN IF EXISTS actor;
|
||||||
|
|
||||||
|
-- Backfill: add notes to entries if not present (fresh installs already have it)
|
||||||
|
ALTER TABLE entries ADD COLUMN IF NOT EXISTS notes TEXT NOT NULL DEFAULT '';
|
||||||
|
|
||||||
-- ── secrets_history: field-level snapshot ────────────────────────────────
|
-- ── secrets_history: field-level snapshot ────────────────────────────────
|
||||||
CREATE TABLE IF NOT EXISTS secrets_history (
|
CREATE TABLE IF NOT EXISTS secrets_history (
|
||||||
@@ -115,7 +116,6 @@ pub async fn migrate(pool: &PgPool) -> Result<()> {
|
|||||||
field_name VARCHAR(256) NOT NULL,
|
field_name VARCHAR(256) NOT NULL,
|
||||||
encrypted BYTEA NOT NULL DEFAULT '\x',
|
encrypted BYTEA NOT NULL DEFAULT '\x',
|
||||||
action VARCHAR(16) NOT NULL,
|
action VARCHAR(16) NOT NULL,
|
||||||
actor VARCHAR(128) NOT NULL DEFAULT '',
|
|
||||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -124,6 +124,9 @@ pub async fn migrate(pool: &PgPool) -> Result<()> {
|
|||||||
CREATE INDEX IF NOT EXISTS idx_secrets_history_secret_id
|
CREATE INDEX IF NOT EXISTS idx_secrets_history_secret_id
|
||||||
ON secrets_history(secret_id);
|
ON secrets_history(secret_id);
|
||||||
|
|
||||||
|
-- Drop redundant actor column (derivable via entries_history JOIN)
|
||||||
|
ALTER TABLE secrets_history DROP COLUMN IF EXISTS actor;
|
||||||
|
|
||||||
-- ── users ─────────────────────────────────────────────────────────────────
|
-- ── users ─────────────────────────────────────────────────────────────────
|
||||||
CREATE TABLE IF NOT EXISTS users (
|
CREATE TABLE IF NOT EXISTS users (
|
||||||
id UUID PRIMARY KEY DEFAULT uuidv7(),
|
id UUID PRIMARY KEY DEFAULT uuidv7(),
|
||||||
@@ -154,21 +157,284 @@ pub async fn migrate(pool: &PgPool) -> Result<()> {
|
|||||||
CREATE INDEX IF NOT EXISTS idx_oauth_accounts_user ON oauth_accounts(user_id);
|
CREATE INDEX IF NOT EXISTS idx_oauth_accounts_user ON oauth_accounts(user_id);
|
||||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_oauth_accounts_user_provider
|
CREATE UNIQUE INDEX IF NOT EXISTS idx_oauth_accounts_user_provider
|
||||||
ON oauth_accounts(user_id, provider);
|
ON oauth_accounts(user_id, provider);
|
||||||
|
|
||||||
|
-- FK: user_id columns -> users(id) (nullable = legacy rows; ON DELETE SET NULL)
|
||||||
|
DO $$ BEGIN
|
||||||
|
IF NOT EXISTS (
|
||||||
|
SELECT 1 FROM pg_constraint WHERE conname = 'fk_entries_user_id'
|
||||||
|
) THEN
|
||||||
|
ALTER TABLE entries
|
||||||
|
ADD CONSTRAINT fk_entries_user_id
|
||||||
|
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE SET NULL;
|
||||||
|
END IF;
|
||||||
|
END $$;
|
||||||
|
|
||||||
|
DO $$ BEGIN
|
||||||
|
IF NOT EXISTS (
|
||||||
|
SELECT 1 FROM pg_constraint WHERE conname = 'fk_entries_history_user_id'
|
||||||
|
) THEN
|
||||||
|
ALTER TABLE entries_history
|
||||||
|
ADD CONSTRAINT fk_entries_history_user_id
|
||||||
|
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE SET NULL;
|
||||||
|
END IF;
|
||||||
|
END $$;
|
||||||
|
|
||||||
|
DO $$ BEGIN
|
||||||
|
IF NOT EXISTS (
|
||||||
|
SELECT 1 FROM pg_constraint WHERE conname = 'fk_audit_log_user_id'
|
||||||
|
) THEN
|
||||||
|
ALTER TABLE audit_log
|
||||||
|
ADD CONSTRAINT fk_audit_log_user_id
|
||||||
|
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE SET NULL;
|
||||||
|
END IF;
|
||||||
|
END $$;
|
||||||
"#,
|
"#,
|
||||||
)
|
)
|
||||||
.execute(pool)
|
.execute(pool)
|
||||||
.await?;
|
.await?;
|
||||||
|
migrate_schema(pool).await?;
|
||||||
|
restore_plaintext_api_keys(pool).await?;
|
||||||
|
|
||||||
tracing::debug!("migrations complete");
|
tracing::debug!("migrations complete");
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Idempotent schema migration: rename namespace→folder, kind→type in existing databases.
|
||||||
|
async fn migrate_schema(pool: &PgPool) -> Result<()> {
|
||||||
|
sqlx::raw_sql(
|
||||||
|
r#"
|
||||||
|
-- ── entries: rename namespace→folder, kind→type ──────────────────────────
|
||||||
|
DO $$ BEGIN
|
||||||
|
IF EXISTS (
|
||||||
|
SELECT 1 FROM information_schema.columns
|
||||||
|
WHERE table_name = 'entries' AND column_name = 'namespace'
|
||||||
|
) THEN
|
||||||
|
ALTER TABLE entries RENAME COLUMN namespace TO folder;
|
||||||
|
END IF;
|
||||||
|
END $$;
|
||||||
|
|
||||||
|
DO $$ BEGIN
|
||||||
|
IF EXISTS (
|
||||||
|
SELECT 1 FROM information_schema.columns
|
||||||
|
WHERE table_name = 'entries' AND column_name = 'kind'
|
||||||
|
) THEN
|
||||||
|
ALTER TABLE entries RENAME COLUMN kind TO type;
|
||||||
|
END IF;
|
||||||
|
END $$;
|
||||||
|
|
||||||
|
-- ── audit_log: rename namespace→folder, kind→type ────────────────────────
|
||||||
|
DO $$ BEGIN
|
||||||
|
IF EXISTS (
|
||||||
|
SELECT 1 FROM information_schema.columns
|
||||||
|
WHERE table_name = 'audit_log' AND column_name = 'namespace'
|
||||||
|
) THEN
|
||||||
|
ALTER TABLE audit_log RENAME COLUMN namespace TO folder;
|
||||||
|
END IF;
|
||||||
|
END $$;
|
||||||
|
|
||||||
|
DO $$ BEGIN
|
||||||
|
IF EXISTS (
|
||||||
|
SELECT 1 FROM information_schema.columns
|
||||||
|
WHERE table_name = 'audit_log' AND column_name = 'kind'
|
||||||
|
) THEN
|
||||||
|
ALTER TABLE audit_log RENAME COLUMN kind TO type;
|
||||||
|
END IF;
|
||||||
|
END $$;
|
||||||
|
|
||||||
|
-- ── entries_history: rename namespace→folder, kind→type ──────────────────
|
||||||
|
DO $$ BEGIN
|
||||||
|
IF EXISTS (
|
||||||
|
SELECT 1 FROM information_schema.columns
|
||||||
|
WHERE table_name = 'entries_history' AND column_name = 'namespace'
|
||||||
|
) THEN
|
||||||
|
ALTER TABLE entries_history RENAME COLUMN namespace TO folder;
|
||||||
|
END IF;
|
||||||
|
END $$;
|
||||||
|
|
||||||
|
DO $$ BEGIN
|
||||||
|
IF EXISTS (
|
||||||
|
SELECT 1 FROM information_schema.columns
|
||||||
|
WHERE table_name = 'entries_history' AND column_name = 'kind'
|
||||||
|
) THEN
|
||||||
|
ALTER TABLE entries_history RENAME COLUMN kind TO type;
|
||||||
|
END IF;
|
||||||
|
END $$;
|
||||||
|
|
||||||
|
-- ── Set empty defaults for new folder/type columns ────────────────────────
|
||||||
|
DO $$ BEGIN
|
||||||
|
IF EXISTS (
|
||||||
|
SELECT 1 FROM information_schema.columns
|
||||||
|
WHERE table_name = 'entries' AND column_name = 'folder'
|
||||||
|
) THEN
|
||||||
|
UPDATE entries SET folder = '' WHERE folder IS NULL;
|
||||||
|
ALTER TABLE entries ALTER COLUMN folder SET NOT NULL;
|
||||||
|
ALTER TABLE entries ALTER COLUMN folder SET DEFAULT '';
|
||||||
|
END IF;
|
||||||
|
END $$;
|
||||||
|
|
||||||
|
DO $$ BEGIN
|
||||||
|
IF EXISTS (
|
||||||
|
SELECT 1 FROM information_schema.columns
|
||||||
|
WHERE table_name = 'entries' AND column_name = 'type'
|
||||||
|
) THEN
|
||||||
|
UPDATE entries SET type = '' WHERE type IS NULL;
|
||||||
|
ALTER TABLE entries ALTER COLUMN type SET NOT NULL;
|
||||||
|
ALTER TABLE entries ALTER COLUMN type SET DEFAULT '';
|
||||||
|
END IF;
|
||||||
|
END $$;
|
||||||
|
|
||||||
|
DO $$ BEGIN
|
||||||
|
IF EXISTS (
|
||||||
|
SELECT 1 FROM information_schema.columns
|
||||||
|
WHERE table_name = 'audit_log' AND column_name = 'folder'
|
||||||
|
) THEN
|
||||||
|
UPDATE audit_log SET folder = '' WHERE folder IS NULL;
|
||||||
|
ALTER TABLE audit_log ALTER COLUMN folder SET NOT NULL;
|
||||||
|
ALTER TABLE audit_log ALTER COLUMN folder SET DEFAULT '';
|
||||||
|
END IF;
|
||||||
|
END $$;
|
||||||
|
|
||||||
|
DO $$ BEGIN
|
||||||
|
IF EXISTS (
|
||||||
|
SELECT 1 FROM information_schema.columns
|
||||||
|
WHERE table_name = 'audit_log' AND column_name = 'type'
|
||||||
|
) THEN
|
||||||
|
UPDATE audit_log SET type = '' WHERE type IS NULL;
|
||||||
|
ALTER TABLE audit_log ALTER COLUMN type SET NOT NULL;
|
||||||
|
ALTER TABLE audit_log ALTER COLUMN type SET DEFAULT '';
|
||||||
|
END IF;
|
||||||
|
END $$;
|
||||||
|
|
||||||
|
DO $$ BEGIN
|
||||||
|
IF EXISTS (
|
||||||
|
SELECT 1 FROM information_schema.columns
|
||||||
|
WHERE table_name = 'entries_history' AND column_name = 'folder'
|
||||||
|
) THEN
|
||||||
|
UPDATE entries_history SET folder = '' WHERE folder IS NULL;
|
||||||
|
ALTER TABLE entries_history ALTER COLUMN folder SET NOT NULL;
|
||||||
|
ALTER TABLE entries_history ALTER COLUMN folder SET DEFAULT '';
|
||||||
|
END IF;
|
||||||
|
END $$;
|
||||||
|
|
||||||
|
DO $$ BEGIN
|
||||||
|
IF EXISTS (
|
||||||
|
SELECT 1 FROM information_schema.columns
|
||||||
|
WHERE table_name = 'entries_history' AND column_name = 'type'
|
||||||
|
) THEN
|
||||||
|
UPDATE entries_history SET type = '' WHERE type IS NULL;
|
||||||
|
ALTER TABLE entries_history ALTER COLUMN type SET NOT NULL;
|
||||||
|
ALTER TABLE entries_history ALTER COLUMN type SET DEFAULT '';
|
||||||
|
END IF;
|
||||||
|
END $$;
|
||||||
|
|
||||||
|
-- ── Rebuild unique indexes on entries: folder is now part of the key ────────
|
||||||
|
-- (user_id, folder, name) allows same name in different folders.
|
||||||
|
DROP INDEX IF EXISTS idx_entries_unique_legacy;
|
||||||
|
DROP INDEX IF EXISTS idx_entries_unique_user;
|
||||||
|
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS idx_entries_unique_legacy
|
||||||
|
ON entries(folder, name)
|
||||||
|
WHERE user_id IS NULL;
|
||||||
|
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS idx_entries_unique_user
|
||||||
|
ON entries(user_id, folder, name)
|
||||||
|
WHERE user_id IS NOT NULL;
|
||||||
|
|
||||||
|
-- ── Replace old namespace/kind indexes ────────────────────────────────────
|
||||||
|
DROP INDEX IF EXISTS idx_entries_namespace;
|
||||||
|
DROP INDEX IF EXISTS idx_entries_kind;
|
||||||
|
DROP INDEX IF EXISTS idx_audit_log_ns_kind;
|
||||||
|
DROP INDEX IF EXISTS idx_entries_history_ns_kind_name;
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_entries_folder
|
||||||
|
ON entries(folder) WHERE folder <> '';
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_entries_type
|
||||||
|
ON entries(type) WHERE type <> '';
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_audit_log_folder_type
|
||||||
|
ON audit_log(folder, type);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_entries_history_folder_type_name
|
||||||
|
ON entries_history(folder, type, name, version DESC);
|
||||||
|
|
||||||
|
-- ── Drop legacy actor columns ─────────────────────────────────────────────
|
||||||
|
ALTER TABLE secrets_history DROP COLUMN IF EXISTS actor;
|
||||||
|
ALTER TABLE audit_log DROP COLUMN IF EXISTS actor;
|
||||||
|
"#,
|
||||||
|
)
|
||||||
|
.execute(pool)
|
||||||
|
.await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn restore_plaintext_api_keys(pool: &PgPool) -> Result<()> {
|
||||||
|
let has_users_api_key: bool = sqlx::query_scalar(
|
||||||
|
"SELECT EXISTS (
|
||||||
|
SELECT 1
|
||||||
|
FROM information_schema.columns
|
||||||
|
WHERE table_schema = 'public'
|
||||||
|
AND table_name = 'users'
|
||||||
|
AND column_name = 'api_key'
|
||||||
|
)",
|
||||||
|
)
|
||||||
|
.fetch_one(pool)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
if !has_users_api_key {
|
||||||
|
sqlx::query("ALTER TABLE users ADD COLUMN api_key TEXT")
|
||||||
|
.execute(pool)
|
||||||
|
.await?;
|
||||||
|
sqlx::query("CREATE UNIQUE INDEX IF NOT EXISTS idx_users_api_key ON users(api_key) WHERE api_key IS NOT NULL")
|
||||||
|
.execute(pool)
|
||||||
|
.await?;
|
||||||
|
}
|
||||||
|
|
||||||
|
let has_api_keys_table: bool = sqlx::query_scalar(
|
||||||
|
"SELECT EXISTS (
|
||||||
|
SELECT 1
|
||||||
|
FROM information_schema.tables
|
||||||
|
WHERE table_schema = 'public'
|
||||||
|
AND table_name = 'api_keys'
|
||||||
|
)",
|
||||||
|
)
|
||||||
|
.fetch_one(pool)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
if !has_api_keys_table {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(sqlx::FromRow)]
|
||||||
|
struct UserWithoutKey {
|
||||||
|
id: uuid::Uuid,
|
||||||
|
}
|
||||||
|
|
||||||
|
let users_without_key: Vec<UserWithoutKey> =
|
||||||
|
sqlx::query_as("SELECT DISTINCT user_id AS id FROM api_keys WHERE user_id NOT IN (SELECT id FROM users WHERE api_key IS NOT NULL)")
|
||||||
|
.fetch_all(pool)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
for user in users_without_key {
|
||||||
|
let new_key = crate::service::api_key::generate_api_key();
|
||||||
|
sqlx::query("UPDATE users SET api_key = $1 WHERE id = $2")
|
||||||
|
.bind(&new_key)
|
||||||
|
.bind(user.id)
|
||||||
|
.execute(pool)
|
||||||
|
.await?;
|
||||||
|
}
|
||||||
|
|
||||||
|
sqlx::query("DROP TABLE IF EXISTS api_keys")
|
||||||
|
.execute(pool)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
// ── Entry-level history snapshot ─────────────────────────────────────────────
|
// ── Entry-level history snapshot ─────────────────────────────────────────────
|
||||||
|
|
||||||
pub struct EntrySnapshotParams<'a> {
|
pub struct EntrySnapshotParams<'a> {
|
||||||
pub entry_id: uuid::Uuid,
|
pub entry_id: uuid::Uuid,
|
||||||
pub user_id: Option<uuid::Uuid>,
|
pub user_id: Option<uuid::Uuid>,
|
||||||
pub namespace: &'a str,
|
pub folder: &'a str,
|
||||||
pub kind: &'a str,
|
pub entry_type: &'a str,
|
||||||
pub name: &'a str,
|
pub name: &'a str,
|
||||||
pub version: i64,
|
pub version: i64,
|
||||||
pub action: &'a str,
|
pub action: &'a str,
|
||||||
@@ -180,21 +446,19 @@ pub async fn snapshot_entry_history(
|
|||||||
tx: &mut sqlx::Transaction<'_, sqlx::Postgres>,
|
tx: &mut sqlx::Transaction<'_, sqlx::Postgres>,
|
||||||
p: EntrySnapshotParams<'_>,
|
p: EntrySnapshotParams<'_>,
|
||||||
) -> Result<()> {
|
) -> Result<()> {
|
||||||
let actor = current_actor();
|
|
||||||
sqlx::query(
|
sqlx::query(
|
||||||
"INSERT INTO entries_history \
|
"INSERT INTO entries_history \
|
||||||
(entry_id, namespace, kind, name, version, action, tags, metadata, actor, user_id) \
|
(entry_id, folder, type, name, version, action, tags, metadata, user_id) \
|
||||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)",
|
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)",
|
||||||
)
|
)
|
||||||
.bind(p.entry_id)
|
.bind(p.entry_id)
|
||||||
.bind(p.namespace)
|
.bind(p.folder)
|
||||||
.bind(p.kind)
|
.bind(p.entry_type)
|
||||||
.bind(p.name)
|
.bind(p.name)
|
||||||
.bind(p.version)
|
.bind(p.version)
|
||||||
.bind(p.action)
|
.bind(p.action)
|
||||||
.bind(p.tags)
|
.bind(p.tags)
|
||||||
.bind(p.metadata)
|
.bind(p.metadata)
|
||||||
.bind(&actor)
|
|
||||||
.bind(p.user_id)
|
.bind(p.user_id)
|
||||||
.execute(&mut **tx)
|
.execute(&mut **tx)
|
||||||
.await?;
|
.await?;
|
||||||
@@ -216,11 +480,10 @@ pub async fn snapshot_secret_history(
|
|||||||
tx: &mut sqlx::Transaction<'_, sqlx::Postgres>,
|
tx: &mut sqlx::Transaction<'_, sqlx::Postgres>,
|
||||||
p: SecretSnapshotParams<'_>,
|
p: SecretSnapshotParams<'_>,
|
||||||
) -> Result<()> {
|
) -> Result<()> {
|
||||||
let actor = current_actor();
|
|
||||||
sqlx::query(
|
sqlx::query(
|
||||||
"INSERT INTO secrets_history \
|
"INSERT INTO secrets_history \
|
||||||
(entry_id, secret_id, entry_version, field_name, encrypted, action, actor) \
|
(entry_id, secret_id, entry_version, field_name, encrypted, action) \
|
||||||
VALUES ($1, $2, $3, $4, $5, $6, $7)",
|
VALUES ($1, $2, $3, $4, $5, $6)",
|
||||||
)
|
)
|
||||||
.bind(p.entry_id)
|
.bind(p.entry_id)
|
||||||
.bind(p.secret_id)
|
.bind(p.secret_id)
|
||||||
@@ -228,7 +491,6 @@ pub async fn snapshot_secret_history(
|
|||||||
.bind(p.field_name)
|
.bind(p.field_name)
|
||||||
.bind(p.encrypted)
|
.bind(p.encrypted)
|
||||||
.bind(p.action)
|
.bind(p.action)
|
||||||
.bind(&actor)
|
|
||||||
.execute(&mut **tx)
|
.execute(&mut **tx)
|
||||||
.await?;
|
.await?;
|
||||||
Ok(())
|
Ok(())
|
||||||
|
|||||||
@@ -4,14 +4,18 @@ use serde_json::Value;
|
|||||||
use std::collections::BTreeMap;
|
use std::collections::BTreeMap;
|
||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
|
|
||||||
/// A top-level entry (server, service, key, …).
|
/// A top-level entry (server, service, key, person, …).
|
||||||
/// Sensitive fields are stored separately in `secrets`.
|
/// Sensitive fields are stored separately in `secrets`.
|
||||||
#[derive(Debug, Serialize, Deserialize, sqlx::FromRow)]
|
#[derive(Debug, Serialize, Deserialize, sqlx::FromRow)]
|
||||||
pub struct Entry {
|
pub struct Entry {
|
||||||
pub id: Uuid,
|
pub id: Uuid,
|
||||||
pub namespace: String,
|
pub user_id: Option<Uuid>,
|
||||||
pub kind: String,
|
pub folder: String,
|
||||||
|
#[serde(rename = "type")]
|
||||||
|
#[sqlx(rename = "type")]
|
||||||
|
pub entry_type: String,
|
||||||
pub name: String,
|
pub name: String,
|
||||||
|
pub notes: String,
|
||||||
pub tags: Vec<String>,
|
pub tags: Vec<String>,
|
||||||
pub metadata: Value,
|
pub metadata: Value,
|
||||||
pub version: i64,
|
pub version: i64,
|
||||||
@@ -39,8 +43,12 @@ pub struct SecretField {
|
|||||||
pub struct EntryRow {
|
pub struct EntryRow {
|
||||||
pub id: Uuid,
|
pub id: Uuid,
|
||||||
pub version: i64,
|
pub version: i64,
|
||||||
|
pub folder: String,
|
||||||
|
#[sqlx(rename = "type")]
|
||||||
|
pub entry_type: String,
|
||||||
pub tags: Vec<String>,
|
pub tags: Vec<String>,
|
||||||
pub metadata: Value,
|
pub metadata: Value,
|
||||||
|
pub notes: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Minimal secret field row fetched before snapshots or cascade deletes.
|
/// Minimal secret field row fetched before snapshots or cascade deletes.
|
||||||
@@ -127,10 +135,14 @@ pub struct ExportData {
|
|||||||
/// A single entry with decrypted secrets for export/import.
|
/// A single entry with decrypted secrets for export/import.
|
||||||
#[derive(Debug, Serialize, Deserialize)]
|
#[derive(Debug, Serialize, Deserialize)]
|
||||||
pub struct ExportEntry {
|
pub struct ExportEntry {
|
||||||
pub namespace: String,
|
|
||||||
pub kind: String,
|
|
||||||
pub name: String,
|
pub name: String,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
|
pub folder: String,
|
||||||
|
#[serde(default, rename = "type")]
|
||||||
|
pub entry_type: String,
|
||||||
|
#[serde(default)]
|
||||||
|
pub notes: String,
|
||||||
|
#[serde(default)]
|
||||||
pub tags: Vec<String>,
|
pub tags: Vec<String>,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub metadata: Value,
|
pub metadata: Value,
|
||||||
@@ -180,11 +192,12 @@ pub struct AuditLogEntry {
|
|||||||
pub id: i64,
|
pub id: i64,
|
||||||
pub user_id: Option<Uuid>,
|
pub user_id: Option<Uuid>,
|
||||||
pub action: String,
|
pub action: String,
|
||||||
pub namespace: String,
|
pub folder: String,
|
||||||
pub kind: String,
|
#[serde(rename = "type")]
|
||||||
|
#[sqlx(rename = "type")]
|
||||||
|
pub entry_type: String,
|
||||||
pub name: String,
|
pub name: String,
|
||||||
pub detail: Value,
|
pub detail: Value,
|
||||||
pub actor: String,
|
|
||||||
pub created_at: DateTime<Utc>,
|
pub created_at: DateTime<Utc>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -159,18 +159,20 @@ pub fn flatten_json_fields(prefix: &str, value: &Value) -> Vec<(String, Value)>
|
|||||||
|
|
||||||
#[derive(Debug, serde::Serialize)]
|
#[derive(Debug, serde::Serialize)]
|
||||||
pub struct AddResult {
|
pub struct AddResult {
|
||||||
pub namespace: String,
|
|
||||||
pub kind: String,
|
|
||||||
pub name: String,
|
pub name: String,
|
||||||
|
pub folder: String,
|
||||||
|
#[serde(rename = "type")]
|
||||||
|
pub entry_type: String,
|
||||||
pub tags: Vec<String>,
|
pub tags: Vec<String>,
|
||||||
pub meta_keys: Vec<String>,
|
pub meta_keys: Vec<String>,
|
||||||
pub secret_keys: Vec<String>,
|
pub secret_keys: Vec<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct AddParams<'a> {
|
pub struct AddParams<'a> {
|
||||||
pub namespace: &'a str,
|
|
||||||
pub kind: &'a str,
|
|
||||||
pub name: &'a str,
|
pub name: &'a str,
|
||||||
|
pub folder: &'a str,
|
||||||
|
pub entry_type: &'a str,
|
||||||
|
pub notes: &'a str,
|
||||||
pub tags: &'a [String],
|
pub tags: &'a [String],
|
||||||
pub meta_entries: &'a [String],
|
pub meta_entries: &'a [String],
|
||||||
pub secret_entries: &'a [String],
|
pub secret_entries: &'a [String],
|
||||||
@@ -186,25 +188,23 @@ pub async fn run(pool: &PgPool, params: AddParams<'_>, master_key: &[u8; 32]) ->
|
|||||||
|
|
||||||
let mut tx = pool.begin().await?;
|
let mut tx = pool.begin().await?;
|
||||||
|
|
||||||
// Fetch existing entry (user-scoped or global depending on user_id)
|
// Fetch existing entry by (user_id, folder, name) — the natural unique key
|
||||||
let existing: Option<EntryRow> = if let Some(uid) = params.user_id {
|
let existing: Option<EntryRow> = if let Some(uid) = params.user_id {
|
||||||
sqlx::query_as(
|
sqlx::query_as(
|
||||||
"SELECT id, version, tags, metadata FROM entries \
|
"SELECT id, version, folder, type, tags, metadata, notes FROM entries \
|
||||||
WHERE user_id = $1 AND namespace = $2 AND kind = $3 AND name = $4",
|
WHERE user_id = $1 AND folder = $2 AND name = $3",
|
||||||
)
|
)
|
||||||
.bind(uid)
|
.bind(uid)
|
||||||
.bind(params.namespace)
|
.bind(params.folder)
|
||||||
.bind(params.kind)
|
|
||||||
.bind(params.name)
|
.bind(params.name)
|
||||||
.fetch_optional(&mut *tx)
|
.fetch_optional(&mut *tx)
|
||||||
.await?
|
.await?
|
||||||
} else {
|
} else {
|
||||||
sqlx::query_as(
|
sqlx::query_as(
|
||||||
"SELECT id, version, tags, metadata FROM entries \
|
"SELECT id, version, folder, type, tags, metadata, notes FROM entries \
|
||||||
WHERE user_id IS NULL AND namespace = $1 AND kind = $2 AND name = $3",
|
WHERE user_id IS NULL AND folder = $1 AND name = $2",
|
||||||
)
|
)
|
||||||
.bind(params.namespace)
|
.bind(params.folder)
|
||||||
.bind(params.kind)
|
|
||||||
.bind(params.name)
|
.bind(params.name)
|
||||||
.fetch_optional(&mut *tx)
|
.fetch_optional(&mut *tx)
|
||||||
.await?
|
.await?
|
||||||
@@ -216,8 +216,8 @@ pub async fn run(pool: &PgPool, params: AddParams<'_>, master_key: &[u8; 32]) ->
|
|||||||
db::EntrySnapshotParams {
|
db::EntrySnapshotParams {
|
||||||
entry_id: ex.id,
|
entry_id: ex.id,
|
||||||
user_id: params.user_id,
|
user_id: params.user_id,
|
||||||
namespace: params.namespace,
|
folder: params.folder,
|
||||||
kind: params.kind,
|
entry_type: params.entry_type,
|
||||||
name: params.name,
|
name: params.name,
|
||||||
version: ex.version,
|
version: ex.version,
|
||||||
action: "add",
|
action: "add",
|
||||||
@@ -232,10 +232,13 @@ pub async fn run(pool: &PgPool, params: AddParams<'_>, master_key: &[u8; 32]) ->
|
|||||||
|
|
||||||
let entry_id: Uuid = if let Some(uid) = params.user_id {
|
let entry_id: Uuid = if let Some(uid) = params.user_id {
|
||||||
sqlx::query_scalar(
|
sqlx::query_scalar(
|
||||||
r#"INSERT INTO entries (user_id, namespace, kind, name, tags, metadata, version, updated_at)
|
r#"INSERT INTO entries (user_id, folder, type, name, notes, tags, metadata, version, updated_at)
|
||||||
VALUES ($1, $2, $3, $4, $5, $6, 1, NOW())
|
VALUES ($1, $2, $3, $4, $5, $6, $7, 1, NOW())
|
||||||
ON CONFLICT (user_id, namespace, kind, name) WHERE user_id IS NOT NULL
|
ON CONFLICT (user_id, folder, name) WHERE user_id IS NOT NULL
|
||||||
DO UPDATE SET
|
DO UPDATE SET
|
||||||
|
folder = EXCLUDED.folder,
|
||||||
|
type = EXCLUDED.type,
|
||||||
|
notes = EXCLUDED.notes,
|
||||||
tags = EXCLUDED.tags,
|
tags = EXCLUDED.tags,
|
||||||
metadata = EXCLUDED.metadata,
|
metadata = EXCLUDED.metadata,
|
||||||
version = entries.version + 1,
|
version = entries.version + 1,
|
||||||
@@ -243,28 +246,33 @@ pub async fn run(pool: &PgPool, params: AddParams<'_>, master_key: &[u8; 32]) ->
|
|||||||
RETURNING id"#,
|
RETURNING id"#,
|
||||||
)
|
)
|
||||||
.bind(uid)
|
.bind(uid)
|
||||||
.bind(params.namespace)
|
.bind(params.folder)
|
||||||
.bind(params.kind)
|
.bind(params.entry_type)
|
||||||
.bind(params.name)
|
.bind(params.name)
|
||||||
|
.bind(params.notes)
|
||||||
.bind(params.tags)
|
.bind(params.tags)
|
||||||
.bind(&metadata)
|
.bind(&metadata)
|
||||||
.fetch_one(&mut *tx)
|
.fetch_one(&mut *tx)
|
||||||
.await?
|
.await?
|
||||||
} else {
|
} else {
|
||||||
sqlx::query_scalar(
|
sqlx::query_scalar(
|
||||||
r#"INSERT INTO entries (namespace, kind, name, tags, metadata, version, updated_at)
|
r#"INSERT INTO entries (folder, type, name, notes, tags, metadata, version, updated_at)
|
||||||
VALUES ($1, $2, $3, $4, $5, 1, NOW())
|
VALUES ($1, $2, $3, $4, $5, $6, 1, NOW())
|
||||||
ON CONFLICT (namespace, kind, name) WHERE user_id IS NULL
|
ON CONFLICT (folder, name) WHERE user_id IS NULL
|
||||||
DO UPDATE SET
|
DO UPDATE SET
|
||||||
|
folder = EXCLUDED.folder,
|
||||||
|
type = EXCLUDED.type,
|
||||||
|
notes = EXCLUDED.notes,
|
||||||
tags = EXCLUDED.tags,
|
tags = EXCLUDED.tags,
|
||||||
metadata = EXCLUDED.metadata,
|
metadata = EXCLUDED.metadata,
|
||||||
version = entries.version + 1,
|
version = entries.version + 1,
|
||||||
updated_at = NOW()
|
updated_at = NOW()
|
||||||
RETURNING id"#,
|
RETURNING id"#,
|
||||||
)
|
)
|
||||||
.bind(params.namespace)
|
.bind(params.folder)
|
||||||
.bind(params.kind)
|
.bind(params.entry_type)
|
||||||
.bind(params.name)
|
.bind(params.name)
|
||||||
|
.bind(params.notes)
|
||||||
.bind(params.tags)
|
.bind(params.tags)
|
||||||
.bind(&metadata)
|
.bind(&metadata)
|
||||||
.fetch_one(&mut *tx)
|
.fetch_one(&mut *tx)
|
||||||
@@ -282,8 +290,8 @@ pub async fn run(pool: &PgPool, params: AddParams<'_>, master_key: &[u8; 32]) ->
|
|||||||
db::EntrySnapshotParams {
|
db::EntrySnapshotParams {
|
||||||
entry_id,
|
entry_id,
|
||||||
user_id: params.user_id,
|
user_id: params.user_id,
|
||||||
namespace: params.namespace,
|
folder: params.folder,
|
||||||
kind: params.kind,
|
entry_type: params.entry_type,
|
||||||
name: params.name,
|
name: params.name,
|
||||||
version: new_entry_version,
|
version: new_entry_version,
|
||||||
action: "create",
|
action: "create",
|
||||||
@@ -348,8 +356,8 @@ pub async fn run(pool: &PgPool, params: AddParams<'_>, master_key: &[u8; 32]) ->
|
|||||||
&mut tx,
|
&mut tx,
|
||||||
params.user_id,
|
params.user_id,
|
||||||
"add",
|
"add",
|
||||||
params.namespace,
|
params.folder,
|
||||||
params.kind,
|
params.entry_type,
|
||||||
params.name,
|
params.name,
|
||||||
serde_json::json!({
|
serde_json::json!({
|
||||||
"tags": params.tags,
|
"tags": params.tags,
|
||||||
@@ -362,9 +370,9 @@ pub async fn run(pool: &PgPool, params: AddParams<'_>, master_key: &[u8; 32]) ->
|
|||||||
tx.commit().await?;
|
tx.commit().await?;
|
||||||
|
|
||||||
Ok(AddResult {
|
Ok(AddResult {
|
||||||
namespace: params.namespace.to_string(),
|
|
||||||
kind: params.kind.to_string(),
|
|
||||||
name: params.name.to_string(),
|
name: params.name.to_string(),
|
||||||
|
folder: params.folder.to_string(),
|
||||||
|
entry_type: params.entry_type.to_string(),
|
||||||
tags: params.tags.to_vec(),
|
tags: params.tags.to_vec(),
|
||||||
meta_keys,
|
meta_keys,
|
||||||
secret_keys,
|
secret_keys,
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ pub async fn list_for_user(pool: &PgPool, user_id: Uuid, limit: i64) -> Result<V
|
|||||||
let limit = limit.clamp(1, 200);
|
let limit = limit.clamp(1, 200);
|
||||||
|
|
||||||
let rows = sqlx::query_as(
|
let rows = sqlx::query_as(
|
||||||
"SELECT id, user_id, action, namespace, kind, name, detail, actor, created_at \
|
"SELECT id, user_id, action, folder, type, name, detail, created_at \
|
||||||
FROM audit_log \
|
FROM audit_log \
|
||||||
WHERE user_id = $1 \
|
WHERE user_id = $1 \
|
||||||
ORDER BY created_at DESC, id DESC \
|
ORDER BY created_at DESC, id DESC \
|
||||||
|
|||||||
@@ -8,9 +8,10 @@ use crate::models::{EntryRow, SecretFieldRow};
|
|||||||
|
|
||||||
#[derive(Debug, serde::Serialize)]
|
#[derive(Debug, serde::Serialize)]
|
||||||
pub struct DeletedEntry {
|
pub struct DeletedEntry {
|
||||||
pub namespace: String,
|
|
||||||
pub kind: String,
|
|
||||||
pub name: String,
|
pub name: String,
|
||||||
|
pub folder: String,
|
||||||
|
#[serde(rename = "type")]
|
||||||
|
pub entry_type: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, serde::Serialize)]
|
#[derive(Debug, serde::Serialize)]
|
||||||
@@ -20,34 +21,29 @@ pub struct DeleteResult {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub struct DeleteParams<'a> {
|
pub struct DeleteParams<'a> {
|
||||||
pub namespace: &'a str,
|
/// If set, delete a single entry by name.
|
||||||
pub kind: Option<&'a str>,
|
|
||||||
pub name: Option<&'a str>,
|
pub name: Option<&'a str>,
|
||||||
|
/// Folder filter for bulk delete.
|
||||||
|
pub folder: Option<&'a str>,
|
||||||
|
/// Type filter for bulk delete.
|
||||||
|
pub entry_type: Option<&'a str>,
|
||||||
pub dry_run: bool,
|
pub dry_run: bool,
|
||||||
pub user_id: Option<Uuid>,
|
pub user_id: Option<Uuid>,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn run(pool: &PgPool, params: DeleteParams<'_>) -> Result<DeleteResult> {
|
pub async fn run(pool: &PgPool, params: DeleteParams<'_>) -> Result<DeleteResult> {
|
||||||
match params.name {
|
match params.name {
|
||||||
Some(name) => {
|
Some(name) => delete_one(pool, name, params.folder, params.dry_run, params.user_id).await,
|
||||||
let kind = params
|
|
||||||
.kind
|
|
||||||
.ok_or_else(|| anyhow::anyhow!("--kind is required when --name is specified"))?;
|
|
||||||
delete_one(
|
|
||||||
pool,
|
|
||||||
params.namespace,
|
|
||||||
kind,
|
|
||||||
name,
|
|
||||||
params.dry_run,
|
|
||||||
params.user_id,
|
|
||||||
)
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
None => {
|
None => {
|
||||||
|
if params.folder.is_none() && params.entry_type.is_none() {
|
||||||
|
anyhow::bail!(
|
||||||
|
"Bulk delete requires at least one of: name, folder, or type filter."
|
||||||
|
);
|
||||||
|
}
|
||||||
delete_bulk(
|
delete_bulk(
|
||||||
pool,
|
pool,
|
||||||
params.namespace,
|
params.folder,
|
||||||
params.kind,
|
params.entry_type,
|
||||||
params.dry_run,
|
params.dry_run,
|
||||||
params.user_id,
|
params.user_id,
|
||||||
)
|
)
|
||||||
@@ -58,93 +54,169 @@ pub async fn run(pool: &PgPool, params: DeleteParams<'_>) -> Result<DeleteResult
|
|||||||
|
|
||||||
async fn delete_one(
|
async fn delete_one(
|
||||||
pool: &PgPool,
|
pool: &PgPool,
|
||||||
namespace: &str,
|
|
||||||
kind: &str,
|
|
||||||
name: &str,
|
name: &str,
|
||||||
|
folder: Option<&str>,
|
||||||
dry_run: bool,
|
dry_run: bool,
|
||||||
user_id: Option<Uuid>,
|
user_id: Option<Uuid>,
|
||||||
) -> Result<DeleteResult> {
|
) -> Result<DeleteResult> {
|
||||||
if dry_run {
|
if dry_run {
|
||||||
let exists: bool = if let Some(uid) = user_id {
|
// Dry-run uses the same disambiguation logic as actual delete:
|
||||||
sqlx::query_scalar(
|
// - 0 matches → nothing to delete
|
||||||
"SELECT EXISTS(SELECT 1 FROM entries \
|
// - 1 match → show what would be deleted (with correct folder/type)
|
||||||
WHERE user_id = $1 AND namespace = $2 AND kind = $3 AND name = $4)",
|
// - 2+ matches → disambiguation error (same as non-dry-run)
|
||||||
|
#[derive(sqlx::FromRow)]
|
||||||
|
struct DryRunRow {
|
||||||
|
folder: String,
|
||||||
|
#[sqlx(rename = "type")]
|
||||||
|
entry_type: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
let rows: Vec<DryRunRow> = if let Some(uid) = user_id {
|
||||||
|
if let Some(f) = folder {
|
||||||
|
sqlx::query_as(
|
||||||
|
"SELECT folder, type FROM entries WHERE user_id = $1 AND folder = $2 AND name = $3",
|
||||||
|
)
|
||||||
|
.bind(uid)
|
||||||
|
.bind(f)
|
||||||
|
.bind(name)
|
||||||
|
.fetch_all(pool)
|
||||||
|
.await?
|
||||||
|
} else {
|
||||||
|
sqlx::query_as("SELECT folder, type FROM entries WHERE user_id = $1 AND name = $2")
|
||||||
|
.bind(uid)
|
||||||
|
.bind(name)
|
||||||
|
.fetch_all(pool)
|
||||||
|
.await?
|
||||||
|
}
|
||||||
|
} else if let Some(f) = folder {
|
||||||
|
sqlx::query_as(
|
||||||
|
"SELECT folder, type FROM entries WHERE user_id IS NULL AND folder = $1 AND name = $2",
|
||||||
)
|
)
|
||||||
.bind(uid)
|
.bind(f)
|
||||||
.bind(namespace)
|
|
||||||
.bind(kind)
|
|
||||||
.bind(name)
|
.bind(name)
|
||||||
.fetch_one(pool)
|
.fetch_all(pool)
|
||||||
.await?
|
.await?
|
||||||
} else {
|
} else {
|
||||||
sqlx::query_scalar(
|
sqlx::query_as("SELECT folder, type FROM entries WHERE user_id IS NULL AND name = $1")
|
||||||
"SELECT EXISTS(SELECT 1 FROM entries \
|
.bind(name)
|
||||||
WHERE user_id IS NULL AND namespace = $1 AND kind = $2 AND name = $3)",
|
.fetch_all(pool)
|
||||||
)
|
.await?
|
||||||
.bind(namespace)
|
|
||||||
.bind(kind)
|
|
||||||
.bind(name)
|
|
||||||
.fetch_one(pool)
|
|
||||||
.await?
|
|
||||||
};
|
};
|
||||||
|
|
||||||
let deleted = if exists {
|
return match rows.len() {
|
||||||
vec![DeletedEntry {
|
0 => Ok(DeleteResult {
|
||||||
namespace: namespace.to_string(),
|
deleted: vec![],
|
||||||
kind: kind.to_string(),
|
dry_run: true,
|
||||||
name: name.to_string(),
|
}),
|
||||||
}]
|
1 => {
|
||||||
} else {
|
let row = rows.into_iter().next().unwrap();
|
||||||
vec![]
|
Ok(DeleteResult {
|
||||||
|
deleted: vec![DeletedEntry {
|
||||||
|
name: name.to_string(),
|
||||||
|
folder: row.folder,
|
||||||
|
entry_type: row.entry_type,
|
||||||
|
}],
|
||||||
|
dry_run: true,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
let folders: Vec<&str> = rows.iter().map(|r| r.folder.as_str()).collect();
|
||||||
|
anyhow::bail!(
|
||||||
|
"Ambiguous: {} entries named '{}' found in folders: [{}]. \
|
||||||
|
Specify 'folder' to disambiguate.",
|
||||||
|
rows.len(),
|
||||||
|
name,
|
||||||
|
folders.join(", ")
|
||||||
|
)
|
||||||
|
}
|
||||||
};
|
};
|
||||||
return Ok(DeleteResult {
|
|
||||||
deleted,
|
|
||||||
dry_run: true,
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut tx = pool.begin().await?;
|
let mut tx = pool.begin().await?;
|
||||||
|
|
||||||
let row: Option<EntryRow> = if let Some(uid) = user_id {
|
// Fetch matching rows with FOR UPDATE; use folder when provided to resolve ambiguity.
|
||||||
|
let rows: Vec<EntryRow> = if let Some(uid) = user_id {
|
||||||
|
if let Some(f) = folder {
|
||||||
|
sqlx::query_as(
|
||||||
|
"SELECT id, version, folder, type, tags, metadata, notes FROM entries \
|
||||||
|
WHERE user_id = $1 AND folder = $2 AND name = $3 FOR UPDATE",
|
||||||
|
)
|
||||||
|
.bind(uid)
|
||||||
|
.bind(f)
|
||||||
|
.bind(name)
|
||||||
|
.fetch_all(&mut *tx)
|
||||||
|
.await?
|
||||||
|
} else {
|
||||||
|
sqlx::query_as(
|
||||||
|
"SELECT id, version, folder, type, tags, metadata, notes FROM entries \
|
||||||
|
WHERE user_id = $1 AND name = $2 FOR UPDATE",
|
||||||
|
)
|
||||||
|
.bind(uid)
|
||||||
|
.bind(name)
|
||||||
|
.fetch_all(&mut *tx)
|
||||||
|
.await?
|
||||||
|
}
|
||||||
|
} else if let Some(f) = folder {
|
||||||
sqlx::query_as(
|
sqlx::query_as(
|
||||||
"SELECT id, version, tags, metadata FROM entries \
|
"SELECT id, version, folder, type, tags, metadata, notes FROM entries \
|
||||||
WHERE user_id = $1 AND namespace = $2 AND kind = $3 AND name = $4 FOR UPDATE",
|
WHERE user_id IS NULL AND folder = $1 AND name = $2 FOR UPDATE",
|
||||||
)
|
)
|
||||||
.bind(uid)
|
.bind(f)
|
||||||
.bind(namespace)
|
|
||||||
.bind(kind)
|
|
||||||
.bind(name)
|
.bind(name)
|
||||||
.fetch_optional(&mut *tx)
|
.fetch_all(&mut *tx)
|
||||||
.await?
|
.await?
|
||||||
} else {
|
} else {
|
||||||
sqlx::query_as(
|
sqlx::query_as(
|
||||||
"SELECT id, version, tags, metadata FROM entries \
|
"SELECT id, version, folder, type, tags, metadata, notes FROM entries \
|
||||||
WHERE user_id IS NULL AND namespace = $1 AND kind = $2 AND name = $3 FOR UPDATE",
|
WHERE user_id IS NULL AND name = $1 FOR UPDATE",
|
||||||
)
|
)
|
||||||
.bind(namespace)
|
|
||||||
.bind(kind)
|
|
||||||
.bind(name)
|
.bind(name)
|
||||||
.fetch_optional(&mut *tx)
|
.fetch_all(&mut *tx)
|
||||||
.await?
|
.await?
|
||||||
};
|
};
|
||||||
|
|
||||||
let Some(row) = row else {
|
let row = match rows.len() {
|
||||||
tx.rollback().await?;
|
0 => {
|
||||||
return Ok(DeleteResult {
|
tx.rollback().await?;
|
||||||
deleted: vec![],
|
return Ok(DeleteResult {
|
||||||
dry_run: false,
|
deleted: vec![],
|
||||||
});
|
dry_run: false,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
1 => rows.into_iter().next().unwrap(),
|
||||||
|
_ => {
|
||||||
|
tx.rollback().await?;
|
||||||
|
let folders: Vec<&str> = rows.iter().map(|r| r.folder.as_str()).collect();
|
||||||
|
anyhow::bail!(
|
||||||
|
"Ambiguous: {} entries named '{}' found in folders: [{}]. \
|
||||||
|
Specify 'folder' to disambiguate.",
|
||||||
|
rows.len(),
|
||||||
|
name,
|
||||||
|
folders.join(", ")
|
||||||
|
)
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
snapshot_and_delete(&mut tx, namespace, kind, name, &row, user_id).await?;
|
let folder = row.folder.clone();
|
||||||
crate::audit::log_tx(&mut tx, user_id, "delete", namespace, kind, name, json!({})).await;
|
let entry_type = row.entry_type.clone();
|
||||||
|
snapshot_and_delete(&mut tx, &folder, &entry_type, name, &row, user_id).await?;
|
||||||
|
crate::audit::log_tx(
|
||||||
|
&mut tx,
|
||||||
|
user_id,
|
||||||
|
"delete",
|
||||||
|
&folder,
|
||||||
|
&entry_type,
|
||||||
|
name,
|
||||||
|
json!({}),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
tx.commit().await?;
|
tx.commit().await?;
|
||||||
|
|
||||||
Ok(DeleteResult {
|
Ok(DeleteResult {
|
||||||
deleted: vec![DeletedEntry {
|
deleted: vec![DeletedEntry {
|
||||||
namespace: namespace.to_string(),
|
|
||||||
kind: kind.to_string(),
|
|
||||||
name: name.to_string(),
|
name: name.to_string(),
|
||||||
|
folder,
|
||||||
|
entry_type,
|
||||||
}],
|
}],
|
||||||
dry_run: false,
|
dry_run: false,
|
||||||
})
|
})
|
||||||
@@ -152,8 +224,8 @@ async fn delete_one(
|
|||||||
|
|
||||||
async fn delete_bulk(
|
async fn delete_bulk(
|
||||||
pool: &PgPool,
|
pool: &PgPool,
|
||||||
namespace: &str,
|
folder: Option<&str>,
|
||||||
kind: Option<&str>,
|
entry_type: Option<&str>,
|
||||||
dry_run: bool,
|
dry_run: bool,
|
||||||
user_id: Option<Uuid>,
|
user_id: Option<Uuid>,
|
||||||
) -> Result<DeleteResult> {
|
) -> Result<DeleteResult> {
|
||||||
@@ -161,62 +233,57 @@ async fn delete_bulk(
|
|||||||
struct FullEntryRow {
|
struct FullEntryRow {
|
||||||
id: Uuid,
|
id: Uuid,
|
||||||
version: i64,
|
version: i64,
|
||||||
kind: String,
|
folder: String,
|
||||||
|
#[sqlx(rename = "type")]
|
||||||
|
entry_type: String,
|
||||||
name: String,
|
name: String,
|
||||||
metadata: serde_json::Value,
|
metadata: serde_json::Value,
|
||||||
tags: Vec<String>,
|
tags: Vec<String>,
|
||||||
|
notes: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
let rows: Vec<FullEntryRow> = match (user_id, kind) {
|
let mut conditions: Vec<String> = Vec::new();
|
||||||
(Some(uid), Some(k)) => {
|
let mut idx: i32 = 1;
|
||||||
sqlx::query_as(
|
|
||||||
"SELECT id, version, kind, name, metadata, tags FROM entries \
|
if user_id.is_some() {
|
||||||
WHERE user_id = $1 AND namespace = $2 AND kind = $3 ORDER BY name",
|
conditions.push(format!("user_id = ${}", idx));
|
||||||
)
|
idx += 1;
|
||||||
.bind(uid)
|
} else {
|
||||||
.bind(namespace)
|
conditions.push("user_id IS NULL".to_string());
|
||||||
.bind(k)
|
}
|
||||||
.fetch_all(pool)
|
if folder.is_some() {
|
||||||
.await?
|
conditions.push(format!("folder = ${}", idx));
|
||||||
}
|
idx += 1;
|
||||||
(Some(uid), None) => {
|
}
|
||||||
sqlx::query_as(
|
if entry_type.is_some() {
|
||||||
"SELECT id, version, kind, name, metadata, tags FROM entries \
|
conditions.push(format!("type = ${}", idx));
|
||||||
WHERE user_id = $1 AND namespace = $2 ORDER BY kind, name",
|
}
|
||||||
)
|
|
||||||
.bind(uid)
|
let where_clause = format!("WHERE {}", conditions.join(" AND "));
|
||||||
.bind(namespace)
|
let sql = format!(
|
||||||
.fetch_all(pool)
|
"SELECT id, version, folder, type, name, metadata, tags, notes \
|
||||||
.await?
|
FROM entries {where_clause} ORDER BY type, name"
|
||||||
}
|
);
|
||||||
(None, Some(k)) => {
|
|
||||||
sqlx::query_as(
|
let mut q = sqlx::query_as::<_, FullEntryRow>(&sql);
|
||||||
"SELECT id, version, kind, name, metadata, tags FROM entries \
|
if let Some(uid) = user_id {
|
||||||
WHERE user_id IS NULL AND namespace = $1 AND kind = $2 ORDER BY name",
|
q = q.bind(uid);
|
||||||
)
|
}
|
||||||
.bind(namespace)
|
if let Some(f) = folder {
|
||||||
.bind(k)
|
q = q.bind(f);
|
||||||
.fetch_all(pool)
|
}
|
||||||
.await?
|
if let Some(t) = entry_type {
|
||||||
}
|
q = q.bind(t);
|
||||||
(None, None) => {
|
}
|
||||||
sqlx::query_as(
|
let rows = q.fetch_all(pool).await?;
|
||||||
"SELECT id, version, kind, name, metadata, tags FROM entries \
|
|
||||||
WHERE user_id IS NULL AND namespace = $1 ORDER BY kind, name",
|
|
||||||
)
|
|
||||||
.bind(namespace)
|
|
||||||
.fetch_all(pool)
|
|
||||||
.await?
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
if dry_run {
|
if dry_run {
|
||||||
let deleted = rows
|
let deleted = rows
|
||||||
.iter()
|
.iter()
|
||||||
.map(|r| DeletedEntry {
|
.map(|r| DeletedEntry {
|
||||||
namespace: namespace.to_string(),
|
|
||||||
kind: r.kind.clone(),
|
|
||||||
name: r.name.clone(),
|
name: r.name.clone(),
|
||||||
|
folder: r.folder.clone(),
|
||||||
|
entry_type: r.entry_type.clone(),
|
||||||
})
|
})
|
||||||
.collect();
|
.collect();
|
||||||
return Ok(DeleteResult {
|
return Ok(DeleteResult {
|
||||||
@@ -230,29 +297,37 @@ async fn delete_bulk(
|
|||||||
let entry_row = EntryRow {
|
let entry_row = EntryRow {
|
||||||
id: row.id,
|
id: row.id,
|
||||||
version: row.version,
|
version: row.version,
|
||||||
|
folder: row.folder.clone(),
|
||||||
|
entry_type: row.entry_type.clone(),
|
||||||
tags: row.tags.clone(),
|
tags: row.tags.clone(),
|
||||||
metadata: row.metadata.clone(),
|
metadata: row.metadata.clone(),
|
||||||
|
notes: row.notes.clone(),
|
||||||
};
|
};
|
||||||
let mut tx = pool.begin().await?;
|
let mut tx = pool.begin().await?;
|
||||||
snapshot_and_delete(
|
snapshot_and_delete(
|
||||||
&mut tx, namespace, &row.kind, &row.name, &entry_row, user_id,
|
&mut tx,
|
||||||
|
&row.folder,
|
||||||
|
&row.entry_type,
|
||||||
|
&row.name,
|
||||||
|
&entry_row,
|
||||||
|
user_id,
|
||||||
)
|
)
|
||||||
.await?;
|
.await?;
|
||||||
crate::audit::log_tx(
|
crate::audit::log_tx(
|
||||||
&mut tx,
|
&mut tx,
|
||||||
user_id,
|
user_id,
|
||||||
"delete",
|
"delete",
|
||||||
namespace,
|
&row.folder,
|
||||||
&row.kind,
|
&row.entry_type,
|
||||||
&row.name,
|
&row.name,
|
||||||
json!({"bulk": true}),
|
json!({"bulk": true}),
|
||||||
)
|
)
|
||||||
.await;
|
.await;
|
||||||
tx.commit().await?;
|
tx.commit().await?;
|
||||||
deleted.push(DeletedEntry {
|
deleted.push(DeletedEntry {
|
||||||
namespace: namespace.to_string(),
|
|
||||||
kind: row.kind.clone(),
|
|
||||||
name: row.name.clone(),
|
name: row.name.clone(),
|
||||||
|
folder: row.folder.clone(),
|
||||||
|
entry_type: row.entry_type.clone(),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -264,8 +339,8 @@ async fn delete_bulk(
|
|||||||
|
|
||||||
async fn snapshot_and_delete(
|
async fn snapshot_and_delete(
|
||||||
tx: &mut sqlx::Transaction<'_, sqlx::Postgres>,
|
tx: &mut sqlx::Transaction<'_, sqlx::Postgres>,
|
||||||
namespace: &str,
|
folder: &str,
|
||||||
kind: &str,
|
entry_type: &str,
|
||||||
name: &str,
|
name: &str,
|
||||||
row: &EntryRow,
|
row: &EntryRow,
|
||||||
user_id: Option<Uuid>,
|
user_id: Option<Uuid>,
|
||||||
@@ -275,8 +350,8 @@ async fn snapshot_and_delete(
|
|||||||
db::EntrySnapshotParams {
|
db::EntrySnapshotParams {
|
||||||
entry_id: row.id,
|
entry_id: row.id,
|
||||||
user_id,
|
user_id,
|
||||||
namespace,
|
folder,
|
||||||
kind,
|
entry_type,
|
||||||
name,
|
name,
|
||||||
version: row.version,
|
version: row.version,
|
||||||
action: "delete",
|
action: "delete",
|
||||||
|
|||||||
@@ -12,8 +12,8 @@ use crate::service::search::{fetch_entries, fetch_secrets_for_entries};
|
|||||||
#[allow(clippy::too_many_arguments)]
|
#[allow(clippy::too_many_arguments)]
|
||||||
pub async fn build_env_map(
|
pub async fn build_env_map(
|
||||||
pool: &PgPool,
|
pool: &PgPool,
|
||||||
namespace: Option<&str>,
|
folder: Option<&str>,
|
||||||
kind: Option<&str>,
|
entry_type: Option<&str>,
|
||||||
name: Option<&str>,
|
name: Option<&str>,
|
||||||
tags: &[String],
|
tags: &[String],
|
||||||
only_fields: &[String],
|
only_fields: &[String],
|
||||||
@@ -21,7 +21,7 @@ pub async fn build_env_map(
|
|||||||
master_key: &[u8; 32],
|
master_key: &[u8; 32],
|
||||||
user_id: Option<Uuid>,
|
user_id: Option<Uuid>,
|
||||||
) -> Result<HashMap<String, String>> {
|
) -> Result<HashMap<String, String>> {
|
||||||
let entries = fetch_entries(pool, namespace, kind, name, tags, None, user_id).await?;
|
let entries = fetch_entries(pool, folder, entry_type, name, tags, None, user_id).await?;
|
||||||
|
|
||||||
let mut combined: HashMap<String, String> = HashMap::new();
|
let mut combined: HashMap<String, String> = HashMap::new();
|
||||||
|
|
||||||
@@ -68,16 +68,8 @@ async fn build_entry_env_map(
|
|||||||
|
|
||||||
// Resolve key_ref
|
// Resolve key_ref
|
||||||
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 = fetch_entries(
|
let key_entries =
|
||||||
pool,
|
fetch_entries(pool, None, Some("key"), Some(key_ref), &[], None, None).await?;
|
||||||
Some(&entry.namespace),
|
|
||||||
Some("key"),
|
|
||||||
Some(key_ref),
|
|
||||||
&[],
|
|
||||||
None,
|
|
||||||
None,
|
|
||||||
)
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
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];
|
||||||
|
|||||||
@@ -9,8 +9,8 @@ use crate::models::{ExportData, ExportEntry, ExportFormat};
|
|||||||
use crate::service::search::{fetch_entries, fetch_secrets_for_entries};
|
use crate::service::search::{fetch_entries, fetch_secrets_for_entries};
|
||||||
|
|
||||||
pub struct ExportParams<'a> {
|
pub struct ExportParams<'a> {
|
||||||
pub namespace: Option<&'a str>,
|
pub folder: Option<&'a str>,
|
||||||
pub kind: Option<&'a str>,
|
pub entry_type: Option<&'a str>,
|
||||||
pub name: Option<&'a str>,
|
pub name: Option<&'a str>,
|
||||||
pub tags: &'a [String],
|
pub tags: &'a [String],
|
||||||
pub query: Option<&'a str>,
|
pub query: Option<&'a str>,
|
||||||
@@ -25,8 +25,8 @@ pub async fn export(
|
|||||||
) -> Result<ExportData> {
|
) -> Result<ExportData> {
|
||||||
let entries = fetch_entries(
|
let entries = fetch_entries(
|
||||||
pool,
|
pool,
|
||||||
params.namespace,
|
params.folder,
|
||||||
params.kind,
|
params.entry_type,
|
||||||
params.name,
|
params.name,
|
||||||
params.tags,
|
params.tags,
|
||||||
params.query,
|
params.query,
|
||||||
@@ -62,9 +62,10 @@ pub async fn export(
|
|||||||
};
|
};
|
||||||
|
|
||||||
export_entries.push(ExportEntry {
|
export_entries.push(ExportEntry {
|
||||||
namespace: entry.namespace.clone(),
|
|
||||||
kind: entry.kind.clone(),
|
|
||||||
name: entry.name.clone(),
|
name: entry.name.clone(),
|
||||||
|
folder: entry.folder.clone(),
|
||||||
|
entry_type: entry.entry_type.clone(),
|
||||||
|
notes: entry.notes.clone(),
|
||||||
tags: entry.tags.clone(),
|
tags: entry.tags.clone(),
|
||||||
metadata: entry.metadata.clone(),
|
metadata: entry.metadata.clone(),
|
||||||
secrets,
|
secrets,
|
||||||
|
|||||||
@@ -5,31 +5,19 @@ use std::collections::HashMap;
|
|||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
|
|
||||||
use crate::crypto;
|
use crate::crypto;
|
||||||
use crate::service::search::{fetch_entries, fetch_secrets_for_entries};
|
use crate::service::search::{fetch_secrets_for_entries, resolve_entry};
|
||||||
|
|
||||||
/// Decrypt a single named field from an entry.
|
/// Decrypt a single named field from an entry.
|
||||||
|
/// `folder` is optional; if omitted and multiple entries share the name, an error is returned.
|
||||||
pub async fn get_secret_field(
|
pub async fn get_secret_field(
|
||||||
pool: &PgPool,
|
pool: &PgPool,
|
||||||
namespace: &str,
|
|
||||||
kind: &str,
|
|
||||||
name: &str,
|
name: &str,
|
||||||
|
folder: Option<&str>,
|
||||||
field_name: &str,
|
field_name: &str,
|
||||||
master_key: &[u8; 32],
|
master_key: &[u8; 32],
|
||||||
user_id: Option<Uuid>,
|
user_id: Option<Uuid>,
|
||||||
) -> Result<Value> {
|
) -> Result<Value> {
|
||||||
let entries = fetch_entries(
|
let entry = resolve_entry(pool, name, folder, user_id).await?;
|
||||||
pool,
|
|
||||||
Some(namespace),
|
|
||||||
Some(kind),
|
|
||||||
Some(name),
|
|
||||||
&[],
|
|
||||||
None,
|
|
||||||
user_id,
|
|
||||||
)
|
|
||||||
.await?;
|
|
||||||
let entry = entries
|
|
||||||
.first()
|
|
||||||
.ok_or_else(|| anyhow::anyhow!("Not found: [{}/{}] {}", namespace, kind, name))?;
|
|
||||||
|
|
||||||
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?;
|
||||||
@@ -44,27 +32,15 @@ pub async fn get_secret_field(
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Decrypt all secret fields from an entry. Returns a map field_name → decrypted Value.
|
/// Decrypt all secret fields from an entry. Returns a map field_name → decrypted Value.
|
||||||
|
/// `folder` is optional; if omitted and multiple entries share the name, an error is returned.
|
||||||
pub async fn get_all_secrets(
|
pub async fn get_all_secrets(
|
||||||
pool: &PgPool,
|
pool: &PgPool,
|
||||||
namespace: &str,
|
|
||||||
kind: &str,
|
|
||||||
name: &str,
|
name: &str,
|
||||||
|
folder: Option<&str>,
|
||||||
master_key: &[u8; 32],
|
master_key: &[u8; 32],
|
||||||
user_id: Option<Uuid>,
|
user_id: Option<Uuid>,
|
||||||
) -> Result<HashMap<String, Value>> {
|
) -> Result<HashMap<String, Value>> {
|
||||||
let entries = fetch_entries(
|
let entry = resolve_entry(pool, name, folder, user_id).await?;
|
||||||
pool,
|
|
||||||
Some(namespace),
|
|
||||||
Some(kind),
|
|
||||||
Some(name),
|
|
||||||
&[],
|
|
||||||
None,
|
|
||||||
user_id,
|
|
||||||
)
|
|
||||||
.await?;
|
|
||||||
let entry = entries
|
|
||||||
.first()
|
|
||||||
.ok_or_else(|| anyhow::anyhow!("Not found: [{}/{}] {}", namespace, kind, name))?;
|
|
||||||
|
|
||||||
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?;
|
||||||
|
|||||||
@@ -3,19 +3,21 @@ use serde_json::Value;
|
|||||||
use sqlx::PgPool;
|
use sqlx::PgPool;
|
||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
|
|
||||||
|
use crate::service::search::resolve_entry;
|
||||||
|
|
||||||
#[derive(Debug, serde::Serialize)]
|
#[derive(Debug, serde::Serialize)]
|
||||||
pub struct HistoryEntry {
|
pub struct HistoryEntry {
|
||||||
pub version: i64,
|
pub version: i64,
|
||||||
pub action: String,
|
pub action: String,
|
||||||
pub actor: String,
|
|
||||||
pub created_at: String,
|
pub created_at: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Return version history for the entry identified by `name`.
|
||||||
|
/// `folder` is optional; if omitted and multiple entries share the name, an error is returned.
|
||||||
pub async fn run(
|
pub async fn run(
|
||||||
pool: &PgPool,
|
pool: &PgPool,
|
||||||
namespace: &str,
|
|
||||||
kind: &str,
|
|
||||||
name: &str,
|
name: &str,
|
||||||
|
folder: Option<&str>,
|
||||||
limit: u32,
|
limit: u32,
|
||||||
user_id: Option<Uuid>,
|
user_id: Option<Uuid>,
|
||||||
) -> Result<Vec<HistoryEntry>> {
|
) -> Result<Vec<HistoryEntry>> {
|
||||||
@@ -23,43 +25,25 @@ pub async fn run(
|
|||||||
struct Row {
|
struct Row {
|
||||||
version: i64,
|
version: i64,
|
||||||
action: String,
|
action: String,
|
||||||
actor: String,
|
|
||||||
created_at: chrono::DateTime<chrono::Utc>,
|
created_at: chrono::DateTime<chrono::Utc>,
|
||||||
}
|
}
|
||||||
|
|
||||||
let rows: Vec<Row> = if let Some(uid) = user_id {
|
let entry = resolve_entry(pool, name, folder, user_id).await?;
|
||||||
sqlx::query_as(
|
|
||||||
"SELECT version, action, actor, created_at FROM entries_history \
|
let rows: Vec<Row> = sqlx::query_as(
|
||||||
WHERE namespace = $1 AND kind = $2 AND name = $3 AND user_id = $4 \
|
"SELECT version, action, created_at FROM entries_history \
|
||||||
ORDER BY id DESC LIMIT $5",
|
WHERE entry_id = $1 ORDER BY id DESC LIMIT $2",
|
||||||
)
|
)
|
||||||
.bind(namespace)
|
.bind(entry.id)
|
||||||
.bind(kind)
|
.bind(limit as i64)
|
||||||
.bind(name)
|
.fetch_all(pool)
|
||||||
.bind(uid)
|
.await?;
|
||||||
.bind(limit as i64)
|
|
||||||
.fetch_all(pool)
|
|
||||||
.await?
|
|
||||||
} else {
|
|
||||||
sqlx::query_as(
|
|
||||||
"SELECT version, action, actor, created_at FROM entries_history \
|
|
||||||
WHERE namespace = $1 AND kind = $2 AND name = $3 AND user_id IS NULL \
|
|
||||||
ORDER BY id DESC LIMIT $4",
|
|
||||||
)
|
|
||||||
.bind(namespace)
|
|
||||||
.bind(kind)
|
|
||||||
.bind(name)
|
|
||||||
.bind(limit as i64)
|
|
||||||
.fetch_all(pool)
|
|
||||||
.await?
|
|
||||||
};
|
|
||||||
|
|
||||||
Ok(rows
|
Ok(rows
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.map(|r| HistoryEntry {
|
.map(|r| HistoryEntry {
|
||||||
version: r.version,
|
version: r.version,
|
||||||
action: r.action,
|
action: r.action,
|
||||||
actor: r.actor,
|
|
||||||
created_at: r.created_at.format("%Y-%m-%dT%H:%M:%SZ").to_string(),
|
created_at: r.created_at.format("%Y-%m-%dT%H:%M:%SZ").to_string(),
|
||||||
})
|
})
|
||||||
.collect())
|
.collect())
|
||||||
@@ -67,12 +51,11 @@ pub async fn run(
|
|||||||
|
|
||||||
pub async fn run_json(
|
pub async fn run_json(
|
||||||
pool: &PgPool,
|
pool: &PgPool,
|
||||||
namespace: &str,
|
|
||||||
kind: &str,
|
|
||||||
name: &str,
|
name: &str,
|
||||||
|
folder: Option<&str>,
|
||||||
limit: u32,
|
limit: u32,
|
||||||
user_id: Option<Uuid>,
|
user_id: Option<Uuid>,
|
||||||
) -> Result<Value> {
|
) -> Result<Value> {
|
||||||
let entries = run(pool, namespace, kind, name, limit, user_id).await?;
|
let entries = run(pool, name, folder, limit, user_id).await?;
|
||||||
Ok(serde_json::to_value(entries)?)
|
Ok(serde_json::to_value(entries)?)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -47,10 +47,9 @@ pub async fn run(
|
|||||||
for entry in &data.entries {
|
for entry in &data.entries {
|
||||||
let exists: bool = sqlx::query_scalar(
|
let exists: bool = sqlx::query_scalar(
|
||||||
"SELECT EXISTS(SELECT 1 FROM entries \
|
"SELECT EXISTS(SELECT 1 FROM entries \
|
||||||
WHERE namespace = $1 AND kind = $2 AND name = $3 AND user_id IS NOT DISTINCT FROM $4)",
|
WHERE folder = $1 AND name = $2 AND user_id IS NOT DISTINCT FROM $3)",
|
||||||
)
|
)
|
||||||
.bind(&entry.namespace)
|
.bind(&entry.folder)
|
||||||
.bind(&entry.kind)
|
|
||||||
.bind(&entry.name)
|
.bind(&entry.name)
|
||||||
.bind(params.user_id)
|
.bind(params.user_id)
|
||||||
.fetch_one(pool)
|
.fetch_one(pool)
|
||||||
@@ -59,9 +58,7 @@ pub async fn run(
|
|||||||
|
|
||||||
if exists && !params.force {
|
if exists && !params.force {
|
||||||
return Err(anyhow::anyhow!(
|
return Err(anyhow::anyhow!(
|
||||||
"Import aborted: conflict on [{}/{}/{}]",
|
"Import aborted: conflict on '{}'",
|
||||||
entry.namespace,
|
|
||||||
entry.kind,
|
|
||||||
entry.name
|
entry.name
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
@@ -81,9 +78,10 @@ pub async fn run(
|
|||||||
match add_run(
|
match add_run(
|
||||||
pool,
|
pool,
|
||||||
AddParams {
|
AddParams {
|
||||||
namespace: &entry.namespace,
|
|
||||||
kind: &entry.kind,
|
|
||||||
name: &entry.name,
|
name: &entry.name,
|
||||||
|
folder: &entry.folder,
|
||||||
|
entry_type: &entry.entry_type,
|
||||||
|
notes: &entry.notes,
|
||||||
tags: &entry.tags,
|
tags: &entry.tags,
|
||||||
meta_entries: &meta_entries,
|
meta_entries: &meta_entries,
|
||||||
secret_entries: &secret_entries,
|
secret_entries: &secret_entries,
|
||||||
@@ -98,8 +96,6 @@ pub async fn run(
|
|||||||
}
|
}
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
tracing::error!(
|
tracing::error!(
|
||||||
namespace = entry.namespace,
|
|
||||||
kind = entry.kind,
|
|
||||||
name = entry.name,
|
name = entry.name,
|
||||||
error = %e,
|
error = %e,
|
||||||
"failed to import entry"
|
"failed to import entry"
|
||||||
|
|||||||
@@ -8,17 +8,19 @@ use crate::db;
|
|||||||
|
|
||||||
#[derive(Debug, serde::Serialize)]
|
#[derive(Debug, serde::Serialize)]
|
||||||
pub struct RollbackResult {
|
pub struct RollbackResult {
|
||||||
pub namespace: String,
|
|
||||||
pub kind: String,
|
|
||||||
pub name: String,
|
pub name: String,
|
||||||
|
pub folder: String,
|
||||||
|
#[serde(rename = "type")]
|
||||||
|
pub entry_type: String,
|
||||||
pub restored_version: i64,
|
pub restored_version: i64,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Roll back entry `name` to `to_version` (or the most recent snapshot if None).
|
||||||
|
/// `folder` is optional; if omitted and multiple entries share the name, an error is returned.
|
||||||
pub async fn run(
|
pub async fn run(
|
||||||
pool: &PgPool,
|
pool: &PgPool,
|
||||||
namespace: &str,
|
|
||||||
kind: &str,
|
|
||||||
name: &str,
|
name: &str,
|
||||||
|
folder: Option<&str>,
|
||||||
to_version: Option<i64>,
|
to_version: Option<i64>,
|
||||||
master_key: &[u8; 32],
|
master_key: &[u8; 32],
|
||||||
user_id: Option<Uuid>,
|
user_id: Option<Uuid>,
|
||||||
@@ -26,69 +28,122 @@ pub async fn run(
|
|||||||
#[derive(sqlx::FromRow)]
|
#[derive(sqlx::FromRow)]
|
||||||
struct EntryHistoryRow {
|
struct EntryHistoryRow {
|
||||||
entry_id: Uuid,
|
entry_id: Uuid,
|
||||||
|
folder: String,
|
||||||
|
#[sqlx(rename = "type")]
|
||||||
|
entry_type: String,
|
||||||
version: i64,
|
version: i64,
|
||||||
action: String,
|
action: String,
|
||||||
tags: Vec<String>,
|
tags: Vec<String>,
|
||||||
metadata: Value,
|
metadata: Value,
|
||||||
}
|
}
|
||||||
|
|
||||||
let snap: Option<EntryHistoryRow> = if let Some(ver) = to_version {
|
// Disambiguate: find the unique entry_id for (name, folder).
|
||||||
if let Some(uid) = user_id {
|
// Query entries_history by entry_id once we know it; first resolve via name + optional folder.
|
||||||
sqlx::query_as(
|
let entry_id: Option<Uuid> = if let Some(uid) = user_id {
|
||||||
"SELECT entry_id, version, action, tags, metadata FROM entries_history \
|
if let Some(f) = folder {
|
||||||
WHERE namespace = $1 AND kind = $2 AND name = $3 AND version = $4 \
|
sqlx::query_scalar(
|
||||||
AND user_id = $5 ORDER BY id DESC LIMIT 1",
|
"SELECT DISTINCT entry_id FROM entries_history \
|
||||||
|
WHERE name = $1 AND folder = $2 AND user_id = $3 LIMIT 1",
|
||||||
)
|
)
|
||||||
.bind(namespace)
|
|
||||||
.bind(kind)
|
|
||||||
.bind(name)
|
.bind(name)
|
||||||
.bind(ver)
|
.bind(f)
|
||||||
.bind(uid)
|
.bind(uid)
|
||||||
.fetch_optional(pool)
|
.fetch_optional(pool)
|
||||||
.await?
|
.await?
|
||||||
} else {
|
} else {
|
||||||
sqlx::query_as(
|
let ids: Vec<Uuid> = sqlx::query_scalar(
|
||||||
"SELECT entry_id, version, action, tags, metadata FROM entries_history \
|
"SELECT DISTINCT entry_id FROM entries_history \
|
||||||
WHERE namespace = $1 AND kind = $2 AND name = $3 AND version = $4 \
|
WHERE name = $1 AND user_id = $2",
|
||||||
AND user_id IS NULL ORDER BY id DESC LIMIT 1",
|
|
||||||
)
|
)
|
||||||
.bind(namespace)
|
|
||||||
.bind(kind)
|
|
||||||
.bind(name)
|
.bind(name)
|
||||||
.bind(ver)
|
.bind(uid)
|
||||||
.fetch_optional(pool)
|
.fetch_all(pool)
|
||||||
.await?
|
.await?;
|
||||||
|
match ids.len() {
|
||||||
|
0 => None,
|
||||||
|
1 => Some(ids[0]),
|
||||||
|
_ => {
|
||||||
|
let folders: Vec<String> = sqlx::query_scalar(
|
||||||
|
"SELECT DISTINCT folder FROM entries_history \
|
||||||
|
WHERE name = $1 AND user_id = $2",
|
||||||
|
)
|
||||||
|
.bind(name)
|
||||||
|
.bind(uid)
|
||||||
|
.fetch_all(pool)
|
||||||
|
.await?;
|
||||||
|
anyhow::bail!(
|
||||||
|
"Ambiguous: entries named '{}' exist in folders: [{}]. \
|
||||||
|
Specify 'folder' to disambiguate.",
|
||||||
|
name,
|
||||||
|
folders.join(", ")
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
} else if let Some(uid) = user_id {
|
} else if let Some(f) = folder {
|
||||||
sqlx::query_as(
|
sqlx::query_scalar(
|
||||||
"SELECT entry_id, version, action, tags, metadata FROM entries_history \
|
"SELECT DISTINCT entry_id FROM entries_history \
|
||||||
WHERE namespace = $1 AND kind = $2 AND name = $3 \
|
WHERE name = $1 AND folder = $2 AND user_id IS NULL LIMIT 1",
|
||||||
AND user_id = $4 ORDER BY id DESC LIMIT 1",
|
|
||||||
)
|
)
|
||||||
.bind(namespace)
|
|
||||||
.bind(kind)
|
|
||||||
.bind(name)
|
.bind(name)
|
||||||
.bind(uid)
|
.bind(f)
|
||||||
|
.fetch_optional(pool)
|
||||||
|
.await?
|
||||||
|
} else {
|
||||||
|
let ids: Vec<Uuid> = sqlx::query_scalar(
|
||||||
|
"SELECT DISTINCT entry_id FROM entries_history \
|
||||||
|
WHERE name = $1 AND user_id IS NULL",
|
||||||
|
)
|
||||||
|
.bind(name)
|
||||||
|
.fetch_all(pool)
|
||||||
|
.await?;
|
||||||
|
match ids.len() {
|
||||||
|
0 => None,
|
||||||
|
1 => Some(ids[0]),
|
||||||
|
_ => {
|
||||||
|
let folders: Vec<String> = sqlx::query_scalar(
|
||||||
|
"SELECT DISTINCT folder FROM entries_history \
|
||||||
|
WHERE name = $1 AND user_id IS NULL",
|
||||||
|
)
|
||||||
|
.bind(name)
|
||||||
|
.fetch_all(pool)
|
||||||
|
.await?;
|
||||||
|
anyhow::bail!(
|
||||||
|
"Ambiguous: entries named '{}' exist in folders: [{}]. \
|
||||||
|
Specify 'folder' to disambiguate.",
|
||||||
|
name,
|
||||||
|
folders.join(", ")
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let entry_id = entry_id.ok_or_else(|| anyhow::anyhow!("No history found for '{}'", name))?;
|
||||||
|
|
||||||
|
let snap: Option<EntryHistoryRow> = if let Some(ver) = to_version {
|
||||||
|
sqlx::query_as(
|
||||||
|
"SELECT entry_id, folder, type, version, action, tags, metadata \
|
||||||
|
FROM entries_history \
|
||||||
|
WHERE entry_id = $1 AND version = $2 ORDER BY id DESC LIMIT 1",
|
||||||
|
)
|
||||||
|
.bind(entry_id)
|
||||||
|
.bind(ver)
|
||||||
.fetch_optional(pool)
|
.fetch_optional(pool)
|
||||||
.await?
|
.await?
|
||||||
} else {
|
} else {
|
||||||
sqlx::query_as(
|
sqlx::query_as(
|
||||||
"SELECT entry_id, version, action, tags, metadata FROM entries_history \
|
"SELECT entry_id, folder, type, version, action, tags, metadata \
|
||||||
WHERE namespace = $1 AND kind = $2 AND name = $3 \
|
FROM entries_history \
|
||||||
AND user_id IS NULL ORDER BY id DESC LIMIT 1",
|
WHERE entry_id = $1 ORDER BY id DESC LIMIT 1",
|
||||||
)
|
)
|
||||||
.bind(namespace)
|
.bind(entry_id)
|
||||||
.bind(kind)
|
|
||||||
.bind(name)
|
|
||||||
.fetch_optional(pool)
|
.fetch_optional(pool)
|
||||||
.await?
|
.await?
|
||||||
};
|
};
|
||||||
|
|
||||||
let snap = snap.ok_or_else(|| {
|
let snap = snap.ok_or_else(|| {
|
||||||
anyhow::anyhow!(
|
anyhow::anyhow!(
|
||||||
"No history found for [{}/{}] {}{}.",
|
"No history found for '{}'{}.",
|
||||||
namespace,
|
|
||||||
kind,
|
|
||||||
name,
|
name,
|
||||||
to_version
|
to_version
|
||||||
.map(|v| format!(" at version {}", v))
|
.map(|v| format!(" at version {}", v))
|
||||||
@@ -130,43 +185,32 @@ pub async fn run(
|
|||||||
struct LiveEntry {
|
struct LiveEntry {
|
||||||
id: Uuid,
|
id: Uuid,
|
||||||
version: i64,
|
version: i64,
|
||||||
|
folder: String,
|
||||||
|
#[sqlx(rename = "type")]
|
||||||
|
entry_type: String,
|
||||||
tags: Vec<String>,
|
tags: Vec<String>,
|
||||||
metadata: Value,
|
metadata: Value,
|
||||||
|
#[allow(dead_code)]
|
||||||
|
notes: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
// Query live entry with correct user_id scoping to avoid PK conflicts
|
// Lock the live entry if it exists (matched by entry_id for precision).
|
||||||
let live: Option<LiveEntry> = if let Some(uid) = user_id {
|
let live: Option<LiveEntry> = sqlx::query_as(
|
||||||
sqlx::query_as(
|
"SELECT id, version, folder, type, tags, metadata, notes FROM entries \
|
||||||
"SELECT id, version, tags, metadata FROM entries \
|
WHERE id = $1 FOR UPDATE",
|
||||||
WHERE user_id = $1 AND namespace = $2 AND kind = $3 AND name = $4 FOR UPDATE",
|
)
|
||||||
)
|
.bind(entry_id)
|
||||||
.bind(uid)
|
.fetch_optional(&mut *tx)
|
||||||
.bind(namespace)
|
.await?;
|
||||||
.bind(kind)
|
|
||||||
.bind(name)
|
|
||||||
.fetch_optional(&mut *tx)
|
|
||||||
.await?
|
|
||||||
} else {
|
|
||||||
sqlx::query_as(
|
|
||||||
"SELECT id, version, tags, metadata FROM entries \
|
|
||||||
WHERE user_id IS NULL AND namespace = $1 AND kind = $2 AND name = $3 FOR UPDATE",
|
|
||||||
)
|
|
||||||
.bind(namespace)
|
|
||||||
.bind(kind)
|
|
||||||
.bind(name)
|
|
||||||
.fetch_optional(&mut *tx)
|
|
||||||
.await?
|
|
||||||
};
|
|
||||||
|
|
||||||
let entry_id = if let Some(ref lr) = live {
|
let live_entry_id = if let Some(ref lr) = live {
|
||||||
// Snapshot current state before overwriting
|
|
||||||
if let Err(e) = db::snapshot_entry_history(
|
if let Err(e) = db::snapshot_entry_history(
|
||||||
&mut tx,
|
&mut tx,
|
||||||
db::EntrySnapshotParams {
|
db::EntrySnapshotParams {
|
||||||
entry_id: lr.id,
|
entry_id: lr.id,
|
||||||
user_id,
|
user_id,
|
||||||
namespace,
|
folder: &lr.folder,
|
||||||
kind,
|
entry_type: &lr.entry_type,
|
||||||
name,
|
name,
|
||||||
version: lr.version,
|
version: lr.version,
|
||||||
action: "rollback",
|
action: "rollback",
|
||||||
@@ -209,7 +253,6 @@ pub async fn run(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Update the existing row in-place to preserve its primary key and user_id
|
|
||||||
sqlx::query(
|
sqlx::query(
|
||||||
"UPDATE entries SET tags = $1, metadata = $2, version = version + 1, \
|
"UPDATE entries SET tags = $1, metadata = $2, version = version + 1, \
|
||||||
updated_at = NOW() WHERE id = $3",
|
updated_at = NOW() WHERE id = $3",
|
||||||
@@ -222,16 +265,15 @@ pub async fn run(
|
|||||||
|
|
||||||
lr.id
|
lr.id
|
||||||
} else {
|
} else {
|
||||||
// No live entry — insert a fresh one with a new UUID
|
|
||||||
if let Some(uid) = user_id {
|
if let Some(uid) = user_id {
|
||||||
sqlx::query_scalar(
|
sqlx::query_scalar(
|
||||||
"INSERT INTO entries \
|
"INSERT INTO entries \
|
||||||
(user_id, namespace, kind, name, tags, metadata, version, updated_at) \
|
(user_id, folder, type, name, notes, tags, metadata, version, updated_at) \
|
||||||
VALUES ($1, $2, $3, $4, $5, $6, $7, NOW()) RETURNING id",
|
VALUES ($1, $2, $3, $4, '', $5, $6, $7, NOW()) RETURNING id",
|
||||||
)
|
)
|
||||||
.bind(uid)
|
.bind(uid)
|
||||||
.bind(namespace)
|
.bind(&snap.folder)
|
||||||
.bind(kind)
|
.bind(&snap.entry_type)
|
||||||
.bind(name)
|
.bind(name)
|
||||||
.bind(&snap.tags)
|
.bind(&snap.tags)
|
||||||
.bind(&snap.metadata)
|
.bind(&snap.metadata)
|
||||||
@@ -241,11 +283,11 @@ pub async fn run(
|
|||||||
} else {
|
} else {
|
||||||
sqlx::query_scalar(
|
sqlx::query_scalar(
|
||||||
"INSERT INTO entries \
|
"INSERT INTO entries \
|
||||||
(namespace, kind, name, tags, metadata, version, updated_at) \
|
(folder, type, name, notes, tags, metadata, version, updated_at) \
|
||||||
VALUES ($1, $2, $3, $4, $5, $6, NOW()) RETURNING id",
|
VALUES ($1, $2, $3, '', $4, $5, $6, NOW()) RETURNING id",
|
||||||
)
|
)
|
||||||
.bind(namespace)
|
.bind(&snap.folder)
|
||||||
.bind(kind)
|
.bind(&snap.entry_type)
|
||||||
.bind(name)
|
.bind(name)
|
||||||
.bind(&snap.tags)
|
.bind(&snap.tags)
|
||||||
.bind(&snap.metadata)
|
.bind(&snap.metadata)
|
||||||
@@ -256,7 +298,7 @@ pub async fn run(
|
|||||||
};
|
};
|
||||||
|
|
||||||
sqlx::query("DELETE FROM secrets WHERE entry_id = $1")
|
sqlx::query("DELETE FROM secrets WHERE entry_id = $1")
|
||||||
.bind(entry_id)
|
.bind(live_entry_id)
|
||||||
.execute(&mut *tx)
|
.execute(&mut *tx)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
@@ -265,7 +307,7 @@ pub async fn run(
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
sqlx::query("INSERT INTO secrets (entry_id, field_name, encrypted) VALUES ($1, $2, $3)")
|
sqlx::query("INSERT INTO secrets (entry_id, field_name, encrypted) VALUES ($1, $2, $3)")
|
||||||
.bind(entry_id)
|
.bind(live_entry_id)
|
||||||
.bind(&f.field_name)
|
.bind(&f.field_name)
|
||||||
.bind(&f.encrypted)
|
.bind(&f.encrypted)
|
||||||
.execute(&mut *tx)
|
.execute(&mut *tx)
|
||||||
@@ -276,8 +318,8 @@ pub async fn run(
|
|||||||
&mut tx,
|
&mut tx,
|
||||||
user_id,
|
user_id,
|
||||||
"rollback",
|
"rollback",
|
||||||
namespace,
|
&snap.folder,
|
||||||
kind,
|
&snap.entry_type,
|
||||||
name,
|
name,
|
||||||
serde_json::json!({
|
serde_json::json!({
|
||||||
"restored_version": snap.version,
|
"restored_version": snap.version,
|
||||||
@@ -289,9 +331,9 @@ pub async fn run(
|
|||||||
tx.commit().await?;
|
tx.commit().await?;
|
||||||
|
|
||||||
Ok(RollbackResult {
|
Ok(RollbackResult {
|
||||||
namespace: namespace.to_string(),
|
|
||||||
kind: kind.to_string(),
|
|
||||||
name: name.to_string(),
|
name: name.to_string(),
|
||||||
|
folder: snap.folder,
|
||||||
|
entry_type: snap.entry_type,
|
||||||
restored_version: snap.version,
|
restored_version: snap.version,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,8 +9,8 @@ use crate::models::{Entry, SecretField};
|
|||||||
pub const FETCH_ALL_LIMIT: u32 = 100_000;
|
pub const FETCH_ALL_LIMIT: u32 = 100_000;
|
||||||
|
|
||||||
pub struct SearchParams<'a> {
|
pub struct SearchParams<'a> {
|
||||||
pub namespace: Option<&'a str>,
|
pub folder: Option<&'a str>,
|
||||||
pub kind: Option<&'a str>,
|
pub entry_type: Option<&'a str>,
|
||||||
pub name: Option<&'a str>,
|
pub name: Option<&'a str>,
|
||||||
pub tags: &'a [String],
|
pub tags: &'a [String],
|
||||||
pub query: Option<&'a str>,
|
pub query: Option<&'a str>,
|
||||||
@@ -44,16 +44,16 @@ pub async fn run(pool: &PgPool, params: SearchParams<'_>) -> Result<SearchResult
|
|||||||
/// Fetch entries matching the given filters — returns all matching entries up to FETCH_ALL_LIMIT.
|
/// Fetch entries matching the given filters — returns all matching entries up to FETCH_ALL_LIMIT.
|
||||||
pub async fn fetch_entries(
|
pub async fn fetch_entries(
|
||||||
pool: &PgPool,
|
pool: &PgPool,
|
||||||
namespace: Option<&str>,
|
folder: Option<&str>,
|
||||||
kind: Option<&str>,
|
entry_type: Option<&str>,
|
||||||
name: Option<&str>,
|
name: Option<&str>,
|
||||||
tags: &[String],
|
tags: &[String],
|
||||||
query: Option<&str>,
|
query: Option<&str>,
|
||||||
user_id: Option<Uuid>,
|
user_id: Option<Uuid>,
|
||||||
) -> Result<Vec<Entry>> {
|
) -> Result<Vec<Entry>> {
|
||||||
let params = SearchParams {
|
let params = SearchParams {
|
||||||
namespace,
|
folder,
|
||||||
kind,
|
entry_type,
|
||||||
name,
|
name,
|
||||||
tags,
|
tags,
|
||||||
query,
|
query,
|
||||||
@@ -77,12 +77,12 @@ async fn fetch_entries_paged(pool: &PgPool, a: &SearchParams<'_>) -> Result<Vec<
|
|||||||
conditions.push("user_id IS NULL".to_string());
|
conditions.push("user_id IS NULL".to_string());
|
||||||
}
|
}
|
||||||
|
|
||||||
if a.namespace.is_some() {
|
if a.folder.is_some() {
|
||||||
conditions.push(format!("namespace = ${}", idx));
|
conditions.push(format!("folder = ${}", idx));
|
||||||
idx += 1;
|
idx += 1;
|
||||||
}
|
}
|
||||||
if a.kind.is_some() {
|
if a.entry_type.is_some() {
|
||||||
conditions.push(format!("kind = ${}", idx));
|
conditions.push(format!("type = ${}", idx));
|
||||||
idx += 1;
|
idx += 1;
|
||||||
}
|
}
|
||||||
if a.name.is_some() {
|
if a.name.is_some() {
|
||||||
@@ -106,8 +106,9 @@ async fn fetch_entries_paged(pool: &PgPool, a: &SearchParams<'_>) -> Result<Vec<
|
|||||||
}
|
}
|
||||||
if a.query.is_some() {
|
if a.query.is_some() {
|
||||||
conditions.push(format!(
|
conditions.push(format!(
|
||||||
"(name ILIKE ${i} ESCAPE '\\' OR namespace ILIKE ${i} ESCAPE '\\' \
|
"(name ILIKE ${i} ESCAPE '\\' OR folder ILIKE ${i} ESCAPE '\\' \
|
||||||
OR kind ILIKE ${i} ESCAPE '\\' OR metadata::text ILIKE ${i} ESCAPE '\\' \
|
OR type ILIKE ${i} ESCAPE '\\' OR notes ILIKE ${i} ESCAPE '\\' \
|
||||||
|
OR metadata::text ILIKE ${i} ESCAPE '\\' \
|
||||||
OR EXISTS (SELECT 1 FROM unnest(tags) t WHERE t ILIKE ${i} ESCAPE '\\'))",
|
OR EXISTS (SELECT 1 FROM unnest(tags) t WHERE t ILIKE ${i} ESCAPE '\\'))",
|
||||||
i = idx
|
i = idx
|
||||||
));
|
));
|
||||||
@@ -131,8 +132,8 @@ async fn fetch_entries_paged(pool: &PgPool, a: &SearchParams<'_>) -> Result<Vec<
|
|||||||
};
|
};
|
||||||
|
|
||||||
let sql = format!(
|
let sql = format!(
|
||||||
"SELECT id, COALESCE(user_id, '00000000-0000-0000-0000-000000000000'::uuid) AS user_id, \
|
"SELECT id, user_id, folder, type, name, notes, tags, metadata, version, \
|
||||||
namespace, kind, name, tags, metadata, version, created_at, updated_at \
|
created_at, updated_at \
|
||||||
FROM entries {where_clause} ORDER BY {order} LIMIT ${limit_idx} OFFSET ${offset_idx}"
|
FROM entries {where_clause} ORDER BY {order} LIMIT ${limit_idx} OFFSET ${offset_idx}"
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -141,10 +142,10 @@ async fn fetch_entries_paged(pool: &PgPool, a: &SearchParams<'_>) -> Result<Vec<
|
|||||||
if let Some(uid) = a.user_id {
|
if let Some(uid) = a.user_id {
|
||||||
q = q.bind(uid);
|
q = q.bind(uid);
|
||||||
}
|
}
|
||||||
if let Some(v) = a.namespace {
|
if let Some(v) = a.folder {
|
||||||
q = q.bind(v);
|
q = q.bind(v);
|
||||||
}
|
}
|
||||||
if let Some(v) = a.kind {
|
if let Some(v) = a.entry_type {
|
||||||
q = q.bind(v);
|
q = q.bind(v);
|
||||||
}
|
}
|
||||||
if let Some(v) = a.name {
|
if let Some(v) = a.name {
|
||||||
@@ -207,16 +208,51 @@ pub async fn fetch_secrets_for_entries(
|
|||||||
Ok(map)
|
Ok(map)
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Internal raw row (because user_id is nullable in DB) ─────────────────────
|
/// Resolve exactly one entry by name, with optional folder for disambiguation.
|
||||||
|
///
|
||||||
|
/// - If `folder` is provided: exact `(folder, name)` match.
|
||||||
|
/// - If `folder` is None and exactly one entry matches: returns it.
|
||||||
|
/// - If `folder` is None and multiple entries match: returns an error listing
|
||||||
|
/// the folders and asking the caller to specify one.
|
||||||
|
pub async fn resolve_entry(
|
||||||
|
pool: &PgPool,
|
||||||
|
name: &str,
|
||||||
|
folder: Option<&str>,
|
||||||
|
user_id: Option<Uuid>,
|
||||||
|
) -> Result<crate::models::Entry> {
|
||||||
|
let entries = fetch_entries(pool, folder, None, Some(name), &[], None, user_id).await?;
|
||||||
|
match entries.len() {
|
||||||
|
0 => {
|
||||||
|
if let Some(f) = folder {
|
||||||
|
anyhow::bail!("Not found: '{}' in folder '{}'", name, f)
|
||||||
|
} else {
|
||||||
|
anyhow::bail!("Not found: '{}'", name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
1 => Ok(entries.into_iter().next().unwrap()),
|
||||||
|
_ => {
|
||||||
|
let folders: Vec<&str> = entries.iter().map(|e| e.folder.as_str()).collect();
|
||||||
|
anyhow::bail!(
|
||||||
|
"Ambiguous: {} entries named '{}' found in folders: [{}]. \
|
||||||
|
Specify 'folder' to disambiguate.",
|
||||||
|
entries.len(),
|
||||||
|
name,
|
||||||
|
folders.join(", ")
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Internal raw row (because user_id is nullable in DB) ─────────────────────
|
||||||
#[derive(sqlx::FromRow)]
|
#[derive(sqlx::FromRow)]
|
||||||
struct EntryRaw {
|
struct EntryRaw {
|
||||||
id: Uuid,
|
id: Uuid,
|
||||||
#[allow(dead_code)] // Selected for row shape; Entry model has no user_id field
|
user_id: Option<Uuid>,
|
||||||
user_id: Uuid,
|
folder: String,
|
||||||
namespace: String,
|
#[sqlx(rename = "type")]
|
||||||
kind: String,
|
entry_type: String,
|
||||||
name: String,
|
name: String,
|
||||||
|
notes: String,
|
||||||
tags: Vec<String>,
|
tags: Vec<String>,
|
||||||
metadata: Value,
|
metadata: Value,
|
||||||
version: i64,
|
version: i64,
|
||||||
@@ -228,9 +264,11 @@ impl From<EntryRaw> for Entry {
|
|||||||
fn from(r: EntryRaw) -> Self {
|
fn from(r: EntryRaw) -> Self {
|
||||||
Entry {
|
Entry {
|
||||||
id: r.id,
|
id: r.id,
|
||||||
namespace: r.namespace,
|
user_id: r.user_id,
|
||||||
kind: r.kind,
|
folder: r.folder,
|
||||||
|
entry_type: r.entry_type,
|
||||||
name: r.name,
|
name: r.name,
|
||||||
|
notes: r.notes,
|
||||||
tags: r.tags,
|
tags: r.tags,
|
||||||
metadata: r.metadata,
|
metadata: r.metadata,
|
||||||
version: r.version,
|
version: r.version,
|
||||||
|
|||||||
@@ -13,9 +13,10 @@ use crate::service::add::{
|
|||||||
|
|
||||||
#[derive(Debug, serde::Serialize)]
|
#[derive(Debug, serde::Serialize)]
|
||||||
pub struct UpdateResult {
|
pub struct UpdateResult {
|
||||||
pub namespace: String,
|
|
||||||
pub kind: String,
|
|
||||||
pub name: String,
|
pub name: String,
|
||||||
|
pub folder: String,
|
||||||
|
#[serde(rename = "type")]
|
||||||
|
pub entry_type: String,
|
||||||
pub add_tags: Vec<String>,
|
pub add_tags: Vec<String>,
|
||||||
pub remove_tags: Vec<String>,
|
pub remove_tags: Vec<String>,
|
||||||
pub meta_keys: Vec<String>,
|
pub meta_keys: Vec<String>,
|
||||||
@@ -25,9 +26,10 @@ pub struct UpdateResult {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub struct UpdateParams<'a> {
|
pub struct UpdateParams<'a> {
|
||||||
pub namespace: &'a str,
|
|
||||||
pub kind: &'a str,
|
|
||||||
pub name: &'a str,
|
pub name: &'a str,
|
||||||
|
/// Optional folder for disambiguation when multiple entries share the same name.
|
||||||
|
pub folder: Option<&'a str>,
|
||||||
|
pub notes: Option<&'a str>,
|
||||||
pub add_tags: &'a [String],
|
pub add_tags: &'a [String],
|
||||||
pub remove_tags: &'a [String],
|
pub remove_tags: &'a [String],
|
||||||
pub meta_entries: &'a [String],
|
pub meta_entries: &'a [String],
|
||||||
@@ -44,45 +46,76 @@ pub async fn run(
|
|||||||
) -> Result<UpdateResult> {
|
) -> Result<UpdateResult> {
|
||||||
let mut tx = pool.begin().await?;
|
let mut tx = pool.begin().await?;
|
||||||
|
|
||||||
let row: Option<EntryRow> = if let Some(uid) = params.user_id {
|
// Fetch matching rows with FOR UPDATE; use folder when provided to resolve ambiguity.
|
||||||
|
let rows: Vec<EntryRow> = if let Some(uid) = params.user_id {
|
||||||
|
if let Some(folder) = params.folder {
|
||||||
|
sqlx::query_as(
|
||||||
|
"SELECT id, version, folder, type, tags, metadata, notes FROM entries \
|
||||||
|
WHERE user_id = $1 AND folder = $2 AND name = $3 FOR UPDATE",
|
||||||
|
)
|
||||||
|
.bind(uid)
|
||||||
|
.bind(folder)
|
||||||
|
.bind(params.name)
|
||||||
|
.fetch_all(&mut *tx)
|
||||||
|
.await?
|
||||||
|
} else {
|
||||||
|
sqlx::query_as(
|
||||||
|
"SELECT id, version, folder, type, tags, metadata, notes FROM entries \
|
||||||
|
WHERE user_id = $1 AND name = $2 FOR UPDATE",
|
||||||
|
)
|
||||||
|
.bind(uid)
|
||||||
|
.bind(params.name)
|
||||||
|
.fetch_all(&mut *tx)
|
||||||
|
.await?
|
||||||
|
}
|
||||||
|
} else if let Some(folder) = params.folder {
|
||||||
sqlx::query_as(
|
sqlx::query_as(
|
||||||
"SELECT id, version, tags, metadata FROM entries \
|
"SELECT id, version, folder, type, tags, metadata, notes FROM entries \
|
||||||
WHERE user_id = $1 AND namespace = $2 AND kind = $3 AND name = $4 FOR UPDATE",
|
WHERE user_id IS NULL AND folder = $1 AND name = $2 FOR UPDATE",
|
||||||
)
|
)
|
||||||
.bind(uid)
|
.bind(folder)
|
||||||
.bind(params.namespace)
|
|
||||||
.bind(params.kind)
|
|
||||||
.bind(params.name)
|
.bind(params.name)
|
||||||
.fetch_optional(&mut *tx)
|
.fetch_all(&mut *tx)
|
||||||
.await?
|
.await?
|
||||||
} else {
|
} else {
|
||||||
sqlx::query_as(
|
sqlx::query_as(
|
||||||
"SELECT id, version, tags, metadata FROM entries \
|
"SELECT id, version, folder, type, tags, metadata, notes FROM entries \
|
||||||
WHERE user_id IS NULL AND namespace = $1 AND kind = $2 AND name = $3 FOR UPDATE",
|
WHERE user_id IS NULL AND name = $1 FOR UPDATE",
|
||||||
)
|
)
|
||||||
.bind(params.namespace)
|
|
||||||
.bind(params.kind)
|
|
||||||
.bind(params.name)
|
.bind(params.name)
|
||||||
.fetch_optional(&mut *tx)
|
.fetch_all(&mut *tx)
|
||||||
.await?
|
.await?
|
||||||
};
|
};
|
||||||
|
|
||||||
let row = row.ok_or_else(|| {
|
let row = match rows.len() {
|
||||||
anyhow::anyhow!(
|
0 => {
|
||||||
"Not found: [{}/{}] {}. Use `add` to create it first.",
|
tx.rollback().await?;
|
||||||
params.namespace,
|
anyhow::bail!(
|
||||||
params.kind,
|
"Not found: '{}'. Use `add` to create it first.",
|
||||||
params.name
|
params.name
|
||||||
)
|
)
|
||||||
})?;
|
}
|
||||||
|
1 => rows.into_iter().next().unwrap(),
|
||||||
|
_ => {
|
||||||
|
tx.rollback().await?;
|
||||||
|
let folders: Vec<&str> = rows.iter().map(|r| r.folder.as_str()).collect();
|
||||||
|
anyhow::bail!(
|
||||||
|
"Ambiguous: {} entries named '{}' found in folders: [{}]. \
|
||||||
|
Specify 'folder' to disambiguate.",
|
||||||
|
rows.len(),
|
||||||
|
params.name,
|
||||||
|
folders.join(", ")
|
||||||
|
)
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
if let Err(e) = db::snapshot_entry_history(
|
if let Err(e) = db::snapshot_entry_history(
|
||||||
&mut tx,
|
&mut tx,
|
||||||
db::EntrySnapshotParams {
|
db::EntrySnapshotParams {
|
||||||
entry_id: row.id,
|
entry_id: row.id,
|
||||||
user_id: params.user_id,
|
user_id: params.user_id,
|
||||||
namespace: params.namespace,
|
folder: &row.folder,
|
||||||
kind: params.kind,
|
entry_type: &row.entry_type,
|
||||||
name: params.name,
|
name: params.name,
|
||||||
version: row.version,
|
version: row.version,
|
||||||
action: "update",
|
action: "update",
|
||||||
@@ -117,12 +150,16 @@ pub async fn run(
|
|||||||
}
|
}
|
||||||
let metadata = Value::Object(meta_map);
|
let metadata = Value::Object(meta_map);
|
||||||
|
|
||||||
|
let new_notes = params.notes.unwrap_or(&row.notes);
|
||||||
|
|
||||||
let result = sqlx::query(
|
let result = sqlx::query(
|
||||||
"UPDATE entries SET tags = $1, metadata = $2, version = version + 1, updated_at = NOW() \
|
"UPDATE entries SET tags = $1, metadata = $2, notes = $3, \
|
||||||
WHERE id = $3 AND version = $4",
|
version = version + 1, updated_at = NOW() \
|
||||||
|
WHERE id = $4 AND version = $5",
|
||||||
)
|
)
|
||||||
.bind(&tags)
|
.bind(&tags)
|
||||||
.bind(&metadata)
|
.bind(&metadata)
|
||||||
|
.bind(new_notes)
|
||||||
.bind(row.id)
|
.bind(row.id)
|
||||||
.bind(row.version)
|
.bind(row.version)
|
||||||
.execute(&mut *tx)
|
.execute(&mut *tx)
|
||||||
@@ -131,9 +168,7 @@ pub async fn run(
|
|||||||
if result.rows_affected() == 0 {
|
if result.rows_affected() == 0 {
|
||||||
tx.rollback().await?;
|
tx.rollback().await?;
|
||||||
anyhow::bail!(
|
anyhow::bail!(
|
||||||
"Concurrent modification detected for [{}/{}] {}. Please retry.",
|
"Concurrent modification detected for '{}'. Please retry.",
|
||||||
params.namespace,
|
|
||||||
params.kind,
|
|
||||||
params.name
|
params.name
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -243,8 +278,8 @@ pub async fn run(
|
|||||||
&mut tx,
|
&mut tx,
|
||||||
params.user_id,
|
params.user_id,
|
||||||
"update",
|
"update",
|
||||||
params.namespace,
|
"",
|
||||||
params.kind,
|
"",
|
||||||
params.name,
|
params.name,
|
||||||
serde_json::json!({
|
serde_json::json!({
|
||||||
"add_tags": params.add_tags,
|
"add_tags": params.add_tags,
|
||||||
@@ -260,9 +295,9 @@ pub async fn run(
|
|||||||
tx.commit().await?;
|
tx.commit().await?;
|
||||||
|
|
||||||
Ok(UpdateResult {
|
Ok(UpdateResult {
|
||||||
namespace: params.namespace.to_string(),
|
|
||||||
kind: params.kind.to_string(),
|
|
||||||
name: params.name.to_string(),
|
name: params.name.to_string(),
|
||||||
|
folder: row.folder.clone(),
|
||||||
|
entry_type: row.entry_type.clone(),
|
||||||
add_tags: params.add_tags.to_vec(),
|
add_tags: params.add_tags.to_vec(),
|
||||||
remove_tags: params.remove_tags.to_vec(),
|
remove_tags: params.remove_tags.to_vec(),
|
||||||
meta_keys,
|
meta_keys,
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "secrets-mcp"
|
name = "secrets-mcp"
|
||||||
version = "0.1.9"
|
version = "0.3.0"
|
||||||
edition.workspace = true
|
edition.workspace = true
|
||||||
|
|
||||||
[[bin]]
|
[[bin]]
|
||||||
@@ -17,8 +17,10 @@ rmcp = { version = "1", features = ["server", "macros", "transport-streamable-ht
|
|||||||
axum = "0.8"
|
axum = "0.8"
|
||||||
axum-extra = { version = "0.10", features = ["typed-header"] }
|
axum-extra = { version = "0.10", features = ["typed-header"] }
|
||||||
tower = "0.5"
|
tower = "0.5"
|
||||||
tower-http = { version = "0.6", features = ["cors"] }
|
tower-http = { version = "0.6", features = ["cors", "trace"] }
|
||||||
tower-sessions = "0.14"
|
tower-sessions = "0.14"
|
||||||
|
tower-sessions-sqlx-store-chrono = { version = "0.14", features = ["postgres"] }
|
||||||
|
time = "0.3"
|
||||||
|
|
||||||
# OAuth (manual token exchange via reqwest)
|
# OAuth (manual token exchange via reqwest)
|
||||||
reqwest.workspace = true
|
reqwest.workspace = true
|
||||||
|
|||||||
262
crates/secrets-mcp/src/logging.rs
Normal file
262
crates/secrets-mcp/src/logging.rs
Normal file
@@ -0,0 +1,262 @@
|
|||||||
|
use std::net::SocketAddr;
|
||||||
|
use std::time::Instant;
|
||||||
|
|
||||||
|
use axum::{
|
||||||
|
body::{Body, Bytes, to_bytes},
|
||||||
|
extract::{ConnectInfo, Request},
|
||||||
|
http::{
|
||||||
|
HeaderMap, Method, StatusCode,
|
||||||
|
header::{CONTENT_LENGTH, CONTENT_TYPE, USER_AGENT},
|
||||||
|
},
|
||||||
|
middleware::Next,
|
||||||
|
response::{IntoResponse, Response},
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Axum middleware that logs structured info for every HTTP request.
|
||||||
|
///
|
||||||
|
/// All requests: method, path, status, latency_ms, client_ip, user_agent.
|
||||||
|
/// POST /mcp requests: additionally parses JSON-RPC body for jsonrpc_method,
|
||||||
|
/// tool_name, jsonrpc_id, mcp_session, batch_size.
|
||||||
|
///
|
||||||
|
/// Sensitive headers (Authorization, X-Encryption-Key) and secret values
|
||||||
|
/// are never logged.
|
||||||
|
pub async fn request_logging_middleware(req: Request, next: Next) -> Response {
|
||||||
|
let method = req.method().clone();
|
||||||
|
let path = req.uri().path().to_string();
|
||||||
|
let ip = client_ip(&req);
|
||||||
|
let ua = header_str(req.headers(), USER_AGENT);
|
||||||
|
let content_len = header_str(req.headers(), CONTENT_LENGTH).and_then(|v| v.parse::<u64>().ok());
|
||||||
|
let mcp_session = req
|
||||||
|
.headers()
|
||||||
|
.get("mcp-session-id")
|
||||||
|
.or_else(|| req.headers().get("x-mcp-session"))
|
||||||
|
.and_then(|v| v.to_str().ok())
|
||||||
|
.map(|s| s.to_string());
|
||||||
|
|
||||||
|
let is_mcp_post = path.starts_with("/mcp") && method == Method::POST;
|
||||||
|
let is_json = header_str(req.headers(), CONTENT_TYPE)
|
||||||
|
.map(|ct| ct.contains("application/json"))
|
||||||
|
.unwrap_or(false);
|
||||||
|
|
||||||
|
let start = Instant::now();
|
||||||
|
|
||||||
|
// For MCP JSON-RPC POST requests, buffer body to extract JSON-RPC metadata.
|
||||||
|
// We cap at 512 KiB to avoid buffering large payloads.
|
||||||
|
if is_mcp_post && is_json {
|
||||||
|
let cap = content_len.unwrap_or(0);
|
||||||
|
if cap <= 512 * 1024 {
|
||||||
|
let (parts, body) = req.into_parts();
|
||||||
|
match to_bytes(body, 512 * 1024).await {
|
||||||
|
Ok(bytes) => {
|
||||||
|
let rpc = parse_jsonrpc_meta(&bytes);
|
||||||
|
let req = Request::from_parts(parts, Body::from(bytes));
|
||||||
|
let resp = next.run(req).await;
|
||||||
|
let status = resp.status().as_u16();
|
||||||
|
let elapsed = start.elapsed().as_millis();
|
||||||
|
log_mcp_request(
|
||||||
|
&method,
|
||||||
|
&path,
|
||||||
|
status,
|
||||||
|
elapsed,
|
||||||
|
ip.as_deref(),
|
||||||
|
ua.as_deref(),
|
||||||
|
content_len,
|
||||||
|
mcp_session.as_deref(),
|
||||||
|
&rpc,
|
||||||
|
);
|
||||||
|
return resp;
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
tracing::warn!(path, error = %e, "failed to buffer MCP request body for logging");
|
||||||
|
let elapsed = start.elapsed().as_millis();
|
||||||
|
tracing::info!(
|
||||||
|
method = method.as_str(),
|
||||||
|
path,
|
||||||
|
status = StatusCode::INTERNAL_SERVER_ERROR.as_u16(),
|
||||||
|
elapsed_ms = elapsed,
|
||||||
|
client_ip = ip.as_deref(),
|
||||||
|
ua = ua.as_deref(),
|
||||||
|
content_length = content_len,
|
||||||
|
mcp_session = mcp_session.as_deref(),
|
||||||
|
"mcp request",
|
||||||
|
);
|
||||||
|
return (
|
||||||
|
StatusCode::INTERNAL_SERVER_ERROR,
|
||||||
|
"failed to read request body",
|
||||||
|
)
|
||||||
|
.into_response();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let resp = next.run(req).await;
|
||||||
|
let status = resp.status().as_u16();
|
||||||
|
let elapsed = start.elapsed().as_millis();
|
||||||
|
|
||||||
|
// Known client probe patterns that legitimately 404 — downgrade to debug to
|
||||||
|
// avoid noise in production logs. These are:
|
||||||
|
// • GET /.well-known/* — OAuth/OIDC discovery by MCP clients (RFC 8414 / RFC 9728)
|
||||||
|
// • GET /mcp → 404 — old SSE-transport compatibility probe by clients
|
||||||
|
let is_expected_probe_404 = status == 404
|
||||||
|
&& (path.starts_with("/.well-known/")
|
||||||
|
|| (method == Method::GET && path.starts_with("/mcp")));
|
||||||
|
|
||||||
|
if is_expected_probe_404 {
|
||||||
|
tracing::debug!(
|
||||||
|
method = method.as_str(),
|
||||||
|
path,
|
||||||
|
status,
|
||||||
|
elapsed_ms = elapsed,
|
||||||
|
client_ip = ip.as_deref(),
|
||||||
|
ua = ua.as_deref(),
|
||||||
|
"probe request (not found — expected)",
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
log_http_request(
|
||||||
|
&method,
|
||||||
|
&path,
|
||||||
|
status,
|
||||||
|
elapsed,
|
||||||
|
ip.as_deref(),
|
||||||
|
ua.as_deref(),
|
||||||
|
content_len,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
resp
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Logging helpers ───────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
fn log_http_request(
|
||||||
|
method: &Method,
|
||||||
|
path: &str,
|
||||||
|
status: u16,
|
||||||
|
elapsed_ms: u128,
|
||||||
|
client_ip: Option<&str>,
|
||||||
|
ua: Option<&str>,
|
||||||
|
content_length: Option<u64>,
|
||||||
|
) {
|
||||||
|
tracing::info!(
|
||||||
|
method = method.as_str(),
|
||||||
|
path,
|
||||||
|
status,
|
||||||
|
elapsed_ms,
|
||||||
|
client_ip,
|
||||||
|
ua,
|
||||||
|
content_length,
|
||||||
|
"http request",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(clippy::too_many_arguments)]
|
||||||
|
fn log_mcp_request(
|
||||||
|
method: &Method,
|
||||||
|
path: &str,
|
||||||
|
status: u16,
|
||||||
|
elapsed_ms: u128,
|
||||||
|
client_ip: Option<&str>,
|
||||||
|
ua: Option<&str>,
|
||||||
|
content_length: Option<u64>,
|
||||||
|
mcp_session: Option<&str>,
|
||||||
|
rpc: &JsonRpcMeta,
|
||||||
|
) {
|
||||||
|
tracing::info!(
|
||||||
|
method = method.as_str(),
|
||||||
|
path,
|
||||||
|
status,
|
||||||
|
elapsed_ms,
|
||||||
|
client_ip,
|
||||||
|
ua,
|
||||||
|
content_length,
|
||||||
|
mcp_session,
|
||||||
|
jsonrpc = rpc.rpc_method.as_deref(),
|
||||||
|
tool = rpc.tool_name.as_deref(),
|
||||||
|
jsonrpc_id = rpc.request_id.as_deref(),
|
||||||
|
batch_size = rpc.batch_size,
|
||||||
|
"mcp request",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── JSON-RPC body parsing ─────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
#[derive(Debug, Default)]
|
||||||
|
struct JsonRpcMeta {
|
||||||
|
request_id: Option<String>,
|
||||||
|
rpc_method: Option<String>,
|
||||||
|
tool_name: Option<String>,
|
||||||
|
batch_size: Option<usize>,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse_jsonrpc_meta(bytes: &Bytes) -> JsonRpcMeta {
|
||||||
|
let Ok(value) = serde_json::from_slice::<serde_json::Value>(bytes) else {
|
||||||
|
return JsonRpcMeta::default();
|
||||||
|
};
|
||||||
|
|
||||||
|
if let Some(arr) = value.as_array() {
|
||||||
|
// Batch request: summarise method(s) from first element only
|
||||||
|
let first = arr.first().map(parse_single).unwrap_or_default();
|
||||||
|
return JsonRpcMeta {
|
||||||
|
batch_size: Some(arr.len()),
|
||||||
|
..first
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
parse_single(&value)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse_single(value: &serde_json::Value) -> JsonRpcMeta {
|
||||||
|
let request_id = value.get("id").and_then(json_to_string);
|
||||||
|
let rpc_method = value
|
||||||
|
.get("method")
|
||||||
|
.and_then(|v| v.as_str())
|
||||||
|
.map(|s| s.to_string());
|
||||||
|
let tool_name = value
|
||||||
|
.pointer("/params/name")
|
||||||
|
.and_then(|v| v.as_str())
|
||||||
|
.map(|s| s.to_string());
|
||||||
|
|
||||||
|
JsonRpcMeta {
|
||||||
|
request_id,
|
||||||
|
rpc_method,
|
||||||
|
tool_name,
|
||||||
|
batch_size: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn json_to_string(value: &serde_json::Value) -> Option<String> {
|
||||||
|
match value {
|
||||||
|
serde_json::Value::Null => None,
|
||||||
|
serde_json::Value::String(s) => Some(s.clone()),
|
||||||
|
serde_json::Value::Number(n) => Some(n.to_string()),
|
||||||
|
serde_json::Value::Bool(b) => Some(b.to_string()),
|
||||||
|
other => Some(other.to_string()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Header helpers ────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
fn header_str(headers: &HeaderMap, name: impl axum::http::header::AsHeaderName) -> Option<String> {
|
||||||
|
headers
|
||||||
|
.get(name)
|
||||||
|
.and_then(|v| v.to_str().ok())
|
||||||
|
.map(|s| s.to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn client_ip(req: &Request) -> Option<String> {
|
||||||
|
if let Some(first) = req
|
||||||
|
.headers()
|
||||||
|
.get("x-forwarded-for")
|
||||||
|
.and_then(|v| v.to_str().ok())
|
||||||
|
.and_then(|s| s.split(',').next())
|
||||||
|
{
|
||||||
|
let s = first.trim();
|
||||||
|
if !s.is_empty() {
|
||||||
|
return Some(s.to_string());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
req.extensions()
|
||||||
|
.get::<ConnectInfo<SocketAddr>>()
|
||||||
|
.map(|c| c.ip().to_string())
|
||||||
|
}
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
mod auth;
|
mod auth;
|
||||||
|
mod logging;
|
||||||
mod oauth;
|
mod oauth;
|
||||||
mod tools;
|
mod tools;
|
||||||
mod web;
|
mod web;
|
||||||
@@ -14,8 +15,11 @@ use rmcp::transport::streamable_http_server::{
|
|||||||
use sqlx::PgPool;
|
use sqlx::PgPool;
|
||||||
use tower_http::cors::{Any, CorsLayer};
|
use tower_http::cors::{Any, CorsLayer};
|
||||||
use tower_sessions::cookie::SameSite;
|
use tower_sessions::cookie::SameSite;
|
||||||
use tower_sessions::{MemoryStore, SessionManagerLayer};
|
use tower_sessions::session_store::ExpiredDeletion;
|
||||||
|
use tower_sessions::{Expiry, SessionManagerLayer};
|
||||||
|
use tower_sessions_sqlx_store_chrono::PostgresStore;
|
||||||
use tracing_subscriber::EnvFilter;
|
use tracing_subscriber::EnvFilter;
|
||||||
|
use tracing_subscriber::fmt::time::FormatTime;
|
||||||
|
|
||||||
use secrets_core::config::resolve_db_url;
|
use secrets_core::config::resolve_db_url;
|
||||||
use secrets_core::db::{create_pool, migrate};
|
use secrets_core::db::{create_pool, migrate};
|
||||||
@@ -46,14 +50,30 @@ fn load_oauth_config(prefix: &str, base_url: &str, path: &str) -> Option<OAuthCo
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Log line timestamps in the process local timezone (honors `TZ` / system zone).
|
||||||
|
#[derive(Clone, Copy, Default)]
|
||||||
|
struct LocalRfc3339Time;
|
||||||
|
|
||||||
|
impl FormatTime for LocalRfc3339Time {
|
||||||
|
fn format_time(&self, w: &mut tracing_subscriber::fmt::format::Writer<'_>) -> std::fmt::Result {
|
||||||
|
write!(
|
||||||
|
w,
|
||||||
|
"{}",
|
||||||
|
chrono::Local::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, false)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[tokio::main]
|
#[tokio::main]
|
||||||
async fn main() -> Result<()> {
|
async fn main() -> Result<()> {
|
||||||
// Load .env if present
|
// Load .env if present
|
||||||
let _ = dotenvy::dotenv();
|
let _ = dotenvy::dotenv();
|
||||||
|
|
||||||
tracing_subscriber::fmt()
|
tracing_subscriber::fmt()
|
||||||
|
.with_timer(LocalRfc3339Time)
|
||||||
.with_env_filter(
|
.with_env_filter(
|
||||||
EnvFilter::try_from_default_env().unwrap_or_else(|_| "secrets_mcp=info".into()),
|
EnvFilter::try_from_default_env()
|
||||||
|
.unwrap_or_else(|_| "secrets_mcp=info,tower_http=info".into()),
|
||||||
)
|
)
|
||||||
.init();
|
.init();
|
||||||
|
|
||||||
@@ -70,7 +90,8 @@ async fn main() -> Result<()> {
|
|||||||
|
|
||||||
// ── Configuration ─────────────────────────────────────────────────────────
|
// ── Configuration ─────────────────────────────────────────────────────────
|
||||||
let base_url = load_env_var("BASE_URL").unwrap_or_else(|| "http://localhost:9315".to_string());
|
let base_url = load_env_var("BASE_URL").unwrap_or_else(|| "http://localhost:9315".to_string());
|
||||||
let bind_addr = load_env_var("SECRETS_MCP_BIND").unwrap_or_else(|| "0.0.0.0:9315".to_string());
|
let bind_addr =
|
||||||
|
load_env_var("SECRETS_MCP_BIND").unwrap_or_else(|| "127.0.0.1:9315".to_string());
|
||||||
|
|
||||||
// ── OAuth providers ───────────────────────────────────────────────────────
|
// ── OAuth providers ───────────────────────────────────────────────────────
|
||||||
let google_config = load_oauth_config("GOOGLE", &base_url, "/auth/google/callback");
|
let google_config = load_oauth_config("GOOGLE", &base_url, "/auth/google/callback");
|
||||||
@@ -81,12 +102,23 @@ async fn main() -> Result<()> {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Session store ─────────────────────────────────────────────────────────
|
// ── Session store (PostgreSQL-backed) ─────────────────────────────────────
|
||||||
let session_store = MemoryStore::default();
|
let session_store = PostgresStore::new(pool.clone());
|
||||||
|
session_store
|
||||||
|
.migrate()
|
||||||
|
.await
|
||||||
|
.context("failed to run session table migration")?;
|
||||||
|
// Prune expired rows every hour; task is aborted when the server shuts down.
|
||||||
|
let session_cleanup = tokio::spawn(
|
||||||
|
session_store
|
||||||
|
.clone()
|
||||||
|
.continuously_delete_expired(tokio::time::Duration::from_secs(3600)),
|
||||||
|
);
|
||||||
// Strict would drop the session cookie on redirect from Google → our origin (cross-site nav).
|
// Strict would drop the session cookie on redirect from Google → our origin (cross-site nav).
|
||||||
let session_layer = SessionManagerLayer::new(session_store)
|
let session_layer = SessionManagerLayer::new(session_store)
|
||||||
.with_secure(base_url.starts_with("https://"))
|
.with_secure(base_url.starts_with("https://"))
|
||||||
.with_same_site(SameSite::Lax);
|
.with_same_site(SameSite::Lax)
|
||||||
|
.with_expiry(Expiry::OnInactivity(time::Duration::days(14)));
|
||||||
|
|
||||||
// ── App state ─────────────────────────────────────────────────────────────
|
// ── App state ─────────────────────────────────────────────────────────────
|
||||||
let app_state = AppState {
|
let app_state = AppState {
|
||||||
@@ -120,6 +152,9 @@ async fn main() -> Result<()> {
|
|||||||
let router = Router::new()
|
let router = Router::new()
|
||||||
.merge(web::web_router())
|
.merge(web::web_router())
|
||||||
.nest_service("/mcp", mcp_service)
|
.nest_service("/mcp", mcp_service)
|
||||||
|
.layer(axum::middleware::from_fn(
|
||||||
|
logging::request_logging_middleware,
|
||||||
|
))
|
||||||
.layer(axum::middleware::from_fn_with_state(
|
.layer(axum::middleware::from_fn_with_state(
|
||||||
pool,
|
pool,
|
||||||
auth::bearer_auth_middleware,
|
auth::bearer_auth_middleware,
|
||||||
@@ -144,6 +179,7 @@ async fn main() -> Result<()> {
|
|||||||
.await
|
.await
|
||||||
.context("server error")?;
|
.context("server error")?;
|
||||||
|
|
||||||
|
session_cleanup.abort();
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
use std::time::Instant;
|
||||||
|
|
||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
use rmcp::{
|
use rmcp::{
|
||||||
@@ -16,6 +17,7 @@ use serde::Deserialize;
|
|||||||
use sqlx::PgPool;
|
use sqlx::PgPool;
|
||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
|
|
||||||
|
use secrets_core::models::ExportFormat;
|
||||||
use secrets_core::service::{
|
use secrets_core::service::{
|
||||||
add::{AddParams, run as svc_add},
|
add::{AddParams, run as svc_add},
|
||||||
delete::{DeleteParams, run as svc_delete},
|
delete::{DeleteParams, run as svc_delete},
|
||||||
@@ -29,6 +31,32 @@ use secrets_core::service::{
|
|||||||
|
|
||||||
use crate::auth::AuthUser;
|
use crate::auth::AuthUser;
|
||||||
|
|
||||||
|
// ── MCP client-facing errors (no internal details) ───────────────────────────
|
||||||
|
|
||||||
|
fn mcp_err_missing_http_parts() -> rmcp::ErrorData {
|
||||||
|
rmcp::ErrorData::internal_error("Invalid MCP request context.", None)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn mcp_err_internal_logged(
|
||||||
|
tool: &'static str,
|
||||||
|
user_id: Option<Uuid>,
|
||||||
|
err: impl std::fmt::Display,
|
||||||
|
) -> rmcp::ErrorData {
|
||||||
|
tracing::warn!(tool, ?user_id, error = %err, "tool call failed");
|
||||||
|
rmcp::ErrorData::internal_error(
|
||||||
|
"Request failed due to a server error. Check service logs if you need details.",
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn mcp_err_invalid_encryption_key_logged(err: impl std::fmt::Display) -> rmcp::ErrorData {
|
||||||
|
tracing::warn!(error = %err, "invalid X-Encryption-Key");
|
||||||
|
rmcp::ErrorData::invalid_request(
|
||||||
|
"Invalid X-Encryption-Key: must be exactly 64 hexadecimal characters (32-byte key).",
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
// ── Shared state ──────────────────────────────────────────────────────────────
|
// ── Shared state ──────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
@@ -50,7 +78,7 @@ impl SecretsService {
|
|||||||
let parts = ctx
|
let parts = ctx
|
||||||
.extensions
|
.extensions
|
||||||
.get::<http::request::Parts>()
|
.get::<http::request::Parts>()
|
||||||
.ok_or_else(|| rmcp::ErrorData::internal_error("Missing HTTP parts", None))?;
|
.ok_or_else(mcp_err_missing_http_parts)?;
|
||||||
Ok(parts.extensions.get::<AuthUser>().map(|a| a.user_id))
|
Ok(parts.extensions.get::<AuthUser>().map(|a| a.user_id))
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -59,7 +87,7 @@ impl SecretsService {
|
|||||||
let parts = ctx
|
let parts = ctx
|
||||||
.extensions
|
.extensions
|
||||||
.get::<http::request::Parts>()
|
.get::<http::request::Parts>()
|
||||||
.ok_or_else(|| rmcp::ErrorData::internal_error("Missing HTTP parts", None))?;
|
.ok_or_else(mcp_err_missing_http_parts)?;
|
||||||
parts
|
parts
|
||||||
.extensions
|
.extensions
|
||||||
.get::<AuthUser>()
|
.get::<AuthUser>()
|
||||||
@@ -73,7 +101,7 @@ impl SecretsService {
|
|||||||
let parts = ctx
|
let parts = ctx
|
||||||
.extensions
|
.extensions
|
||||||
.get::<http::request::Parts>()
|
.get::<http::request::Parts>()
|
||||||
.ok_or_else(|| rmcp::ErrorData::internal_error("Missing HTTP parts", None))?;
|
.ok_or_else(mcp_err_missing_http_parts)?;
|
||||||
let hex_str = parts
|
let hex_str = parts
|
||||||
.headers
|
.headers
|
||||||
.get("x-encryption-key")
|
.get("x-encryption-key")
|
||||||
@@ -88,8 +116,29 @@ impl SecretsService {
|
|||||||
.map_err(|_| {
|
.map_err(|_| {
|
||||||
rmcp::ErrorData::invalid_request("Invalid X-Encryption-Key header value", None)
|
rmcp::ErrorData::invalid_request("Invalid X-Encryption-Key header value", None)
|
||||||
})?;
|
})?;
|
||||||
|
let trimmed = hex_str.trim();
|
||||||
|
if trimmed.len() != 64 {
|
||||||
|
tracing::warn!(
|
||||||
|
got_len = trimmed.len(),
|
||||||
|
"X-Encryption-Key has wrong length after trim"
|
||||||
|
);
|
||||||
|
return Err(rmcp::ErrorData::invalid_request(
|
||||||
|
format!(
|
||||||
|
"X-Encryption-Key must be exactly 64 hex characters (32-byte key), got {} characters.",
|
||||||
|
trimmed.len()
|
||||||
|
),
|
||||||
|
None,
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if !trimmed.chars().all(|c| c.is_ascii_hexdigit()) {
|
||||||
|
tracing::warn!("X-Encryption-Key contains non-hexadecimal characters");
|
||||||
|
return Err(rmcp::ErrorData::invalid_request(
|
||||||
|
"X-Encryption-Key contains non-hexadecimal characters.",
|
||||||
|
None,
|
||||||
|
));
|
||||||
|
}
|
||||||
secrets_core::crypto::extract_key_from_hex(hex_str)
|
secrets_core::crypto::extract_key_from_hex(hex_str)
|
||||||
.map_err(|e| rmcp::ErrorData::invalid_request(e.to_string(), None))
|
.map_err(mcp_err_invalid_encryption_key_logged)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Require both user_id and encryption key.
|
/// Require both user_id and encryption key.
|
||||||
@@ -106,17 +155,18 @@ impl SecretsService {
|
|||||||
|
|
||||||
#[derive(Debug, Deserialize, JsonSchema)]
|
#[derive(Debug, Deserialize, JsonSchema)]
|
||||||
struct SearchInput {
|
struct SearchInput {
|
||||||
#[schemars(description = "Namespace filter (e.g. 'refining', 'ricnsmart')")]
|
#[schemars(description = "Fuzzy search across name, folder, type, notes, tags, metadata")]
|
||||||
namespace: Option<String>,
|
query: Option<String>,
|
||||||
#[schemars(description = "Kind filter (e.g. 'server', 'service', 'key')")]
|
#[schemars(description = "Folder filter (e.g. 'refining', 'personal', 'family')")]
|
||||||
kind: Option<String>,
|
folder: Option<String>,
|
||||||
#[schemars(description = "Exact record name")]
|
#[schemars(description = "Type filter (e.g. 'server', 'service', 'person', 'key')")]
|
||||||
|
#[serde(rename = "type")]
|
||||||
|
entry_type: Option<String>,
|
||||||
|
#[schemars(description = "Exact name to match")]
|
||||||
name: Option<String>,
|
name: Option<String>,
|
||||||
#[schemars(description = "Tag filters (all must match)")]
|
#[schemars(description = "Tag filters (all must match)")]
|
||||||
tags: Option<Vec<String>>,
|
tags: Option<Vec<String>>,
|
||||||
#[schemars(description = "Fuzzy search across name, namespace, kind, tags, metadata")]
|
#[schemars(description = "Return only summary fields (name/tags/notes/updated_at)")]
|
||||||
query: Option<String>,
|
|
||||||
#[schemars(description = "Return only summary fields (name/tags/desc/updated_at)")]
|
|
||||||
summary: Option<bool>,
|
summary: Option<bool>,
|
||||||
#[schemars(description = "Sort order: 'name' (default), 'updated', 'created'")]
|
#[schemars(description = "Sort order: 'name' (default), 'updated', 'created'")]
|
||||||
sort: Option<String>,
|
sort: Option<String>,
|
||||||
@@ -128,24 +178,29 @@ struct SearchInput {
|
|||||||
|
|
||||||
#[derive(Debug, Deserialize, JsonSchema)]
|
#[derive(Debug, Deserialize, JsonSchema)]
|
||||||
struct GetSecretInput {
|
struct GetSecretInput {
|
||||||
#[schemars(description = "Namespace of the entry")]
|
|
||||||
namespace: String,
|
|
||||||
#[schemars(description = "Kind of the entry (e.g. 'server', 'service')")]
|
|
||||||
kind: String,
|
|
||||||
#[schemars(description = "Name of the entry")]
|
#[schemars(description = "Name of the entry")]
|
||||||
name: String,
|
name: String,
|
||||||
|
#[schemars(
|
||||||
|
description = "Folder for disambiguation when multiple entries share the same name (optional)"
|
||||||
|
)]
|
||||||
|
folder: Option<String>,
|
||||||
#[schemars(description = "Specific field to retrieve. If omitted, returns all fields.")]
|
#[schemars(description = "Specific field to retrieve. If omitted, returns all fields.")]
|
||||||
field: Option<String>,
|
field: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Deserialize, JsonSchema)]
|
#[derive(Debug, Deserialize, JsonSchema)]
|
||||||
struct AddInput {
|
struct AddInput {
|
||||||
#[schemars(description = "Namespace")]
|
#[schemars(description = "Unique name for this entry")]
|
||||||
namespace: String,
|
|
||||||
#[schemars(description = "Kind (e.g. 'server', 'service', 'key')")]
|
|
||||||
kind: String,
|
|
||||||
#[schemars(description = "Unique name within namespace+kind")]
|
|
||||||
name: String,
|
name: String,
|
||||||
|
#[schemars(description = "Folder for organization (optional, e.g. 'personal', 'refining')")]
|
||||||
|
folder: Option<String>,
|
||||||
|
#[schemars(
|
||||||
|
description = "Type/category of this entry (optional, e.g. 'server', 'person', 'key')"
|
||||||
|
)]
|
||||||
|
#[serde(rename = "type")]
|
||||||
|
entry_type: Option<String>,
|
||||||
|
#[schemars(description = "Free-text notes for this entry (optional)")]
|
||||||
|
notes: Option<String>,
|
||||||
#[schemars(description = "Tags for this entry")]
|
#[schemars(description = "Tags for this entry")]
|
||||||
tags: Option<Vec<String>>,
|
tags: Option<Vec<String>>,
|
||||||
#[schemars(description = "Metadata fields as 'key=value' or 'key:=json' strings")]
|
#[schemars(description = "Metadata fields as 'key=value' or 'key:=json' strings")]
|
||||||
@@ -156,12 +211,14 @@ struct AddInput {
|
|||||||
|
|
||||||
#[derive(Debug, Deserialize, JsonSchema)]
|
#[derive(Debug, Deserialize, JsonSchema)]
|
||||||
struct UpdateInput {
|
struct UpdateInput {
|
||||||
#[schemars(description = "Namespace")]
|
#[schemars(description = "Name of the entry to update")]
|
||||||
namespace: String,
|
|
||||||
#[schemars(description = "Kind")]
|
|
||||||
kind: String,
|
|
||||||
#[schemars(description = "Name")]
|
|
||||||
name: String,
|
name: String,
|
||||||
|
#[schemars(
|
||||||
|
description = "Folder for disambiguation when multiple entries share the same name (optional)"
|
||||||
|
)]
|
||||||
|
folder: Option<String>,
|
||||||
|
#[schemars(description = "Update the notes field")]
|
||||||
|
notes: Option<String>,
|
||||||
#[schemars(description = "Tags to add")]
|
#[schemars(description = "Tags to add")]
|
||||||
add_tags: Option<Vec<String>>,
|
add_tags: Option<Vec<String>>,
|
||||||
#[schemars(description = "Tags to remove")]
|
#[schemars(description = "Tags to remove")]
|
||||||
@@ -178,46 +235,49 @@ struct UpdateInput {
|
|||||||
|
|
||||||
#[derive(Debug, Deserialize, JsonSchema)]
|
#[derive(Debug, Deserialize, JsonSchema)]
|
||||||
struct DeleteInput {
|
struct DeleteInput {
|
||||||
#[schemars(description = "Namespace")]
|
#[schemars(description = "Name of the entry to delete (single delete). \
|
||||||
namespace: String,
|
Omit to bulk delete by folder/type filters.")]
|
||||||
#[schemars(description = "Kind filter (required for single delete)")]
|
|
||||||
kind: Option<String>,
|
|
||||||
#[schemars(description = "Exact name to delete. Omit for bulk delete by namespace+kind.")]
|
|
||||||
name: Option<String>,
|
name: Option<String>,
|
||||||
|
#[schemars(description = "Folder filter for bulk delete")]
|
||||||
|
folder: Option<String>,
|
||||||
|
#[schemars(description = "Type filter for bulk delete")]
|
||||||
|
#[serde(rename = "type")]
|
||||||
|
entry_type: Option<String>,
|
||||||
#[schemars(description = "Preview deletions without writing")]
|
#[schemars(description = "Preview deletions without writing")]
|
||||||
dry_run: Option<bool>,
|
dry_run: Option<bool>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Deserialize, JsonSchema)]
|
#[derive(Debug, Deserialize, JsonSchema)]
|
||||||
struct HistoryInput {
|
struct HistoryInput {
|
||||||
#[schemars(description = "Namespace")]
|
#[schemars(description = "Name of the entry")]
|
||||||
namespace: String,
|
|
||||||
#[schemars(description = "Kind")]
|
|
||||||
kind: String,
|
|
||||||
#[schemars(description = "Name")]
|
|
||||||
name: String,
|
name: String,
|
||||||
|
#[schemars(
|
||||||
|
description = "Folder for disambiguation when multiple entries share the same name (optional)"
|
||||||
|
)]
|
||||||
|
folder: Option<String>,
|
||||||
#[schemars(description = "Max history entries to return (default 20)")]
|
#[schemars(description = "Max history entries to return (default 20)")]
|
||||||
limit: Option<u32>,
|
limit: Option<u32>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Deserialize, JsonSchema)]
|
#[derive(Debug, Deserialize, JsonSchema)]
|
||||||
struct RollbackInput {
|
struct RollbackInput {
|
||||||
#[schemars(description = "Namespace")]
|
#[schemars(description = "Name of the entry")]
|
||||||
namespace: String,
|
|
||||||
#[schemars(description = "Kind")]
|
|
||||||
kind: String,
|
|
||||||
#[schemars(description = "Name")]
|
|
||||||
name: String,
|
name: String,
|
||||||
|
#[schemars(
|
||||||
|
description = "Folder for disambiguation when multiple entries share the same name (optional)"
|
||||||
|
)]
|
||||||
|
folder: Option<String>,
|
||||||
#[schemars(description = "Target version number. Omit to restore the most recent snapshot.")]
|
#[schemars(description = "Target version number. Omit to restore the most recent snapshot.")]
|
||||||
to_version: Option<i64>,
|
to_version: Option<i64>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Deserialize, JsonSchema)]
|
#[derive(Debug, Deserialize, JsonSchema)]
|
||||||
struct ExportInput {
|
struct ExportInput {
|
||||||
#[schemars(description = "Namespace filter")]
|
#[schemars(description = "Folder filter")]
|
||||||
namespace: Option<String>,
|
folder: Option<String>,
|
||||||
#[schemars(description = "Kind filter")]
|
#[schemars(description = "Type filter")]
|
||||||
kind: Option<String>,
|
#[serde(rename = "type")]
|
||||||
|
entry_type: Option<String>,
|
||||||
#[schemars(description = "Exact name filter")]
|
#[schemars(description = "Exact name filter")]
|
||||||
name: Option<String>,
|
name: Option<String>,
|
||||||
#[schemars(description = "Tag filters")]
|
#[schemars(description = "Tag filters")]
|
||||||
@@ -230,10 +290,11 @@ struct ExportInput {
|
|||||||
|
|
||||||
#[derive(Debug, Deserialize, JsonSchema)]
|
#[derive(Debug, Deserialize, JsonSchema)]
|
||||||
struct EnvMapInput {
|
struct EnvMapInput {
|
||||||
#[schemars(description = "Namespace filter")]
|
#[schemars(description = "Folder filter")]
|
||||||
namespace: Option<String>,
|
folder: Option<String>,
|
||||||
#[schemars(description = "Kind filter")]
|
#[schemars(description = "Type filter")]
|
||||||
kind: Option<String>,
|
#[serde(rename = "type")]
|
||||||
|
entry_type: Option<String>,
|
||||||
#[schemars(description = "Exact name filter")]
|
#[schemars(description = "Exact name filter")]
|
||||||
name: Option<String>,
|
name: Option<String>,
|
||||||
#[schemars(description = "Tag filters")]
|
#[schemars(description = "Tag filters")]
|
||||||
@@ -249,32 +310,47 @@ struct EnvMapInput {
|
|||||||
#[tool_router]
|
#[tool_router]
|
||||||
impl SecretsService {
|
impl SecretsService {
|
||||||
#[tool(
|
#[tool(
|
||||||
description = "Search entries in the secrets store. Returns entries with metadata and \
|
description = "Search entries in the secrets store. Requires Bearer API key. Returns \
|
||||||
secret field names (not values). Use secrets_get to decrypt secret values."
|
entries with metadata and secret field names (not values). Use secrets_get to decrypt secret values.",
|
||||||
|
annotations(
|
||||||
|
title = "Search Secrets",
|
||||||
|
read_only_hint = true,
|
||||||
|
idempotent_hint = true
|
||||||
|
)
|
||||||
)]
|
)]
|
||||||
async fn secrets_search(
|
async fn secrets_search(
|
||||||
&self,
|
&self,
|
||||||
Parameters(input): Parameters<SearchInput>,
|
Parameters(input): Parameters<SearchInput>,
|
||||||
ctx: RequestContext<RoleServer>,
|
ctx: RequestContext<RoleServer>,
|
||||||
) -> Result<CallToolResult, rmcp::ErrorData> {
|
) -> Result<CallToolResult, rmcp::ErrorData> {
|
||||||
let user_id = Self::user_id_from_ctx(&ctx)?;
|
let t = Instant::now();
|
||||||
|
let user_id = Self::require_user_id(&ctx)?;
|
||||||
|
tracing::info!(
|
||||||
|
tool = "secrets_search",
|
||||||
|
?user_id,
|
||||||
|
folder = input.folder.as_deref(),
|
||||||
|
entry_type = input.entry_type.as_deref(),
|
||||||
|
name = input.name.as_deref(),
|
||||||
|
query = input.query.as_deref(),
|
||||||
|
"tool call start",
|
||||||
|
);
|
||||||
let tags = input.tags.unwrap_or_default();
|
let tags = input.tags.unwrap_or_default();
|
||||||
let result = svc_search(
|
let result = svc_search(
|
||||||
&self.pool,
|
&self.pool,
|
||||||
SearchParams {
|
SearchParams {
|
||||||
namespace: input.namespace.as_deref(),
|
folder: input.folder.as_deref(),
|
||||||
kind: input.kind.as_deref(),
|
entry_type: input.entry_type.as_deref(),
|
||||||
name: input.name.as_deref(),
|
name: input.name.as_deref(),
|
||||||
tags: &tags,
|
tags: &tags,
|
||||||
query: input.query.as_deref(),
|
query: input.query.as_deref(),
|
||||||
sort: input.sort.as_deref().unwrap_or("name"),
|
sort: input.sort.as_deref().unwrap_or("name"),
|
||||||
limit: input.limit.unwrap_or(20),
|
limit: input.limit.unwrap_or(20),
|
||||||
offset: input.offset.unwrap_or(0),
|
offset: input.offset.unwrap_or(0),
|
||||||
user_id,
|
user_id: Some(user_id),
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
.await
|
.await
|
||||||
.map_err(|e| rmcp::ErrorData::internal_error(e.to_string(), None))?;
|
.map_err(|e| mcp_err_internal_logged("secrets_search", Some(user_id), e))?;
|
||||||
|
|
||||||
let summary = input.summary.unwrap_or(false);
|
let summary = input.summary.unwrap_or(false);
|
||||||
let entries: Vec<serde_json::Value> = result
|
let entries: Vec<serde_json::Value> = result
|
||||||
@@ -283,12 +359,11 @@ impl SecretsService {
|
|||||||
.map(|e| {
|
.map(|e| {
|
||||||
if summary {
|
if summary {
|
||||||
serde_json::json!({
|
serde_json::json!({
|
||||||
"namespace": e.namespace,
|
|
||||||
"kind": e.kind,
|
|
||||||
"name": e.name,
|
"name": e.name,
|
||||||
|
"folder": e.folder,
|
||||||
|
"type": e.entry_type,
|
||||||
"tags": e.tags,
|
"tags": e.tags,
|
||||||
"desc": e.metadata.get("desc").or_else(|| e.metadata.get("url"))
|
"notes": e.notes,
|
||||||
.and_then(|v| v.as_str()).unwrap_or(""),
|
|
||||||
"updated_at": e.updated_at.format("%Y-%m-%dT%H:%M:%SZ").to_string(),
|
"updated_at": e.updated_at.format("%Y-%m-%dT%H:%M:%SZ").to_string(),
|
||||||
})
|
})
|
||||||
} else {
|
} else {
|
||||||
@@ -299,9 +374,10 @@ impl SecretsService {
|
|||||||
.unwrap_or_default();
|
.unwrap_or_default();
|
||||||
serde_json::json!({
|
serde_json::json!({
|
||||||
"id": e.id,
|
"id": e.id,
|
||||||
"namespace": e.namespace,
|
|
||||||
"kind": e.kind,
|
|
||||||
"name": e.name,
|
"name": e.name,
|
||||||
|
"folder": e.folder,
|
||||||
|
"type": e.entry_type,
|
||||||
|
"notes": e.notes,
|
||||||
"tags": e.tags,
|
"tags": e.tags,
|
||||||
"metadata": e.metadata,
|
"metadata": e.metadata,
|
||||||
"secret_fields": schema,
|
"secret_fields": schema,
|
||||||
@@ -312,6 +388,14 @@ impl SecretsService {
|
|||||||
})
|
})
|
||||||
.collect();
|
.collect();
|
||||||
|
|
||||||
|
let count = entries.len();
|
||||||
|
tracing::info!(
|
||||||
|
tool = "secrets_search",
|
||||||
|
?user_id,
|
||||||
|
result_count = count,
|
||||||
|
elapsed_ms = t.elapsed().as_millis(),
|
||||||
|
"tool call ok",
|
||||||
|
);
|
||||||
let json = serde_json::to_string_pretty(&entries).unwrap_or_else(|_| "[]".to_string());
|
let json = serde_json::to_string_pretty(&entries).unwrap_or_else(|_| "[]".to_string());
|
||||||
Ok(CallToolResult::success(vec![Content::text(json)]))
|
Ok(CallToolResult::success(vec![Content::text(json)]))
|
||||||
}
|
}
|
||||||
@@ -319,43 +403,68 @@ impl SecretsService {
|
|||||||
#[tool(
|
#[tool(
|
||||||
description = "Get decrypted secret field values for an entry. Requires your \
|
description = "Get decrypted secret field values for an entry. Requires your \
|
||||||
encryption key via X-Encryption-Key header (64 hex chars, PBKDF2-derived). \
|
encryption key via X-Encryption-Key header (64 hex chars, PBKDF2-derived). \
|
||||||
Returns all fields, or a specific field if 'field' is provided."
|
Returns all fields, or a specific field if 'field' is provided.",
|
||||||
|
annotations(
|
||||||
|
title = "Get Secret Values",
|
||||||
|
read_only_hint = true,
|
||||||
|
idempotent_hint = true
|
||||||
|
)
|
||||||
)]
|
)]
|
||||||
async fn secrets_get(
|
async fn secrets_get(
|
||||||
&self,
|
&self,
|
||||||
Parameters(input): Parameters<GetSecretInput>,
|
Parameters(input): Parameters<GetSecretInput>,
|
||||||
ctx: RequestContext<RoleServer>,
|
ctx: RequestContext<RoleServer>,
|
||||||
) -> Result<CallToolResult, rmcp::ErrorData> {
|
) -> Result<CallToolResult, rmcp::ErrorData> {
|
||||||
|
let t = Instant::now();
|
||||||
let (user_id, user_key) = Self::require_user_and_key(&ctx)?;
|
let (user_id, user_key) = Self::require_user_and_key(&ctx)?;
|
||||||
|
tracing::info!(
|
||||||
|
tool = "secrets_get",
|
||||||
|
?user_id,
|
||||||
|
name = %input.name,
|
||||||
|
field = input.field.as_deref(),
|
||||||
|
"tool call start",
|
||||||
|
);
|
||||||
|
|
||||||
if let Some(field_name) = &input.field {
|
if let Some(field_name) = &input.field {
|
||||||
let value = get_secret_field(
|
let value = get_secret_field(
|
||||||
&self.pool,
|
&self.pool,
|
||||||
&input.namespace,
|
|
||||||
&input.kind,
|
|
||||||
&input.name,
|
&input.name,
|
||||||
|
input.folder.as_deref(),
|
||||||
field_name,
|
field_name,
|
||||||
&user_key,
|
&user_key,
|
||||||
Some(user_id),
|
Some(user_id),
|
||||||
)
|
)
|
||||||
.await
|
.await
|
||||||
.map_err(|e| rmcp::ErrorData::internal_error(e.to_string(), None))?;
|
.map_err(|e| mcp_err_internal_logged("secrets_get", Some(user_id), e))?;
|
||||||
|
|
||||||
|
tracing::info!(
|
||||||
|
tool = "secrets_get",
|
||||||
|
?user_id,
|
||||||
|
elapsed_ms = t.elapsed().as_millis(),
|
||||||
|
"tool call ok",
|
||||||
|
);
|
||||||
let result = serde_json::json!({ field_name: value });
|
let result = serde_json::json!({ field_name: value });
|
||||||
let json = serde_json::to_string_pretty(&result).unwrap_or_default();
|
let json = serde_json::to_string_pretty(&result).unwrap_or_default();
|
||||||
Ok(CallToolResult::success(vec![Content::text(json)]))
|
Ok(CallToolResult::success(vec![Content::text(json)]))
|
||||||
} else {
|
} else {
|
||||||
let secrets = get_all_secrets(
|
let secrets = get_all_secrets(
|
||||||
&self.pool,
|
&self.pool,
|
||||||
&input.namespace,
|
|
||||||
&input.kind,
|
|
||||||
&input.name,
|
&input.name,
|
||||||
|
input.folder.as_deref(),
|
||||||
&user_key,
|
&user_key,
|
||||||
Some(user_id),
|
Some(user_id),
|
||||||
)
|
)
|
||||||
.await
|
.await
|
||||||
.map_err(|e| rmcp::ErrorData::internal_error(e.to_string(), None))?;
|
.map_err(|e| mcp_err_internal_logged("secrets_get", Some(user_id), e))?;
|
||||||
|
|
||||||
|
let count = secrets.len();
|
||||||
|
tracing::info!(
|
||||||
|
tool = "secrets_get",
|
||||||
|
?user_id,
|
||||||
|
field_count = count,
|
||||||
|
elapsed_ms = t.elapsed().as_millis(),
|
||||||
|
"tool call ok",
|
||||||
|
);
|
||||||
let json = serde_json::to_string_pretty(&secrets).unwrap_or_default();
|
let json = serde_json::to_string_pretty(&secrets).unwrap_or_default();
|
||||||
Ok(CallToolResult::success(vec![Content::text(json)]))
|
Ok(CallToolResult::success(vec![Content::text(json)]))
|
||||||
}
|
}
|
||||||
@@ -364,25 +473,39 @@ impl SecretsService {
|
|||||||
#[tool(
|
#[tool(
|
||||||
description = "Add or upsert an entry with metadata and encrypted secret fields. \
|
description = "Add or upsert an entry with metadata and encrypted secret fields. \
|
||||||
Requires X-Encryption-Key header. \
|
Requires X-Encryption-Key header. \
|
||||||
Meta and secret values use 'key=value', 'key=@file', or 'key:=<json>' format."
|
Meta and secret values use 'key=value', 'key=@file', or 'key:=<json>' format.",
|
||||||
|
annotations(title = "Add Secret Entry")
|
||||||
)]
|
)]
|
||||||
async fn secrets_add(
|
async fn secrets_add(
|
||||||
&self,
|
&self,
|
||||||
Parameters(input): Parameters<AddInput>,
|
Parameters(input): Parameters<AddInput>,
|
||||||
ctx: RequestContext<RoleServer>,
|
ctx: RequestContext<RoleServer>,
|
||||||
) -> Result<CallToolResult, rmcp::ErrorData> {
|
) -> Result<CallToolResult, rmcp::ErrorData> {
|
||||||
|
let t = Instant::now();
|
||||||
let (user_id, user_key) = Self::require_user_and_key(&ctx)?;
|
let (user_id, user_key) = Self::require_user_and_key(&ctx)?;
|
||||||
|
tracing::info!(
|
||||||
|
tool = "secrets_add",
|
||||||
|
?user_id,
|
||||||
|
name = %input.name,
|
||||||
|
folder = input.folder.as_deref(),
|
||||||
|
entry_type = input.entry_type.as_deref(),
|
||||||
|
"tool call start",
|
||||||
|
);
|
||||||
|
|
||||||
let tags = input.tags.unwrap_or_default();
|
let tags = input.tags.unwrap_or_default();
|
||||||
let meta = input.meta.unwrap_or_default();
|
let meta = input.meta.unwrap_or_default();
|
||||||
let secrets = input.secrets.unwrap_or_default();
|
let secrets = input.secrets.unwrap_or_default();
|
||||||
|
let folder = input.folder.as_deref().unwrap_or("");
|
||||||
|
let entry_type = input.entry_type.as_deref().unwrap_or("");
|
||||||
|
let notes = input.notes.as_deref().unwrap_or("");
|
||||||
|
|
||||||
let result = svc_add(
|
let result = svc_add(
|
||||||
&self.pool,
|
&self.pool,
|
||||||
AddParams {
|
AddParams {
|
||||||
namespace: &input.namespace,
|
|
||||||
kind: &input.kind,
|
|
||||||
name: &input.name,
|
name: &input.name,
|
||||||
|
folder,
|
||||||
|
entry_type,
|
||||||
|
notes,
|
||||||
tags: &tags,
|
tags: &tags,
|
||||||
meta_entries: &meta,
|
meta_entries: &meta,
|
||||||
secret_entries: &secrets,
|
secret_entries: &secrets,
|
||||||
@@ -391,22 +514,37 @@ impl SecretsService {
|
|||||||
&user_key,
|
&user_key,
|
||||||
)
|
)
|
||||||
.await
|
.await
|
||||||
.map_err(|e| rmcp::ErrorData::internal_error(e.to_string(), None))?;
|
.map_err(|e| mcp_err_internal_logged("secrets_add", Some(user_id), e))?;
|
||||||
|
|
||||||
|
tracing::info!(
|
||||||
|
tool = "secrets_add",
|
||||||
|
?user_id,
|
||||||
|
name = %input.name,
|
||||||
|
elapsed_ms = t.elapsed().as_millis(),
|
||||||
|
"tool call ok",
|
||||||
|
);
|
||||||
let json = serde_json::to_string_pretty(&result).unwrap_or_default();
|
let json = serde_json::to_string_pretty(&result).unwrap_or_default();
|
||||||
Ok(CallToolResult::success(vec![Content::text(json)]))
|
Ok(CallToolResult::success(vec![Content::text(json)]))
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tool(
|
#[tool(
|
||||||
description = "Incrementally update an existing entry. Requires X-Encryption-Key header. \
|
description = "Incrementally update an existing entry. Requires X-Encryption-Key header. \
|
||||||
Only the fields you specify are changed; everything else is preserved."
|
Only the fields you specify are changed; everything else is preserved.",
|
||||||
|
annotations(title = "Update Secret Entry")
|
||||||
)]
|
)]
|
||||||
async fn secrets_update(
|
async fn secrets_update(
|
||||||
&self,
|
&self,
|
||||||
Parameters(input): Parameters<UpdateInput>,
|
Parameters(input): Parameters<UpdateInput>,
|
||||||
ctx: RequestContext<RoleServer>,
|
ctx: RequestContext<RoleServer>,
|
||||||
) -> Result<CallToolResult, rmcp::ErrorData> {
|
) -> Result<CallToolResult, rmcp::ErrorData> {
|
||||||
|
let t = Instant::now();
|
||||||
let (user_id, user_key) = Self::require_user_and_key(&ctx)?;
|
let (user_id, user_key) = Self::require_user_and_key(&ctx)?;
|
||||||
|
tracing::info!(
|
||||||
|
tool = "secrets_update",
|
||||||
|
?user_id,
|
||||||
|
name = %input.name,
|
||||||
|
"tool call start",
|
||||||
|
);
|
||||||
|
|
||||||
let add_tags = input.add_tags.unwrap_or_default();
|
let add_tags = input.add_tags.unwrap_or_default();
|
||||||
let remove_tags = input.remove_tags.unwrap_or_default();
|
let remove_tags = input.remove_tags.unwrap_or_default();
|
||||||
@@ -418,9 +556,9 @@ impl SecretsService {
|
|||||||
let result = svc_update(
|
let result = svc_update(
|
||||||
&self.pool,
|
&self.pool,
|
||||||
UpdateParams {
|
UpdateParams {
|
||||||
namespace: &input.namespace,
|
|
||||||
kind: &input.kind,
|
|
||||||
name: &input.name,
|
name: &input.name,
|
||||||
|
folder: input.folder.as_deref(),
|
||||||
|
notes: input.notes.as_deref(),
|
||||||
add_tags: &add_tags,
|
add_tags: &add_tags,
|
||||||
remove_tags: &remove_tags,
|
remove_tags: &remove_tags,
|
||||||
meta_entries: &meta,
|
meta_entries: &meta,
|
||||||
@@ -432,109 +570,180 @@ impl SecretsService {
|
|||||||
&user_key,
|
&user_key,
|
||||||
)
|
)
|
||||||
.await
|
.await
|
||||||
.map_err(|e| rmcp::ErrorData::internal_error(e.to_string(), None))?;
|
.map_err(|e| mcp_err_internal_logged("secrets_update", Some(user_id), e))?;
|
||||||
|
|
||||||
|
tracing::info!(
|
||||||
|
tool = "secrets_update",
|
||||||
|
?user_id,
|
||||||
|
name = %input.name,
|
||||||
|
elapsed_ms = t.elapsed().as_millis(),
|
||||||
|
"tool call ok",
|
||||||
|
);
|
||||||
let json = serde_json::to_string_pretty(&result).unwrap_or_default();
|
let json = serde_json::to_string_pretty(&result).unwrap_or_default();
|
||||||
Ok(CallToolResult::success(vec![Content::text(json)]))
|
Ok(CallToolResult::success(vec![Content::text(json)]))
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tool(
|
#[tool(
|
||||||
description = "Delete one entry (specify namespace+kind+name) or bulk delete all \
|
description = "Delete one entry by name, or bulk delete entries matching folder and/or type. \
|
||||||
entries matching namespace+kind. Use dry_run=true to preview."
|
Use dry_run=true to preview.",
|
||||||
|
annotations(title = "Delete Secret Entry", destructive_hint = true)
|
||||||
)]
|
)]
|
||||||
async fn secrets_delete(
|
async fn secrets_delete(
|
||||||
&self,
|
&self,
|
||||||
Parameters(input): Parameters<DeleteInput>,
|
Parameters(input): Parameters<DeleteInput>,
|
||||||
ctx: RequestContext<RoleServer>,
|
ctx: RequestContext<RoleServer>,
|
||||||
) -> Result<CallToolResult, rmcp::ErrorData> {
|
) -> Result<CallToolResult, rmcp::ErrorData> {
|
||||||
|
let t = Instant::now();
|
||||||
let user_id = Self::user_id_from_ctx(&ctx)?;
|
let user_id = Self::user_id_from_ctx(&ctx)?;
|
||||||
|
tracing::info!(
|
||||||
|
tool = "secrets_delete",
|
||||||
|
?user_id,
|
||||||
|
name = input.name.as_deref(),
|
||||||
|
folder = input.folder.as_deref(),
|
||||||
|
entry_type = input.entry_type.as_deref(),
|
||||||
|
dry_run = input.dry_run.unwrap_or(false),
|
||||||
|
"tool call start",
|
||||||
|
);
|
||||||
|
|
||||||
let result = svc_delete(
|
let result = svc_delete(
|
||||||
&self.pool,
|
&self.pool,
|
||||||
DeleteParams {
|
DeleteParams {
|
||||||
namespace: &input.namespace,
|
|
||||||
kind: input.kind.as_deref(),
|
|
||||||
name: input.name.as_deref(),
|
name: input.name.as_deref(),
|
||||||
|
folder: input.folder.as_deref(),
|
||||||
|
entry_type: input.entry_type.as_deref(),
|
||||||
dry_run: input.dry_run.unwrap_or(false),
|
dry_run: input.dry_run.unwrap_or(false),
|
||||||
user_id,
|
user_id,
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
.await
|
.await
|
||||||
.map_err(|e| rmcp::ErrorData::internal_error(e.to_string(), None))?;
|
.map_err(|e| mcp_err_internal_logged("secrets_delete", user_id, e))?;
|
||||||
|
|
||||||
|
tracing::info!(
|
||||||
|
tool = "secrets_delete",
|
||||||
|
?user_id,
|
||||||
|
elapsed_ms = t.elapsed().as_millis(),
|
||||||
|
"tool call ok",
|
||||||
|
);
|
||||||
let json = serde_json::to_string_pretty(&result).unwrap_or_default();
|
let json = serde_json::to_string_pretty(&result).unwrap_or_default();
|
||||||
Ok(CallToolResult::success(vec![Content::text(json)]))
|
Ok(CallToolResult::success(vec![Content::text(json)]))
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tool(
|
#[tool(
|
||||||
description = "View change history for an entry. Returns a list of versions with \
|
description = "View change history for an entry. Returns a list of versions with \
|
||||||
actions and timestamps."
|
actions and timestamps.",
|
||||||
|
annotations(
|
||||||
|
title = "View Secret History",
|
||||||
|
read_only_hint = true,
|
||||||
|
idempotent_hint = true
|
||||||
|
)
|
||||||
)]
|
)]
|
||||||
async fn secrets_history(
|
async fn secrets_history(
|
||||||
&self,
|
&self,
|
||||||
Parameters(input): Parameters<HistoryInput>,
|
Parameters(input): Parameters<HistoryInput>,
|
||||||
_ctx: RequestContext<RoleServer>,
|
ctx: RequestContext<RoleServer>,
|
||||||
) -> Result<CallToolResult, rmcp::ErrorData> {
|
) -> Result<CallToolResult, rmcp::ErrorData> {
|
||||||
|
let t = Instant::now();
|
||||||
|
let user_id = Self::user_id_from_ctx(&ctx)?;
|
||||||
|
tracing::info!(
|
||||||
|
tool = "secrets_history",
|
||||||
|
?user_id,
|
||||||
|
name = %input.name,
|
||||||
|
"tool call start",
|
||||||
|
);
|
||||||
|
|
||||||
let result = svc_history(
|
let result = svc_history(
|
||||||
&self.pool,
|
&self.pool,
|
||||||
&input.namespace,
|
|
||||||
&input.kind,
|
|
||||||
&input.name,
|
&input.name,
|
||||||
|
input.folder.as_deref(),
|
||||||
input.limit.unwrap_or(20),
|
input.limit.unwrap_or(20),
|
||||||
None,
|
user_id,
|
||||||
)
|
)
|
||||||
.await
|
.await
|
||||||
.map_err(|e| rmcp::ErrorData::internal_error(e.to_string(), None))?;
|
.map_err(|e| mcp_err_internal_logged("secrets_history", user_id, e))?;
|
||||||
|
|
||||||
|
tracing::info!(
|
||||||
|
tool = "secrets_history",
|
||||||
|
?user_id,
|
||||||
|
elapsed_ms = t.elapsed().as_millis(),
|
||||||
|
"tool call ok",
|
||||||
|
);
|
||||||
let json = serde_json::to_string_pretty(&result).unwrap_or_default();
|
let json = serde_json::to_string_pretty(&result).unwrap_or_default();
|
||||||
Ok(CallToolResult::success(vec![Content::text(json)]))
|
Ok(CallToolResult::success(vec![Content::text(json)]))
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tool(
|
#[tool(
|
||||||
description = "Rollback an entry to a previous version. Requires X-Encryption-Key header. \
|
description = "Rollback an entry to a previous version. Requires X-Encryption-Key header. \
|
||||||
Omit to_version to restore the most recent snapshot."
|
Omit to_version to restore the most recent snapshot.",
|
||||||
|
annotations(title = "Rollback Secret Entry", destructive_hint = true)
|
||||||
)]
|
)]
|
||||||
async fn secrets_rollback(
|
async fn secrets_rollback(
|
||||||
&self,
|
&self,
|
||||||
Parameters(input): Parameters<RollbackInput>,
|
Parameters(input): Parameters<RollbackInput>,
|
||||||
ctx: RequestContext<RoleServer>,
|
ctx: RequestContext<RoleServer>,
|
||||||
) -> Result<CallToolResult, rmcp::ErrorData> {
|
) -> Result<CallToolResult, rmcp::ErrorData> {
|
||||||
|
let t = Instant::now();
|
||||||
let (user_id, user_key) = Self::require_user_and_key(&ctx)?;
|
let (user_id, user_key) = Self::require_user_and_key(&ctx)?;
|
||||||
|
tracing::info!(
|
||||||
|
tool = "secrets_rollback",
|
||||||
|
?user_id,
|
||||||
|
name = %input.name,
|
||||||
|
to_version = input.to_version,
|
||||||
|
"tool call start",
|
||||||
|
);
|
||||||
|
|
||||||
let result = svc_rollback(
|
let result = svc_rollback(
|
||||||
&self.pool,
|
&self.pool,
|
||||||
&input.namespace,
|
|
||||||
&input.kind,
|
|
||||||
&input.name,
|
&input.name,
|
||||||
|
input.folder.as_deref(),
|
||||||
input.to_version,
|
input.to_version,
|
||||||
&user_key,
|
&user_key,
|
||||||
Some(user_id),
|
Some(user_id),
|
||||||
)
|
)
|
||||||
.await
|
.await
|
||||||
.map_err(|e| rmcp::ErrorData::internal_error(e.to_string(), None))?;
|
.map_err(|e| mcp_err_internal_logged("secrets_rollback", Some(user_id), e))?;
|
||||||
|
|
||||||
|
tracing::info!(
|
||||||
|
tool = "secrets_rollback",
|
||||||
|
?user_id,
|
||||||
|
elapsed_ms = t.elapsed().as_millis(),
|
||||||
|
"tool call ok",
|
||||||
|
);
|
||||||
let json = serde_json::to_string_pretty(&result).unwrap_or_default();
|
let json = serde_json::to_string_pretty(&result).unwrap_or_default();
|
||||||
Ok(CallToolResult::success(vec![Content::text(json)]))
|
Ok(CallToolResult::success(vec![Content::text(json)]))
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tool(
|
#[tool(
|
||||||
description = "Export matching entries with decrypted secrets as JSON/TOML/YAML string. \
|
description = "Export matching entries with decrypted secrets as JSON/TOML/YAML string. \
|
||||||
Requires X-Encryption-Key header. Useful for backup or data migration."
|
Requires X-Encryption-Key header. Useful for backup or data migration.",
|
||||||
|
annotations(
|
||||||
|
title = "Export Secrets",
|
||||||
|
read_only_hint = true,
|
||||||
|
idempotent_hint = true
|
||||||
|
)
|
||||||
)]
|
)]
|
||||||
async fn secrets_export(
|
async fn secrets_export(
|
||||||
&self,
|
&self,
|
||||||
Parameters(input): Parameters<ExportInput>,
|
Parameters(input): Parameters<ExportInput>,
|
||||||
ctx: RequestContext<RoleServer>,
|
ctx: RequestContext<RoleServer>,
|
||||||
) -> Result<CallToolResult, rmcp::ErrorData> {
|
) -> Result<CallToolResult, rmcp::ErrorData> {
|
||||||
|
let t = Instant::now();
|
||||||
let (user_id, user_key) = Self::require_user_and_key(&ctx)?;
|
let (user_id, user_key) = Self::require_user_and_key(&ctx)?;
|
||||||
let tags = input.tags.unwrap_or_default();
|
let tags = input.tags.unwrap_or_default();
|
||||||
let format = input.format.as_deref().unwrap_or("json");
|
let format = input.format.as_deref().unwrap_or("json");
|
||||||
|
tracing::info!(
|
||||||
|
tool = "secrets_export",
|
||||||
|
?user_id,
|
||||||
|
folder = input.folder.as_deref(),
|
||||||
|
entry_type = input.entry_type.as_deref(),
|
||||||
|
format,
|
||||||
|
"tool call start",
|
||||||
|
);
|
||||||
|
|
||||||
let data = svc_export(
|
let data = svc_export(
|
||||||
&self.pool,
|
&self.pool,
|
||||||
ExportParams {
|
ExportParams {
|
||||||
namespace: input.namespace.as_deref(),
|
folder: input.folder.as_deref(),
|
||||||
kind: input.kind.as_deref(),
|
entry_type: input.entry_type.as_deref(),
|
||||||
name: input.name.as_deref(),
|
name: input.name.as_deref(),
|
||||||
tags: &tags,
|
tags: &tags,
|
||||||
query: input.query.as_deref(),
|
query: input.query.as_deref(),
|
||||||
@@ -544,34 +753,62 @@ impl SecretsService {
|
|||||||
Some(&user_key),
|
Some(&user_key),
|
||||||
)
|
)
|
||||||
.await
|
.await
|
||||||
.map_err(|e| rmcp::ErrorData::internal_error(e.to_string(), None))?;
|
.map_err(|e| mcp_err_internal_logged("secrets_export", Some(user_id), e))?;
|
||||||
|
|
||||||
let serialized = format
|
let fmt = format.parse::<ExportFormat>().map_err(|e| {
|
||||||
.parse::<secrets_core::models::ExportFormat>()
|
tracing::warn!(
|
||||||
.and_then(|fmt| fmt.serialize(&data))
|
tool = "secrets_export",
|
||||||
.map_err(|e| rmcp::ErrorData::internal_error(e.to_string(), None))?;
|
?user_id,
|
||||||
|
error = %e,
|
||||||
|
"invalid export format"
|
||||||
|
);
|
||||||
|
rmcp::ErrorData::invalid_request(
|
||||||
|
"Invalid export format. Use json, toml, or yaml.",
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
let serialized = fmt
|
||||||
|
.serialize(&data)
|
||||||
|
.map_err(|e| mcp_err_internal_logged("secrets_export", Some(user_id), e))?;
|
||||||
|
|
||||||
|
tracing::info!(
|
||||||
|
tool = "secrets_export",
|
||||||
|
?user_id,
|
||||||
|
entry_count = data.entries.len(),
|
||||||
|
elapsed_ms = t.elapsed().as_millis(),
|
||||||
|
"tool call ok",
|
||||||
|
);
|
||||||
Ok(CallToolResult::success(vec![Content::text(serialized)]))
|
Ok(CallToolResult::success(vec![Content::text(serialized)]))
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tool(
|
#[tool(
|
||||||
description = "Build the environment variable map from entry secrets with decrypted \
|
description = "Build the environment variable map from entry secrets with decrypted \
|
||||||
plaintext values. Requires X-Encryption-Key header. \
|
plaintext values. Requires X-Encryption-Key header. \
|
||||||
Returns a JSON object of VAR_NAME -> plaintext_value ready for injection."
|
Returns a JSON object of VAR_NAME -> plaintext_value ready for injection.",
|
||||||
|
annotations(title = "Build Env Map", read_only_hint = true, idempotent_hint = true)
|
||||||
)]
|
)]
|
||||||
async fn secrets_env_map(
|
async fn secrets_env_map(
|
||||||
&self,
|
&self,
|
||||||
Parameters(input): Parameters<EnvMapInput>,
|
Parameters(input): Parameters<EnvMapInput>,
|
||||||
ctx: RequestContext<RoleServer>,
|
ctx: RequestContext<RoleServer>,
|
||||||
) -> Result<CallToolResult, rmcp::ErrorData> {
|
) -> Result<CallToolResult, rmcp::ErrorData> {
|
||||||
|
let t = Instant::now();
|
||||||
let (user_id, user_key) = Self::require_user_and_key(&ctx)?;
|
let (user_id, user_key) = Self::require_user_and_key(&ctx)?;
|
||||||
let tags = input.tags.unwrap_or_default();
|
let tags = input.tags.unwrap_or_default();
|
||||||
let only_fields = input.only_fields.unwrap_or_default();
|
let only_fields = input.only_fields.unwrap_or_default();
|
||||||
|
tracing::info!(
|
||||||
|
tool = "secrets_env_map",
|
||||||
|
?user_id,
|
||||||
|
folder = input.folder.as_deref(),
|
||||||
|
entry_type = input.entry_type.as_deref(),
|
||||||
|
prefix = input.prefix.as_deref().unwrap_or(""),
|
||||||
|
"tool call start",
|
||||||
|
);
|
||||||
|
|
||||||
let env_map = secrets_core::service::env_map::build_env_map(
|
let env_map = secrets_core::service::env_map::build_env_map(
|
||||||
&self.pool,
|
&self.pool,
|
||||||
input.namespace.as_deref(),
|
input.folder.as_deref(),
|
||||||
input.kind.as_deref(),
|
input.entry_type.as_deref(),
|
||||||
input.name.as_deref(),
|
input.name.as_deref(),
|
||||||
&tags,
|
&tags,
|
||||||
&only_fields,
|
&only_fields,
|
||||||
@@ -580,8 +817,16 @@ impl SecretsService {
|
|||||||
Some(user_id),
|
Some(user_id),
|
||||||
)
|
)
|
||||||
.await
|
.await
|
||||||
.map_err(|e| rmcp::ErrorData::internal_error(e.to_string(), None))?;
|
.map_err(|e| mcp_err_internal_logged("secrets_env_map", Some(user_id), e))?;
|
||||||
|
|
||||||
|
let entry_count = env_map.len();
|
||||||
|
tracing::info!(
|
||||||
|
tool = "secrets_env_map",
|
||||||
|
?user_id,
|
||||||
|
entry_count,
|
||||||
|
elapsed_ms = t.elapsed().as_millis(),
|
||||||
|
"tool call ok",
|
||||||
|
);
|
||||||
let json = serde_json::to_string_pretty(&env_map).unwrap_or_default();
|
let json = serde_json::to_string_pretty(&env_map).unwrap_or_default();
|
||||||
Ok(CallToolResult::success(vec![Content::text(json)]))
|
Ok(CallToolResult::success(vec![Content::text(json)]))
|
||||||
}
|
}
|
||||||
@@ -593,13 +838,17 @@ impl SecretsService {
|
|||||||
impl ServerHandler for SecretsService {
|
impl ServerHandler for SecretsService {
|
||||||
fn get_info(&self) -> InitializeResult {
|
fn get_info(&self) -> InitializeResult {
|
||||||
let mut info = InitializeResult::new(ServerCapabilities::builder().enable_tools().build());
|
let mut info = InitializeResult::new(ServerCapabilities::builder().enable_tools().build());
|
||||||
info.server_info = Implementation::new("secrets-mcp", env!("CARGO_PKG_VERSION"));
|
info.server_info = Implementation::new("secrets-mcp", env!("CARGO_PKG_VERSION"))
|
||||||
info.protocol_version = ProtocolVersion::V_2025_03_26;
|
.with_title("Secrets MCP")
|
||||||
|
.with_description(
|
||||||
|
"Secure cross-device secrets and configuration management with encrypted secret fields.",
|
||||||
|
);
|
||||||
|
info.protocol_version = ProtocolVersion::V_2025_06_18;
|
||||||
info.instructions = Some(
|
info.instructions = Some(
|
||||||
"Manage cross-device secrets and configuration securely. \
|
"Manage cross-device secrets and configuration securely. \
|
||||||
Data is encrypted with your passphrase-derived key. \
|
Data is encrypted with your passphrase-derived key. \
|
||||||
Include your 64-char hex key in the X-Encryption-Key header for all read/write operations. \
|
Include your 64-char hex key in the X-Encryption-Key header for all read/write operations. \
|
||||||
Use secrets_search to discover entries (no key needed), \
|
Use secrets_search to discover entries (Bearer token required; encryption key not needed), \
|
||||||
secrets_get to decrypt secret values, \
|
secrets_get to decrypt secret values, \
|
||||||
and secrets_add/secrets_update to write encrypted secrets."
|
and secrets_add/secrets_update to write encrypted secrets."
|
||||||
.to_string(),
|
.to_string(),
|
||||||
|
|||||||
@@ -39,6 +39,15 @@ const SESSION_LOGIN_PROVIDER: &str = "login_provider";
|
|||||||
#[template(path = "login.html")]
|
#[template(path = "login.html")]
|
||||||
struct LoginTemplate {
|
struct LoginTemplate {
|
||||||
has_google: bool,
|
has_google: bool,
|
||||||
|
base_url: String,
|
||||||
|
version: &'static str,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Template)]
|
||||||
|
#[template(path = "home.html")]
|
||||||
|
struct HomeTemplate {
|
||||||
|
is_logged_in: bool,
|
||||||
|
base_url: String,
|
||||||
version: &'static str,
|
version: &'static str,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -76,12 +85,22 @@ fn google_cfg(state: &AppState) -> Option<&OAuthConfig> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async fn current_user_id(session: &Session) -> Option<Uuid> {
|
async fn current_user_id(session: &Session) -> Option<Uuid> {
|
||||||
session
|
match session.get::<String>(SESSION_USER_ID).await {
|
||||||
.get::<String>(SESSION_USER_ID)
|
Ok(opt) => match opt {
|
||||||
.await
|
Some(s) => match Uuid::parse_str(&s) {
|
||||||
.ok()
|
Ok(id) => Some(id),
|
||||||
.flatten()
|
Err(e) => {
|
||||||
.and_then(|s| Uuid::parse_str(&s).ok())
|
tracing::warn!(error = %e, user_id_str = %s, "invalid user_id UUID in session");
|
||||||
|
None
|
||||||
|
}
|
||||||
|
},
|
||||||
|
None => None,
|
||||||
|
},
|
||||||
|
Err(e) => {
|
||||||
|
tracing::warn!(error = %e, "failed to read user_id from session");
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn request_client_ip(headers: &HeaderMap, connect_info: ConnectInfo<SocketAddr>) -> Option<String> {
|
fn request_client_ip(headers: &HeaderMap, connect_info: ConnectInfo<SocketAddr>) -> Option<String> {
|
||||||
@@ -112,12 +131,20 @@ fn request_user_agent(headers: &HeaderMap) -> Option<String> {
|
|||||||
|
|
||||||
pub fn web_router() -> Router<AppState> {
|
pub fn web_router() -> Router<AppState> {
|
||||||
Router::new()
|
Router::new()
|
||||||
|
.route("/robots.txt", get(robots_txt))
|
||||||
|
.route("/llms.txt", get(llms_txt))
|
||||||
|
.route("/ai.txt", get(ai_txt))
|
||||||
.route("/favicon.svg", get(favicon_svg))
|
.route("/favicon.svg", get(favicon_svg))
|
||||||
.route(
|
.route(
|
||||||
"/favicon.ico",
|
"/favicon.ico",
|
||||||
get(|| async { Redirect::permanent("/favicon.svg") }),
|
get(|| async { Redirect::permanent("/favicon.svg") }),
|
||||||
)
|
)
|
||||||
.route("/", get(login_page))
|
.route(
|
||||||
|
"/.well-known/oauth-protected-resource",
|
||||||
|
get(oauth_protected_resource_metadata),
|
||||||
|
)
|
||||||
|
.route("/", get(home_page))
|
||||||
|
.route("/login", get(login_page))
|
||||||
.route("/auth/google", get(auth_google))
|
.route("/auth/google", get(auth_google))
|
||||||
.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))
|
||||||
@@ -135,6 +162,33 @@ pub fn web_router() -> Router<AppState> {
|
|||||||
.route("/api/apikey/regenerate", post(api_apikey_regenerate))
|
.route("/api/apikey/regenerate", post(api_apikey_regenerate))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn text_asset_response(content: &'static str, content_type: &'static str) -> Response {
|
||||||
|
Response::builder()
|
||||||
|
.status(StatusCode::OK)
|
||||||
|
.header(header::CONTENT_TYPE, content_type)
|
||||||
|
.header(header::CACHE_CONTROL, "public, max-age=86400")
|
||||||
|
.body(Body::from(content))
|
||||||
|
.expect("text asset response")
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn robots_txt() -> Response {
|
||||||
|
text_asset_response(
|
||||||
|
include_str!("../static/robots.txt"),
|
||||||
|
"text/plain; charset=utf-8",
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn llms_txt() -> Response {
|
||||||
|
text_asset_response(
|
||||||
|
include_str!("../static/llms.txt"),
|
||||||
|
"text/markdown; charset=utf-8",
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn ai_txt() -> Response {
|
||||||
|
llms_txt().await
|
||||||
|
}
|
||||||
|
|
||||||
async fn favicon_svg() -> Response {
|
async fn favicon_svg() -> Response {
|
||||||
Response::builder()
|
Response::builder()
|
||||||
.status(StatusCode::OK)
|
.status(StatusCode::OK)
|
||||||
@@ -144,6 +198,21 @@ async fn favicon_svg() -> Response {
|
|||||||
.expect("favicon response")
|
.expect("favicon response")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ── Home page (public) ───────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
async fn home_page(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
session: Session,
|
||||||
|
) -> Result<Response, StatusCode> {
|
||||||
|
let is_logged_in = current_user_id(&session).await.is_some();
|
||||||
|
let tmpl = HomeTemplate {
|
||||||
|
is_logged_in,
|
||||||
|
base_url: state.base_url.clone(),
|
||||||
|
version: env!("CARGO_PKG_VERSION"),
|
||||||
|
};
|
||||||
|
render_template(tmpl)
|
||||||
|
}
|
||||||
|
|
||||||
// ── Login page ────────────────────────────────────────────────────────────────
|
// ── Login page ────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
async fn login_page(
|
async fn login_page(
|
||||||
@@ -156,6 +225,7 @@ async fn login_page(
|
|||||||
|
|
||||||
let tmpl = LoginTemplate {
|
let tmpl = LoginTemplate {
|
||||||
has_google: state.google_config.is_some(),
|
has_google: state.google_config.is_some(),
|
||||||
|
base_url: state.base_url.clone(),
|
||||||
version: env!("CARGO_PKG_VERSION"),
|
version: env!("CARGO_PKG_VERSION"),
|
||||||
};
|
};
|
||||||
render_template(tmpl)
|
render_template(tmpl)
|
||||||
@@ -173,7 +243,10 @@ async fn auth_google(
|
|||||||
session
|
session
|
||||||
.insert(SESSION_OAUTH_STATE, &oauth_state)
|
.insert(SESSION_OAUTH_STATE, &oauth_state)
|
||||||
.await
|
.await
|
||||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
.map_err(|e| {
|
||||||
|
tracing::error!(error = %e, "failed to insert oauth_state into session");
|
||||||
|
StatusCode::INTERNAL_SERVER_ERROR
|
||||||
|
})?;
|
||||||
|
|
||||||
let url = google_auth_url(config, &oauth_state);
|
let url = google_auth_url(config, &oauth_state);
|
||||||
Ok(Redirect::to(&url).into_response())
|
Ok(Redirect::to(&url).into_response())
|
||||||
@@ -235,31 +308,33 @@ where
|
|||||||
{
|
{
|
||||||
if let Some(err) = params.error {
|
if let Some(err) = params.error {
|
||||||
tracing::warn!(provider, error = %err, "OAuth error");
|
tracing::warn!(provider, error = %err, "OAuth error");
|
||||||
return Ok(Redirect::to("/?error=oauth_error").into_response());
|
return Ok(Redirect::to("/login?error=oauth_error").into_response());
|
||||||
}
|
}
|
||||||
|
|
||||||
let Some(code) = params.code else {
|
let Some(code) = params.code else {
|
||||||
tracing::warn!(provider, "OAuth callback missing code");
|
tracing::warn!(provider, "OAuth callback missing code");
|
||||||
return Ok(Redirect::to("/?error=oauth_missing_code").into_response());
|
return Ok(Redirect::to("/login?error=oauth_missing_code").into_response());
|
||||||
};
|
};
|
||||||
let Some(returned_state) = params.state.as_deref() else {
|
let Some(returned_state) = params.state.as_deref() else {
|
||||||
tracing::warn!(provider, "OAuth callback missing state");
|
tracing::warn!(provider, "OAuth callback missing state");
|
||||||
return Ok(Redirect::to("/?error=oauth_missing_state").into_response());
|
return Ok(Redirect::to("/login?error=oauth_missing_state").into_response());
|
||||||
};
|
};
|
||||||
|
|
||||||
let expected_state: Option<String> = session
|
let expected_state: Option<String> = session.get(SESSION_OAUTH_STATE).await.map_err(|e| {
|
||||||
.get(SESSION_OAUTH_STATE)
|
tracing::error!(provider, error = %e, "failed to read oauth_state from session");
|
||||||
.await
|
StatusCode::INTERNAL_SERVER_ERROR
|
||||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
})?;
|
||||||
if expected_state.as_deref() != Some(returned_state) {
|
if expected_state.as_deref() != Some(returned_state) {
|
||||||
tracing::warn!(
|
tracing::warn!(
|
||||||
provider,
|
provider,
|
||||||
expected_present = expected_state.is_some(),
|
expected_present = expected_state.is_some(),
|
||||||
"OAuth state mismatch (empty session often means SameSite=Strict or server restart)"
|
"OAuth state mismatch (empty session often means SameSite=Strict or server restart)"
|
||||||
);
|
);
|
||||||
return Ok(Redirect::to("/?error=oauth_state").into_response());
|
return Ok(Redirect::to("/login?error=oauth_state").into_response());
|
||||||
|
}
|
||||||
|
if let Err(e) = session.remove::<String>(SESSION_OAUTH_STATE).await {
|
||||||
|
tracing::warn!(provider, error = %e, "failed to remove oauth_state from session");
|
||||||
}
|
}
|
||||||
session.remove::<String>(SESSION_OAUTH_STATE).await.ok();
|
|
||||||
|
|
||||||
let config = match provider {
|
let config = match provider {
|
||||||
"google" => state
|
"google" => state
|
||||||
@@ -276,17 +351,25 @@ where
|
|||||||
StatusCode::INTERNAL_SERVER_ERROR
|
StatusCode::INTERNAL_SERVER_ERROR
|
||||||
})?;
|
})?;
|
||||||
|
|
||||||
let bind_mode: bool = session
|
let bind_mode: bool = match session.get::<bool>(SESSION_OAUTH_BIND_MODE).await {
|
||||||
.get(SESSION_OAUTH_BIND_MODE)
|
Ok(v) => v.unwrap_or(false),
|
||||||
.await
|
Err(e) => {
|
||||||
.unwrap_or(None)
|
tracing::error!(
|
||||||
.unwrap_or(false);
|
provider,
|
||||||
|
error = %e,
|
||||||
|
"failed to read oauth_bind_mode from session"
|
||||||
|
);
|
||||||
|
return Err(StatusCode::INTERNAL_SERVER_ERROR);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
if bind_mode {
|
if bind_mode {
|
||||||
let user_id = current_user_id(session)
|
let user_id = current_user_id(session)
|
||||||
.await
|
.await
|
||||||
.ok_or(StatusCode::UNAUTHORIZED)?;
|
.ok_or(StatusCode::UNAUTHORIZED)?;
|
||||||
session.remove::<bool>(SESSION_OAUTH_BIND_MODE).await.ok();
|
if let Err(e) = session.remove::<bool>(SESSION_OAUTH_BIND_MODE).await {
|
||||||
|
tracing::warn!(provider, error = %e, "failed to remove oauth_bind_mode from session after bind");
|
||||||
|
}
|
||||||
|
|
||||||
let profile = OAuthProfile {
|
let profile = OAuthProfile {
|
||||||
provider: user_info.provider,
|
provider: user_info.provider,
|
||||||
@@ -321,19 +404,28 @@ where
|
|||||||
StatusCode::INTERNAL_SERVER_ERROR
|
StatusCode::INTERNAL_SERVER_ERROR
|
||||||
})?;
|
})?;
|
||||||
|
|
||||||
// Ensure the user has an API key (auto-creates on first login).
|
|
||||||
if let Err(e) = ensure_api_key(&state.pool, user.id).await {
|
|
||||||
tracing::warn!(error = %e, "failed to ensure api key for user");
|
|
||||||
}
|
|
||||||
|
|
||||||
session
|
session
|
||||||
.insert(SESSION_USER_ID, user.id.to_string())
|
.insert(SESSION_USER_ID, user.id.to_string())
|
||||||
.await
|
.await
|
||||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
.map_err(|e| {
|
||||||
|
tracing::error!(
|
||||||
|
error = %e,
|
||||||
|
user_id = %user.id,
|
||||||
|
"failed to insert user_id into session after OAuth"
|
||||||
|
);
|
||||||
|
StatusCode::INTERNAL_SERVER_ERROR
|
||||||
|
})?;
|
||||||
session
|
session
|
||||||
.insert(SESSION_LOGIN_PROVIDER, &provider)
|
.insert(SESSION_LOGIN_PROVIDER, &provider)
|
||||||
.await
|
.await
|
||||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
.map_err(|e| {
|
||||||
|
tracing::error!(
|
||||||
|
provider,
|
||||||
|
error = %e,
|
||||||
|
"failed to insert login_provider into session after OAuth"
|
||||||
|
);
|
||||||
|
StatusCode::INTERNAL_SERVER_ERROR
|
||||||
|
})?;
|
||||||
|
|
||||||
log_login(
|
log_login(
|
||||||
&state.pool,
|
&state.pool,
|
||||||
@@ -351,7 +443,9 @@ where
|
|||||||
// ── Logout ────────────────────────────────────────────────────────────────────
|
// ── Logout ────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
async fn auth_logout(session: Session) -> impl IntoResponse {
|
async fn auth_logout(session: Session) -> impl IntoResponse {
|
||||||
session.flush().await.ok();
|
if let Err(e) = session.flush().await {
|
||||||
|
tracing::warn!(error = %e, "failed to flush session on logout");
|
||||||
|
}
|
||||||
Redirect::to("/")
|
Redirect::to("/")
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -362,15 +456,15 @@ async fn dashboard(
|
|||||||
session: Session,
|
session: Session,
|
||||||
) -> Result<Response, StatusCode> {
|
) -> Result<Response, StatusCode> {
|
||||||
let Some(user_id) = current_user_id(&session).await else {
|
let Some(user_id) = current_user_id(&session).await else {
|
||||||
return Ok(Redirect::to("/").into_response());
|
return Ok(Redirect::to("/login").into_response());
|
||||||
};
|
};
|
||||||
|
|
||||||
let user = match get_user_by_id(&state.pool, user_id)
|
let user = match get_user_by_id(&state.pool, user_id).await.map_err(|e| {
|
||||||
.await
|
tracing::error!(error = %e, %user_id, "failed to load user for dashboard");
|
||||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
|
StatusCode::INTERNAL_SERVER_ERROR
|
||||||
{
|
})? {
|
||||||
Some(u) => u,
|
Some(u) => u,
|
||||||
None => return Ok(Redirect::to("/").into_response()),
|
None => return Ok(Redirect::to("/login").into_response()),
|
||||||
};
|
};
|
||||||
|
|
||||||
let tmpl = DashboardTemplate {
|
let tmpl = DashboardTemplate {
|
||||||
@@ -389,15 +483,15 @@ async fn audit_page(
|
|||||||
session: Session,
|
session: Session,
|
||||||
) -> Result<Response, StatusCode> {
|
) -> Result<Response, StatusCode> {
|
||||||
let Some(user_id) = current_user_id(&session).await else {
|
let Some(user_id) = current_user_id(&session).await else {
|
||||||
return Ok(Redirect::to("/").into_response());
|
return Ok(Redirect::to("/login").into_response());
|
||||||
};
|
};
|
||||||
|
|
||||||
let user = match get_user_by_id(&state.pool, user_id)
|
let user = match get_user_by_id(&state.pool, user_id).await.map_err(|e| {
|
||||||
.await
|
tracing::error!(error = %e, %user_id, "failed to load user for audit page");
|
||||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
|
StatusCode::INTERNAL_SERVER_ERROR
|
||||||
{
|
})? {
|
||||||
Some(u) => u,
|
Some(u) => u,
|
||||||
None => return Ok(Redirect::to("/").into_response()),
|
None => return Ok(Redirect::to("/login").into_response()),
|
||||||
};
|
};
|
||||||
|
|
||||||
let rows = list_for_user(&state.pool, user_id, 100)
|
let rows = list_for_user(&state.pool, user_id, 100)
|
||||||
@@ -412,7 +506,7 @@ async fn audit_page(
|
|||||||
.map(|row| AuditEntryView {
|
.map(|row| AuditEntryView {
|
||||||
created_at_iso: row.created_at.to_rfc3339_opts(SecondsFormat::Secs, true),
|
created_at_iso: row.created_at.to_rfc3339_opts(SecondsFormat::Secs, true),
|
||||||
action: row.action,
|
action: row.action,
|
||||||
target: format_audit_target(&row.namespace, &row.kind, &row.name),
|
target: format_audit_target(&row.folder, &row.entry_type, &row.name),
|
||||||
detail: serde_json::to_string_pretty(&row.detail).unwrap_or_else(|_| "{}".to_string()),
|
detail: serde_json::to_string_pretty(&row.detail).unwrap_or_else(|_| "{}".to_string()),
|
||||||
})
|
})
|
||||||
.collect();
|
.collect();
|
||||||
@@ -440,7 +534,10 @@ async fn account_bind_google(
|
|||||||
session
|
session
|
||||||
.insert(SESSION_OAUTH_BIND_MODE, true)
|
.insert(SESSION_OAUTH_BIND_MODE, true)
|
||||||
.await
|
.await
|
||||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
.map_err(|e| {
|
||||||
|
tracing::error!(error = %e, "failed to insert oauth_bind_mode into session");
|
||||||
|
StatusCode::INTERNAL_SERVER_ERROR
|
||||||
|
})?;
|
||||||
|
|
||||||
let redirect_uri = format!("{}/account/bind/google/callback", state.base_url);
|
let redirect_uri = format!("{}/account/bind/google/callback", state.base_url);
|
||||||
let mut cfg = state
|
let mut cfg = state
|
||||||
@@ -449,7 +546,13 @@ async fn account_bind_google(
|
|||||||
.ok_or(StatusCode::SERVICE_UNAVAILABLE)?;
|
.ok_or(StatusCode::SERVICE_UNAVAILABLE)?;
|
||||||
cfg.redirect_uri = redirect_uri;
|
cfg.redirect_uri = redirect_uri;
|
||||||
let st = random_state();
|
let st = random_state();
|
||||||
session.insert(SESSION_OAUTH_STATE, &st).await.ok();
|
if let Err(e) = session.insert(SESSION_OAUTH_STATE, &st).await {
|
||||||
|
tracing::error!(error = %e, "failed to insert oauth_state for account bind flow");
|
||||||
|
if let Err(rm) = session.remove::<bool>(SESSION_OAUTH_BIND_MODE).await {
|
||||||
|
tracing::warn!(error = %rm, "failed to roll back oauth_bind_mode after oauth_state insert failure");
|
||||||
|
}
|
||||||
|
return Err(StatusCode::INTERNAL_SERVER_ERROR);
|
||||||
|
}
|
||||||
|
|
||||||
Ok(Redirect::to(&google_auth_url(&cfg, &st)).into_response())
|
Ok(Redirect::to(&google_auth_url(&cfg, &st)).into_response())
|
||||||
}
|
}
|
||||||
@@ -493,7 +596,10 @@ async fn account_unbind(
|
|||||||
let current_login_provider = session
|
let current_login_provider = session
|
||||||
.get::<String>(SESSION_LOGIN_PROVIDER)
|
.get::<String>(SESSION_LOGIN_PROVIDER)
|
||||||
.await
|
.await
|
||||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
.map_err(|e| {
|
||||||
|
tracing::error!(error = %e, "failed to read login_provider from session");
|
||||||
|
StatusCode::INTERNAL_SERVER_ERROR
|
||||||
|
})?;
|
||||||
|
|
||||||
unbind_oauth_account(
|
unbind_oauth_account(
|
||||||
&state.pool,
|
&state.pool,
|
||||||
@@ -533,7 +639,10 @@ async fn api_key_salt(
|
|||||||
|
|
||||||
let user = get_user_by_id(&state.pool, user_id)
|
let user = get_user_by_id(&state.pool, user_id)
|
||||||
.await
|
.await
|
||||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
|
.map_err(|e| {
|
||||||
|
tracing::error!(error = %e, %user_id, "failed to load user for key-salt API");
|
||||||
|
StatusCode::INTERNAL_SERVER_ERROR
|
||||||
|
})?
|
||||||
.ok_or(StatusCode::UNAUTHORIZED)?;
|
.ok_or(StatusCode::UNAUTHORIZED)?;
|
||||||
|
|
||||||
if user.key_salt.is_none() {
|
if user.key_salt.is_none() {
|
||||||
@@ -577,10 +686,17 @@ async fn api_key_setup(
|
|||||||
.await
|
.await
|
||||||
.ok_or(StatusCode::UNAUTHORIZED)?;
|
.ok_or(StatusCode::UNAUTHORIZED)?;
|
||||||
|
|
||||||
let salt = hex::decode_hex(&body.salt).map_err(|_| StatusCode::BAD_REQUEST)?;
|
let salt = hex::decode_hex(&body.salt).map_err(|e| {
|
||||||
let key_check = hex::decode_hex(&body.key_check).map_err(|_| StatusCode::BAD_REQUEST)?;
|
tracing::warn!(error = %e, "invalid hex in key-setup salt");
|
||||||
|
StatusCode::BAD_REQUEST
|
||||||
|
})?;
|
||||||
|
let key_check = hex::decode_hex(&body.key_check).map_err(|e| {
|
||||||
|
tracing::warn!(error = %e, "invalid hex in key-setup key_check");
|
||||||
|
StatusCode::BAD_REQUEST
|
||||||
|
})?;
|
||||||
|
|
||||||
if salt.len() != 32 {
|
if salt.len() != 32 {
|
||||||
|
tracing::warn!(salt_len = salt.len(), "key-setup salt must be 32 bytes");
|
||||||
return Err(StatusCode::BAD_REQUEST);
|
return Err(StatusCode::BAD_REQUEST);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -609,9 +725,10 @@ async fn api_apikey_get(
|
|||||||
.await
|
.await
|
||||||
.ok_or(StatusCode::UNAUTHORIZED)?;
|
.ok_or(StatusCode::UNAUTHORIZED)?;
|
||||||
|
|
||||||
let api_key = ensure_api_key(&state.pool, user_id)
|
let api_key = ensure_api_key(&state.pool, user_id).await.map_err(|e| {
|
||||||
.await
|
tracing::error!(error = %e, %user_id, "ensure_api_key failed");
|
||||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
StatusCode::INTERNAL_SERVER_ERROR
|
||||||
|
})?;
|
||||||
|
|
||||||
Ok(Json(ApiKeyResponse { api_key }))
|
Ok(Json(ApiKeyResponse { api_key }))
|
||||||
}
|
}
|
||||||
@@ -626,11 +743,36 @@ async fn api_apikey_regenerate(
|
|||||||
|
|
||||||
let api_key = regenerate_api_key(&state.pool, user_id)
|
let api_key = regenerate_api_key(&state.pool, user_id)
|
||||||
.await
|
.await
|
||||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
.map_err(|e| {
|
||||||
|
tracing::error!(error = %e, %user_id, "regenerate_api_key failed");
|
||||||
|
StatusCode::INTERNAL_SERVER_ERROR
|
||||||
|
})?;
|
||||||
|
|
||||||
Ok(Json(ApiKeyResponse { api_key }))
|
Ok(Json(ApiKeyResponse { api_key }))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ── OAuth / Well-known ────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
/// RFC 9728 — OAuth 2.0 Protected Resource Metadata.
|
||||||
|
///
|
||||||
|
/// Advertises that this server accepts Bearer tokens in the `Authorization`
|
||||||
|
/// header. We deliberately omit `authorization_servers` because this service
|
||||||
|
/// issues its own API keys (no external OAuth AS is involved). MCP clients
|
||||||
|
/// that probe this endpoint will see the resource identifier and stop looking
|
||||||
|
/// for a delegated OAuth flow.
|
||||||
|
async fn oauth_protected_resource_metadata(State(state): State<AppState>) -> impl IntoResponse {
|
||||||
|
let body = serde_json::json!({
|
||||||
|
"resource": state.base_url,
|
||||||
|
"bearer_methods_supported": ["header"],
|
||||||
|
"resource_documentation": format!("{}/dashboard", state.base_url),
|
||||||
|
});
|
||||||
|
(
|
||||||
|
StatusCode::OK,
|
||||||
|
[(header::CONTENT_TYPE, "application/json")],
|
||||||
|
axum::Json(body),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
// ── Helper ────────────────────────────────────────────────────────────────────
|
// ── Helper ────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
fn render_template<T: Template>(tmpl: T) -> Result<Response, StatusCode> {
|
fn render_template<T: Template>(tmpl: T) -> Result<Response, StatusCode> {
|
||||||
@@ -641,10 +783,15 @@ fn render_template<T: Template>(tmpl: T) -> Result<Response, StatusCode> {
|
|||||||
Ok(Html(html).into_response())
|
Ok(Html(html).into_response())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn format_audit_target(namespace: &str, kind: &str, name: &str) -> String {
|
fn format_audit_target(folder: &str, entry_type: &str, name: &str) -> String {
|
||||||
if namespace == "auth" {
|
// Auth events (folder="auth") use entry_type/name as provider-scoped target.
|
||||||
format!("{}/{}", kind, name)
|
if folder == "auth" {
|
||||||
|
format!("{}/{}", entry_type, name)
|
||||||
|
} else if !folder.is_empty() && !entry_type.is_empty() {
|
||||||
|
format!("[{}/{}] {}", folder, entry_type, name)
|
||||||
|
} else if !folder.is_empty() {
|
||||||
|
format!("[{}] {}", folder, name)
|
||||||
} else {
|
} else {
|
||||||
format!("[{}/{}] {}", namespace, kind, name)
|
name.to_string()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
28
crates/secrets-mcp/static/llms.txt
Normal file
28
crates/secrets-mcp/static/llms.txt
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
# Secrets MCP
|
||||||
|
|
||||||
|
> 给 AI 与自动化工具的简要说明。本站是 **secrets-mcp**:Streamable HTTP **MCP**(Model Context Protocol)与 **Web 控制台** 的组合,用于在多租户场景下存储条目元数据与加密后的秘密字段;持久化在 PostgreSQL。用户通过 OAuth(如已配置)登录 Web;MCP 调用使用 API Key 与加密相关请求头。
|
||||||
|
|
||||||
|
## 公开页面
|
||||||
|
|
||||||
|
- **`/`**:公开首页,说明安全架构(客户端密钥派生、密文存储、多租户与审计等),无需登录。
|
||||||
|
|
||||||
|
## 不应抓取或索引的内容
|
||||||
|
|
||||||
|
- **`/mcp`**:MCP 流式 HTTP 端点(JSON-RPC 等),**不是** HTML 文档,也不适合作为公开知识库来源。
|
||||||
|
- **`/api/*`**:会话或 API Key 相关的 HTTP API。
|
||||||
|
- **`/login`**:登录入口页(`noindex` / robots 通常 disallow)。
|
||||||
|
- **`/dashboard`、`/audit`、`/auth/*`、`/account/*`**:需浏览器会话,属于用户私有界面与 OAuth 流程。
|
||||||
|
|
||||||
|
## 给 AI 助手的实用提示
|
||||||
|
|
||||||
|
- 向用户说明连接方式时:MCP 基址为 `{BASE_URL}/mcp`(`BASE_URL` 由部署方设置),通常需要 `Authorization: Bearer <api_key>`;读写加密秘密时还需按部署文档传递 `X-Encryption-Key` 等头(与客户端模式有关)。
|
||||||
|
- **不要编造**本实例的数据库 URL、OAuth 密钥、回调地址或任何凭据;一律以用户环境变量与运维文档为准。
|
||||||
|
- Web 端在浏览器内用密码短语派生密钥完成端到端加密;MCP 路径下服务端可能在请求周期内临时使用客户端提供的密钥处理密文(架构细节见项目 README「加密架构」)。
|
||||||
|
|
||||||
|
## 延伸阅读
|
||||||
|
|
||||||
|
- 源码仓库:<https://gitea.refining.dev/refining/secrets>(`README.md`、`AGENTS.md` 含环境变量、表结构与运维约定)。
|
||||||
|
|
||||||
|
## 关于本文件
|
||||||
|
|
||||||
|
- 遵循常见的 **`/llms.txt`** 约定,便于人类与 LLM 快速了解站点性质与抓取边界;同文可在 **`/ai.txt`** 获取。
|
||||||
31
crates/secrets-mcp/static/robots.txt
Normal file
31
crates/secrets-mcp/static/robots.txt
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
# Secrets MCP — robots.txt
|
||||||
|
# 本站为需登录的私密控制台与 MCP API;以下路径请勿抓取,以免浪费配额并避免误索引敏感端点。
|
||||||
|
# This host serves an authenticated dashboard and machine APIs; please skip crawling the paths below.
|
||||||
|
|
||||||
|
User-agent: *
|
||||||
|
Disallow: /mcp
|
||||||
|
Disallow: /api/
|
||||||
|
Disallow: /dashboard
|
||||||
|
Disallow: /audit
|
||||||
|
Disallow: /auth/
|
||||||
|
Disallow: /login
|
||||||
|
Disallow: /account/
|
||||||
|
|
||||||
|
# 首页 `/` 为公开安全说明页,允许抓取。
|
||||||
|
|
||||||
|
# 面向 AI / LLM 的机器可读站点说明(Markdown):/llms.txt
|
||||||
|
# Human & AI-readable site summary: /llms.txt (also /ai.txt)
|
||||||
|
|
||||||
|
User-agent: GPTBot
|
||||||
|
User-agent: Google-Extended
|
||||||
|
User-agent: anthropic-ai
|
||||||
|
User-agent: Claude-Web
|
||||||
|
User-agent: PerplexityBot
|
||||||
|
User-agent: Bytespider
|
||||||
|
Disallow: /mcp
|
||||||
|
Disallow: /api/
|
||||||
|
Disallow: /dashboard
|
||||||
|
Disallow: /audit
|
||||||
|
Disallow: /auth/
|
||||||
|
Disallow: /login
|
||||||
|
Disallow: /account/
|
||||||
269
crates/secrets-mcp/templates/home.html
Normal file
269
crates/secrets-mcp/templates/home.html
Normal file
@@ -0,0 +1,269 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="zh-CN">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<meta name="description" content="Secrets MCP:基于 Model Context Protocol 的密钥与配置管理。密码短语在浏览器本地 PBKDF2 派生,密文 AES-GCM 存储,完整审计与历史版本。">
|
||||||
|
<meta name="keywords" content="secrets management,MCP,Model Context Protocol,end-to-end encryption,AES-GCM,PBKDF2,API key,密钥管理">
|
||||||
|
<meta name="robots" content="index, follow">
|
||||||
|
<link rel="canonical" href="{{ base_url }}/">
|
||||||
|
<link rel="icon" href="/favicon.svg?v={{ version }}" type="image/svg+xml">
|
||||||
|
<title>Secrets MCP — 端到端加密的密钥管理</title>
|
||||||
|
<meta property="og:type" content="website">
|
||||||
|
<meta property="og:url" content="{{ base_url }}/">
|
||||||
|
<meta property="og:title" content="Secrets MCP — 端到端加密的密钥管理">
|
||||||
|
<meta property="og:description" content="密码短语客户端派生,密文存储;MCP API 与 Web 控制台,多租户与审计。">
|
||||||
|
<meta name="twitter:card" content="summary">
|
||||||
|
<meta name="twitter:title" content="Secrets MCP — 端到端加密的密钥管理">
|
||||||
|
<meta name="twitter:description" content="密码短语客户端派生,密文存储;MCP API 与 Web 控制台,多租户与审计。">
|
||||||
|
<style>
|
||||||
|
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
|
||||||
|
@import url('https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@500;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;
|
||||||
|
}
|
||||||
|
html, body { height: 100%; overflow: hidden; }
|
||||||
|
@supports (height: 100dvh) {
|
||||||
|
html, body { height: 100dvh; }
|
||||||
|
}
|
||||||
|
body {
|
||||||
|
background: var(--bg);
|
||||||
|
color: var(--text);
|
||||||
|
font-family: 'Inter', sans-serif;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
}
|
||||||
|
.nav {
|
||||||
|
flex-shrink: 0;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
padding: 14px 24px;
|
||||||
|
border-bottom: 1px solid var(--border);
|
||||||
|
background: var(--surface);
|
||||||
|
}
|
||||||
|
.brand {
|
||||||
|
font-family: 'JetBrains Mono', monospace;
|
||||||
|
font-size: 15px;
|
||||||
|
font-weight: 600;
|
||||||
|
color: var(--text);
|
||||||
|
text-decoration: none;
|
||||||
|
}
|
||||||
|
.brand span { color: var(--accent); }
|
||||||
|
.nav-right { display: flex; align-items: center; gap: 14px; }
|
||||||
|
.lang-bar { display: flex; gap: 2px; background: rgba(255,255,255,0.04); border-radius: 6px; padding: 2px; }
|
||||||
|
.lang-btn {
|
||||||
|
padding: 4px 10px; border: none; background: none; color: var(--text-muted);
|
||||||
|
font-size: 12px; cursor: pointer; border-radius: 4px;
|
||||||
|
}
|
||||||
|
.lang-btn.active { background: var(--border); color: var(--text); }
|
||||||
|
.cta {
|
||||||
|
display: inline-flex; align-items: center; justify-content: center;
|
||||||
|
padding: 8px 18px; border-radius: 8px; font-size: 13px; font-weight: 600;
|
||||||
|
text-decoration: none; border: 1px solid var(--accent);
|
||||||
|
background: rgba(88, 166, 255, 0.12); color: var(--accent);
|
||||||
|
transition: background 0.15s, color 0.15s;
|
||||||
|
}
|
||||||
|
.cta:hover { background: var(--accent); color: var(--bg); }
|
||||||
|
.main {
|
||||||
|
flex: 1;
|
||||||
|
min-height: 0;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
padding: 16px 24px 12px;
|
||||||
|
gap: 20px;
|
||||||
|
}
|
||||||
|
.hero { text-align: center; max-width: 720px; }
|
||||||
|
.hero h1 { font-size: clamp(20px, 4vw, 28px); font-weight: 600; margin-bottom: 8px; line-height: 1.25; }
|
||||||
|
.hero .tagline { color: var(--text-muted); font-size: clamp(13px, 2vw, 15px); line-height: 1.5; }
|
||||||
|
.grid {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(3, 1fr);
|
||||||
|
gap: 12px;
|
||||||
|
width: 100%;
|
||||||
|
max-width: 900px;
|
||||||
|
}
|
||||||
|
@media (max-width: 900px) {
|
||||||
|
.grid { grid-template-columns: repeat(2, 1fr); }
|
||||||
|
}
|
||||||
|
@media (max-width: 480px) {
|
||||||
|
.grid { grid-template-columns: 1fr; gap: 8px; }
|
||||||
|
.main { justify-content: flex-start; padding-top: 12px; }
|
||||||
|
}
|
||||||
|
.card {
|
||||||
|
background: var(--surface);
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: 10px;
|
||||||
|
padding: 14px 14px 12px;
|
||||||
|
min-height: 0;
|
||||||
|
}
|
||||||
|
.card-icon {
|
||||||
|
width: 32px; height: 32px; border-radius: 8px;
|
||||||
|
background: var(--surface2);
|
||||||
|
display: flex; align-items: center; justify-content: center;
|
||||||
|
margin-bottom: 10px; color: var(--accent);
|
||||||
|
}
|
||||||
|
.card-icon svg { width: 18px; height: 18px; }
|
||||||
|
.card h2 { font-size: 13px; font-weight: 600; margin-bottom: 6px; line-height: 1.3; }
|
||||||
|
.card p { font-size: 12px; color: var(--text-muted); line-height: 1.45; }
|
||||||
|
.foot {
|
||||||
|
flex-shrink: 0;
|
||||||
|
text-align: center;
|
||||||
|
padding: 8px 16px 12px;
|
||||||
|
font-size: 11px;
|
||||||
|
color: var(--text-muted);
|
||||||
|
border-top: 1px solid var(--border);
|
||||||
|
background: var(--surface);
|
||||||
|
}
|
||||||
|
.foot a { color: var(--accent); text-decoration: none; }
|
||||||
|
.foot a:hover { text-decoration: underline; }
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<header class="nav">
|
||||||
|
<a class="brand" href="/">secrets<span>-mcp</span></a>
|
||||||
|
<div class="nav-right">
|
||||||
|
<div class="lang-bar">
|
||||||
|
<button type="button" class="lang-btn" onclick="setLang('zh-CN')">简</button>
|
||||||
|
<button type="button" class="lang-btn" onclick="setLang('zh-TW')">繁</button>
|
||||||
|
<button type="button" class="lang-btn" onclick="setLang('en')">EN</button>
|
||||||
|
</div>
|
||||||
|
{% if is_logged_in %}
|
||||||
|
<a class="cta" href="/dashboard" data-i18n="ctaDashboard">进入控制台</a>
|
||||||
|
{% else %}
|
||||||
|
<a class="cta" href="/login" data-i18n="ctaLogin">登录</a>
|
||||||
|
{% endif %}
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
<main class="main">
|
||||||
|
<div class="hero">
|
||||||
|
<h1 data-i18n="heroTitle">端到端加密的密钥与配置管理</h1>
|
||||||
|
<p class="tagline" data-i18n="heroTagline">Streamable HTTP MCP 与 Web 控制台:元数据与密文分库存储,密钥永不离开你的客户端逻辑。</p>
|
||||||
|
</div>
|
||||||
|
<div class="grid">
|
||||||
|
<article class="card">
|
||||||
|
<div class="card-icon" aria-hidden="true">
|
||||||
|
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 11c1.66 0 3-1.34 3-3V5c0-1.66-1.34-3-3-3S9 3.34 9 5v3c0 1.66 1.34 3 3 3z"/><path d="M19 10v1a7 7 0 01-14 0v-1"/><path d="M12 14v7M9 18h6"/></svg>
|
||||||
|
</div>
|
||||||
|
<h2 data-i18n="c1t">客户端密钥派生</h2>
|
||||||
|
<p data-i18n="c1d">PBKDF2-SHA256(约 60 万次)在浏览器本地从密码短语派生密钥;服务端仅保存盐与校验值,不持有密码或明文主密钥。</p>
|
||||||
|
</article>
|
||||||
|
<article class="card">
|
||||||
|
<div class="card-icon" aria-hidden="true">
|
||||||
|
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="11" width="18" height="11" rx="2"/><path d="M7 11V7a5 5 0 0110 0v4"/></svg>
|
||||||
|
</div>
|
||||||
|
<h2 data-i18n="c2t">AES-256-GCM 加密</h2>
|
||||||
|
<p data-i18n="c2d">敏感字段以 AES-GCM 密文落库;Web 端在本地加解密,明文默认不经过服务端持久化。</p>
|
||||||
|
</article>
|
||||||
|
<article class="card">
|
||||||
|
<div class="card-icon" aria-hidden="true">
|
||||||
|
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M14 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V8z"/><path d="M14 2v6h6M16 13H8M16 17H8M10 9H8"/></svg>
|
||||||
|
</div>
|
||||||
|
<h2 data-i18n="c3t">审计与历史</h2>
|
||||||
|
<p data-i18n="c3d">操作写入审计日志;条目与密文保留历史版本,支持按版本查看与恢复。</p>
|
||||||
|
</article>
|
||||||
|
</div>
|
||||||
|
</main>
|
||||||
|
<footer class="foot">
|
||||||
|
<span data-i18n="versionLabel">版本</span> {{ version }} ·
|
||||||
|
<a href="/llms.txt">llms.txt</a>
|
||||||
|
<span data-i18n="sep"> · </span>
|
||||||
|
<a href="https://gitea.refining.dev/refining/secrets" target="_blank" rel="noopener noreferrer" data-i18n="footRepo">源码仓库</a>
|
||||||
|
{% if !is_logged_in %}
|
||||||
|
<span data-i18n="sep"> · </span>
|
||||||
|
<a href="/login" data-i18n="footLogin">登录</a>
|
||||||
|
{% endif %}
|
||||||
|
</footer>
|
||||||
|
<script>
|
||||||
|
const T = {
|
||||||
|
'zh-CN': {
|
||||||
|
docTitle: 'Secrets MCP — 端到端加密的密钥管理',
|
||||||
|
ctaDashboard: '进入控制台',
|
||||||
|
ctaLogin: '登录',
|
||||||
|
heroTitle: '端到端加密的密钥与配置管理',
|
||||||
|
heroTagline: 'Streamable HTTP MCP 与 Web 控制台:元数据与密文分库存储,密钥永不离开你的客户端逻辑。',
|
||||||
|
c1t: '客户端密钥派生',
|
||||||
|
c1d: 'PBKDF2-SHA256(约 60 万次)在浏览器本地从密码短语派生密钥;服务端仅保存盐与校验值,不持有密码或明文主密钥。',
|
||||||
|
c2t: 'AES-256-GCM 加密',
|
||||||
|
c2d: '敏感字段以 AES-GCM 密文落库;Web 端在本地加解密,明文默认不经过服务端持久化。',
|
||||||
|
c3t: '审计与历史',
|
||||||
|
c3d: '操作写入审计日志;条目与密文保留历史版本,支持按版本查看与恢复。',
|
||||||
|
versionLabel: '版本',
|
||||||
|
sep: ' · ',
|
||||||
|
footRepo: '源码仓库',
|
||||||
|
footLogin: '登录',
|
||||||
|
},
|
||||||
|
'zh-TW': {
|
||||||
|
docTitle: 'Secrets MCP — 端到端加密的金鑰管理',
|
||||||
|
ctaDashboard: '進入控制台',
|
||||||
|
ctaLogin: '登入',
|
||||||
|
heroTitle: '端到端加密的金鑰與設定管理',
|
||||||
|
heroTagline: 'Streamable HTTP MCP 與 Web 控制台:中繼資料與密文分庫儲存,金鑰不離開你的用戶端邏輯。',
|
||||||
|
c1t: '用戶端金鑰派生',
|
||||||
|
c1d: 'PBKDF2-SHA256(約 60 萬次)在瀏覽器本地從密碼片語派生金鑰;伺服端僅保存鹽與校驗值,不持有密碼或明文主金鑰。',
|
||||||
|
c2t: 'AES-256-GCM 加密',
|
||||||
|
c2d: '敏感欄位以 AES-GCM 密文落庫;Web 端在本地加解密,明文預設不經伺服端持久化。',
|
||||||
|
c3t: '稽核與歷史',
|
||||||
|
c3d: '操作寫入稽核日誌;條目與密文保留歷史版本,支援依版本檢視與還原。',
|
||||||
|
versionLabel: '版本',
|
||||||
|
sep: ' · ',
|
||||||
|
footRepo: '原始碼倉庫',
|
||||||
|
footLogin: '登入',
|
||||||
|
},
|
||||||
|
'en': {
|
||||||
|
docTitle: 'Secrets MCP — End-to-end encrypted secrets',
|
||||||
|
ctaDashboard: 'Open dashboard',
|
||||||
|
ctaLogin: 'Sign in',
|
||||||
|
heroTitle: 'End-to-end encrypted secrets and configuration',
|
||||||
|
heroTagline: 'Streamable HTTP MCP plus web console: metadata and ciphertext stored separately; keys stay on your client.',
|
||||||
|
c1t: 'Client-side key derivation',
|
||||||
|
c1d: 'PBKDF2-SHA256 (~600k iterations) derives keys from your passphrase in the browser; the server stores only salt and a verification blob, never your password or raw master key.',
|
||||||
|
c2t: 'AES-256-GCM',
|
||||||
|
c2d: 'Secret fields are stored as AES-GCM ciphertext; the web UI encrypts and decrypts locally so plaintext is not persisted server-side by default.',
|
||||||
|
c3t: 'Audit and history',
|
||||||
|
c3d: 'Operations are audited; entries and secrets keep version history for review and rollback.',
|
||||||
|
versionLabel: 'Version',
|
||||||
|
sep: ' · ',
|
||||||
|
footRepo: 'Source repository',
|
||||||
|
footLogin: 'Sign in',
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let currentLang = localStorage.getItem('lang') || 'zh-CN';
|
||||||
|
|
||||||
|
function t(key) {
|
||||||
|
return (T[currentLang] && T[currentLang][key]) || T['en'][key] || key;
|
||||||
|
}
|
||||||
|
|
||||||
|
function applyLang() {
|
||||||
|
document.documentElement.lang = currentLang;
|
||||||
|
document.title = t('docTitle');
|
||||||
|
document.querySelectorAll('[data-i18n]').forEach(el => {
|
||||||
|
const key = el.getAttribute('data-i18n');
|
||||||
|
el.textContent = t(key);
|
||||||
|
});
|
||||||
|
document.querySelectorAll('.lang-btn').forEach(btn => {
|
||||||
|
const map = { 'zh-CN': '简', 'zh-TW': '繁', 'en': 'EN' };
|
||||||
|
btn.classList.toggle('active', btn.textContent === map[currentLang]);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function setLang(lang) {
|
||||||
|
currentLang = lang;
|
||||||
|
localStorage.setItem('lang', lang);
|
||||||
|
applyLang();
|
||||||
|
}
|
||||||
|
|
||||||
|
applyLang();
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -3,8 +3,19 @@
|
|||||||
<head>
|
<head>
|
||||||
<meta charset="UTF-8">
|
<meta charset="UTF-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<meta name="robots" content="noindex, follow">
|
||||||
|
<meta name="description" content="登录 Secrets MCP Web 控制台,安全管理跨设备加密 secrets。">
|
||||||
|
<meta name="keywords" content="Secrets MCP,登录,OAuth,密钥管理">
|
||||||
|
<link rel="canonical" href="{{ base_url }}/login">
|
||||||
<link rel="icon" href="/favicon.svg?v={{ version }}" type="image/svg+xml">
|
<link rel="icon" href="/favicon.svg?v={{ version }}" type="image/svg+xml">
|
||||||
<title>Secrets — Sign In</title>
|
<title>登录 — Secrets MCP</title>
|
||||||
|
<meta property="og:type" content="website">
|
||||||
|
<meta property="og:url" content="{{ base_url }}/login">
|
||||||
|
<meta property="og:title" content="登录 — Secrets MCP">
|
||||||
|
<meta property="og:description" content="登录 Web 控制台,管理加密存储的密钥与配置。">
|
||||||
|
<meta name="twitter:card" content="summary">
|
||||||
|
<meta name="twitter:title" content="登录 — Secrets MCP">
|
||||||
|
<meta name="twitter:description" content="登录 Web 控制台,管理加密存储的密钥与配置。">
|
||||||
<style>
|
<style>
|
||||||
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
|
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
|
||||||
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&display=swap');
|
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&display=swap');
|
||||||
@@ -17,6 +28,7 @@
|
|||||||
--accent: #58a6ff;
|
--accent: #58a6ff;
|
||||||
--accent-hover: #79b8ff;
|
--accent-hover: #79b8ff;
|
||||||
--google: #4285f4;
|
--google: #4285f4;
|
||||||
|
--danger: #f85149;
|
||||||
}
|
}
|
||||||
body { background: var(--bg); color: var(--text); font-family: 'Inter', sans-serif;
|
body { background: var(--bg); color: var(--text); font-family: 'Inter', sans-serif;
|
||||||
min-height: 100vh; display: flex; align-items: center; justify-content: center; }
|
min-height: 100vh; display: flex; align-items: center; justify-content: center; }
|
||||||
@@ -25,11 +37,24 @@
|
|||||||
padding: 48px 40px; width: 100%; max-width: 400px;
|
padding: 48px 40px; width: 100%; max-width: 400px;
|
||||||
box-shadow: 0 8px 32px rgba(0,0,0,0.4);
|
box-shadow: 0 8px 32px rgba(0,0,0,0.4);
|
||||||
}
|
}
|
||||||
.topbar { display: flex; justify-content: flex-end; margin-bottom: 20px; }
|
.topbar { display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 20px; gap: 12px; }
|
||||||
.lang-bar { display: flex; gap: 2px; background: rgba(255,255,255,0.04); border-radius: 6px; padding: 2px; }
|
.back-home {
|
||||||
|
font-size: 13px; color: var(--accent); text-decoration: none; white-space: nowrap;
|
||||||
|
}
|
||||||
|
.back-home:hover { text-decoration: underline; }
|
||||||
|
.lang-bar { display: flex; gap: 2px; background: rgba(255,255,255,0.04); border-radius: 6px; padding: 2px; flex-shrink: 0; }
|
||||||
.lang-btn { padding: 3px 9px; border: none; background: none; color: var(--text-muted);
|
.lang-btn { padding: 3px 9px; border: none; background: none; color: var(--text-muted);
|
||||||
font-size: 12px; cursor: pointer; border-radius: 4px; }
|
font-size: 12px; cursor: pointer; border-radius: 4px; }
|
||||||
.lang-btn.active { background: var(--border); color: var(--text); }
|
.lang-btn.active { background: var(--border); color: var(--text); }
|
||||||
|
.oauth-alert {
|
||||||
|
display: none;
|
||||||
|
margin-bottom: 16px; padding: 10px 12px; border-radius: 8px;
|
||||||
|
font-size: 13px; line-height: 1.4;
|
||||||
|
background: rgba(248, 81, 73, 0.12);
|
||||||
|
border: 1px solid rgba(248, 81, 73, 0.35);
|
||||||
|
color: #ffa198;
|
||||||
|
}
|
||||||
|
.oauth-alert.visible { display: block; }
|
||||||
h1 { font-size: 22px; font-weight: 600; margin-bottom: 8px; }
|
h1 { font-size: 22px; font-weight: 600; margin-bottom: 8px; }
|
||||||
.subtitle { color: var(--text-muted); font-size: 14px; margin-bottom: 32px; }
|
.subtitle { color: var(--text-muted); font-size: 14px; margin-bottom: 32px; }
|
||||||
.btn {
|
.btn {
|
||||||
@@ -48,12 +73,14 @@
|
|||||||
<body>
|
<body>
|
||||||
<div class="card">
|
<div class="card">
|
||||||
<div class="topbar">
|
<div class="topbar">
|
||||||
|
<a class="back-home" href="/" data-i18n="backHome">返回首页</a>
|
||||||
<div class="lang-bar">
|
<div class="lang-bar">
|
||||||
<button class="lang-btn" onclick="setLang('zh-CN')">简</button>
|
<button type="button" class="lang-btn" onclick="setLang('zh-CN')">简</button>
|
||||||
<button class="lang-btn" onclick="setLang('zh-TW')">繁</button>
|
<button type="button" class="lang-btn" onclick="setLang('zh-TW')">繁</button>
|
||||||
<button class="lang-btn" onclick="setLang('en')">EN</button>
|
<button type="button" class="lang-btn" onclick="setLang('en')">EN</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
<div id="oauth-alert" class="oauth-alert" role="alert"></div>
|
||||||
<h1 data-i18n="title">登录</h1>
|
<h1 data-i18n="title">登录</h1>
|
||||||
<p class="subtitle" data-i18n="subtitle">安全管理你的跨设备 secrets。</p>
|
<p class="subtitle" data-i18n="subtitle">安全管理你的跨设备 secrets。</p>
|
||||||
|
|
||||||
@@ -78,22 +105,40 @@
|
|||||||
<script>
|
<script>
|
||||||
const T = {
|
const T = {
|
||||||
'zh-CN': {
|
'zh-CN': {
|
||||||
|
docTitle: '登录 — Secrets MCP',
|
||||||
|
backHome: '返回首页',
|
||||||
title: '登录',
|
title: '登录',
|
||||||
subtitle: '安全管理你的跨设备 secrets。',
|
subtitle: '安全管理你的跨设备 secrets。',
|
||||||
google: '使用 Google 登录',
|
google: '使用 Google 登录',
|
||||||
noProviders: '未配置登录方式,请联系管理员。',
|
noProviders: '未配置登录方式,请联系管理员。',
|
||||||
|
err_oauth_error: '登录失败:授权提供方返回错误,请重试。',
|
||||||
|
err_oauth_missing_code: '登录失败:未收到授权码,请重试。',
|
||||||
|
err_oauth_missing_state: '登录失败:缺少安全校验参数,请重试。',
|
||||||
|
err_oauth_state: '登录失败:会话校验不匹配(可能因 Cookie 策略或服务器重启)。请返回首页再试。',
|
||||||
},
|
},
|
||||||
'zh-TW': {
|
'zh-TW': {
|
||||||
|
docTitle: '登入 — Secrets MCP',
|
||||||
|
backHome: '返回首頁',
|
||||||
title: '登入',
|
title: '登入',
|
||||||
subtitle: '安全管理你的跨裝置 secrets。',
|
subtitle: '安全管理你的跨裝置 secrets。',
|
||||||
google: '使用 Google 登入',
|
google: '使用 Google 登入',
|
||||||
noProviders: '尚未設定登入方式,請聯絡管理員。',
|
noProviders: '尚未設定登入方式,請聯絡管理員。',
|
||||||
|
err_oauth_error: '登入失敗:授權方回傳錯誤,請再試一次。',
|
||||||
|
err_oauth_missing_code: '登入失敗:未取得授權碼,請再試一次。',
|
||||||
|
err_oauth_missing_state: '登入失敗:缺少安全校驗參數,請再試一次。',
|
||||||
|
err_oauth_state: '登入失敗:工作階段校驗不符(可能與 Cookie 政策或伺服器重啟有關)。請回到首頁再試。',
|
||||||
},
|
},
|
||||||
'en': {
|
'en': {
|
||||||
|
docTitle: 'Sign in — Secrets MCP',
|
||||||
|
backHome: 'Back to home',
|
||||||
title: 'Sign in',
|
title: 'Sign in',
|
||||||
subtitle: 'Manage your cross-device secrets securely.',
|
subtitle: 'Manage your cross-device secrets securely.',
|
||||||
google: 'Continue with Google',
|
google: 'Continue with Google',
|
||||||
noProviders: 'No login providers configured. Please contact your administrator.',
|
noProviders: 'No login providers configured. Please contact your administrator.',
|
||||||
|
err_oauth_error: 'Sign-in failed: the identity provider returned an error. Please try again.',
|
||||||
|
err_oauth_missing_code: 'Sign-in failed: no authorization code was returned. Please try again.',
|
||||||
|
err_oauth_missing_state: 'Sign-in failed: missing security state. Please try again.',
|
||||||
|
err_oauth_state: 'Sign-in failed: session state mismatch (often cookies or server restart). Open the home page and try again.',
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -101,8 +146,23 @@
|
|||||||
|
|
||||||
function t(key) { return T[currentLang][key] || T['en'][key] || key; }
|
function t(key) { return T[currentLang][key] || T['en'][key] || key; }
|
||||||
|
|
||||||
|
function showOAuthError() {
|
||||||
|
const params = new URLSearchParams(window.location.search);
|
||||||
|
const code = params.get('error');
|
||||||
|
const el = document.getElementById('oauth-alert');
|
||||||
|
if (!code || !code.startsWith('oauth_')) {
|
||||||
|
el.classList.remove('visible');
|
||||||
|
el.textContent = '';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const key = 'err_' + code;
|
||||||
|
el.textContent = t(key) || t('err_oauth_error');
|
||||||
|
el.classList.add('visible');
|
||||||
|
}
|
||||||
|
|
||||||
function applyLang() {
|
function applyLang() {
|
||||||
document.documentElement.lang = currentLang;
|
document.documentElement.lang = currentLang;
|
||||||
|
document.title = t('docTitle');
|
||||||
document.querySelectorAll('[data-i18n]').forEach(el => {
|
document.querySelectorAll('[data-i18n]').forEach(el => {
|
||||||
const key = el.getAttribute('data-i18n');
|
const key = el.getAttribute('data-i18n');
|
||||||
el.textContent = t(key);
|
el.textContent = t(key);
|
||||||
@@ -111,6 +171,7 @@
|
|||||||
const map = { 'zh-CN': '简', 'zh-TW': '繁', 'en': 'EN' };
|
const map = { 'zh-CN': '简', 'zh-TW': '繁', 'en': 'EN' };
|
||||||
btn.classList.toggle('active', btn.textContent === map[currentLang]);
|
btn.classList.toggle('active', btn.textContent === map[currentLang]);
|
||||||
});
|
});
|
||||||
|
showOAuthError();
|
||||||
}
|
}
|
||||||
|
|
||||||
function setLang(lang) {
|
function setLang(lang) {
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
# 复制此文件为 .env 并填写真实值
|
# 复制此文件为 .env 并填写真实值
|
||||||
|
|
||||||
# ─── 数据库 ───────────────────────────────────────────────────────────
|
# ─── 数据库 ───────────────────────────────────────────────────────────
|
||||||
|
# Web 会话(tower-sessions)与业务数据共用此库;启动时会自动 migrate 会话表,无需额外环境变量。
|
||||||
SECRETS_DATABASE_URL=postgres://postgres:PASSWORD@HOST:PORT/secrets-mcp
|
SECRETS_DATABASE_URL=postgres://postgres:PASSWORD@HOST:PORT/secrets-mcp
|
||||||
|
|
||||||
# ─── 服务地址 ─────────────────────────────────────────────────────────
|
# ─── 服务地址 ─────────────────────────────────────────────────────────
|
||||||
@@ -21,6 +22,9 @@ GOOGLE_CLIENT_SECRET=
|
|||||||
# WECHAT_APP_CLIENT_ID=
|
# WECHAT_APP_CLIENT_ID=
|
||||||
# WECHAT_APP_CLIENT_SECRET=
|
# WECHAT_APP_CLIENT_SECRET=
|
||||||
|
|
||||||
|
# ─── 日志(可选)──────────────────────────────────────────────────────
|
||||||
|
# RUST_LOG=secrets_mcp=debug
|
||||||
|
|
||||||
# ─── 注意 ─────────────────────────────────────────────────────────────
|
# ─── 注意 ─────────────────────────────────────────────────────────────
|
||||||
# SERVER_MASTER_KEY 已不再需要。
|
# SERVER_MASTER_KEY 已不再需要。
|
||||||
# 新架构(E2EE)中,加密密钥由用户密码短语在客户端本地派生,服务端不持有原始密钥。
|
# 新架构(E2EE)中,加密密钥由用户密码短语在客户端本地派生,服务端不持有原始密钥。
|
||||||
|
|||||||
22
scripts/cleanup-orphan-user-ids.sql
Normal file
22
scripts/cleanup-orphan-user-ids.sql
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
-- Run against prod BEFORE deploying secrets-mcp with FK migration.
|
||||||
|
-- Requires: write access to SECRETS_DATABASE_URL.
|
||||||
|
-- Example: psql "$SECRETS_DATABASE_URL" -v ON_ERROR_STOP=1 -f scripts/cleanup-orphan-user-ids.sql
|
||||||
|
|
||||||
|
BEGIN;
|
||||||
|
|
||||||
|
UPDATE entries
|
||||||
|
SET user_id = NULL
|
||||||
|
WHERE user_id IS NOT NULL
|
||||||
|
AND NOT EXISTS (SELECT 1 FROM users u WHERE u.id = entries.user_id);
|
||||||
|
|
||||||
|
UPDATE entries_history
|
||||||
|
SET user_id = NULL
|
||||||
|
WHERE user_id IS NOT NULL
|
||||||
|
AND NOT EXISTS (SELECT 1 FROM users u WHERE u.id = entries_history.user_id);
|
||||||
|
|
||||||
|
UPDATE audit_log
|
||||||
|
SET user_id = NULL
|
||||||
|
WHERE user_id IS NOT NULL
|
||||||
|
AND NOT EXISTS (SELECT 1 FROM users u WHERE u.id = audit_log.user_id);
|
||||||
|
|
||||||
|
COMMIT;
|
||||||
194
scripts/migrate-v0.3.0.sql
Normal file
194
scripts/migrate-v0.3.0.sql
Normal file
@@ -0,0 +1,194 @@
|
|||||||
|
-- ============================================================================
|
||||||
|
-- migrate-v0.3.0.sql
|
||||||
|
-- Schema migration from v0.2.x → v0.3.0
|
||||||
|
--
|
||||||
|
-- Changes:
|
||||||
|
-- • entries: namespace → folder, kind → type; add notes column
|
||||||
|
-- • audit_log: namespace → folder, kind → type
|
||||||
|
-- • entries_history: namespace → folder, kind → type; add user_id column
|
||||||
|
-- • Unique index: (user_id, name) → (user_id, folder, name)
|
||||||
|
-- Same name in different folders is now allowed; no rename needed.
|
||||||
|
--
|
||||||
|
-- Safe to run multiple times (fully idempotent).
|
||||||
|
-- Preserves all data in users, entries, secrets.
|
||||||
|
-- ============================================================================
|
||||||
|
|
||||||
|
BEGIN;
|
||||||
|
|
||||||
|
-- ── entries: rename namespace→folder, kind→type ──────────────────────────────
|
||||||
|
DO $$ BEGIN
|
||||||
|
IF EXISTS (
|
||||||
|
SELECT 1 FROM information_schema.columns
|
||||||
|
WHERE table_name = 'entries' AND column_name = 'namespace'
|
||||||
|
) THEN
|
||||||
|
ALTER TABLE entries RENAME COLUMN namespace TO folder;
|
||||||
|
END IF;
|
||||||
|
END $$;
|
||||||
|
|
||||||
|
DO $$ BEGIN
|
||||||
|
IF EXISTS (
|
||||||
|
SELECT 1 FROM information_schema.columns
|
||||||
|
WHERE table_name = 'entries' AND column_name = 'kind'
|
||||||
|
) THEN
|
||||||
|
ALTER TABLE entries RENAME COLUMN kind TO type;
|
||||||
|
END IF;
|
||||||
|
END $$;
|
||||||
|
|
||||||
|
-- Set NOT NULL + default for folder/type in entries
|
||||||
|
DO $$ BEGIN
|
||||||
|
IF EXISTS (
|
||||||
|
SELECT 1 FROM information_schema.columns
|
||||||
|
WHERE table_name = 'entries' AND column_name = 'folder'
|
||||||
|
) THEN
|
||||||
|
UPDATE entries SET folder = '' WHERE folder IS NULL;
|
||||||
|
ALTER TABLE entries ALTER COLUMN folder SET NOT NULL;
|
||||||
|
ALTER TABLE entries ALTER COLUMN folder SET DEFAULT '';
|
||||||
|
END IF;
|
||||||
|
END $$;
|
||||||
|
|
||||||
|
DO $$ BEGIN
|
||||||
|
IF EXISTS (
|
||||||
|
SELECT 1 FROM information_schema.columns
|
||||||
|
WHERE table_name = 'entries' AND column_name = 'type'
|
||||||
|
) THEN
|
||||||
|
UPDATE entries SET type = '' WHERE type IS NULL;
|
||||||
|
ALTER TABLE entries ALTER COLUMN type SET NOT NULL;
|
||||||
|
ALTER TABLE entries ALTER COLUMN type SET DEFAULT '';
|
||||||
|
END IF;
|
||||||
|
END $$;
|
||||||
|
|
||||||
|
-- Add notes column to entries if missing
|
||||||
|
ALTER TABLE entries ADD COLUMN IF NOT EXISTS notes TEXT NOT NULL DEFAULT '';
|
||||||
|
|
||||||
|
-- ── audit_log: rename namespace→folder, kind→type ────────────────────────────
|
||||||
|
DO $$ BEGIN
|
||||||
|
IF EXISTS (
|
||||||
|
SELECT 1 FROM information_schema.columns
|
||||||
|
WHERE table_name = 'audit_log' AND column_name = 'namespace'
|
||||||
|
) THEN
|
||||||
|
ALTER TABLE audit_log RENAME COLUMN namespace TO folder;
|
||||||
|
END IF;
|
||||||
|
END $$;
|
||||||
|
|
||||||
|
DO $$ BEGIN
|
||||||
|
IF EXISTS (
|
||||||
|
SELECT 1 FROM information_schema.columns
|
||||||
|
WHERE table_name = 'audit_log' AND column_name = 'kind'
|
||||||
|
) THEN
|
||||||
|
ALTER TABLE audit_log RENAME COLUMN kind TO type;
|
||||||
|
END IF;
|
||||||
|
END $$;
|
||||||
|
|
||||||
|
DO $$ BEGIN
|
||||||
|
IF EXISTS (
|
||||||
|
SELECT 1 FROM information_schema.columns
|
||||||
|
WHERE table_name = 'audit_log' AND column_name = 'folder'
|
||||||
|
) THEN
|
||||||
|
UPDATE audit_log SET folder = '' WHERE folder IS NULL;
|
||||||
|
ALTER TABLE audit_log ALTER COLUMN folder SET NOT NULL;
|
||||||
|
ALTER TABLE audit_log ALTER COLUMN folder SET DEFAULT '';
|
||||||
|
END IF;
|
||||||
|
END $$;
|
||||||
|
|
||||||
|
DO $$ BEGIN
|
||||||
|
IF EXISTS (
|
||||||
|
SELECT 1 FROM information_schema.columns
|
||||||
|
WHERE table_name = 'audit_log' AND column_name = 'type'
|
||||||
|
) THEN
|
||||||
|
UPDATE audit_log SET type = '' WHERE type IS NULL;
|
||||||
|
ALTER TABLE audit_log ALTER COLUMN type SET NOT NULL;
|
||||||
|
ALTER TABLE audit_log ALTER COLUMN type SET DEFAULT '';
|
||||||
|
END IF;
|
||||||
|
END $$;
|
||||||
|
|
||||||
|
ALTER TABLE audit_log DROP COLUMN IF EXISTS actor;
|
||||||
|
|
||||||
|
-- ── entries_history: rename namespace→folder, kind→type; add user_id ─────────
|
||||||
|
DO $$ BEGIN
|
||||||
|
IF EXISTS (
|
||||||
|
SELECT 1 FROM information_schema.columns
|
||||||
|
WHERE table_name = 'entries_history' AND column_name = 'namespace'
|
||||||
|
) THEN
|
||||||
|
ALTER TABLE entries_history RENAME COLUMN namespace TO folder;
|
||||||
|
END IF;
|
||||||
|
END $$;
|
||||||
|
|
||||||
|
DO $$ BEGIN
|
||||||
|
IF EXISTS (
|
||||||
|
SELECT 1 FROM information_schema.columns
|
||||||
|
WHERE table_name = 'entries_history' AND column_name = 'kind'
|
||||||
|
) THEN
|
||||||
|
ALTER TABLE entries_history RENAME COLUMN kind TO type;
|
||||||
|
END IF;
|
||||||
|
END $$;
|
||||||
|
|
||||||
|
DO $$ BEGIN
|
||||||
|
IF EXISTS (
|
||||||
|
SELECT 1 FROM information_schema.columns
|
||||||
|
WHERE table_name = 'entries_history' AND column_name = 'folder'
|
||||||
|
) THEN
|
||||||
|
UPDATE entries_history SET folder = '' WHERE folder IS NULL;
|
||||||
|
ALTER TABLE entries_history ALTER COLUMN folder SET NOT NULL;
|
||||||
|
ALTER TABLE entries_history ALTER COLUMN folder SET DEFAULT '';
|
||||||
|
END IF;
|
||||||
|
END $$;
|
||||||
|
|
||||||
|
DO $$ BEGIN
|
||||||
|
IF EXISTS (
|
||||||
|
SELECT 1 FROM information_schema.columns
|
||||||
|
WHERE table_name = 'entries_history' AND column_name = 'type'
|
||||||
|
) THEN
|
||||||
|
UPDATE entries_history SET type = '' WHERE type IS NULL;
|
||||||
|
ALTER TABLE entries_history ALTER COLUMN type SET NOT NULL;
|
||||||
|
ALTER TABLE entries_history ALTER COLUMN type SET DEFAULT '';
|
||||||
|
END IF;
|
||||||
|
END $$;
|
||||||
|
|
||||||
|
ALTER TABLE entries_history ADD COLUMN IF NOT EXISTS user_id UUID;
|
||||||
|
ALTER TABLE entries_history DROP COLUMN IF EXISTS actor;
|
||||||
|
|
||||||
|
-- ── secrets_history: drop actor column ───────────────────────────────────────
|
||||||
|
ALTER TABLE secrets_history DROP COLUMN IF EXISTS actor;
|
||||||
|
|
||||||
|
-- ── Rebuild unique indexes: (user_id, folder, name) ──────────────────────────
|
||||||
|
-- Note: folder is now part of the key, so same name in different folders is
|
||||||
|
-- naturally distinct — no rename of existing rows needed.
|
||||||
|
DROP INDEX IF EXISTS idx_entries_unique_legacy;
|
||||||
|
DROP INDEX IF EXISTS idx_entries_unique_user;
|
||||||
|
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS idx_entries_unique_legacy
|
||||||
|
ON entries(folder, name)
|
||||||
|
WHERE user_id IS NULL;
|
||||||
|
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS idx_entries_unique_user
|
||||||
|
ON entries(user_id, folder, name)
|
||||||
|
WHERE user_id IS NOT NULL;
|
||||||
|
|
||||||
|
-- ── Replace old namespace/kind indexes with folder/type ──────────────────────
|
||||||
|
DROP INDEX IF EXISTS idx_entries_namespace;
|
||||||
|
DROP INDEX IF EXISTS idx_entries_kind;
|
||||||
|
DROP INDEX IF EXISTS idx_audit_log_ns_kind;
|
||||||
|
DROP INDEX IF EXISTS idx_entries_history_ns_kind_name;
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_entries_folder
|
||||||
|
ON entries(folder) WHERE folder <> '';
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_entries_type
|
||||||
|
ON entries(type) WHERE type <> '';
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_entries_user_id
|
||||||
|
ON entries(user_id) WHERE user_id IS NOT NULL;
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_audit_log_folder_type
|
||||||
|
ON audit_log(folder, type);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_entries_history_folder_type_name
|
||||||
|
ON entries_history(folder, type, name, version DESC);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_entries_history_user_id
|
||||||
|
ON entries_history(user_id) WHERE user_id IS NOT NULL;
|
||||||
|
|
||||||
|
COMMIT;
|
||||||
|
|
||||||
|
-- ── Verification queries (run these manually to confirm) ─────────────────────
|
||||||
|
-- SELECT column_name, data_type FROM information_schema.columns
|
||||||
|
-- WHERE table_name = 'entries' ORDER BY ordinal_position;
|
||||||
|
-- SELECT indexname, indexdef FROM pg_indexes WHERE tablename = 'entries';
|
||||||
|
-- SELECT COUNT(*) FROM entries;
|
||||||
|
-- SELECT COUNT(*) FROM users;
|
||||||
|
-- SELECT COUNT(*) FROM secrets;
|
||||||
Reference in New Issue
Block a user