Skip to content

Commit 3c2c36d

Browse files
authored
feat(security): fail-closed webhooks, API authentication, CORS hardening, and trusted Semgrep rules (#22)
## Summary Hardens revue daemon against unauthenticated access, injection, and untrusted rule execution: 1. **Fail-Closed Webhooks (CWE-306)**: Webhook signature verification fails closed (returns `401 Unauthorized`) when no secret is configured, unless explicitly opted-in with `--insecure-webhooks`. 2. **API Authentication (CWE-306)**: Mutating endpoints (`/api/trigger`, `/api/feedback`, `/api/feedback/delete`, `/api/rules/synthesize`) require `REVUE_API_KEY` via `Authorization: Bearer <key>` or `X-Revue-Key: <key>`. When unset, access is strictly confined to loopback clients (`127.0.0.1`, `::1`); remote callers receive `403 Forbidden`. 3. **CORS Hardening**: Replaced wildcard `allow_origin(Any)` with configured `server.cors_origins` and standard local origins. 4. **Local Bind by Default**: Default listen address changed from `0.0.0.0:8383` to `127.0.0.1:8383`. 5. **Trusted Semgrep Rule Isolation (CWE-829)**: Pass 0 AST scan loads rules strictly from daemon config (`config.review.semgrep_config`) or host repository, never from the untrusted PR checkout root. 6. **Path Traversal Sanitization (CWE-22)**: `resolve_repo_root` rejects `..` and invalid path components. 7. **Unique Review Identifiers & Feedback Error Propagation**: Review IDs are partitioned by repo and sequence counter (`rev-manual-{repo}-{pr}-{seq}`); feedback DB write errors return `500` instead of `200`. ## Verification - Added unit tests for loopback restriction, API key authentication, and traversal rejection. - All 74 unit tests and benchmarks pass in Nix development shell. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **New Features** * Added configurable API-key protection for review and feedback actions, supporting bearer tokens and a dedicated request header. Keys can be set in configuration, on the command line or through the environment. * Webhooks require a secret by default; insecure mode can be enabled through configuration or the command line. * CORS access can be configured, with local development origins supported. * **Security** * The daemon now listens on localhost by default. Without an API key, API access is limited to loopback connections. * Repository names with hidden or invalid path components are rejected. * **Bug Fixes** * Manual review records are retained separately, with clearer review identifiers. * Review scans use trusted rule configuration rather than configuration from the scanned checkout. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
1 parent 1aa5b0a commit 3c2c36d

7 files changed

Lines changed: 478 additions & 55 deletions

File tree

‎Cargo.lock‎

Lines changed: 1 addition & 0 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 & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,4 +38,5 @@ sha2 = "0.11.1"
3838
hex = "0.4.3"
3939
regex = "1.13.1"
4040
chrono = { version = "0.4", default-features = false, features = ["clock", "std"] }
41+
subtle = "2.6"
4142
sqlx = { version = "0.9.0", default-features = false, features = ["runtime-tokio", "tls-rustls", "sqlite", "postgres", "macros", "migrate"] }

‎src/config.rs‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,12 +13,46 @@ pub struct RevueConfig {
1313
pub providers: ProvidersConfig,
1414
#[serde(default)]
1515
pub review: ReviewSection,
16+
#[serde(default)]
17+
pub server: ServerConfig,
1618
}
1719

1820
fn default_version() -> u32 {
1921
1
2022
}
2123

24+
/// Server listening and authentication settings.
25+
#[derive(Debug, Clone, Serialize, Deserialize)]
26+
pub struct ServerConfig {
27+
/// Default bind address (defaults to 127.0.0.1:8383)
28+
#[serde(default = "default_bind_addr")]
29+
pub bind: String,
30+
/// Optional API key for authenticating /api routes (or set REVUE_API_KEY)
31+
#[serde(default)]
32+
pub api_key: Option<String>,
33+
/// Allow unauthenticated webhooks (insecure testing mode only)
34+
#[serde(default)]
35+
pub insecure_webhooks: bool,
36+
/// Allowed CORS origins
37+
#[serde(default)]
38+
pub cors_origins: Vec<String>,
39+
}
40+
41+
fn default_bind_addr() -> String {
42+
"127.0.0.1:8383".to_string()
43+
}
44+
45+
impl Default for ServerConfig {
46+
fn default() -> Self {
47+
Self {
48+
bind: default_bind_addr(),
49+
api_key: std::env::var("REVUE_API_KEY").ok(),
50+
insecure_webhooks: false,
51+
cors_origins: Vec::new(),
52+
}
53+
}
54+
}
55+
2256
#[derive(Debug, Clone, Serialize, Deserialize)]
2357
pub struct ForgeConfig {
2458
/// Forge type: "forgejo", "gitea", "github", or "auto"
@@ -190,6 +224,7 @@ impl Default for RevueConfig {
190224
forge: ForgeConfig::default(),
191225
providers: ProvidersConfig::default(),
192226
review: ReviewSection::default(),
227+
server: ServerConfig::default(),
193228
}
194229
}
195230
}
@@ -242,6 +277,10 @@ impl RevueConfig {
242277
cfg.forge.webhook_secret = std::env::var("REVUE_WEBHOOK_SECRET").ok();
243278
}
244279

280+
if cfg.server.api_key.is_none() {
281+
cfg.server.api_key = std::env::var("REVUE_API_KEY").ok();
282+
}
283+
245284
Ok(cfg)
246285
}
247286

‎src/main.rs‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -68,13 +68,21 @@ enum Commands {
6868
/// Run the webhook daemon for Forgejo and GitHub
6969
Daemon {
7070
/// Address to bind the HTTP webhook listener
71-
#[arg(short, long, default_value = "0.0.0.0:8383")]
71+
#[arg(short, long, default_value = "127.0.0.1:8383")]
7272
listen: String,
7373

7474
/// Webhook HMAC secret for signature verification (or set REVUE_WEBHOOK_SECRET)
7575
#[arg(long, env = "REVUE_WEBHOOK_SECRET")]
7676
webhook_secret: Option<String>,
7777

78+
/// API key for authenticating /api routes (or set REVUE_API_KEY)
79+
#[arg(long, env = "REVUE_API_KEY")]
80+
api_key: Option<String>,
81+
82+
/// Allow unauthenticated webhooks (insecure testing mode only)
83+
#[arg(long, default_value_t = false)]
84+
insecure_webhooks: bool,
85+
7886
/// Directory containing static web dashboard assets (defaults to ./web/build)
7987
#[arg(long, env = "REVUE_STATIC_DIR")]
8088
static_dir: Option<String>,
@@ -160,6 +168,8 @@ async fn main() -> Result<()> {
160168
Commands::Daemon {
161169
listen,
162170
webhook_secret,
171+
api_key,
172+
insecure_webhooks,
163173
static_dir,
164174
database_url,
165175
} => {
@@ -170,6 +180,8 @@ async fn main() -> Result<()> {
170180
webhook_secret.as_deref(),
171181
static_dir.as_deref(),
172182
database_url.as_deref(),
183+
api_key.as_deref(),
184+
insecure_webhooks,
173185
)
174186
.await?;
175187
}

‎src/reviewer.rs‎

Lines changed: 84 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -228,13 +228,14 @@ fn parse_semgrep_findings_with_spans(raw_json: &str) -> Vec<(ReviewIssue, Option
228228
pub async fn run_semgrep_pass0(
229229
diff: &ParsedDiff,
230230
config: &RevueConfig,
231-
repo_path: Option<&std::path::Path>,
231+
scan_root: Option<&std::path::Path>,
232+
trusted_rules_root: Option<&std::path::Path>,
232233
) -> Vec<ReviewIssue> {
233234
if !config.review.semgrep || diff.files.is_empty() {
234235
return Vec::new();
235236
}
236237

237-
let root = match repo_path {
238+
let root = match scan_root {
238239
Some(r) => r,
239240
None => {
240241
tracing::debug!("No local checkout path provided for Semgrep Pass 0; skipping");
@@ -267,19 +268,83 @@ pub async fn run_semgrep_pass0(
267268
return Vec::new();
268269
}
269270

271+
// Resolve trusted Semgrep configuration from daemon settings or canonical host checkout,
272+
// NEVER from the untrusted PR checkout root.
270273
let config_arg = if let Some(cfg) = &config.review.semgrep_config {
271-
Some(cfg.clone())
272-
} else if root.join(".semgrep").exists() {
273-
Some(root.join(".semgrep").to_string_lossy().to_string())
274-
} else if root.join(".semgrep.yml").exists() {
275-
Some(root.join(".semgrep.yml").to_string_lossy().to_string())
276-
} else if root.join(".semgrep.yaml").exists() {
277-
Some(root.join(".semgrep.yaml").to_string_lossy().to_string())
274+
let p = std::path::Path::new(cfg);
275+
if let Ok(canon) = p.canonicalize() {
276+
Some(canon.to_string_lossy().to_string())
277+
} else if cfg.starts_with("p/")
278+
|| cfg.starts_with("r/")
279+
|| cfg.starts_with("s/")
280+
|| cfg.starts_with("http://")
281+
|| cfg.starts_with("https://")
282+
{
283+
// Valid Semgrep registry ID or URL
284+
Some(cfg.clone())
285+
} else if cfg == "auto" {
286+
// Note: Semgrep CLI rejects '--config auto' when '--metrics=off' is passed.
287+
// Upstream: semgrep/semgrep#11649 (open)
288+
tracing::warn!(
289+
"Semgrep '--config auto' requires metrics; with '--metrics=off' this fails before scanning. Specify an explicit ruleset like 'p/default'."
290+
);
291+
Some(cfg.clone())
292+
} else {
293+
// Local file/directory path that does not exist or cannot be canonicalized
294+
tracing::warn!(
295+
"Rejecting unresolvable local Semgrep config path: {}",
296+
cfg
297+
);
298+
return Vec::new();
299+
}
300+
} else if let Some(trusted) = trusted_rules_root {
301+
if trusted.join(".semgrep").exists() {
302+
trusted.join(".semgrep").canonicalize().ok().map(|p| p.to_string_lossy().to_string())
303+
} else if trusted.join(".semgrep.yml").exists() {
304+
trusted.join(".semgrep.yml").canonicalize().ok().map(|p| p.to_string_lossy().to_string())
305+
} else if trusted.join(".semgrep.yaml").exists() {
306+
trusted.join(".semgrep.yaml").canonicalize().ok().map(|p| p.to_string_lossy().to_string())
307+
} else {
308+
None
309+
}
278310
} else {
279-
tracing::debug!(
280-
"No Semgrep rules configuration (.semgrep/ or .semgrep.yml) found; skipping Pass 0"
281-
);
282-
return Vec::new();
311+
None
312+
};
313+
314+
// When scanning an untrusted PR checkout distinct from the trusted rules checkout,
315+
// ensure resolved config does not reside within the scan root.
316+
if let (Some(scan), Some(ref cfg_str)) = (scan_root, &config_arg) {
317+
let is_distinct_checkout = match trusted_rules_root {
318+
Some(trusted) => match (scan.canonicalize(), trusted.canonicalize()) {
319+
(Ok(s), Ok(t)) => s != t,
320+
_ => true,
321+
},
322+
None => true,
323+
};
324+
if is_distinct_checkout {
325+
if let Ok(scan_canon) = scan.canonicalize() {
326+
let cfg_path = std::path::Path::new(cfg_str);
327+
if let Ok(cfg_canon) = cfg_path.canonicalize() {
328+
if cfg_canon.starts_with(&scan_canon) {
329+
tracing::warn!(
330+
"Rejecting Semgrep config resolving inside PR checkout: {:?}",
331+
cfg_canon
332+
);
333+
return Vec::new();
334+
}
335+
}
336+
}
337+
}
338+
}
339+
340+
let config_arg = match config_arg {
341+
Some(c) => Some(c),
342+
None => {
343+
tracing::debug!(
344+
"No trusted Semgrep rules configuration (.semgrep/ or .semgrep.yml) found; skipping Pass 0"
345+
);
346+
return Vec::new();
347+
}
283348
};
284349

285350
let semgrep_bin = std::env::var("SEMGREP_BIN").unwrap_or_else(|_| "semgrep".to_string());
@@ -704,13 +769,14 @@ pub async fn execute_review_pipeline(
704769
chain: &ProviderChain,
705770
false_positives: &[crate::db::FindingFeedback],
706771
repo_path: Option<&std::path::Path>,
772+
trusted_rules_root: Option<&std::path::Path>,
707773
intent: Option<&PrMetadata>,
708774
existing_comments: &[crate::forges::DiscussionComment],
709775
) -> Result<ReviewExecutionResult> {
710776
let start_time = std::time::Instant::now();
711777
let pass0_issues = if config.review.semgrep {
712778
info!("Executing Review Pass 0 (Semgrep AST scan)...");
713-
run_semgrep_pass0(diff, config, repo_path).await
779+
run_semgrep_pass0(diff, config, repo_path, trusted_rules_root).await
714780
} else {
715781
Vec::new()
716782
};
@@ -828,7 +894,7 @@ pub async fn review_diff_content(
828894
let config = RevueConfig::find_and_load(config_path)?;
829895
let parsed = crate::diff::ParsedDiff::parse(raw_diff)?;
830896
let chain = build_provider_chain(&config);
831-
let res = execute_review_pipeline(&parsed, &config, &chain, &[], None, None, &[]).await?;
897+
let res = execute_review_pipeline(&parsed, &config, &chain, &[], None, None, None, &[]).await?;
832898
Ok((
833899
ReviewOutput {
834900
summary: res.summary,
@@ -870,6 +936,7 @@ pub async fn run_diff_review(base: &str, format: &str, config_path: Option<&str>
870936
&chain,
871937
&[],
872938
Some(std::path::Path::new(".")),
939+
Some(std::path::Path::new(".")),
873940
None,
874941
&[],
875942
)
@@ -991,13 +1058,15 @@ pub async fn run_pr_review(
9911058
.await
9921059
.unwrap_or_default();
9931060

1061+
let host_repo = crate::tree::resolve_repo_root(repo);
9941062
let chain = build_provider_chain(&config);
9951063
let res = execute_review_pipeline(
9961064
&parsed,
9971065
&config,
9981066
&chain,
9991067
&false_positives,
10001068
local_checkout,
1069+
host_repo.as_deref(),
10011070
Some(&metadata),
10021071
&existing_comments,
10031072
)

0 commit comments

Comments
 (0)