Skip to content

Commit 7fc6bf8

Browse files
committed
feat: Quickwit-only audit logs, cloud-native S3 storage, multi-arch Docker images
Audit log storage: - Remove audit_logs PostgreSQL table (migration 007/011) - Audit logs stored exclusively in Quickwit (no PG fallback) - Handler queries Quickwit Search API directly - Remove FromRow derive from AuditLog model - Add 90-day retention policy to Quickwit index Cloud-native S3 storage: - Parameterize Quickwit S3 config in docker-compose.yml (QW_STORAGE_URI, QW_S3_ACCESS_KEY_ID, QW_S3_ENDPOINT, etc.) - Support AWS S3, GCS, Azure Blob, MinIO, RustFS backends - Add storage config to Helm values.yaml - Document S3 configuration in deployment guides (en + zh-CN) Multi-arch Docker images: - Dockerfile.server: conditional amd64/arm64 musl cross-compilation - CI: add QEMU + platforms: linux/amd64,linux/arm64 for both images Documentation updates: - Fix QUICKWIT_INDEX default: agentbastion-audit -> audit_logs - Mark SYSLOG_ADDR as deprecated (use DB-driven log forwarders) - Update architecture data flow (audit -> Quickwit only) - Add cloud-native S3 storage section to deployment guides - Update README tech stack to highlight S3-backed Quickwit - Remove stale SYSLOG_ADDR from docker-compose.yml Previous improvements (included in this commit): - SSRF DNS rebinding protection, setup race condition fix - Progressive login lockout, pagination, PII salting - Dynamic pricing, RBAC require_permission middleware - Frontend: ConfirmDialog, i18n fixes, error handling - Docker resource limits, Tokio features slim down
1 parent 390d95e commit 7fc6bf8

40 files changed

Lines changed: 1056 additions & 335 deletions

‎.github/workflows/ci.yml‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -109,6 +109,9 @@ jobs:
109109
- name: Set image prefix
110110
run: echo "IMAGE_PREFIX=ghcr.io/$(echo '${{ github.repository_owner }}' | tr '[:upper:]' '[:lower:]')" >> $GITHUB_ENV
111111

112+
- name: Set up QEMU
113+
uses: docker/setup-qemu-action@v3
114+
112115
- name: Set up Docker Buildx
113116
uses: docker/setup-buildx-action@v3
114117

@@ -118,6 +121,7 @@ jobs:
118121
context: .
119122
file: deploy/docker/Dockerfile.server
120123
push: true
124+
platforms: linux/amd64,linux/arm64
121125
tags: |
122126
${{ env.IMAGE_PREFIX }}/agent-bastion-server:latest
123127
${{ env.IMAGE_PREFIX }}/agent-bastion-server:${{ github.sha }}
@@ -130,6 +134,7 @@ jobs:
130134
context: .
131135
file: deploy/docker/Dockerfile.web
132136
push: true
137+
platforms: linux/amd64,linux/arm64
133138
tags: |
134139
${{ env.IMAGE_PREFIX }}/agent-bastion-web:latest
135140
${{ env.IMAGE_PREFIX }}/agent-bastion-web:${{ github.sha }}

‎Cargo.lock‎

Lines changed: 0 additions & 22 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎Cargo.toml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ tower-http = { version = "0.6", features = [
2222
"cors", "trace", "compression-gzip", "request-id",
2323
"limit", "timeout", "catch-panic", "sensitive-headers", "set-header",
2424
] }
25-
tokio = { version = "1", features = ["full"] }
25+
tokio = { version = "1", features = ["rt-multi-thread", "macros", "net", "time", "sync", "io-util"] }
2626

2727
# Database
2828
sqlx = { version = "0.8", features = ["runtime-tokio", "postgres", "uuid", "chrono", "json", "migrate", "rust_decimal"] }

‎README.md‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -85,7 +85,7 @@ AgentBastion solves all of this with a single deployment.
8585
### Observability
8686
- **Prometheus metrics** — `GET /metrics` endpoint on the gateway port (3000) exposing `gateway_requests_total`, `gateway_request_duration_seconds`, `gateway_tokens_total`, `gateway_rate_limited_total`, `circuit_breaker_state`, and more
8787
- **Enhanced health checks** — `/health/live` (liveness probe), `/health/ready` (readiness probe with PostgreSQL and Redis checks), `/api/health` (detailed latency and pool statistics)
88-
- **Quickwit-powered audit logs** — full-text search across all API calls and tool invocations
88+
- **Quickwit-powered audit logs** — full-text search across all API calls and tool invocations, stored exclusively in Quickwit with S3-backed cloud-native storage (AWS S3, GCS, Azure Blob, or self-hosted RustFS/MinIO)
8989
- **Audit log forwarding** — multi-channel delivery: UDP/TCP Syslog (RFC 5424), Kafka, and HTTP webhooks — route audit events to any SIEM, data lake, or alerting pipeline
9090
- **Usage analytics** — token consumption by user, team, model, and time period
9191
- **Cost analytics** — MTD spend, budget utilization, per-model cost breakdown
@@ -99,8 +99,8 @@ AgentBastion solves all of this with a single deployment.
9999
| Frontend | React 19, TypeScript 6, Vite 8, shadcn/ui, Tailwind CSS 4 |
100100
| Database | PostgreSQL 18 |
101101
| Cache & Rate Limiting | Redis 8 |
102-
| Audit Log Search | Quickwit 0.8 |
103-
| Object Storage | RustFS (S3-compatible) |
102+
| Audit Log Search | Quickwit 0.8 (S3-backed, cloud-native) |
103+
| Object Storage | AWS S3 / GCS / Azure Blob / RustFS (S3-compatible) |
104104
| SSO | Zitadel (or any OIDC provider) |
105105
| Containers | Distroless (2MB runtime), Helm Chart for K8s |
106106

‎README.zh-CN.md‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -85,7 +85,7 @@ AgentBastion 一次部署,全部解决。
8585
### 可观测性
8686
- **Prometheus 指标** — Gateway 端口 (3000) 的 `GET /metrics` 端点,暴露 `gateway_requests_total`、`gateway_request_duration_seconds`、`gateway_tokens_total`、`gateway_rate_limited_total`、`circuit_breaker_state` 等指标
8787
- **增强健康检查** — `/health/live`(存活探针)、`/health/ready`(就绪探针,检测 PostgreSQL 和 Redis)、`/api/health`(详细延迟和连接池统计)
88-
- **Quickwit 审计日志** — 全文搜索所有 API 调用和工具调用记录
88+
- **Quickwit 审计日志** — 全文搜索所有 API 调用和工具调用记录,审计日志仅存储在 Quickwit 中,支持 S3 云原生存储后端(AWS S3、GCS、Azure Blob 或自托管 RustFS/MinIO)
8989
- **审计日志转发** — 多通道投递:UDP/TCP Syslog (RFC 5424)、Kafka、HTTP Webhook — 将审计事件路由至任意 SIEM、数据湖或告警管道
9090
- **使用量分析** — 按用户、团队、模型、时间段的 Token 消耗统计
9191
- **费用分析** — 月度累计支出、预算使用率、按模型费用明细
@@ -99,8 +99,8 @@ AgentBastion 一次部署,全部解决。
9999
| 前端 | React 19, TypeScript 6, Vite 8, shadcn/ui, Tailwind CSS 4 |
100100
| 数据库 | PostgreSQL 18 |
101101
| 缓存与限流 | Redis 8 |
102-
| 审计日志搜索 | Quickwit 0.8 |
103-
| 对象存储 | RustFS (S3 兼容) |
102+
| 审计日志搜索 | Quickwit 0.8 (S3 存储后端,云原生) |
103+
| 对象存储 | AWS S3 / GCS / Azure Blob / RustFS (S3 兼容) |
104104
| 单点登录 | Zitadel (或任何 OIDC 提供商) |
105105
| 容器 | Distroless (2MB 运行镜像), Helm Chart (K8s) |
106106

‎crates/common/src/audit.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -239,6 +239,7 @@ async fn audit_worker(
239239
Some(entry) = rx.recv() => {
240240
// Forward to all enabled forwarders immediately
241241
forward_to_all(&http_client, &registry, &db, &entry).await;
242+
242243
batch.push(entry);
243244
if batch.len() >= 50 {
244245
flush_to_quickwit(&http_client, &config, &mut batch).await;

‎crates/common/src/config.rs‎

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -31,11 +31,10 @@ impl AppConfig {
3131
dotenvy::dotenv().ok();
3232

3333
Ok(Self {
34-
database_url: std::env::var("DATABASE_URL").unwrap_or_else(|_| {
35-
"postgres://postgres:postgres@localhost:5432/agent_bastion".into()
36-
}),
34+
database_url: std::env::var("DATABASE_URL")
35+
.expect("DATABASE_URL environment variable is required"),
3736
redis_url: std::env::var("REDIS_URL")
38-
.unwrap_or_else(|_| "redis://localhost:6379".into()),
37+
.expect("REDIS_URL environment variable is required"),
3938
jwt_secret: std::env::var("JWT_SECRET")
4039
.expect("JWT_SECRET environment variable is required"),
4140
encryption_key: std::env::var("ENCRYPTION_KEY")

‎crates/common/src/dynamic_config.rs‎

Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,11 +50,17 @@ impl DynamicConfig {
5050
}
5151

5252
/// Update one or more settings in the database and refresh the cache.
53+
/// Validates values before persisting.
5354
pub async fn update(
5455
&self,
5556
updates: &HashMap<String, Value>,
5657
updated_by: Option<uuid::Uuid>,
5758
) -> anyhow::Result<()> {
59+
// Validate values before persisting
60+
for (key, value) in updates {
61+
validate_setting(key, value)?;
62+
}
63+
5864
let mut tx = self.db.begin().await?;
5965

6066
for (key, value) in updates {
@@ -297,3 +303,89 @@ pub struct SettingEntry {
297303
pub description: Option<String>,
298304
pub updated_at: chrono::DateTime<chrono::Utc>,
299305
}
306+
307+
/// Validate a setting value before persisting.
308+
/// Returns an error if the value is invalid for the given key.
309+
fn validate_setting(key: &str, value: &Value) -> anyhow::Result<()> {
310+
match key {
311+
// Integer settings with minimum bounds
312+
k if k.ends_with("_secs") || k.ends_with("_days") || k.ends_with("_hours") => {
313+
let n = value
314+
.as_i64()
315+
.ok_or_else(|| anyhow::anyhow!("{key}: expected an integer value"))?;
316+
if n < 0 {
317+
anyhow::bail!("{key}: value must be non-negative, got {n}");
318+
}
319+
}
320+
321+
// JWT TTLs need reasonable bounds
322+
"auth.jwt_access_ttl_secs" => {
323+
let n = value.as_i64().ok_or_else(|| anyhow::anyhow!("{key}: expected integer"))?;
324+
if n < 60 || n > 86400 {
325+
anyhow::bail!("{key}: must be between 60 and 86400 seconds");
326+
}
327+
}
328+
"auth.jwt_refresh_ttl_days" => {
329+
let n = value.as_i64().ok_or_else(|| anyhow::anyhow!("{key}: expected integer"))?;
330+
if n < 1 || n > 365 {
331+
anyhow::bail!("{key}: must be between 1 and 365 days");
332+
}
333+
}
334+
335+
// Budget thresholds must be between 0.0 and 1.0
336+
"budget.alert_thresholds" => {
337+
let arr = value
338+
.as_array()
339+
.ok_or_else(|| anyhow::anyhow!("{key}: expected an array of numbers"))?;
340+
for v in arr {
341+
let n = v.as_f64().ok_or_else(|| anyhow::anyhow!("{key}: array elements must be numbers"))?;
342+
if !(0.0..=1.0).contains(&n) {
343+
anyhow::bail!("{key}: threshold values must be between 0.0 and 1.0, got {n}");
344+
}
345+
}
346+
}
347+
348+
// Webhook URL validation
349+
"budget.webhook_url" => {
350+
if let Some(url) = value.as_str() {
351+
if !url.is_empty() && !url.starts_with("http://") && !url.starts_with("https://") {
352+
anyhow::bail!("{key}: must be a valid http/https URL");
353+
}
354+
}
355+
}
356+
357+
// Boolean settings
358+
"setup.initialized" | "auth.allow_registration" => {
359+
value
360+
.as_bool()
361+
.ok_or_else(|| anyhow::anyhow!("{key}: expected a boolean value"))?;
362+
}
363+
364+
// String settings — basic non-empty check for critical ones
365+
"setup.site_name" => {
366+
let s = value
367+
.as_str()
368+
.ok_or_else(|| anyhow::anyhow!("{key}: expected a string value"))?;
369+
if s.is_empty() || s.len() > 200 {
370+
anyhow::bail!("{key}: must be between 1 and 200 characters");
371+
}
372+
}
373+
374+
// PII patterns: basic validation (regex compilation checked at gateway layer)
375+
"gateway.pii_patterns" => {
376+
if let Some(arr) = value.as_array() {
377+
for item in arr {
378+
if item.get("regex").and_then(|v| v.as_str()).is_none() {
379+
anyhow::bail!("{key}: each pattern must have a 'regex' string field");
380+
}
381+
if item.get("placeholder_prefix").and_then(|v| v.as_str()).is_none() {
382+
anyhow::bail!("{key}: each pattern must have a 'placeholder_prefix' string field");
383+
}
384+
}
385+
}
386+
}
387+
388+
_ => {} // Unknown keys pass through — forward-compatible
389+
}
390+
Ok(())
391+
}

‎crates/common/src/models/audit_log.rs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
use chrono::{DateTime, Utc};
22
use serde::{Deserialize, Serialize};
3-
use sqlx::FromRow;
43
use uuid::Uuid;
54

6-
#[derive(Debug, Clone, Serialize, Deserialize, FromRow)]
5+
/// Audit log entry returned from Quickwit search.
6+
#[derive(Debug, Clone, Serialize, Deserialize)]
77
pub struct AuditLog {
88
pub id: Uuid,
99
pub user_id: Option<Uuid>,

‎crates/gateway/src/cost_tracker.rs‎

Lines changed: 73 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
1+
use std::collections::HashMap;
2+
13
/// Tracks and calculates costs for AI API calls based on per-model pricing.
24
///
35
/// Prices are in USD per 1 million tokens.
46
pub struct CostTracker {
57
/// (model_pattern, input_price_per_1m, output_price_per_1m)
6-
price_table: Vec<(&'static str, f64, f64)>,
8+
price_table: Vec<(String, f64, f64)>,
79
}
810

911
impl Default for CostTracker {
@@ -13,36 +15,64 @@ impl Default for CostTracker {
1315
}
1416

1517
impl CostTracker {
16-
pub fn new() -> Self {
17-
// Prices in USD per 1M tokens: (model_prefix, input, output)
18-
let price_table = vec![
18+
/// Built-in default price table (USD per 1M tokens).
19+
fn default_price_table() -> Vec<(String, f64, f64)> {
20+
vec![
1921
// OpenAI models
20-
("gpt-4o-mini", 0.15, 0.60),
21-
("gpt-4o", 2.50, 10.00),
22-
("gpt-4-turbo", 10.00, 30.00),
23-
("gpt-4", 30.00, 60.00),
24-
("gpt-3.5-turbo", 0.50, 1.50),
25-
("o1-mini", 3.00, 12.00),
26-
("o1-preview", 15.00, 60.00),
27-
("o1", 15.00, 60.00),
28-
("o3-mini", 1.10, 4.40),
22+
("gpt-4o-mini".into(), 0.15, 0.60),
23+
("gpt-4o".into(), 2.50, 10.00),
24+
("gpt-4-turbo".into(), 10.00, 30.00),
25+
("gpt-4".into(), 30.00, 60.00),
26+
("gpt-3.5-turbo".into(), 0.50, 1.50),
27+
("o1-mini".into(), 3.00, 12.00),
28+
("o1-preview".into(), 15.00, 60.00),
29+
("o1".into(), 15.00, 60.00),
30+
("o3-mini".into(), 1.10, 4.40),
2931
// Anthropic models
30-
("claude-sonnet-4", 3.00, 15.00),
31-
("claude-3-5-sonnet", 3.00, 15.00),
32-
("claude-3-5-haiku", 0.80, 4.00),
33-
("claude-3-opus", 15.00, 75.00),
34-
("claude-3-haiku", 0.25, 1.25),
35-
("claude-3-sonnet", 3.00, 15.00),
36-
("claude-haiku", 0.80, 4.00),
37-
("claude-opus", 15.00, 75.00),
32+
("claude-sonnet-4".into(), 3.00, 15.00),
33+
("claude-3-5-sonnet".into(), 3.00, 15.00),
34+
("claude-3-5-haiku".into(), 0.80, 4.00),
35+
("claude-3-opus".into(), 15.00, 75.00),
36+
("claude-3-haiku".into(), 0.25, 1.25),
37+
("claude-3-sonnet".into(), 3.00, 15.00),
38+
("claude-haiku".into(), 0.80, 4.00),
39+
("claude-opus".into(), 15.00, 75.00),
3840
// Google models
39-
("gemini-1.5-pro", 3.50, 10.50),
40-
("gemini-1.5-flash", 0.075, 0.30),
41-
("gemini-2.0-flash", 0.10, 0.40),
42-
("gemini-2.5-pro", 1.25, 10.00),
43-
];
41+
("gemini-1.5-pro".into(), 3.50, 10.50),
42+
("gemini-1.5-flash".into(), 0.075, 0.30),
43+
("gemini-2.0-flash".into(), 0.10, 0.40),
44+
("gemini-2.5-pro".into(), 1.25, 10.00),
45+
]
46+
}
4447

45-
Self { price_table }
48+
pub fn new() -> Self {
49+
Self {
50+
price_table: Self::default_price_table(),
51+
}
52+
}
53+
54+
/// Create a `CostTracker` with custom price overrides.
55+
///
56+
/// Entries in `overrides` take precedence over built-in defaults.
57+
/// Keys are model prefixes, values are `(input_per_1m, output_per_1m)`.
58+
pub fn with_overrides(overrides: HashMap<String, (f64, f64)>) -> Self {
59+
let defaults = Self::default_price_table();
60+
61+
// Custom prices first so they are matched before defaults
62+
let mut table: Vec<(String, f64, f64)> = overrides
63+
.into_iter()
64+
.map(|(k, (i, o))| (k, i, o))
65+
.collect();
66+
// Sort custom entries by pattern length descending (longer = more specific first)
67+
table.sort_by(|a, b| b.0.len().cmp(&a.0.len()));
68+
// Append defaults for any models not overridden
69+
for entry in defaults {
70+
if !table.iter().any(|(p, _, _)| p == &entry.0) {
71+
table.push(entry);
72+
}
73+
}
74+
75+
Self { price_table: table }
4676
}
4777

4878
/// Calculate the cost in USD for a given model and token counts.
@@ -63,9 +93,10 @@ impl CostTracker {
6393
fn lookup_price(&self, model: &str) -> (f64, f64) {
6494
let model_lower = model.to_lowercase();
6595

66-
for &(pattern, input, output) in &self.price_table {
67-
if model_lower.starts_with(pattern) || model_lower.contains(pattern) {
68-
return (input, output);
96+
for (pattern, input, output) in &self.price_table {
97+
if model_lower.starts_with(pattern.as_str()) || model_lower.contains(pattern.as_str())
98+
{
99+
return (*input, *output);
69100
}
70101
}
71102

@@ -109,4 +140,16 @@ mod tests {
109140
// input: 3.00, output: 15.00 -> 18.00
110141
assert!((cost - 18.0).abs() < 1e-9, "got {cost}");
111142
}
143+
144+
#[test]
145+
fn custom_price_override() {
146+
let mut overrides = std::collections::HashMap::new();
147+
overrides.insert("gpt-4o".into(), (5.00, 20.00));
148+
let tracker = CostTracker::with_overrides(overrides);
149+
let cost = tracker.calculate_cost("gpt-4o", 1_000_000, 0);
150+
assert!((cost - 5.0).abs() < 1e-9, "got {cost}");
151+
// Models not overridden should still use defaults
152+
let cost2 = tracker.calculate_cost("claude-3-opus", 1_000_000, 0);
153+
assert!((cost2 - 15.0).abs() < 1e-9, "got {cost2}");
154+
}
112155
}

0 commit comments

Comments
 (0)