feat(identity): confirm registration email atomically
This commit is contained in:
1 parent
8e7ce8d71c
commit
fade4e76e4
75 files changed
+4188
-403
No files matched your search
+2
-7
@@ -8,6 +8,7 @@ REPORTS := $(CURDIR)/reports
|
||||
CACHE := $(CURDIR)/.cache
|
||||
TRIVY ?= $(BIN)/trivy
|
||||
GITLEAKS ?= $(BIN)/gitleaks
|
||||
GITLEAKS_CONFIG ?= $(CURDIR)/gitleaks/gitleaks.toml
|
||||
SEMGREP ?= $(BIN)/semgrep
|
||||
GOVULNCHECK ?= $(BIN)/govulncheck
|
||||
UV ?= uv
|
||||
@@ -60,13 +61,7 @@ filesystem: | $(REPORTS) $(CACHE) ## Scan dependency manifests and infrastructur
|
||||
|
||||
secrets: | $(REPORTS) ## Scan current files and full Git history with redacted output.
|
||||
@rm -f "$(REPORTS)/gitleaks-files.json" "$(REPORTS)/gitleaks-history.json" "$(REPORTS)/gitleaks-version.txt"
|
||||
@test -d "$(ROOT)/.git" -o -f "$(ROOT)/.git" || { echo 'Secret history scanning requires a Git checkout.' >&2; exit 2; }
|
||||
@test "$$(git -C "$(ROOT)" rev-parse --is-shallow-repository)" = false || { echo 'Fetch full Git history before scanning secrets.' >&2; exit 2; }
|
||||
$(GITLEAKS) version > "$(REPORTS)/gitleaks-version.txt"
|
||||
@cd "$(ROOT)"; status=0; \
|
||||
$(GITLEAKS) dir --config security/gitleaks/gitleaks.toml --redact=100 --no-banner --ignore-gitleaks-allow --report-format json --report-path "$(REPORTS)/gitleaks-files.json" . || status=1; \
|
||||
$(GITLEAKS) git --config security/gitleaks/gitleaks.toml --redact=100 --no-banner --ignore-gitleaks-allow --log-opts="--all" --report-format json --report-path "$(REPORTS)/gitleaks-history.json" . || status=1; \
|
||||
exit "$$status"
|
||||
$(PYTHON) "$(CURDIR)/scan_inputs.py" --root "$(ROOT)" --scanner "$(GITLEAKS)" --config "$(GITLEAKS_CONFIG)" --reports "$(REPORTS)"
|
||||
|
||||
go: | $(REPORTS) ## Scan reachable vulnerable Go symbols; preserve the native failing exit status.
|
||||
@rm -f "$(REPORTS)/govulncheck.txt" "$(REPORTS)/govulncheck-version.txt"
|
||||
|
||||
@@ -9,3 +9,86 @@ paths = [
|
||||
'''(^|/)(node_modules|\.venv[^/]*|\.cache|\.mypy_cache|\.ruff_cache|\.pytest_cache|__pycache__|dist|bin)/''',
|
||||
'''^security/(\.bin|\.tools|reports)/''',
|
||||
]
|
||||
|
||||
# These exceptions match one rule, repository path, and complete finding text.
|
||||
|
||||
[[allowlists]]
|
||||
description = "Reason: generated copy of the public OpenAPI request example; owner: project maintainers; expires: 2026-11-07."
|
||||
condition = "AND"
|
||||
regexTarget = "match"
|
||||
targetRules = ["generic-api-key"]
|
||||
paths = ["^api/core/openapi\\.bundle\\.yml$"]
|
||||
regexes = [
|
||||
"^token: q3Zt9b2Kx7LmP4vR8sW1yC6nD0fH5jA2eG9uI3oT7kE$",
|
||||
]
|
||||
|
||||
[[allowlists]]
|
||||
description = "Reason: public OpenAPI request example; owner: project maintainers; expires: 2026-11-07."
|
||||
condition = "AND"
|
||||
regexTarget = "match"
|
||||
targetRules = ["generic-api-key"]
|
||||
paths = ["^api/core/routes/identity_email_verifications\\.yml$"]
|
||||
regexes = [
|
||||
"^token: q3Zt9b2Kx7LmP4vR8sW1yC6nD0fH5jA2eG9uI3oT7kE$",
|
||||
]
|
||||
|
||||
[[allowlists]]
|
||||
description = "Reason: synthetic HTTP test fixture; owner: project maintainers; expires: 2026-11-07."
|
||||
condition = "AND"
|
||||
regexTarget = "match"
|
||||
targetRules = ["generic-api-key"]
|
||||
paths = ["^backend/internal/adapter/primary/http/router_test\\.go$"]
|
||||
regexes = [
|
||||
"^testIdempotencyKey = \"5f0c6a8e-3b0e-4c47-9f4c-2a8f9e5d7c11\"$",
|
||||
"^token\":\"q3Zt9b2Kx7LmP4vR8sW1yC6nD0fH5jA2eG9uI3oT7kE\"$",
|
||||
]
|
||||
|
||||
[[allowlists]]
|
||||
description = "Reason: static Redis rate-limit bucket-key prefix, not an authentication credential; owner: project maintainers; expires: 2026-11-07."
|
||||
condition = "AND"
|
||||
regexTarget = "match"
|
||||
targetRules = ["generic-api-key"]
|
||||
paths = ["^backend/internal/adapter/secondary/redis/ratelimit\\.go$"]
|
||||
regexes = [
|
||||
"^keys, rateLimitKeyPrefix\\+\"$",
|
||||
]
|
||||
|
||||
[[allowlists]]
|
||||
description = "Reason: synthetic password test value; owner: project maintainers; expires: 2026-11-07."
|
||||
condition = "AND"
|
||||
regexTarget = "match"
|
||||
targetRules = ["generic-api-key"]
|
||||
paths = ["^backend/internal/domain/password_test\\.go$"]
|
||||
regexes = [
|
||||
"^testPasswordHash, \"c2FsdHNhbHRzYWx0\"$",
|
||||
]
|
||||
|
||||
[[allowlists]]
|
||||
description = "Reason: synthetic redaction test value; owner: project maintainers; expires: 2026-11-07."
|
||||
condition = "AND"
|
||||
regexTarget = "match"
|
||||
targetRules = ["generic-api-key"]
|
||||
paths = ["^backend/internal/domain/redaction_test\\.go$"]
|
||||
regexes = [
|
||||
"^testPasswordHash, \"c2FsdHNhbHRzYWx0\"$",
|
||||
]
|
||||
|
||||
[[allowlists]]
|
||||
description = "Reason: synthetic generated-client compatibility fixture; owner: project maintainers; expires: 2026-11-07."
|
||||
condition = "AND"
|
||||
regexTarget = "match"
|
||||
targetRules = ["generic-api-key"]
|
||||
paths = ["^backend/testdata/ogen_compat_test\\.go$"]
|
||||
regexes = [
|
||||
"^Idempotency-Key\": \"5f0c6a8e-3b0e-4c47-9f4c-2a8f9e5d7c11\"$",
|
||||
]
|
||||
|
||||
[[allowlists]]
|
||||
description = "Reason: synthetic AWS credential-format release-manifest fixture; owner: project maintainers; expires: 2026-11-07."
|
||||
condition = "AND"
|
||||
regexTarget = "match"
|
||||
targetRules = ["aws-access-token"]
|
||||
paths = ["^deploy/scripts/test_release_manifest\\.py$"]
|
||||
regexes = [
|
||||
"^AKIAABCDEFGHIJKLMNOP$",
|
||||
]
|
||||
@@ -0,0 +1,306 @@
|
||||
"""Prepare and scan the Git-aware input set for Gitleaks."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import contextlib
|
||||
import errno
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import stat
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
class ScanError(Exception):
|
||||
"""Raised when the scanner cannot build or validate its inputs."""
|
||||
|
||||
|
||||
def git_inputs(root: Path) -> list[str]:
|
||||
result = subprocess.run(
|
||||
[
|
||||
"git",
|
||||
"-C",
|
||||
str(root),
|
||||
"ls-files",
|
||||
"-z",
|
||||
"--cached",
|
||||
"--others",
|
||||
"--exclude-standard",
|
||||
],
|
||||
check=False,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
)
|
||||
if result.returncode != 0:
|
||||
raise ScanError("Git could not enumerate current secret-scan inputs.")
|
||||
return sorted(
|
||||
{os.fsdecode(value) for value in result.stdout.split(b"\0") if value},
|
||||
key=os.fsencode,
|
||||
)
|
||||
|
||||
|
||||
def _parts(path: str) -> tuple[str, ...]:
|
||||
parts = tuple(path.split("/"))
|
||||
if not path or path.startswith("/") or any(part in ("", ".", "..") for part in parts):
|
||||
raise ScanError("Git returned an unsafe input path.")
|
||||
return parts
|
||||
|
||||
|
||||
def _open_regular_file(root_fd: int, parts: tuple[str, ...]) -> int | None:
|
||||
if (
|
||||
not hasattr(os, "O_NOFOLLOW")
|
||||
or not hasattr(os, "O_DIRECTORY")
|
||||
or not hasattr(os, "O_NONBLOCK")
|
||||
or os.open not in os.supports_dir_fd
|
||||
):
|
||||
raise ScanError("Safe no-follow file access is unavailable on this platform.")
|
||||
|
||||
directory_fd = os.dup(root_fd)
|
||||
try:
|
||||
for part in parts[:-1]:
|
||||
next_fd = os.open(
|
||||
part,
|
||||
os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW,
|
||||
dir_fd=directory_fd,
|
||||
)
|
||||
os.close(directory_fd)
|
||||
directory_fd = next_fd
|
||||
|
||||
try:
|
||||
file_fd = os.open(
|
||||
parts[-1],
|
||||
os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK,
|
||||
dir_fd=directory_fd,
|
||||
)
|
||||
except OSError as error:
|
||||
if error.errno in (errno.ENOENT, errno.ENOTDIR, errno.ELOOP):
|
||||
return None
|
||||
raise
|
||||
|
||||
if not stat.S_ISREG(os.fstat(file_fd).st_mode):
|
||||
os.close(file_fd)
|
||||
return None
|
||||
return file_fd
|
||||
except OSError as error:
|
||||
if error.errno in (errno.ENOENT, errno.ENOTDIR, errno.ELOOP):
|
||||
return None
|
||||
raise ScanError("A current secret-scan input could not be opened safely.") from error
|
||||
finally:
|
||||
os.close(directory_fd)
|
||||
|
||||
|
||||
def copy_git_inputs(root: Path, destination: Path) -> int:
|
||||
root = root.resolve(strict=True)
|
||||
destination_info = os.lstat(destination)
|
||||
if not stat.S_ISDIR(destination_info.st_mode) or destination_info.st_mode & 0o077:
|
||||
raise ScanError("The temporary scan directory must be a private directory.")
|
||||
|
||||
root_fd = os.open(root, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
|
||||
copied = 0
|
||||
try:
|
||||
for path in git_inputs(root):
|
||||
parts = _parts(path)
|
||||
source_fd = _open_regular_file(root_fd, parts)
|
||||
if source_fd is None:
|
||||
# Deleted tracked files and symlinks are not current file inputs.
|
||||
continue
|
||||
|
||||
target = destination.joinpath(*parts)
|
||||
target_fd: int | None = None
|
||||
target_created = False
|
||||
try:
|
||||
target.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
target_fd = os.open(
|
||||
target,
|
||||
os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW,
|
||||
0o600,
|
||||
)
|
||||
target_created = True
|
||||
with os.fdopen(source_fd, "rb") as source:
|
||||
source_fd = -1
|
||||
with os.fdopen(target_fd, "wb") as output:
|
||||
target_fd = None
|
||||
os.fchmod(output.fileno(), 0o600)
|
||||
shutil.copyfileobj(source, output, length=1024 * 1024)
|
||||
copied += 1
|
||||
except OSError as error:
|
||||
if target_created:
|
||||
with contextlib.suppress(OSError):
|
||||
target.unlink()
|
||||
raise ScanError(
|
||||
"A current secret-scan input could not be copied safely."
|
||||
) from error
|
||||
finally:
|
||||
if source_fd >= 0:
|
||||
os.close(source_fd)
|
||||
if target_fd is not None:
|
||||
os.close(target_fd)
|
||||
finally:
|
||||
os.close(root_fd)
|
||||
return copied
|
||||
|
||||
|
||||
def validate_report(path: Path) -> bool:
|
||||
try:
|
||||
with path.open("r", encoding="utf-8") as report_file:
|
||||
report = json.load(report_file)
|
||||
except (OSError, UnicodeError, json.JSONDecodeError):
|
||||
print(f"Gitleaks report is missing or invalid: {path}", file=sys.stderr)
|
||||
return False
|
||||
|
||||
if not isinstance(report, list) or any(
|
||||
not isinstance(item, dict)
|
||||
or not isinstance(item.get("RuleID"), str)
|
||||
or not isinstance(item.get("File"), str)
|
||||
for item in report
|
||||
):
|
||||
print(f"Gitleaks report has an invalid structure: {path}", file=sys.stderr)
|
||||
return False
|
||||
if report:
|
||||
print(f"Gitleaks report contains findings: {path}", file=sys.stderr)
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def _is_full_git_checkout(root: Path) -> bool:
|
||||
if not (root / ".git").exists():
|
||||
print("Secret history scanning requires a Git checkout.", file=sys.stderr)
|
||||
return False
|
||||
|
||||
repository_root = subprocess.run(
|
||||
["git", "-C", str(root), "rev-parse", "--show-toplevel"],
|
||||
check=False,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.DEVNULL,
|
||||
text=True,
|
||||
)
|
||||
shallow = subprocess.run(
|
||||
["git", "-C", str(root), "rev-parse", "--is-shallow-repository"],
|
||||
check=False,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.DEVNULL,
|
||||
text=True,
|
||||
)
|
||||
if (
|
||||
repository_root.returncode != 0
|
||||
or Path(repository_root.stdout.strip()).resolve() != root
|
||||
or shallow.returncode != 0
|
||||
or shallow.stdout.strip() != "false"
|
||||
):
|
||||
print("Secret history scanning requires a full repository-root checkout.", file=sys.stderr)
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def run_scan(root: Path, scanner: str, config: Path, reports: Path) -> int:
|
||||
root = root.resolve(strict=True)
|
||||
config = config.resolve(strict=True)
|
||||
reports = reports.resolve()
|
||||
reports.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
files_report = reports / "gitleaks-files.json"
|
||||
history_report = reports / "gitleaks-history.json"
|
||||
version_report = reports / "gitleaks-version.txt"
|
||||
for report in (files_report, history_report, version_report):
|
||||
report.unlink(missing_ok=True)
|
||||
|
||||
if os.sep in scanner or (os.altsep and os.altsep in scanner):
|
||||
scanner = str(Path(scanner).resolve())
|
||||
else:
|
||||
scanner = shutil.which(scanner) or scanner
|
||||
|
||||
if not _is_full_git_checkout(root):
|
||||
return 2
|
||||
|
||||
status = 0
|
||||
old_umask = os.umask(0o077)
|
||||
try:
|
||||
with version_report.open("w", encoding="utf-8") as version_file:
|
||||
version = subprocess.run(
|
||||
[scanner, "version"],
|
||||
check=False,
|
||||
stdout=version_file,
|
||||
)
|
||||
if version.returncode != 0:
|
||||
status = 1
|
||||
|
||||
try:
|
||||
with tempfile.TemporaryDirectory(
|
||||
prefix="gitleaks-scan-", dir=os.environ.get("TMPDIR")
|
||||
) as scan_root:
|
||||
scan_path = Path(scan_root)
|
||||
os.chmod(scan_path, 0o700)
|
||||
copy_git_inputs(root, scan_path)
|
||||
current = subprocess.run(
|
||||
[
|
||||
scanner,
|
||||
"dir",
|
||||
"--config",
|
||||
str(config),
|
||||
"--redact=100",
|
||||
"--no-banner",
|
||||
"--ignore-gitleaks-allow",
|
||||
"--report-format",
|
||||
"json",
|
||||
"--report-path",
|
||||
str(files_report),
|
||||
".",
|
||||
],
|
||||
cwd=scan_path,
|
||||
check=False,
|
||||
)
|
||||
if current.returncode != 0:
|
||||
status = 1
|
||||
|
||||
history = subprocess.run(
|
||||
[
|
||||
scanner,
|
||||
"git",
|
||||
"--config",
|
||||
str(config),
|
||||
"--redact=100",
|
||||
"--no-banner",
|
||||
"--ignore-gitleaks-allow",
|
||||
"--log-opts=--all",
|
||||
"--report-format",
|
||||
"json",
|
||||
"--report-path",
|
||||
str(history_report),
|
||||
str(root),
|
||||
],
|
||||
cwd=root,
|
||||
check=False,
|
||||
)
|
||||
if history.returncode != 0:
|
||||
status = 1
|
||||
except (OSError, ScanError) as error:
|
||||
print(f"Gitleaks could not prepare current inputs: {error}", file=sys.stderr)
|
||||
return 1
|
||||
finally:
|
||||
os.umask(old_umask)
|
||||
|
||||
for report in (files_report, history_report):
|
||||
if not validate_report(report):
|
||||
status = 1
|
||||
return status
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--root", type=Path, required=True)
|
||||
parser.add_argument("--scanner", required=True)
|
||||
parser.add_argument("--config", type=Path, required=True)
|
||||
parser.add_argument("--reports", type=Path, required=True)
|
||||
args = parser.parse_args()
|
||||
try:
|
||||
return run_scan(args.root, args.scanner, args.config, args.reports)
|
||||
except (OSError, ScanError) as error:
|
||||
print(f"Gitleaks check failed: {error}", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -4,6 +4,9 @@ import contextlib
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import secrets
|
||||
import subprocess
|
||||
import sys
|
||||
import tarfile
|
||||
@@ -13,6 +16,7 @@ from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
import install
|
||||
import scan_inputs
|
||||
|
||||
SECURITY = Path(__file__).resolve().parents[1]
|
||||
|
||||
@@ -25,6 +29,285 @@ class SecurityChecksTest(unittest.TestCase):
|
||||
self.addCleanup(self.temporary.cleanup)
|
||||
self.folder = Path(self.temporary.name)
|
||||
|
||||
def _init_git_repo(self, root: Path) -> None:
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
subprocess.run(["git", "init", str(root)], check=True, capture_output=True)
|
||||
identity = (
|
||||
("user.name", "Security Test"),
|
||||
("user.email", "security-test@example.invalid"),
|
||||
)
|
||||
for key, value in identity:
|
||||
subprocess.run(
|
||||
["git", "-C", str(root), "config", key, value],
|
||||
check=True,
|
||||
capture_output=True,
|
||||
)
|
||||
|
||||
def _commit(self, root: Path) -> None:
|
||||
subprocess.run(["git", "-C", str(root), "add", "-A"], check=True, capture_output=True)
|
||||
subprocess.run(
|
||||
["git", "-C", str(root), "commit", "-m", "fixture"],
|
||||
check=True,
|
||||
capture_output=True,
|
||||
)
|
||||
|
||||
def _run_gitleaks_make(
|
||||
self,
|
||||
root: Path,
|
||||
reports: Path,
|
||||
scanner: Path,
|
||||
*,
|
||||
config: Path | None = None,
|
||||
) -> subprocess.CompletedProcess[str]:
|
||||
env = os.environ.copy()
|
||||
env.setdefault("TMPDIR", str(self.folder))
|
||||
return subprocess.run(
|
||||
[
|
||||
"make",
|
||||
"-C",
|
||||
str(SECURITY),
|
||||
"secrets",
|
||||
f"ROOT={root}",
|
||||
f"REPORTS={reports}",
|
||||
f"GITLEAKS={scanner}",
|
||||
f"GITLEAKS_CONFIG={config or SECURITY / 'gitleaks/gitleaks.toml'}",
|
||||
],
|
||||
env=env,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
)
|
||||
|
||||
def test_current_input_copy_keeps_tracked_ignored_files_and_skips_unsafe_inputs(self) -> None:
|
||||
root = self.folder / "copy-repo"
|
||||
self._init_git_repo(root)
|
||||
(root / ".gitignore").write_text(".env\nignored-*\n", encoding="utf-8")
|
||||
(root / "tracked.txt").write_text("tracked fixture\n", encoding="utf-8")
|
||||
(root / ".env").write_text("tracked ignored fixture\n", encoding="utf-8")
|
||||
(root / "deleted.txt").write_text("deleted fixture\n", encoding="utf-8")
|
||||
outside = self.folder / "outside.txt"
|
||||
outside.write_text("outside fixture\n", encoding="utf-8")
|
||||
(root / "outside-link").symlink_to(outside)
|
||||
subprocess.run(
|
||||
[
|
||||
"git",
|
||||
"-C",
|
||||
str(root),
|
||||
"add",
|
||||
".gitignore",
|
||||
"tracked.txt",
|
||||
"deleted.txt",
|
||||
"outside-link",
|
||||
],
|
||||
check=True,
|
||||
capture_output=True,
|
||||
)
|
||||
subprocess.run(
|
||||
["git", "-C", str(root), "add", "-f", ".env"],
|
||||
check=True,
|
||||
capture_output=True,
|
||||
)
|
||||
self._commit(root)
|
||||
(root / "deleted.txt").unlink()
|
||||
(root / "incoming $(touch marker).txt").write_text(
|
||||
"untracked fixture\n", encoding="utf-8"
|
||||
)
|
||||
(root / "ignored-local.txt").write_text("ignored fixture\n", encoding="utf-8")
|
||||
fifo = root / "untracked-pipe"
|
||||
if hasattr(os, "mkfifo"):
|
||||
os.mkfifo(fifo)
|
||||
|
||||
destination = self.folder / "private-scan"
|
||||
destination.mkdir(mode=0o700)
|
||||
os.chmod(destination, 0o700)
|
||||
copied = scan_inputs.copy_git_inputs(root, destination)
|
||||
|
||||
self.assertGreater(copied, 0)
|
||||
self.assertTrue((destination / ".env").is_file())
|
||||
self.assertTrue((destination / "incoming $(touch marker).txt").is_file())
|
||||
self.assertFalse((destination / "ignored-local.txt").exists())
|
||||
self.assertFalse((destination / "deleted.txt").exists())
|
||||
self.assertFalse((destination / "outside-link").exists())
|
||||
self.assertFalse((self.folder / "marker").exists())
|
||||
if hasattr(os, "mkfifo"):
|
||||
self.assertFalse((destination / "untracked-pipe").exists())
|
||||
self.assertEqual((destination / ".env").stat().st_mode & 0o777, 0o600)
|
||||
self.assertEqual(destination.stat().st_mode & 0o777, 0o700)
|
||||
self.assertEqual(outside.read_text(encoding="utf-8"), "outside fixture\n")
|
||||
|
||||
def test_gitleaks_reports_findings_and_keeps_full_history_scan(self) -> None:
|
||||
scanner = SECURITY / ".bin" / "gitleaks"
|
||||
if not scanner.is_file():
|
||||
self.skipTest("local Gitleaks binary is not installed")
|
||||
|
||||
root = self.folder / "scan-repo"
|
||||
self._init_git_repo(root)
|
||||
(root / ".gitignore").write_text(".env\n", encoding="utf-8")
|
||||
(root / ".env").write_text(
|
||||
"API_KEY=synthetic" + secrets.token_hex(24) + "\n", encoding="utf-8"
|
||||
)
|
||||
subprocess.run(
|
||||
["git", "-C", str(root), "add", ".gitignore"],
|
||||
check=True,
|
||||
capture_output=True,
|
||||
)
|
||||
subprocess.run(
|
||||
["git", "-C", str(root), "add", "-f", ".env"],
|
||||
check=True,
|
||||
capture_output=True,
|
||||
)
|
||||
self._commit(root)
|
||||
|
||||
(root / "incoming $(touch marker).txt").write_text(
|
||||
"API_KEY=synthetic" + secrets.token_hex(24) + "\n", encoding="utf-8"
|
||||
)
|
||||
outside = self.folder / "outside-secret.txt"
|
||||
outside.write_text(
|
||||
"API_KEY=synthetic" + secrets.token_hex(24) + "\n", encoding="utf-8"
|
||||
)
|
||||
(root / "outside-link").symlink_to(outside)
|
||||
reports = self.folder / "gitleaks-reports"
|
||||
|
||||
result = self._run_gitleaks_make(root, reports, scanner)
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
current = json.loads((reports / "gitleaks-files.json").read_text(encoding="utf-8"))
|
||||
history = json.loads((reports / "gitleaks-history.json").read_text(encoding="utf-8"))
|
||||
current_paths = {item["File"] for item in current}
|
||||
history_paths = {item["File"] for item in history}
|
||||
self.assertIn(".env", current_paths)
|
||||
self.assertIn("incoming $(touch marker).txt", current_paths)
|
||||
self.assertNotIn("outside-link", current_paths)
|
||||
self.assertIn(".env", history_paths)
|
||||
self.assertFalse((self.folder / "marker").exists())
|
||||
self.assertEqual((reports / "gitleaks-files.json").stat().st_mode & 0o777, 0o600)
|
||||
|
||||
(root / "incoming $(touch marker).txt").unlink()
|
||||
subprocess.run(
|
||||
["git", "-C", str(root), "rm", "--cached", ".env"],
|
||||
check=True,
|
||||
capture_output=True,
|
||||
)
|
||||
(root / ".env").write_text(
|
||||
"API_KEY=synthetic" + secrets.token_hex(24) + "\n", encoding="utf-8"
|
||||
)
|
||||
result = self._run_gitleaks_make(root, reports, scanner)
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
current = json.loads((reports / "gitleaks-files.json").read_text(encoding="utf-8"))
|
||||
history = json.loads((reports / "gitleaks-history.json").read_text(encoding="utf-8"))
|
||||
self.assertEqual(current, [])
|
||||
self.assertIn(".env", {item["File"] for item in history})
|
||||
|
||||
def test_gitleaks_allowlist_requires_exact_path_match_and_rule(self) -> None:
|
||||
scanner = SECURITY / ".bin" / "gitleaks"
|
||||
if not scanner.is_file():
|
||||
self.skipTest("local Gitleaks binary is not installed")
|
||||
|
||||
allowed_path = Path("deploy/scripts/test_release_manifest.py")
|
||||
config_text = (SECURITY / "gitleaks/gitleaks.toml").read_text(encoding="utf-8")
|
||||
exception = next(
|
||||
section
|
||||
for section in config_text.split("[[allowlists]]")
|
||||
if "test_release_manifest" in section
|
||||
)
|
||||
regex_section = exception.split("regexes = [", 1)[1].split("]", 1)[0]
|
||||
regex_match = re.search(r'^\s*"([^"\n]+)"', regex_section, flags=re.MULTILINE)
|
||||
self.assertIsNotNone(regex_match)
|
||||
pattern = regex_match.group(1)
|
||||
self.assertTrue(pattern.startswith("^") and pattern.endswith("$"))
|
||||
fixture_line = pattern[1:-1]
|
||||
self.assertTrue(fixture_line.startswith("AKIA") and fixture_line.isalnum())
|
||||
source = (SECURITY.parent / allowed_path).read_text(encoding="utf-8")
|
||||
self.assertTrue(fixture_line in source)
|
||||
|
||||
root = self.folder / "allowlist-repo"
|
||||
self._init_git_repo(root)
|
||||
(root / "clean.txt").write_text("clean history fixture\n", encoding="utf-8")
|
||||
self._commit(root)
|
||||
(root / allowed_path).parent.mkdir(parents=True)
|
||||
changed_fixture = fixture_line[:-1] + ("Z" if fixture_line[-1] != "Z" else "Y")
|
||||
(root / allowed_path).write_text(
|
||||
fixture_line
|
||||
+ "\n"
|
||||
+ changed_fixture
|
||||
+ "\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
(root / "unrelated.txt").write_text(fixture_line + "\n", encoding="utf-8")
|
||||
|
||||
config = self.folder / "target-rule-config.toml"
|
||||
config.write_text(
|
||||
config_text
|
||||
+ "\n[[rules]]\n"
|
||||
+ 'id = "fixture-literal"\n'
|
||||
+ 'description = "Test rule for allowlist target scope"\n'
|
||||
+ f"regex = '''(?m)^{fixture_line}$'''\n"
|
||||
+ "secretGroup = 0\n"
|
||||
+ 'keywords = ["AKIA"]\n',
|
||||
encoding="utf-8",
|
||||
)
|
||||
reports = self.folder / "allowlist-reports"
|
||||
|
||||
result = self._run_gitleaks_make(root, reports, scanner, config=config)
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
current = json.loads((reports / "gitleaks-files.json").read_text(encoding="utf-8"))
|
||||
finding_pairs = {(item["RuleID"], item["File"]) for item in current}
|
||||
allowed_name = allowed_path.as_posix()
|
||||
self.assertIn(("aws-access-token", allowed_name), finding_pairs)
|
||||
self.assertIn(("aws-access-token", "unrelated.txt"), finding_pairs)
|
||||
self.assertIn(("fixture-literal", allowed_name), finding_pairs)
|
||||
self.assertIn(("fixture-literal", "unrelated.txt"), finding_pairs)
|
||||
allowed_rule_count = sum(
|
||||
item["RuleID"] == "aws-access-token" and item["File"] == allowed_name
|
||||
for item in current
|
||||
)
|
||||
self.assertEqual(allowed_rule_count, 1)
|
||||
|
||||
def test_gitleaks_missing_malformed_nonzero_and_nonempty_reports_fail(self) -> None:
|
||||
root = self.folder / "fake-scan-repo"
|
||||
self._init_git_repo(root)
|
||||
(root / "clean.txt").write_text("clean fixture\n", encoding="utf-8")
|
||||
self._commit(root)
|
||||
|
||||
for mode in ("missing", "malformed", "nonzero", "finding"):
|
||||
with self.subTest(mode=mode):
|
||||
scanner = self.folder / f"scanner-{mode}"
|
||||
scanner.write_text(
|
||||
f"#!{sys.executable}\n"
|
||||
"import json, sys\n"
|
||||
"from pathlib import Path\n"
|
||||
f"mode = {mode!r}\n"
|
||||
"args = sys.argv[1:]\n"
|
||||
"if args == ['version']:\n"
|
||||
" print('synthetic scanner')\n"
|
||||
" raise SystemExit(0)\n"
|
||||
"report_path = Path(args[args.index('--report-path') + 1])\n"
|
||||
"if args[0] == 'dir' and mode == 'missing':\n"
|
||||
" raise SystemExit(0)\n"
|
||||
"if args[0] == 'dir' and mode == 'malformed':\n"
|
||||
" report_path.write_text('{', encoding='utf-8')\n"
|
||||
" raise SystemExit(0)\n"
|
||||
"if args[0] == 'dir' and mode == 'nonzero':\n"
|
||||
" report_path.write_text('[]', encoding='utf-8')\n"
|
||||
" raise SystemExit(17)\n"
|
||||
"if args[0] == 'dir' and mode == 'finding':\n"
|
||||
" report_path.write_text(\n"
|
||||
" json.dumps([{'RuleID': 'generic-api-key', 'File': 'fixture.txt'}]),\n"
|
||||
" encoding='utf-8'\n"
|
||||
" )\n"
|
||||
" raise SystemExit(0)\n"
|
||||
"report_path.write_text('[]', encoding='utf-8')\n"
|
||||
"raise SystemExit(0)\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
scanner.chmod(0o700)
|
||||
reports = self.folder / f"reports-{mode}"
|
||||
reports.mkdir()
|
||||
for name in ("gitleaks-files.json", "gitleaks-history.json"):
|
||||
(reports / name).write_text("stale report", encoding="utf-8")
|
||||
result = self._run_gitleaks_make(root, reports, scanner)
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertTrue((reports / "gitleaks-version.txt").is_file())
|
||||
|
||||
def test_installer_rejects_checksum_mismatch_without_replacing_binary(self) -> None:
|
||||
binary_dir = self.folder / ".bin"
|
||||
binary_dir.mkdir()
|
||||
|
||||
Reference in new issue
Block a user