From 247ab55b6c5d8a44355b48b9b45c9b2788bfd9a0 Mon Sep 17 00:00:00 2001 From: galion96 Date: Sun, 6 Dec 2026 19:10:49 +0100 Subject: [PATCH] Refuse Terraform state in the local preflight Terraform state files store resource attributes such as passwords and private keys in plaintext, but contain none of the token prefixes the line scanner recognises. Refuse *.tfstate, *.tfstate.backup and paths under .terraform/ before upload, with the same exact-path --allow-path override as .env. The committed .terraform.lock.hcl stays reviewable. --- README.md | 2 +- src/preflight.rs | 134 ++++++++++++++++++++++++++++++++++++++++++- tests/local_patch.rs | 43 ++++++++++++++ 3 files changed, 177 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index fbbac1b..2f8b857 100644 --- a/README.md +++ b/README.md @@ -64,7 +64,7 @@ Native knowledge, fix and configuration commands send the selected organization ## Reviews, history, and reruns -`proofline review --path src/main.rs` reviews only that file's local changes against the normal merge-base. The path is literal and repository-relative; the command refuses directories, globs, and `..`. Combine it with `--staged` to read the index, or `--include-untracked` to select a new, non-ignored file. The command preserves the real index and applies the usual secret preflight. You cannot combine `--path` with pushed-commit, range, or pull-request review. +`proofline review --path src/main.rs` reviews only that file's local changes against the normal merge-base. The path is literal and repository-relative; the command refuses directories, globs, and `..`. Combine it with `--staged` to read the index, or `--include-untracked` to select a new, non-ignored file. The command preserves the real index and applies the usual secret preflight, which also refuses Terraform state (`*.tfstate`, `*.tfstate.backup` and files under `.terraform/`) unless each exact path is passed to `--allow-path`. You cannot combine `--path` with pushed-commit, range, or pull-request review. `proofline reviews --repository-id UUID --cursor CURSOR` returns one page with its continuation metadata, and all flags are optional. `proofline routing REVIEW_ID` reads recorded routing. `proofline run --repo owner/name --pr 7 --run 2` reads one retained run, and `proofline history --repo owner/name --pr 7` reads all recorded runs. These commands can find the reviews your token can still read after a repository disconnects. With a clone URL or Git remote, they resolve the project on its registered host and read its runs by repository ID. A repository with no reviews in the organization exits nonzero. `proofline findings --pr 7` finds the pull request's newest review through the same route and counts only runs of the repository whose full name matches. None of these commands reads the organization's review list. diff --git a/src/preflight.rs b/src/preflight.rs index 592ec54..1c5bb9d 100644 --- a/src/preflight.rs +++ b/src/preflight.rs @@ -12,6 +12,10 @@ pub(crate) enum PreflightError { "local patch includes the sensitive .env path {0:?}; remove it before upload, or pass --allow-path for that exact path" )] EnvironmentPath(String), + #[error( + "local patch includes the Terraform state path {0:?}, which stores resource attributes such as passwords and keys in plaintext; remove it before upload, or pass --allow-path for that exact path" + )] + TerraformStatePath(String), #[error( "local patch contains {kind} at {path:?}:{line} ({coordinate}); remove it before upload, or pass --allow-path for that exact path" )] @@ -44,6 +48,7 @@ pub(crate) fn check(changes: &LocalChanges, allowed: &[String]) -> Result<(), Pr if line.starts_with("diff --git ") { let file = paths.next().ok_or(PreflightError::InvalidPatch)?; environment_paths(file, allowed)?; + terraform_state_paths(file, allowed)?; current = Some(file); hunk = None; continue; @@ -86,6 +91,36 @@ fn environment_paths(file: &PatchPaths, allowed: &[String]) -> Result<(), Prefli Ok(()) } +/// Terraform state, its backups, per-workspace state, and the `.terraform` +/// working directory (which caches backend state and configuration) carry +/// resource attributes in plaintext. The lock file `.terraform.lock.hcl` is +/// meant to be committed and stays reviewable. +fn terraform_state_paths(file: &PatchPaths, allowed: &[String]) -> Result<(), PreflightError> { + for path in [&file.old, &file.new] + .iter() + .filter_map(|path| path.as_deref()) + { + if !is_allowed(path, allowed) && is_terraform_state(path) { + return Err(PreflightError::TerraformStatePath(path.to_owned())); + } + } + Ok(()) +} + +fn is_terraform_state(path: &str) -> bool { + let mut parts = path.split('/').peekable(); + while let Some(part) = parts.next() { + if parts.peek().is_some() { + if part == ".terraform" { + return true; + } + } else { + return part.ends_with(".tfstate") || part.ends_with(".tfstate.backup"); + } + } + false +} + fn hunk_lines(line: &str) -> Result { let mut fields = line.split_whitespace(); if fields.next() != Some("@@") { @@ -291,7 +326,104 @@ fn secret_shape(text: &str) -> Option<&'static str> { #[cfg(test)] mod tests { - use super::secret_shape; + use super::{PreflightError, check, is_terraform_state, secret_shape}; + use crate::git::{LocalChanges, PatchPaths}; + + fn changes(old: Option<&str>, new: Option<&str>) -> LocalChanges { + let a = old.or(new).unwrap(); + let b = new.or(old).unwrap(); + LocalChanges { + base_commit_sha: "0".repeat(40), + patch: format!("diff --git a/{a} b/{b}\n"), + paths: vec![PatchPaths { + old: old.map(str::to_owned), + new: new.map(str::to_owned), + }], + } + } + + #[test] + fn terraform_state_paths_are_recognised_but_lock_files_and_sources_are_not() { + for path in [ + "terraform.tfstate", + "infra/prod/terraform.tfstate", + "terraform.tfstate.backup", + "infra/terraform.tfstate.d/staging/terraform.tfstate", + "exported.tfstate", + ".terraform/terraform.tfstate", + "infra/.terraform/providers/registry.terraform.io/hashicorp/aws/plugin", + ] { + assert!(is_terraform_state(path), "{path}"); + } + for path in [ + ".terraform.lock.hcl", + "infra/.terraform.lock.hcl", + "main.tf", + "infra/terraform.tfvars", + "docs/tfstate.md", + "terraform.tfstate.md", + ".terraform", + "notes/.terraform-version", + ] { + assert!(!is_terraform_state(path), "{path}"); + } + } + + #[test] + fn terraform_state_is_refused_on_add_delete_and_both_rename_endpoints() { + let cases = [ + ( + None, + Some("infra/terraform.tfstate"), + "infra/terraform.tfstate", + ), + ( + Some("infra/terraform.tfstate"), + None, + "infra/terraform.tfstate", + ), + ( + Some("state/old.tfstate"), + Some("state/old.json"), + "state/old.tfstate", + ), + ( + Some("state/old.json"), + Some("state/new.tfstate"), + "state/new.tfstate", + ), + ]; + for (old, new, refused) in cases { + match check(&changes(old, new), &[]) { + Err(PreflightError::TerraformStatePath(path)) => assert_eq!(path, refused), + other => panic!("{old:?} -> {new:?}: {other:?}"), + } + } + } + + #[test] + fn terraform_state_needs_every_exact_endpoint_allowed() { + let rename = changes(Some("old.tfstate"), Some("infra/new.tfstate")); + let error = check(&rename, &["old.tfstate".to_owned()]).unwrap_err(); + assert!( + matches!(error, PreflightError::TerraformStatePath(path) if path == "infra/new.tfstate") + ); + let error = check(&rename, &["infra".to_owned()]).unwrap_err(); + assert!(matches!(error, PreflightError::TerraformStatePath(path) if path == "old.tfstate")); + check( + &rename, + &["old.tfstate".to_owned(), "infra/new.tfstate".to_owned()], + ) + .unwrap(); + let message = check(&changes(None, Some("terraform.tfstate")), &[]) + .unwrap_err() + .to_string(); + assert!( + message.contains("Terraform state path \"terraform.tfstate\""), + "{message}" + ); + assert!(message.contains("--allow-path"), "{message}"); + } #[test] fn credential_families_refuse_minimum_bodies_but_accept_short_or_invalid_ones() { diff --git a/tests/local_patch.rs b/tests/local_patch.rs index 1c41110..ce4c316 100644 --- a/tests/local_patch.rs +++ b/tests/local_patch.rs @@ -722,6 +722,49 @@ async fn exact_overrides_keep_other_paths_blocked_and_upload_the_original_patch( server.close().await; } +#[tokio::test] +async fn terraform_state_refuses_before_http_and_keeps_the_lock_file_reviewable() { + let password = "db-password-from-state"; + let checkout = Checkout::new(&[]).await; + checkout + .write( + "infra/terraform.tfstate", + &format!("{{\"resources\":[{{\"password\":\"{password}\"}}]}}\n"), + ) + .await; + checkout + .write("infra/.terraform.lock.hcl", "# provider locks\n") + .await; + checkout + .write("infra/main.tf", "resource \"null\" \"x\" {}\n") + .await; + let expected = checkout.staged_patch().await; + assert!(expected.contains(password)); + let index = checkout.index().await; + let server = Server::start(true).await; + let output = checkout.review(&server, &[], &[]).await; + assert_refusal( + &output, + "Terraform state path \"infra/terraform.tfstate\"", + password, + ); + server.assert_no_requests(); + assert_eq!(checkout.index().await, index); + let output = checkout + .review(&server, &["infra/terraform.tfstate"], &[]) + .await; + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + assert_eq!( + *server.fixture.uploads.lock().unwrap(), + vec![json!({ "base_commit_sha": checkout.base, "patch": expected })] + ); + server.close().await; +} + #[tokio::test] async fn a_sensitive_rename_requires_both_exact_endpoints() { let private = "-----BEGIN PRIVATE KEY-----";