feat(identity): confirm registration email atomically

This commit is contained in:
TakuyaYagam1 committed 2026-10-07 09:12:15 +03:00
1 parent 8e7ce8d71c
commit fade4e76e4
75 files changed
+4188 -403

No files matched your search

+283
View File
@@ -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()