refactor(backend): standardize errors and simplify configuration and test setup

This commit is contained in:
TakuyaYagam1 committed 2026-10-05 16:15:30 +03:00
1 parent 1535c19b8c
commit 138666a7bb
92 files changed
+3994 -210

No files matched your search

+5
View File
@@ -0,0 +1,5 @@
/.bin/
/.tools/
/.cache/
/reports/
/__pycache__/
+96
View File
@@ -0,0 +1,96 @@
SHELL := /usr/bin/env bash
.SHELLFLAGS := -eu -o pipefail -c
.DEFAULT_GOAL := help
ROOT := $(abspath ..)
BIN := $(CURDIR)/.bin
REPORTS := $(CURDIR)/reports
CACHE := $(CURDIR)/.cache
TRIVY ?= $(BIN)/trivy
GITLEAKS ?= $(BIN)/gitleaks
SEMGREP ?= $(BIN)/semgrep
GOVULNCHECK ?= $(BIN)/govulncheck
UV ?= uv
GO ?= go
DOCKER ?= docker
PYTHON ?= python3
export SEMGREP_SEND_METRICS := off
export SEMGREP_ENABLE_VERSION_CHECK := 0
.PHONY: help install install-trivy install-gitleaks install-semgrep install-go check filesystem secrets go semgrep test rule-test images
help: ## Show security commands.
@awk 'BEGIN {FS = ":.*## "} /^[a-zA-Z0-9_-]+:.*## / {printf "%-18s %s\n", $$1, $$2}' $(MAKEFILE_LIST)
install: ## Install current stable scanners locally without changing global tools.
$(MAKE) install-trivy install-gitleaks install-semgrep install-go
install-trivy: ## Install the latest stable Trivy release with SHA256 verification.
$(PYTHON) install.py trivy
install-gitleaks: ## Install the latest stable Gitleaks release with SHA256 verification.
$(PYTHON) install.py gitleaks
install-semgrep: ## Install Semgrep in an isolated uv tool environment.
UV_TOOL_DIR="$(CURDIR)/.tools" UV_TOOL_BIN_DIR="$(BIN)" UV_PYTHON_INSTALL_DIR="$(CURDIR)/.tools/python" UV_CACHE_DIR="$(CACHE)/uv" $(UV) tool install --python 3.13 --upgrade semgrep
install-go: ## Install the current govulncheck without modifying the backend module.
GOBIN="$(BIN)" $(GO) install golang.org/x/vuln/cmd/govulncheck@latest
$(REPORTS) $(CACHE):
mkdir -p "$@"
check: ## Run every source check and fail if any scanner fails or reports blocking findings.
@status=0; for target in filesystem secrets go semgrep; do \
$(MAKE) "$$target" || status=1; \
done; exit "$$status"
filesystem: | $(REPORTS) $(CACHE) ## Scan dependency manifests and infrastructure configuration.
@rm -f "$(REPORTS)/trivy-filesystem.json" "$(REPORTS)/trivy-version.txt"
@cd "$(ROOT)"; status=0; \
$(TRIVY) fs --config security/trivy/filesystem.yml --cache-dir "$(CACHE)/trivy" --output "$(REPORTS)/trivy-filesystem.json" . || status=$$?; \
$(TRIVY) --cache-dir "$(CACHE)/trivy" --version > "$(REPORTS)/trivy-version.txt" || status=1; \
exit "$$status"
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"
go: | $(REPORTS) ## Scan reachable vulnerable Go symbols; preserve the native failing exit status.
@rm -f "$(REPORTS)/govulncheck.txt" "$(REPORTS)/govulncheck-version.txt"
$(GOVULNCHECK) -version > "$(REPORTS)/govulncheck-version.txt"
cd "$(ROOT)/backend" && $(GOVULNCHECK) ./... 2>&1 | tee "$(REPORTS)/govulncheck.txt"
semgrep: | $(REPORTS) ## Check frontend and ML source with reviewed local rules.
@rm -f "$(REPORTS)/semgrep.json" "$(REPORTS)/semgrep-version.txt"
$(SEMGREP) --version > "$(REPORTS)/semgrep-version.txt"
cd "$(ROOT)" && $(SEMGREP) scan --strict --error --disable-nosem --metrics off --config security/semgrep/frontend.yml --config security/semgrep/python.yml --json-output "$(REPORTS)/semgrep.json" frontend/src ml/src
rule-test: ## Validate security rules against positive and negative fixtures.
cd "$(ROOT)" && $(SEMGREP) --test --metrics off --config security/semgrep security/semgrep/tests
test: rule-test ## Check rule fixtures, installer integrity, and scanner failure handling.
PYTHONDONTWRITEBYTECODE=1 $(PYTHON) -m unittest discover -s tests
images: | $(REPORTS) $(CACHE) ## Build and scan the exact backend, frontend, and ML images without publishing.
@for service in backend frontend ml; do rm -f "$(REPORTS)/trivy-$$service.json" "$(REPORTS)/$$service-image-id.txt"; done
@rm -f "$(REPORTS)/trivy-version.txt"
$(TRIVY) --cache-dir "$(CACHE)/trivy" --version > "$(REPORTS)/trivy-version.txt"
@status=0; for service in backend frontend ml; do \
tag="lincodex-security-$$service:local"; \
context="$(ROOT)"; if [ "$$service" = backend ]; then context="$(ROOT)/backend"; fi; \
if $(DOCKER) build --pull -f "$(ROOT)/$$service/Dockerfile" -t "$$tag" "$$context"; then \
if image_id=$$($(DOCKER) image inspect --format '{{.Id}}' "$$tag"); then \
printf '%s\n' "$$image_id" > "$(REPORTS)/$$service-image-id.txt"; \
$(TRIVY) image --image-src docker --config trivy/image.yml --cache-dir "$(CACHE)/trivy" --output "$(REPORTS)/trivy-$$service.json" "$$image_id" || status=1; \
else status=1; fi; \
else status=1; fi; \
done; \
$(TRIVY) --cache-dir "$(CACHE)/trivy" --version > "$(REPORTS)/trivy-version.txt" || status=1; \
exit "$$status"
+11
View File
@@ -0,0 +1,11 @@
title = "Lincodex secret scanning"
[extend]
useDefault = true
[[allowlists]]
description = "Local dependencies, scanner tools, and build outputs"
paths = [
'''(^|/)(node_modules|\.venv[^/]*|\.cache|\.mypy_cache|\.ruff_cache|\.pytest_cache|__pycache__|dist|bin)/''',
'''^security/(\.bin|\.tools|reports)/''',
]
+78
View File
@@ -0,0 +1,78 @@
"""Install release binaries locally after checking upstream SHA256 manifests."""
import argparse
import hashlib
import io
import json
import os
import platform
import re
import tarfile
import urllib.request
from pathlib import Path
def download(url: str) -> bytes:
request = urllib.request.Request(url, headers={"User-Agent": "lincodex-security"})
with urllib.request.urlopen(request, timeout=120) as response:
return response.read()
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("tool", choices=["trivy", "gitleaks"])
args = parser.parse_args()
system = platform.system()
machine = platform.machine()
if system != "Linux" or machine not in {"x86_64", "aarch64", "arm64"}:
parser.error("The binary installer supports Linux amd64/arm64.")
owner = "aquasecurity" if args.tool == "trivy" else "gitleaks"
repository = f"{owner}/{args.tool}"
release = json.loads(
download(f"https://api.github.com/repos/{repository}/releases/latest")
)
tag = release["tag_name"]
if not re.fullmatch(r"v\d+\.\d+\.\d+", tag):
raise ValueError(f"Unexpected stable release tag: {tag}")
version = tag.removeprefix("v")
if args.tool == "trivy":
arch = "64bit" if machine == "x86_64" else "ARM64"
archive_name = f"trivy_{version}_Linux-{arch}.tar.gz"
else:
arch = "x64" if machine == "x86_64" else "arm64"
archive_name = f"gitleaks_{version}_linux_{arch}.tar.gz"
base = f"https://github.com/{repository}/releases/download/{tag}"
manifest = download(f"{base}/{args.tool}_{version}_checksums.txt").decode()
checksums = {}
for line in manifest.splitlines():
fields = line.split()
if len(fields) == 2:
checksums[fields[1].lstrip("*")] = fields[0]
archive = download(f"{base}/{archive_name}")
expected = checksums.get(archive_name)
if expected is None or hashlib.sha256(archive).hexdigest() != expected:
raise ValueError(f"SHA256 verification failed for {archive_name}")
destination = Path(__file__).resolve().parent / ".bin"
destination.mkdir(exist_ok=True)
with tarfile.open(fileobj=io.BytesIO(archive), mode="r:gz") as bundle:
member = bundle.getmember(args.tool)
if not member.isfile():
raise ValueError("Expected a regular executable in the release archive")
binary = bundle.extractfile(member)
if binary is None:
raise ValueError("Release executable is missing")
temporary = destination / f".{args.tool}.download"
try:
temporary.write_bytes(binary.read())
temporary.chmod(0o755)
os.replace(temporary, destination / args.tool)
finally:
temporary.unlink(missing_ok=True)
print(f"Installed {args.tool} {version}; SHA256 verified.")
if __name__ == "__main__":
main()
+25
View File
@@ -0,0 +1,25 @@
rules:
- id: frontend-no-dynamic-code
languages: [javascript, typescript]
message: Avoid eval and Function constructors. Use explicit functions and JSON.parse for data.
severity: ERROR
pattern-either:
- pattern: eval(...)
- pattern: new Function(...)
- pattern: Function(...)
- id: frontend-no-document-write
languages: [javascript, typescript]
message: Avoid document.write and document.writeln. Render content through React.
severity: ERROR
pattern-either:
- pattern: document.write(...)
- pattern: document.writeln(...)
- id: frontend-no-inner-html-assignment
languages: [javascript, typescript]
message: Avoid direct innerHTML assignments. Use textContent or React rendering.
severity: ERROR
pattern-either:
- pattern: $TARGET.innerHTML = $VALUE
- pattern: $TARGET.innerHTML += $VALUE
+55
View File
@@ -0,0 +1,55 @@
rules:
- id: python-no-dynamic-code
languages: [python]
message: Avoid eval and exec. Parse structured data instead of executing input.
severity: ERROR
pattern-either:
- pattern: eval(...)
- pattern: exec(...)
- id: python-safe-yaml-loader
languages: [python]
message: Use yaml.safe_load, yaml.safe_load_all, or an explicit SafeLoader or CSafeLoader.
severity: ERROR
patterns:
- pattern-either:
- pattern: yaml.load(...)
- pattern: yaml.load_all(...)
- pattern-not: yaml.load(..., Loader=yaml.SafeLoader, ...)
- pattern-not: yaml.load(..., Loader=yaml.CSafeLoader, ...)
- pattern-not: yaml.load_all(..., Loader=yaml.SafeLoader, ...)
- pattern-not: yaml.load_all(..., Loader=yaml.CSafeLoader, ...)
- pattern-not: yaml.load($DATA, yaml.SafeLoader)
- pattern-not: yaml.load($DATA, yaml.CSafeLoader)
- pattern-not: yaml.load_all($DATA, yaml.SafeLoader)
- pattern-not: yaml.load_all($DATA, yaml.CSafeLoader)
- id: python-no-subprocess-shell
languages: [python]
message: Pass an argument list to subprocess without shell=True.
severity: ERROR
patterns:
- pattern: subprocess.$CALL(..., shell=True, ...)
- metavariable-regex:
metavariable: $CALL
regex: ^(run|Popen|call|check_call|check_output)$
- id: python-no-disabled-tls
languages: [python]
message: Keep TLS certificate verification enabled in requests and httpx.
severity: ERROR
patterns:
- pattern-either:
- pattern: requests.$CALL(..., verify=False, ...)
- pattern: httpx.$CALL(..., verify=False, ...)
- metavariable-regex:
metavariable: $CALL
regex: ^(request|get|post|put|patch|delete|head|options|stream|Client|AsyncClient)$
- id: python-no-pickle-load
languages: [python]
message: Avoid pickle deserialization for service data. Use a non-executable format such as JSON.
severity: ERROR
pattern-either:
- pattern: pickle.load(...)
- pattern: pickle.loads(...)
+26
View File
@@ -0,0 +1,26 @@
// Static scanner fixtures. Never execute this file.
function dynamicCode(source: string) {
// ruleid: frontend-no-dynamic-code
eval(source);
// ruleid: frontend-no-dynamic-code
new Function(source);
// ruleid: frontend-no-dynamic-code
Function(source);
// ok: frontend-no-dynamic-code
JSON.parse(source);
}
function renderText(node: HTMLElement, text: string) {
// ruleid: frontend-no-document-write
document.write(text);
// ruleid: frontend-no-document-write
document.writeln(text);
// ruleid: frontend-no-inner-html-assignment
node.innerHTML = text;
// ruleid: frontend-no-inner-html-assignment
node.innerHTML += text;
// ok: frontend-no-inner-html-assignment, frontend-no-document-write
node.textContent = text;
// ok: frontend-no-inner-html-assignment
return <span>{text}</span>;
}
+82
View File
@@ -0,0 +1,82 @@
# Static scanner fixtures. Never import or execute this file.
import ast
import json
import pickle
import subprocess
import httpx
import requests
import yaml
from subprocess import run
from yaml import SafeLoader
def dynamic_code(source):
# ruleid: python-no-dynamic-code
eval(source)
# ruleid: python-no-dynamic-code
exec(source)
# ok: python-no-dynamic-code
ast.literal_eval(source)
# ok: python-no-dynamic-code
json.loads(source)
def yaml_data(source):
# ruleid: python-safe-yaml-loader
yaml.load(source)
# ruleid: python-safe-yaml-loader
yaml.load(source, Loader=yaml.Loader)
# ruleid: python-safe-yaml-loader
yaml.load_all(source, Loader=yaml.UnsafeLoader)
# ok: python-safe-yaml-loader
yaml.safe_load(source)
# ok: python-safe-yaml-loader
yaml.safe_load_all(source)
# ok: python-safe-yaml-loader
yaml.load(source, Loader=yaml.SafeLoader)
# ok: python-safe-yaml-loader
yaml.load(source, Loader=SafeLoader)
# ok: python-safe-yaml-loader
yaml.load(source, yaml.CSafeLoader)
# ok: python-safe-yaml-loader
yaml.load_all(source, Loader=yaml.SafeLoader)
def processes(command):
# ruleid: python-no-subprocess-shell
subprocess.run(command, shell=True, check=True)
# ruleid: python-no-subprocess-shell
subprocess.Popen(command, shell=True)
# ruleid: python-no-subprocess-shell
run(command, shell=True)
# ok: python-no-subprocess-shell
subprocess.run(["tool", command], check=True)
# ok: python-no-subprocess-shell
subprocess.run(["tool", command], shell=False, check=True)
def http_clients(url):
# ruleid: python-no-disabled-tls
requests.get(url, verify=False, timeout=5)
# ruleid: python-no-disabled-tls
httpx.post(url, verify=False)
# ruleid: python-no-disabled-tls
httpx.Client(verify=False)
# ruleid: python-no-disabled-tls
httpx.AsyncClient(verify=False)
# ok: python-no-disabled-tls
requests.get(url, verify=True, timeout=5)
# ok: python-no-disabled-tls
httpx.Client()
# ok: python-no-disabled-tls
httpx.get(url, verify="certificates.pem")
def serialized_data(source, file):
# ruleid: python-no-pickle-load
pickle.loads(source)
# ruleid: python-no-pickle-load
pickle.load(file)
# ok: python-no-pickle-load
json.loads(source)
+136
View File
@@ -0,0 +1,136 @@
"""Check installer integrity and scanner failure propagation without network access."""
import contextlib
import hashlib
import io
import json
import subprocess
import sys
import tarfile
import tempfile
import unittest
from pathlib import Path
from unittest.mock import patch
import install
SECURITY = Path(__file__).resolve().parents[1]
class SecurityChecksTest(unittest.TestCase):
def setUp(self) -> None:
cache = SECURITY / ".cache"
cache.mkdir(exist_ok=True)
self.temporary = tempfile.TemporaryDirectory(prefix="checks-", dir=cache)
self.addCleanup(self.temporary.cleanup)
self.folder = Path(self.temporary.name)
def test_installer_rejects_checksum_mismatch_without_replacing_binary(self) -> None:
binary_dir = self.folder / ".bin"
binary_dir.mkdir()
existing = binary_dir / "trivy"
existing.write_bytes(b"existing tool")
responses = [
json.dumps({"tag_name": "v1.2.3"}).encode(),
("0" * 64 + " trivy_1.2.3_Linux-64bit.tar.gz\n").encode(),
b"download with an incorrect checksum",
]
with (
patch.object(sys, "argv", ["install.py", "trivy"]),
patch.object(install, "__file__", str(self.folder / "install.py")),
patch.object(install.platform, "system", return_value="Linux"),
patch.object(install.platform, "machine", return_value="x86_64"),
patch.object(install, "download", side_effect=responses),
self.assertRaisesRegex(ValueError, "SHA256 verification failed"),
):
install.main()
self.assertEqual(existing.read_bytes(), b"existing tool")
def test_installer_writes_only_the_verified_executable(self) -> None:
archive = io.BytesIO()
payload = b"synthetic executable fixture"
with tarfile.open(fileobj=archive, mode="w:gz") as bundle:
member = tarfile.TarInfo("trivy")
member.size = len(payload)
bundle.addfile(member, io.BytesIO(payload))
data = archive.getvalue()
responses = [
json.dumps({"tag_name": "v1.2.3"}).encode(),
(
hashlib.sha256(data).hexdigest() + " trivy_1.2.3_Linux-64bit.tar.gz\n"
).encode(),
data,
]
with (
patch.object(sys, "argv", ["install.py", "trivy"]),
patch.object(install, "__file__", str(self.folder / "install.py")),
patch.object(install.platform, "system", return_value="Linux"),
patch.object(install.platform, "machine", return_value="x86_64"),
patch.object(install, "download", side_effect=responses),
contextlib.redirect_stdout(io.StringIO()),
):
install.main()
executable = self.folder / ".bin" / "trivy"
self.assertEqual(executable.read_bytes(), payload)
self.assertEqual(executable.stat().st_mode & 0o777, 0o755)
def test_go_scan_preserves_failure_through_report_pipeline(self) -> None:
scanner = self.folder / "scanner"
for code in (0, 3, 17):
with self.subTest(exit_code=code):
scanner.write_text(
"#!/usr/bin/env bash\n"
'if [ "$1" = -version ]; then exit 0; fi\n'
'echo "Synthetic scan result"\n'
f"exit {code}\n"
)
scanner.chmod(0o700)
reports = self.folder / "reports"
result = subprocess.run(
["make", "go", f"GOVULNCHECK={scanner}", f"REPORTS={reports}"],
cwd=SECURITY,
capture_output=True,
text=True,
check=False,
)
self.assertEqual(result.returncode == 0, code == 0, result.stderr)
self.assertEqual(
(reports / "govulncheck.txt").read_text(), "Synthetic scan result\n"
)
def test_failed_preflight_removes_previous_scan_reports(self) -> None:
outputs = {
"filesystem": ["trivy-filesystem.json"],
"secrets": ["gitleaks-files.json", "gitleaks-history.json"],
"go": ["govulncheck.txt"],
"semgrep": ["semgrep.json"],
"images": ["trivy-ml.json", "ml-image-id.txt"],
}
for target, filenames in outputs.items():
with self.subTest(target=target):
reports = self.folder / target
reports.mkdir()
for filename in filenames:
(reports / filename).write_text("previous result")
result = subprocess.run(
[
"make",
target,
f"REPORTS={reports}",
f"ROOT={self.folder}",
"TRIVY=/nonexistent/scanner",
"SEMGREP=/nonexistent/scanner",
"GOVULNCHECK=/nonexistent/scanner",
],
cwd=SECURITY,
capture_output=True,
text=True,
check=False,
)
self.assertNotEqual(result.returncode, 0)
for filename in filenames:
self.assertFalse((reports / filename).exists(), filename)
if __name__ == "__main__":
unittest.main()
+35
View File
@@ -0,0 +1,35 @@
exit-code: 1
format: json
ignorefile: security/trivy/ignore.yml
severity:
- HIGH
- CRITICAL
timeout: 10m
scan:
disable-telemetry: true
show-suppressed: true
scanners:
- vuln
- misconfig
file-patterns:
- 'pip:(^|/)requirements-[^/]+\.txt$'
skip-dirs:
- "**/.git"
- "**/node_modules"
- "**/.venv*"
- "**/.cache"
- "**/.mypy_cache"
- "**/.ruff_cache"
- "**/.pytest_cache"
- "**/__pycache__"
- "**/dist"
- "**/bin"
- "security/.bin"
- "security/.tools"
- "security/reports"
skip-files:
- ".env"
vulnerability:
ignore-unfixed: false
pkg:
include-dev-deps: true
+11
View File
@@ -0,0 +1,11 @@
vulnerabilities:
# Temporary exception approved by the project owner on 2026-10-05.
# No upstream fix is available; this finding would otherwise block dependency CI.
# Remove this exception when a fixed release is available, or review before expiry.
- id: CVE-2026-93687
paths:
- frontend/pnpm-lock.yaml
purls:
- pkg:npm/braces@3.0.3
expired_at: 2026-10-19
statement: "Owner: project maintainers. No fixed braces release is available; temporarily accepted to unblock dependency CI."
+13
View File
@@ -0,0 +1,13 @@
exit-code: 1
format: json
severity:
- HIGH
- CRITICAL
timeout: 10m
scan:
disable-telemetry: true
scanners:
- vuln
- misconfig
vulnerability:
ignore-unfixed: false