Skip to content

Commit 57993b4

Browse files
SecAegisclaude
andcommitted
fix: pass CI — fix all clippy warnings, rustfmt, add PostgreSQL/Redis services
- Fix unused imports, dead code, collapsible if, deprecated API, div_ceil - Add PostgreSQL and Redis service containers to CI for integration tests - Provide test env vars (JWT_SECRET, ENCRYPTION_KEY, DATABASE_URL) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
1 parent 9789aa3 commit 57993b4

54 files changed

Lines changed: 590 additions & 522 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎.github/workflows/ci.yml‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,37 @@ jobs:
1414
rust:
1515
name: Rust Check & Test
1616
runs-on: ubuntu-latest
17+
18+
services:
19+
postgres:
20+
image: postgres:18-alpine
21+
env:
22+
POSTGRES_USER: postgres
23+
POSTGRES_PASSWORD: postgres
24+
POSTGRES_DB: agent_bastion_test
25+
ports:
26+
- 5432:5432
27+
options: >-
28+
--health-cmd pg_isready
29+
--health-interval 5s
30+
--health-timeout 5s
31+
--health-retries 5
32+
redis:
33+
image: redis:8-alpine
34+
ports:
35+
- 6379:6379
36+
options: >-
37+
--health-cmd "redis-cli ping"
38+
--health-interval 5s
39+
--health-timeout 5s
40+
--health-retries 5
41+
42+
env:
43+
DATABASE_URL: postgres://postgres:postgres@localhost:5432/agent_bastion_test
44+
REDIS_URL: redis://localhost:6379
45+
JWT_SECRET: ci-test-jwt-secret-not-for-production-use-00
46+
ENCRYPTION_KEY: 0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef
47+
1748
steps:
1849
- uses: actions/checkout@v4
1950
- uses: dtolnay/rust-toolchain@stable

‎crates/auth/src/api_key.rs‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -44,8 +44,14 @@ mod tests {
4444
#[test]
4545
fn generate_api_key_has_correct_prefix() {
4646
let key = generate_api_key();
47-
assert!(key.plaintext.starts_with("ab-"), "key should start with ab- prefix");
48-
assert!(key.prefix.starts_with("ab-"), "prefix should start with ab-");
47+
assert!(
48+
key.plaintext.starts_with("ab-"),
49+
"key should start with ab- prefix"
50+
);
51+
assert!(
52+
key.prefix.starts_with("ab-"),
53+
"prefix should start with ab-"
54+
);
4955
assert_eq!(key.prefix.len(), 11, "prefix should be 11 chars (ab- + 8)");
5056
}
5157

‎crates/auth/src/jwt.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
use chrono::{Duration, Utc};
2-
use jsonwebtoken::{decode, encode, DecodingKey, EncodingKey, Header, Validation};
2+
use jsonwebtoken::{DecodingKey, EncodingKey, Header, Validation, decode, encode};
33
use serde::{Deserialize, Serialize};
44
use sha2::{Digest, Sha256};
55
use uuid::Uuid;

‎crates/auth/src/oidc.rs‎

Lines changed: 6 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
use openidconnect::core::{CoreAuthenticationFlow, CoreClient, CoreProviderMetadata};
22
use openidconnect::{
3-
AuthUrl, AuthorizationCode, ClientId, ClientSecret, CsrfToken, IssuerUrl, Nonce,
4-
RedirectUrl, Scope, TokenResponse, TokenUrl,
3+
AuthUrl, AuthorizationCode, ClientId, ClientSecret, CsrfToken, IssuerUrl, Nonce, RedirectUrl,
4+
Scope, TokenResponse, TokenUrl,
55
};
66
use serde::{Deserialize, Serialize};
77
use std::sync::Arc;
@@ -43,10 +43,9 @@ impl OidcManager {
4343
let issuer = IssuerUrl::new(issuer_url.to_string())?;
4444
let http_client = openidconnect::reqwest::Client::new();
4545

46-
let provider_metadata =
47-
CoreProviderMetadata::discover_async(issuer.clone(), &http_client)
48-
.await
49-
.map_err(|e| anyhow::anyhow!("OIDC discovery failed: {e}"))?;
46+
let provider_metadata = CoreProviderMetadata::discover_async(issuer.clone(), &http_client)
47+
.await
48+
.map_err(|e| anyhow::anyhow!("OIDC discovery failed: {e}"))?;
5049

5150
let auth_url = provider_metadata.authorization_endpoint().clone();
5251
let token_url = provider_metadata
@@ -94,11 +93,7 @@ impl OidcManager {
9493
}
9594

9695
/// Exchange authorization code for tokens, return user info.
97-
pub async fn exchange_code(
98-
&self,
99-
code: &str,
100-
nonce: &Nonce,
101-
) -> anyhow::Result<OidcUserInfo> {
96+
pub async fn exchange_code(&self, code: &str, nonce: &Nonce) -> anyhow::Result<OidcUserInfo> {
10297
let client = CoreClient::from_provider_metadata(
10398
self.inner.provider_metadata.clone(),
10499
self.inner.client_id.clone(),

‎crates/auth/src/password.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
use argon2::{
2-
password_hash::{rand_core::OsRng, PasswordHash, PasswordHasher, PasswordVerifier, SaltString},
32
Argon2,
3+
password_hash::{PasswordHash, PasswordHasher, PasswordVerifier, SaltString, rand_core::OsRng},
44
};
55

66
pub fn hash_password(password: &str) -> anyhow::Result<String> {

‎crates/auth/src/rbac.rs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ impl SystemRole {
2020
}
2121
}
2222

23-
pub fn from_str(s: &str) -> Option<Self> {
23+
pub fn parse(s: &str) -> Option<Self> {
2424
match s {
2525
"super_admin" => Some(SystemRole::SuperAdmin),
2626
"admin" => Some(SystemRole::Admin),
@@ -114,7 +114,7 @@ mod tests {
114114
];
115115
for role in &roles {
116116
let s = role.as_str();
117-
let parsed = SystemRole::from_str(s);
117+
let parsed = SystemRole::parse(s);
118118
assert_eq!(parsed.as_ref(), Some(role), "roundtrip failed for {s}");
119119
}
120120
}

‎crates/common/src/audit.rs‎

Lines changed: 63 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ use sqlx::PgPool;
44
use std::collections::HashMap;
55
use std::net::UdpSocket;
66
use std::sync::Arc;
7-
use tokio::sync::{mpsc, RwLock};
7+
use tokio::sync::{RwLock, mpsc};
88
use uuid::Uuid;
99

1010
use crate::models::LogForwarder;
@@ -88,8 +88,14 @@ mod tests {
8888
.user_agent("curl/8.0");
8989

9090
assert_eq!(entry.action, "api.request");
91-
assert_eq!(entry.user_id.as_deref(), Some(user_id.to_string()).as_deref());
92-
assert_eq!(entry.api_key_id.as_deref(), Some(api_key_id.to_string()).as_deref());
91+
assert_eq!(
92+
entry.user_id.as_deref(),
93+
Some(user_id.to_string()).as_deref()
94+
);
95+
assert_eq!(
96+
entry.api_key_id.as_deref(),
97+
Some(api_key_id.to_string()).as_deref()
98+
);
9399
assert_eq!(entry.resource.as_deref(), Some("/v1/chat/completions"));
94100
assert_eq!(entry.detail, Some(detail));
95101
assert_eq!(entry.ip_address.as_deref(), Some("10.0.0.1"));
@@ -199,7 +205,13 @@ async fn reload_forwarders(db: &PgPool, registry: &ForwarderRegistry) {
199205
} else {
200206
None
201207
};
202-
map.insert(row.id, ForwarderRuntime { config: row, udp_socket });
208+
map.insert(
209+
row.id,
210+
ForwarderRuntime {
211+
config: row,
212+
udp_socket,
213+
},
214+
);
203215
}
204216

205217
let mut guard = registry.write().await;
@@ -295,14 +307,22 @@ async fn forward_to_all(
295307
// ---------------------------------------------------------------------------
296308

297309
fn send_udp_syslog(runtime: &ForwarderRuntime, entry: &AuditEntry) -> Result<(), String> {
298-
let addr = runtime.config.config.get("address")
310+
let addr = runtime
311+
.config
312+
.config
313+
.get("address")
299314
.and_then(|v| v.as_str())
300315
.ok_or("Missing 'address' in udp_syslog config")?;
301-
let facility: u8 = runtime.config.config.get("facility")
316+
let facility: u8 = runtime
317+
.config
318+
.config
319+
.get("facility")
302320
.and_then(|v| v.as_u64())
303321
.unwrap_or(16) as u8; // default: local0
304322

305-
let socket = runtime.udp_socket.as_ref()
323+
let socket = runtime
324+
.udp_socket
325+
.as_ref()
306326
.ok_or("UDP socket not initialized")?;
307327

308328
let severity = 6u8; // informational
@@ -331,16 +351,21 @@ fn send_udp_syslog(runtime: &ForwarderRuntime, entry: &AuditEntry) -> Result<(),
331351
resource = entry.resource.as_deref().unwrap_or("-"),
332352
);
333353

334-
socket.send_to(message.as_bytes(), addr)
354+
socket
355+
.send_to(message.as_bytes(), addr)
335356
.map(|_| ())
336357
.map_err(|e| format!("Syslog UDP send failed: {e}"))
337358
}
338359

339360
async fn send_tcp_syslog(config: &LogForwarder, entry: &AuditEntry) -> Result<(), String> {
340-
let addr = config.config.get("address")
361+
let addr = config
362+
.config
363+
.get("address")
341364
.and_then(|v| v.as_str())
342365
.ok_or("Missing 'address' in tcp_syslog config")?;
343-
let facility: u8 = config.config.get("facility")
366+
let facility: u8 = config
367+
.config
368+
.get("facility")
344369
.and_then(|v| v.as_u64())
345370
.unwrap_or(16) as u8;
346371

@@ -364,9 +389,11 @@ async fn send_tcp_syslog(config: &LogForwarder, entry: &AuditEntry) -> Result<()
364389
resource = entry.resource.as_deref().unwrap_or("-"),
365390
);
366391

367-
let mut stream = tokio::net::TcpStream::connect(addr).await
392+
let mut stream = tokio::net::TcpStream::connect(addr)
393+
.await
368394
.map_err(|e| format!("TCP syslog connect failed: {e}"))?;
369-
tokio::io::AsyncWriteExt::write_all(&mut stream, message.as_bytes()).await
395+
tokio::io::AsyncWriteExt::write_all(&mut stream, message.as_bytes())
396+
.await
370397
.map_err(|e| format!("TCP syslog write failed: {e}"))
371398
}
372399

@@ -376,10 +403,14 @@ async fn send_kafka(
376403
entry: &AuditEntry,
377404
) -> Result<(), String> {
378405
// Kafka via REST proxy (Confluent-compatible)
379-
let broker_url = config.config.get("broker_url")
406+
let broker_url = config
407+
.config
408+
.get("broker_url")
380409
.and_then(|v| v.as_str())
381410
.ok_or("Missing 'broker_url' in kafka config")?;
382-
let topic = config.config.get("topic")
411+
let topic = config
412+
.config
413+
.get("topic")
383414
.and_then(|v| v.as_str())
384415
.ok_or("Missing 'topic' in kafka config")?;
385416

@@ -390,7 +421,8 @@ async fn send_kafka(
390421
});
391422

392423
let url = format!("{}/topics/{}", broker_url.trim_end_matches('/'), topic);
393-
let resp = client.post(&url)
424+
let resp = client
425+
.post(&url)
394426
.header("Content-Type", "application/vnd.kafka.json.v2+json")
395427
.json(&payload)
396428
.send()
@@ -410,11 +442,14 @@ async fn send_webhook(
410442
config: &LogForwarder,
411443
entry: &AuditEntry,
412444
) -> Result<(), String> {
413-
let url = config.config.get("url")
445+
let url = config
446+
.config
447+
.get("url")
414448
.and_then(|v| v.as_str())
415449
.ok_or("Missing 'url' in webhook config")?;
416450

417-
let mut req = client.post(url)
451+
let mut req = client
452+
.post(url)
418453
.header("Content-Type", "application/json")
419454
.json(entry);
420455

@@ -423,7 +458,9 @@ async fn send_webhook(
423458
req = req.header("Authorization", token);
424459
}
425460

426-
let resp = req.send().await
461+
let resp = req
462+
.send()
463+
.await
427464
.map_err(|e| format!("Webhook request failed: {e}"))?;
428465

429466
if resp.status().is_success() {
@@ -441,7 +478,14 @@ async fn send_webhook(
441478

442479
fn sanitize_detail(detail: &mut Option<serde_json::Value>) {
443480
if let Some(serde_json::Value::Object(map)) = detail {
444-
let sensitive_keys = ["password", "secret", "api_key", "token", "authorization", "key_hash"];
481+
let sensitive_keys = [
482+
"password",
483+
"secret",
484+
"api_key",
485+
"token",
486+
"authorization",
487+
"key_hash",
488+
];
445489
for key in &sensitive_keys {
446490
map.remove(*key);
447491
}

‎crates/common/src/config.rs‎

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

3333
Ok(Self {
34-
database_url: std::env::var("DATABASE_URL")
35-
.unwrap_or_else(|_| "postgres://postgres:postgres@localhost:5432/agent_bastion".into()),
34+
database_url: std::env::var("DATABASE_URL").unwrap_or_else(|_| {
35+
"postgres://postgres:postgres@localhost:5432/agent_bastion".into()
36+
}),
3637
redis_url: std::env::var("REDIS_URL")
3738
.unwrap_or_else(|_| "redis://localhost:6379".into()),
3839
jwt_secret: std::env::var("JWT_SECRET")
3940
.expect("JWT_SECRET environment variable is required"),
4041
encryption_key: std::env::var("ENCRYPTION_KEY")
4142
.expect("ENCRYPTION_KEY environment variable is required"),
42-
server_host: std::env::var("SERVER_HOST")
43-
.unwrap_or_else(|_| "0.0.0.0".into()),
43+
server_host: std::env::var("SERVER_HOST").unwrap_or_else(|_| "0.0.0.0".into()),
4444
gateway_port: std::env::var("GATEWAY_PORT")
4545
.unwrap_or_else(|_| "3000".into())
4646
.parse()?,
@@ -55,8 +55,7 @@ impl AppConfig {
5555

5656
// Quickwit
5757
quickwit_url: std::env::var("QUICKWIT_URL").ok(),
58-
quickwit_index: std::env::var("QUICKWIT_INDEX")
59-
.unwrap_or_else(|_| "audit_logs".into()),
58+
quickwit_index: std::env::var("QUICKWIT_INDEX").unwrap_or_else(|_| "audit_logs".into()),
6059

6160
// OIDC
6261
oidc_issuer_url: std::env::var("OIDC_ISSUER_URL").ok(),

‎crates/common/src/crypto.rs‎

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,12 @@
11
use aes_gcm::{
2-
aead::{Aead, KeyInit},
32
Aes256Gcm, Nonce,
3+
aead::{Aead, KeyInit},
44
};
5-
use rand::Rng;
65

76
/// Encrypt data using AES-256-GCM.
87
/// Returns: 12-byte nonce || ciphertext || 16-byte tag (all concatenated).
98
pub fn encrypt(plaintext: &[u8], key: &[u8; 32]) -> anyhow::Result<Vec<u8>> {
10-
let cipher =
11-
Aes256Gcm::new_from_slice(key).map_err(|e| anyhow::anyhow!("Invalid key: {e}"))?;
9+
let cipher = Aes256Gcm::new_from_slice(key).map_err(|e| anyhow::anyhow!("Invalid key: {e}"))?;
1210

1311
let mut nonce_bytes = [0u8; 12];
1412
rand::fill(&mut nonce_bytes);
@@ -32,8 +30,7 @@ pub fn decrypt(encrypted: &[u8], key: &[u8; 32]) -> anyhow::Result<Vec<u8>> {
3230
return Err(anyhow::anyhow!("Ciphertext too short"));
3331
}
3432

35-
let cipher =
36-
Aes256Gcm::new_from_slice(key).map_err(|e| anyhow::anyhow!("Invalid key: {e}"))?;
33+
let cipher = Aes256Gcm::new_from_slice(key).map_err(|e| anyhow::anyhow!("Invalid key: {e}"))?;
3734

3835
let nonce = Nonce::from_slice(&encrypted[..12]);
3936
let ciphertext = &encrypted[12..];
@@ -103,7 +100,9 @@ mod tests {
103100

104101
#[test]
105102
fn parse_encryption_key_invalid_hex() {
106-
let result = parse_encryption_key("zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz");
103+
let result = parse_encryption_key(
104+
"zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz",
105+
);
107106
assert!(result.is_err(), "non-hex chars should be rejected");
108107
}
109108
}

‎crates/common/src/db.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
use sqlx::postgres::PgPoolOptions;
21
use sqlx::PgPool;
2+
use sqlx::postgres::PgPoolOptions;
33

44
pub async fn create_pool(database_url: &str) -> anyhow::Result<PgPool> {
55
if !database_url.contains("sslmode=") {

0 commit comments

Comments
 (0)