@runsec/mcp 1.0.28 → 1.0.37

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. package/dist/data/.rag-cache.json +1 -0
  2. package/dist/data/skills/_exploit_overrides.json +16 -0
  3. package/dist/data/skills/advanced-agent-cloud/index.md +94 -0
  4. package/dist/data/skills/advanced-agent-cloud/patterns.md +46 -0
  5. package/dist/data/skills/advanced-agent-cloud/skill.json +38 -0
  6. package/dist/data/skills/app-logic/index.md +69 -0
  7. package/dist/data/skills/app-logic/patterns.md +23 -0
  8. package/dist/data/skills/app-logic/skill.json +24 -0
  9. package/dist/data/skills/auth-keycloak/index.md +69 -0
  10. package/dist/data/skills/auth-keycloak/patterns.md +46 -0
  11. package/dist/data/skills/auth-keycloak/skill.json +51 -0
  12. package/dist/data/skills/browser-agent/index.md +58 -0
  13. package/dist/data/skills/browser-agent/patterns.md +15 -0
  14. package/dist/data/skills/browser-agent/skill.json +24 -0
  15. package/dist/data/skills/cloud-secrets/index.md +66 -0
  16. package/dist/data/skills/cloud-secrets/patterns.md +19 -0
  17. package/dist/data/skills/cloud-secrets/skill.json +28 -0
  18. package/dist/data/skills/csharp-dotnet/index.md +103 -0
  19. package/dist/data/skills/csharp-dotnet/patterns.md +270 -0
  20. package/dist/data/skills/csharp-dotnet/skill.json +27 -0
  21. package/dist/data/skills/desktop-vsto-suite/index.md +202 -0
  22. package/dist/data/skills/desktop-vsto-suite/patterns.md +154 -0
  23. package/dist/data/skills/desktop-vsto-suite/skill.json +26 -0
  24. package/dist/data/skills/devops-security/index.md +64 -0
  25. package/dist/data/skills/devops-security/patterns.md +23 -0
  26. package/dist/data/skills/devops-security/skill.json +42 -0
  27. package/dist/data/skills/domain-access-management/index.md +123 -0
  28. package/dist/data/skills/domain-access-management/patterns.md +58 -0
  29. package/dist/data/skills/domain-access-management/skill.json +36 -0
  30. package/dist/data/skills/domain-data-privacy/index.md +98 -0
  31. package/dist/data/skills/domain-data-privacy/patterns.md +48 -0
  32. package/dist/data/skills/domain-data-privacy/skill.json +36 -0
  33. package/dist/data/skills/domain-input-validation/index.md +210 -0
  34. package/dist/data/skills/domain-input-validation/patterns.md +158 -0
  35. package/dist/data/skills/domain-input-validation/skill.json +24 -0
  36. package/dist/data/skills/domain-platform-hardening/index.md +169 -0
  37. package/dist/data/skills/domain-platform-hardening/patterns.md +96 -0
  38. package/dist/data/skills/domain-platform-hardening/skill.json +27 -0
  39. package/dist/data/skills/ds-ml-security/patterns.md +137 -0
  40. package/dist/data/skills/fastapi-async/index.md +83 -0
  41. package/dist/data/skills/fastapi-async/patterns.md +329 -0
  42. package/dist/data/skills/fastapi-async/skill.json +32 -0
  43. package/dist/data/skills/frontend-react/index.md +26 -0
  44. package/dist/data/skills/frontend-react/patterns.md +226 -0
  45. package/dist/data/skills/frontend-react/skill.json +24 -0
  46. package/dist/data/skills/go-core/index.md +86 -0
  47. package/dist/data/skills/go-core/patterns.md +272 -0
  48. package/dist/data/skills/go-core/skill.json +22 -0
  49. package/dist/data/skills/hft-cpp-security/patterns.md +37 -0
  50. package/dist/data/skills/index.md +73 -0
  51. package/dist/data/skills/infra-k8s-helm/index.md +138 -0
  52. package/dist/data/skills/infra-k8s-helm/patterns.md +279 -0
  53. package/dist/data/skills/infra-k8s-helm/skill.json +41 -0
  54. package/dist/data/skills/integration-security/index.md +73 -0
  55. package/dist/data/skills/integration-security/patterns.md +132 -0
  56. package/dist/data/skills/integration-security/skill.json +30 -0
  57. package/dist/data/skills/java-enterprise/index.md +31 -0
  58. package/dist/data/skills/java-enterprise/patterns.md +816 -0
  59. package/dist/data/skills/java-enterprise/skill.json +26 -0
  60. package/dist/data/skills/java-spring/index.md +65 -0
  61. package/dist/data/skills/java-spring/patterns.md +22 -0
  62. package/dist/data/skills/java-spring/skill.json +23 -0
  63. package/dist/data/skills/license-compliance/index.md +58 -0
  64. package/dist/data/skills/license-compliance/patterns.md +12 -0
  65. package/dist/data/skills/license-compliance/skill.json +28 -0
  66. package/dist/data/skills/mobile-security/patterns.md +42 -0
  67. package/dist/data/skills/nodejs-nestjs/index.md +71 -0
  68. package/dist/data/skills/nodejs-nestjs/patterns.md +288 -0
  69. package/dist/data/skills/nodejs-nestjs/skill.json +24 -0
  70. package/dist/data/skills/observability/index.md +68 -0
  71. package/dist/data/skills/observability/patterns.md +22 -0
  72. package/dist/data/skills/observability/skill.json +26 -0
  73. package/dist/data/skills/php-security/patterns.md +202 -0
  74. package/dist/data/skills/ru-regulatory/index.md +72 -0
  75. package/dist/data/skills/ru-regulatory/patterns.md +28 -0
  76. package/dist/data/skills/ru-regulatory/skill.json +53 -0
  77. package/dist/data/skills/ruby-rails/index.md +65 -0
  78. package/dist/data/skills/ruby-rails/patterns.md +172 -0
  79. package/dist/data/skills/ruby-rails/skill.json +24 -0
  80. package/dist/data/skills/rust-security/patterns.md +152 -0
  81. package/dist/data/trufflehog-config.yaml +407 -0
  82. package/dist/index.js +3830 -400
  83. package/package.json +2 -3
@@ -0,0 +1,64 @@
1
+ # Devops Security
2
+
3
+ ## Stack overview
4
+
5
+ See [`patterns.md`](patterns.md) for Anti-Pattern / Safe-Pattern definitions for this domain.
6
+
7
+ ## Top threats
8
+
9
+ - Map concrete rows from the pattern table to your architecture.
10
+
11
+ ## Pattern catalog
12
+
13
+ Complete Anti-Pattern / Safe-Pattern definitions live in [`patterns.md`](patterns.md). The table below is a **table of contents** by metric ID.
14
+
15
+ | ID | Metric | Stack |
16
+ |---|---|---|
17
+ | `DVS-001` | Dockerfile: Запуск от root (USER root / отсутствие USER) | Создать непривилегированного пользователя (`useradd -m appuser`) и запускать контейнер через `USER appuser`. |
18
+ | `DVS-002` | Dockerfile: Теги latest в базовых образах | Фиксировать образ по версии/диджесту (`FROM node:20.12.2`, `FROM alpine@sha256:...`). |
19
+ | `DVS-003` | Dockerfile: Секреты в ENV/ARG | Использовать runtime secret injection (Vault/ESO/K8s Secret), исключить секреты из Docker build layers. |
20
+ | `DVS-004` | SLSA L1/L2: отсутствует provenance-аттестация сборки | Генерировать provenance-аттестацию (builder, source, digest, timestamp, workflow id) и сохранять ее как обязательный артефакт релиза. |
21
+ | `DVS-005` | NIST SSDF: зависимости с известными CVE допускаются в релиз | Блокировать релиз при High/Critical CVE, учитывать результаты Syft/SCA в policy gate и сохранять решение в CI logs. |
22
+ | `DVS-006` | Hermetic Builds: внешние сетевые вызовы в build-стадии | sh` |
23
+ | `DVS-007` | VEX Filter: CVE не фильтруются по VEX-статусу `not_affected` | При policy-gate учитывать VEX-аттестации; CVE со статусом `not_affected` маркировать как исключение с audit trail. |
24
+ | `DVS-008` | Artifact Signing: release-образы публикуются без подписи | Обязательная подпись артефактов (например, cosign), валидация подписи при деплое и хранение attestations. |
25
+ | `DVS-009` | Reproducible Build: недетерминированные сборки без проверки повторяемости | Пинning base images/dependencies, deterministic flags и периодическая проверка reproducibility hash между сборками. |
26
+ | `CWE-1104` | Use of Unmaintained/Outdated Components in dependency manifests | Обновлять зависимости до поддерживаемых версий (например, `django>=3.2`, `pillow>=10.3.0`) и включать SCA gate в CI. |
27
+ | `CWE-798-ALEMBIC-URL` | Hardcoded DB credentials in `alembic.ini` (`sqlalchemy.url`) | Убрать plaintext credentials из `alembic.ini`, использовать env/secret manager и подстановку URL только через защищенный runtime config. |
28
+ | `CWE-116-VITE-PROXY-HEADER-FWD` | Unsafe Vite proxy forwarding of sensitive headers (`Host`, `Cookie`) to untrusted upstream | Validate data with Zod and sanitize DOM/HTML sinks with DOMPurify before rendering. |
29
+ | `CWE-427-NSIS-EXEC-RELATIVE` | NSIS execution of external binaries via relative/unquoted paths (`Exec`/`ExecWait`) | Использовать только абсолютные/канонизированные пути в кавычках, проверять подпись/хэш и исключать запуск бинарников из непроверенных относительных путей. |
30
+ | `CWE-377-NSIS-OUTPATH-PERM` | Insecure NSIS output path/library attributes in privileged system directories | Избегать записи в системные каталоги без проверки прав/контекста, явно задавать безопасные `SetDefaultLibAttributes` и контролировать install target policy. |
31
+ | `DVS-015` | Downloading binaries/scripts without checksum verification (CWE-353) | После скачивания обязательно проверять `sha256sum -c` (или подпись), прерывать pipeline при mismatch. |
32
+ | `DVS-016` | `wget | CWE Final Certification |
33
+ | `DVS-017` | Dockerfile remote artifact ADD/RUN without expected hash check (CWE-353) | CWE Final Certification |
34
+ | `DVS-018` | CI job executes downloaded CLI/plugin from URL directly (CWE-353) | Использовать dependency lockfiles/hashes (`--require-hashes`) и trusted registries вместо direct URL execution. |
35
+ | `DVS-019` | Terraform/Ansible bootstrap scripts fetched over network without integrity enforcement ... | Обязательно задавать `checksum`/signature verification и policy-gate, блокирующий unverified bootstrap artifacts. |
36
+ | `DVS-020` | Скачивание и выполнение кода без проверки целостности (CWE-494) | Только verified artifacts: hash/signature gate до execute; запрет pipe-to-shell в Dockerfile. |
37
+ | `DVS-021` | Подключение зависимостей из untrusted VCS URL без фиксации коммита (CWE-829) | Lockfile + immutable commit refs; policy deny `git+https` без SHA. |
38
+
39
+ ## Verification
40
+
41
+ **Verification:** Check the gold testbed file(s) below for `Vulnerable: <ID>` markers (static Semgrep + `detection-matrix.md` ground truth).
42
+
43
+ - [`gold-standard-testbed/`](../gold-standard-testbed/) (see `detection-matrix.md` for ID → file mapping)
44
+
45
+ After changing [`patterns.md`](patterns.md), run from the repo root:
46
+
47
+ ```bash
48
+ python scripts/sync_semgrep.py
49
+ ```
50
+
51
+ ## Workflow: Recon → Scan → Verify
52
+
53
+ ### 1) Recon
54
+ - Map entrypoints, data flows, and trust boundaries for this stack.
55
+ - Identify which metrics in [`patterns.md`](patterns.md) apply to the code under review.
56
+
57
+ ### 2) Scan
58
+ - Run Semgrep with `semgrep-rules/<skill>.yaml` (generated) and correlate with Anti-Patterns.
59
+ - Eliminate findings that cannot bind to a metric row.
60
+
61
+ ### 3) Verify
62
+ - Confirm markers or scanner hits for touched IDs in the gold testbed when adding metrics.
63
+ - Emit findings as `Vulnerable: <PREFIX>-<NNN>` in written reviews.
64
+
@@ -0,0 +1,23 @@
1
+ | ID | Название метрики | Anti-Pattern (Vulnerable Code/YAML) | Safe-Pattern (Remediation) | Stack | Источник fix_template | Exploit scenario |
2
+ |---|---|---|---|---|---|---|
3
+ | DVS-001 | Dockerfile: Запуск от root (USER root / отсутствие USER) | `FROM python:3.11`<br>`...`<br>`USER root` | Создать непривилегированного пользователя (`useradd -m appuser`) и запускать контейнер через `USER appuser`. | DevOps/Supply Chain | Docker CIS Benchmark | Создать непривилегированного пользователя (`useradd -m appuser`) и запускать контейнер через `USER appuser`. | Атакующий доставляет входные данные, соответствующие anti-pattern; реальный ущерб зависит от приёмника (sink), конфигурации и границ доверия. | <!-- semantic_anchor: dvs-001 dockerfile запуск от root user отсутствие from python 3 11 создать непривилегированного пользователя useradd appuser запускать контейнер -->
4
+ | DVS-002 | Dockerfile: Теги latest в базовых образах | `FROM node:latest`<br>`FROM alpine:latest` | Фиксировать образ по версии/диджесту (`FROM node:20.12.2`, `FROM alpine@sha256:...`). | DevOps/Supply Chain | Supply-chain hardening | Фиксировать образ по версии/диджесту (`FROM node:20.12.2`, `FROM alpine@sha256:...`). | Атакующий доставляет входные данные, соответствующие anti-pattern; реальный ущерб зависит от приёмника (sink), конфигурации и границ доверия. | <!-- semantic_anchor: dvs-002 dockerfile latest теги в базовых образах from node alpine фиксировать по версии digest supply chain -->
5
+ | DVS-003 | Dockerfile: Секреты в ENV/ARG | `ENV DB_PASSWORD=supersecret`<br>`ARG AWS_SECRET_ACCESS_KEY=...` | Использовать runtime secret injection (Vault/ESO/K8s Secret), исключить секреты из Docker build layers. | DevOps/Supply Chain | `CWE-798`, Vault best practices | Использовать runtime secret injection (Vault/ESO/K8s Secret), исключить секреты из Docker build layers. | Атакующий доставляет входные данные, соответствующие anti-pattern; реальный ущерб зависит от приёмника (sink), конфигурации и границ доверия. | <!-- semantic_anchor: dvs-003 dockerfile секреты env arg db password aws secret access key использовать runtime secret injection vault eso исключить из build layers -->
6
+ | DVS-004 | SLSA L1/L2: отсутствует provenance-аттестация сборки | `docker build -t app:1.0 .`<br>`# no provenance attestation` | Генерировать provenance-аттестацию (builder, source, digest, timestamp, workflow id) и сохранять ее как обязательный артефакт релиза. | DevOps/Supply Chain | SLSA v1.0 (L1/L2) | Генерировать provenance-аттестацию (builder, source, digest, timestamp, workflow id) и сохранять ее как обязательный артефакт релиза. | Атакующий доставляет входные данные, соответствующие anti-pattern; реальный ущерб зависит от приёмника (sink), конфигурации и границ доверия. | <!-- semantic_anchor: dvs-004 slsa l1 l2 provenance attestation builder source digest workflow -->
7
+ | DVS-005 | NIST SSDF: зависимости с известными CVE допускаются в релиз | `pip install vulnerable-lib==1.2.0`<br>`# syft report ignored` | Блокировать релиз при High/Critical CVE, учитывать результаты Syft/SCA в policy gate и сохранять решение в CI logs. | DevOps/Supply Chain | NIST SSDF, supply-chain policy | Блокировать релиз при High/Critical CVE, учитывать результаты Syft/SCA в policy gate и сохранять решение в CI logs. | Атакующий доставляет входные данные, соответствующие anti-pattern; реальный ущерб зависит от приёмника (sink), конфигурации и границ доверия. | <!-- semantic_anchor: dvs-005 nist ssdf cve syft sca policy gate dependencies release -->
8
+ | DVS-006 | Hermetic Builds: внешние сетевые вызовы в build-стадии | `RUN apt-get update && curl https://example.com/install.sh | sh` | DevOps/Supply Chain | SLSA L3 build integrity | sh` | Атакующий доставляет входные данные, соответствующие anti-pattern; реальный ущерб зависит от приёмника (sink), конфигурации и границ доверия. | <!-- semantic_anchor: dvs-006 hermetic builds no external network curl wget docker run proxy nexus -->
9
+ | DVS-007 | VEX Filter: CVE не фильтруются по VEX-статусу `not_affected` | `if cve.severity >= "HIGH": fail_build()`<br>`# ignores VEX not_affected` | При policy-gate учитывать VEX-аттестации; CVE со статусом `not_affected` маркировать как исключение с audit trail. | DevOps/Supply Chain | VEX / CSAF, NIST SSDF | При policy-gate учитывать VEX-аттестации; CVE со статусом `not_affected` маркировать как исключение с audit trail. | Атакующий доставляет входные данные, соответствующие anti-pattern; реальный ущерб зависит от приёмника (sink), конфигурации и границ доверия. | <!-- semantic_anchor: dvs-007 vex filter not_affected cve sca syft policy gate csaf -->
10
+ | DVS-008 | Artifact Signing: release-образы публикуются без подписи | `docker push registry/app:1.0.0`<br>`# no cosign/signature` | Обязательная подпись артефактов (например, cosign), валидация подписи при деплое и хранение attestations. | DevOps/Supply Chain | SLSA L3, NIST SSDF | Обязательная подпись артефактов (например, cosign), валидация подписи при деплое и хранение attestations. | Атакующий доставляет входные данные, соответствующие anti-pattern; реальный ущерб зависит от приёмника (sink), конфигурации и границ доверия. | <!-- semantic_anchor: dvs-008 artifact signing cosign signature attestation deploy verification -->
11
+ | DVS-009 | Reproducible Build: недетерминированные сборки без проверки повторяемости | `FROM base:latest`<br>`RUN pip install -r requirements.txt` | Пинning base images/dependencies, deterministic flags и периодическая проверка reproducibility hash между сборками. | DevOps/Supply Chain | Supply chain reproducibility controls | Пинning base images/dependencies, deterministic flags и периодическая проверка reproducibility hash между сборками. | Атакующий доставляет входные данные, соответствующие anti-pattern; реальный ущерб зависит от приёмника (sink), конфигурации и границ доверия. | <!-- semantic_anchor: dvs-009 reproducible build deterministic hash pinned dependencies latest tag -->
12
+ | CWE-1104 | Use of Unmaintained/Outdated Components in dependency manifests | `django==2.2.28`<br>`pillow==9.0.0` | Обновлять зависимости до поддерживаемых версий (например, `django>=3.2`, `pillow>=10.3.0`) и включать SCA gate в CI. | DevOps/Supply Chain | CWE Final Certification | Обновлять зависимости до поддерживаемых версий (например, `django>=3.2`, `pillow>=10.3.0`) и включать SCA gate в CI. | Атакующий доставляет входные данные, соответствующие anti-pattern; реальный ущерб зависит от приёмника (sink), конфигурации и границ доверия. |
13
+ | CWE-798-ALEMBIC-URL | Hardcoded DB credentials in `alembic.ini` (`sqlalchemy.url`) | `sqlalchemy.url = postgresql://user:password@db/app` | Убрать plaintext credentials из `alembic.ini`, использовать env/secret manager и подстановку URL только через защищенный runtime config. | DevOps/Supply Chain | CWE Final Certification | Убрать plaintext credentials из `alembic.ini`, использовать env/secret manager и подстановку URL только через защищенный runtime config. | Атакующий доставляет входные данные, соответствующие anti-pattern; реальный ущерб зависит от приёмника (sink), конфигурации и границ доверия. |
14
+ | CWE-116-VITE-PROXY-HEADER-FWD | Unsafe Vite proxy forwarding of sensitive headers (`Host`, `Cookie`) to untrusted upstream | `server.proxy["/api"] = { target: "https://external", changeOrigin: true }` + неконтролируемый `proxyReq` headers pass-through | Для `vite.config.ts` ограничивать proxy trusted targets, фильтровать/удалять `Host/Cookie/Authorization` перед проксированием и применять explicit header allowlist. | Node.js/Vite | CWE Final Certification | Validate data with Zod and sanitize DOM/HTML sinks with DOMPurify before rendering. | Атакующий доставляет входные данные, соответствующие anti-pattern; реальный ущерб зависит от приёмника (sink), конфигурации и границ доверия. |
15
+ | CWE-427-NSIS-EXEC-RELATIVE | NSIS execution of external binaries via relative/unquoted paths (`Exec`/`ExecWait`) | `ExecWait tools\\helper.exe`<br>`Exec ..\\bin\\setup.exe` | Использовать только абсолютные/канонизированные пути в кавычках, проверять подпись/хэш и исключать запуск бинарников из непроверенных относительных путей. | NSIS/Installers | CWE Final Certification | Использовать только абсолютные/канонизированные пути в кавычках, проверять подпись/хэш и исключать запуск бинарников из непроверенных относительных путей. | Атакующий доставляет входные данные, соответствующие anti-pattern; реальный ущерб зависит от приёмника (sink), конфигурации и границ доверия. |
16
+ | CWE-377-NSIS-OUTPATH-PERM | Insecure NSIS output path/library attributes in privileged system directories | `SetOutPath $WINDIR\\System32` без проверок<br>отсутствует `SetDefaultLibAttributes` | Избегать записи в системные каталоги без проверки прав/контекста, явно задавать безопасные `SetDefaultLibAttributes` и контролировать install target policy. | NSIS/Installers | CWE Final Certification | Избегать записи в системные каталоги без проверки прав/контекста, явно задавать безопасные `SetDefaultLibAttributes` и контролировать install target policy. | Атакующий доставляет входные данные, соответствующие anti-pattern; реальный ущерб зависит от приёмника (sink), конфигурации и границ доверия. |
17
+ | DVS-015 | Downloading binaries/scripts without checksum verification (CWE-353) | `curl -L https://example.com/tool.sh -o /usr/local/bin/tool` | После скачивания обязательно проверять `sha256sum -c` (или подпись), прерывать pipeline при mismatch. | DevOps/Supply Chain | CWE Final Certification | После скачивания обязательно проверять `sha256sum -c` (или подпись), прерывать pipeline при mismatch. | Атакующий доставляет входные данные, соответствующие anti-pattern; реальный ущерб зависит от приёмника (sink), конфигурации и границ доверия. |
18
+ | DVS-016 | `wget | bash` installer pattern without integrity pinning (CWE-353) | `wget -qO- https://example.com/install.sh | bash` | Исключить pipe-to-shell; скачивать артефакт отдельно и валидировать sha256/signature перед выполнением. | DevOps/Supply Chain | CWE Final Certification | Атакующий доставляет входные данные, соответствующие anti-pattern; реальный ущерб зависит от приёмника (sink), конфигурации и границ доверия. |
19
+ | DVS-017 | Dockerfile remote artifact ADD/RUN without expected hash check (CWE-353) | `RUN curl -fsSL https://vendor/bin -o /tmp/bin && chmod +x /tmp/bin` | Фиксировать expected hash в build args/metadata и проверять `echo "$HASH /tmp/bin" | sha256sum -c -`. | DevOps/Supply Chain | CWE Final Certification | Атакующий доставляет входные данные, соответствующие anti-pattern; реальный ущерб зависит от приёмника (sink), конфигурации и границ доверия. |
20
+ | DVS-018 | CI job executes downloaded CLI/plugin from URL directly (CWE-353) | `python -m pip install https://.../package.whl` без hash pin | Использовать dependency lockfiles/hashes (`--require-hashes`) и trusted registries вместо direct URL execution. | DevOps/Supply Chain | CWE Final Certification | Использовать dependency lockfiles/hashes (`--require-hashes`) и trusted registries вместо direct URL execution. | Атакующий доставляет входные данные, соответствующие anti-pattern; реальный ущерб зависит от приёмника (sink), конфигурации и границ доверия. |
21
+ | DVS-019 | Terraform/Ansible bootstrap scripts fetched over network without integrity enforcement (CWE-353) | `ansible.builtin.get_url` без checksum<br>`remote-exec` с raw URL script | Обязательно задавать `checksum`/signature verification и policy-gate, блокирующий unverified bootstrap artifacts. | DevOps/Supply Chain | CWE Final Certification | Обязательно задавать `checksum`/signature verification и policy-gate, блокирующий unverified bootstrap artifacts. | Атакующий доставляет входные данные, соответствующие anti-pattern; реальный ущерб зависит от приёмника (sink), конфигурации и границ доверия. |
22
+ | DVS-020 | Скачивание и выполнение кода без проверки целостности (CWE-494) | `RUN curl -fsSL https://vendor/install.sh \| bash` | Скачать в файл, проверить `sha256sum`/подпись `cosign`, затем `bash` с `set -euo pipefail`. | DevOps/Supply Chain | `CWE-494` | Только verified artifacts: hash/signature gate до execute; запрет pipe-to-shell в Dockerfile. | Атакующий доставляет входные данные, соответствующие anti-pattern; реальный ущерб зависит от приёмника (sink), конфигурации и границ доверия. | <!-- semantic_anchor: dvs-020 curl install sh bash pipe cwe494 guardian -->
23
+ | DVS-021 | Подключение зависимостей из untrusted VCS URL без фиксации коммита (CWE-829) | `pip install git+https://github.com/user/repo.git`<br>`npm install git+https://github.com/x/y.git` | Пиновать commit SHA/tag + verify signature; приватный registry mirror. | DevOps/Supply Chain | `CWE-829` | Lockfile + immutable commit refs; policy deny `git+https` без SHA. | Атакующий доставляет входные данные, соответствующие anti-pattern; реальный ущерб зависит от приёмника (sink), конфигурации и границ доверия. | <!-- semantic_anchor: dvs-021 pip install git https github cwe829 guardian -->
@@ -0,0 +1,42 @@
1
+ {
2
+ "skill_id": "devops-security",
3
+ "name": "DevOps Security",
4
+ "activation_triggers": [
5
+ "docker-user-nonroot",
6
+ "docker-no-latest-tag",
7
+ "docker-no-secret-env",
8
+ "cb-gost-devsecops",
9
+ "cb-gost-devsecops-docker",
10
+ "slsa-provenance",
11
+ "hermetic-build",
12
+ "vex-filter",
13
+ "artifact-signing",
14
+ "reproducible-build"
15
+ ],
16
+ "relevant_extensions": [
17
+ ".dockerfile",
18
+ ".yml",
19
+ ".yaml",
20
+ ".tf",
21
+ ".sh"
22
+ ],
23
+ "tools": [
24
+ "semgrep",
25
+ "syft",
26
+ "trufflehog"
27
+ ],
28
+ "rules_path": "core/skills/devops-security/patterns.md",
29
+ "few_shot_examples": "core/gold-standard-testbed/devops_security_vulnerable.Dockerfile",
30
+ "mitigation_logic": {
31
+ "RRC-010": {
32
+ "exception_rule": "Для облачной K8s-инфраструктуры требование программного затирания (shred) признается неэффективным и может быть заменено инфраструктурным контролем.",
33
+ "status_override": "OK",
34
+ "equivalent_control": "Шифрование данных At-Rest на уровне PVC/StorageClass (AES-256) с подтвержденной политикой управления ключами.",
35
+ "evidence_requirements": [
36
+ "StorageClass/PVC конфигурации с включенным encryption at rest.",
37
+ "Подтверждение алгоритма AES-256 и действующего KMS-профиля."
38
+ ]
39
+ }
40
+ },
41
+ "security_priority": 10
42
+ }
@@ -0,0 +1,123 @@
1
+ # Domain Access Management
2
+
3
+ ## Stack overview
4
+
5
+ Authentication, authorization, BOLA/IDOR, session controls, and architectural auth risks grouped by function.
6
+
7
+ ## Top threats
8
+
9
+ - **Use strict Pydantic BaseModel schemas for input/output, including response_model and field allowlists.**: 19 metrics (`PY-100`, `PY-105`, `PY-011`, `PY-013`)
10
+ - **Validate data with Zod and sanitize DOM/HTML sinks with DOMPurify before rendering.**: 14 metrics (`NJS-009`, `NJS-016`, `NJS-024`, `NJS-026`)
11
+ - **Cache key по subject+scope+tenant+ttl.**: 1 metrics (`APP-119`)
12
+ - **Central revocation + backchannel logout.**: 1 metrics (`APP-108`)
13
+ - **Fail-closed при ошибке внешнего IdP.**: 1 metrics (`APP-102`)
14
+ - **Rate-limit + progressive delay + lockout.**: 1 metrics (`APP-112`)
15
+ - **Re-auth/step-up перед привилегированными операциями.**: 1 metrics (`APP-105`)
16
+ - **Risk-based controls, captcha/behavioral checks.**: 1 metrics (`APP-117`)
17
+ - **Scope-bound short-lived tokens per service.**: 1 metrics (`APP-107`)
18
+ - **Signed delegation token + bounded TTL + audit.**: 1 metrics (`APP-115`)
19
+ - **Вводить idempotency-key и single-flight для token issue.**: 1 metrics (`APP-100`)
20
+ - **Включать tenant claim + enforce в policy layer.**: 1 metrics (`APP-113`)
21
+ - **Для create/update использовать явный whitelist полей (DTO/pick), блокировать системные/привилегированные атрибуты и валидировать типы.**: 1 metrics (`CWE-20-ORM-MASS-ASSIGN`)
22
+ - **Для чувствительных операций использовать `ipcMain.handle` + строгую валидацию payload и проверку источника/role.**: 1 metrics (`DSK-105`)
23
+ - **Исключить вывод токенов даже в debug-режиме, применять редактирование/маскирование чувствительных данных в логах.**: 1 metrics (`MOB-010`)
24
+ - **Использовать POST/PUT/PATCH + CSRF guards.**: 1 metrics (`APP-109`)
25
+ - **Обязательный MFA gate для high-risk операций.**: 1 metrics (`APP-104`)
26
+ - **Обязательный timeout + retry budget + circuit breaker.**: 1 metrics (`APP-101`)
27
+ - **Привязка токена к nonce/device/session fingerprint.**: 1 metrics (`APP-103`)
28
+ - **Проверять subject/scope до исполнения job.**: 1 metrics (`APP-110`)
29
+ - **Ротация по SLA + автоотзыв компрометированных ключей.**: 1 metrics (`APP-111`)
30
+ - **Централизованный security audit log.**: 1 metrics (`APP-114`)
31
+ - **Явная обработка ошибок + forced re-auth.**: 1 metrics (`APP-116`)
32
+ - **Явный consent prompt + least-scope default.**: 1 metrics (`APP-118`)
33
+ - **Явный least-privilege allowlist ролей.**: 1 metrics (`APP-106`)
34
+
35
+ ## Pattern catalog
36
+
37
+ Complete Anti-Pattern / Safe-Pattern definitions live in [`patterns.md`](patterns.md). The table below is a **table of contents** by metric ID.
38
+
39
+ | ID | Metric | Stack |
40
+ |---|---|---|
41
+ | `PY-100` | Fail-Open Auth (env token) | Use strict Pydantic BaseModel schemas for input/output, including response_model and field allowlists. |
42
+ | `PY-105` | BOLA in Django queryset | Use strict Pydantic BaseModel schemas for input/output, including response_model and field allowlists. |
43
+ | `NJS-009` | JWT verify without strict policy | Validate data with Zod and sanitize DOM/HTML sinks with DOMPurify before rendering. |
44
+ | `NJS-016` | Missing ownership check (IDOR/BOLA) | Validate data with Zod and sanitize DOM/HTML sinks with DOMPurify before rendering. |
45
+ | `NJS-024` | Weak session cookie policy | Validate data with Zod and sanitize DOM/HTML sinks with DOMPurify before rendering. |
46
+ | `NJS-026` | Mass Assignment | Validate data with Zod and sanitize DOM/HTML sinks with DOMPurify before rendering. |
47
+ | `PY-011` | JWT algorithm confusion | Use strict Pydantic BaseModel schemas for input/output, including response_model and field allowlists. |
48
+ | `PY-013` | ORM mass assignment | Use strict Pydantic BaseModel schemas for input/output, including response_model and field allowlists. |
49
+ | `FTS-018` | Hidden UI Auth Bypass | Validate data with Zod and sanitize DOM/HTML sinks with DOMPurify before rendering. |
50
+ | `FTS-019` | Loose comparison in access checks | Validate data with Zod and sanitize DOM/HTML sinks with DOMPurify before rendering. |
51
+ | `APP-100` | Duplicate token issuance in parallel flow | Вводить idempotency-key и single-flight для token issue. |
52
+ | `APP-101` | Missing client timeout policy | Обязательный timeout + retry budget + circuit breaker. |
53
+ | `APP-102` | Fail-open fallback on auth provider error | Fail-closed при ошибке внешнего IdP. |
54
+ | `APP-103` | Missing token replay binding | Привязка токена к nonce/device/session fingerprint. |
55
+ | `APP-104` | Missing MFA enforcement on critical action | Обязательный MFA gate для high-risk операций. |
56
+ | `APP-105` | Admin action without re-auth | Re-auth/step-up перед привилегированными операциями. |
57
+ | `APP-106` | Broad role wildcard in policy | Явный least-privilege allowlist ролей. |
58
+ | `APP-107` | Static service token reuse | Scope-bound short-lived tokens per service. |
59
+ | `APP-108` | Missing session revocation propagation | Central revocation + backchannel logout. |
60
+ | `APP-109` | Privileged action via GET | Использовать POST/PUT/PATCH + CSRF guards. |
61
+ | `APP-110` | Missing authz check in background worker | Проверять subject/scope до исполнения job. |
62
+ | `APP-111` | Weak API key rotation policy | Ротация по SLA + автоотзыв компрометированных ключей. |
63
+ | `APP-112` | No lockout on auth brute force | Rate-limit + progressive delay + lockout. |
64
+ | `APP-113` | No tenant isolation in access token | Включать tenant claim + enforce в policy layer. |
65
+ | `APP-114` | Missing auth audit trail | Централизованный security audit log. |
66
+ | `APP-115` | Insecure impersonation flow | Signed delegation token + bounded TTL + audit. |
67
+ | `APP-116` | Silent token refresh failures | Явная обработка ошибок + forced re-auth. |
68
+ | `APP-117` | No anti-automation controls on auth APIs | Risk-based controls, captcha/behavioral checks. |
69
+ | `APP-118` | Missing consent boundary for delegated scopes | Явный consent prompt + least-scope default. |
70
+ | `APP-119` | Auth cache poisoning risk | Cache key по subject+scope+tenant+ttl. |
71
+ | `PY-010` | Insecure random for security tokens | Use strict Pydantic BaseModel schemas for input/output, including response_model and field allowlists. |
72
+ | `PY-012` | SQL string interpolation in execute | Use strict Pydantic BaseModel schemas for input/output, including response_model and field allowlists. |
73
+ | `PY-017` | Missing rate limit on sensitive endpoints | Use strict Pydantic BaseModel schemas for input/output, including response_model and field allowlists. |
74
+ | `PY-023` | Playwright context isolation missing per session | Use strict Pydantic BaseModel schemas for input/output, including response_model and field allowlists. |
75
+ | `PY-026` | Sensitive data in logs | Use strict Pydantic BaseModel schemas for input/output, including response_model and field allowlists. |
76
+ | `PY-028` | Missing CSRF on state-changing form endpoints | Use strict Pydantic BaseModel schemas for input/output, including response_model and field allowlists. |
77
+ | `DJA-007` | Insecure Cookie Flags (SESSION/CSRF) | Use strict Pydantic BaseModel schemas for input/output, including response_model and field allowlists. |
78
+ | `DJA-012` | Unsafe Session Serializer: `PickleSerializer` | Use strict Pydantic BaseModel schemas for input/output, including response_model and field allowlists. |
79
+ | `DJA-014` | Weak password hasher | Use strict Pydantic BaseModel schemas for input/output, including response_model and field allowlists. |
80
+ | `MOB-010` | Hardcoded Tokens in Debug Logs | Исключить вывод токенов даже в debug-режиме, применять редактирование/маскирование чувствительных данных в логах. |
81
+ | `DSK-105` | Insecure IPC channel for sensitive actions | Для чувствительных операций использовать `ipcMain.handle` + строгую валидацию payload и проверку источника/role. |
82
+ | `NJS-032` | Insecure JWT Secret Storage via direct env read | Validate data with Zod and sanitize DOM/HTML sinks with DOMPurify before rendering. |
83
+ | `NJS-033` | Weak mTLS/TLS config with `rejectUnauthorized: false` | Validate data with Zod and sanitize DOM/HTML sinks with DOMPurify before rendering. |
84
+ | `FTS-002` | Insecure Client Storage: sensitive tokens/data in web storage | Validate data with Zod and sanitize DOM/HTML sinks with DOMPurify before rendering. |
85
+ | `FTS-003` | Sensitive Console Logging in production builds | Validate data with Zod and sanitize DOM/HTML sinks with DOMPurify before rendering. |
86
+ | `FTS-005` | Client-Side Logic Bypass: critical checks only in frontend | Validate data with Zod and sanitize DOM/HTML sinks with DOMPurify before rendering. |
87
+ | `FTS-014` | Insecure Pseudo-Random for security tokens | Validate data with Zod and sanitize DOM/HTML sinks with DOMPurify before rendering. |
88
+ | `CWE-755-PY` | Fail-Open Error Handling in auth-critical Python paths | Use strict Pydantic BaseModel schemas for input/output, including response_model and field allowlists. |
89
+ | `CWE-384-PY` | Session Fixation in custom Python auth views | Use strict Pydantic BaseModel schemas for input/output, including response_model and field allowlists. |
90
+ | `CWE-613-PY` | Insufficient Session Expiration in Python auth flows | Use strict Pydantic BaseModel schemas for input/output, including response_model and field allowlists. |
91
+ | `CWE-770-PY` | Missing API Rate Limiting for auth/critical endpoints (Python) | Use strict Pydantic BaseModel schemas for input/output, including response_model and field allowlists. |
92
+ | `CWE-770-JS` | Missing API Rate Limiting in Node auth routes | Validate data with Zod and sanitize DOM/HTML sinks with DOMPurify before rendering. |
93
+ | `CWE-20-ORM-MASS-ASSIGN` | ORM Mass Assignment via full payload object without explicit whitelist | Для create/update использовать явный whitelist полей (DTO/pick), блокировать системные/привилегированные атрибуты и валидировать типы. |
94
+ | `CWE-287-KEYCLOAK-JWT-AUD-ISS` | Missing `aud`/`iss` validation in Keycloak JWT verification (`python-jose`) | Use strict Pydantic BaseModel schemas for input/output, including response_model and field allowlists. |
95
+ | `CWE-613-KEYCLOAK-SESSION-CHECKS` | Weak session/token lifetime checks in Keycloak integration | Use strict Pydantic BaseModel schemas for input/output, including response_model and field allowlists. |
96
+ | `CWE-862-NEXTJS-SERVER-ACTION` | Missing authorization checks in Next.js Server Actions (`'use server'`) | Validate data with Zod and sanitize DOM/HTML sinks with DOMPurify before rendering. |
97
+
98
+ ## Verification
99
+
100
+ **Verification:** Check the gold testbed file(s) below for `Vulnerable: <ID>` markers (static Semgrep + `detection-matrix.md` ground truth).
101
+
102
+ - [`gold-standard-testbed/gap_fill_vulnerable.py`](../gold-standard-testbed/gap_fill_vulnerable.py)
103
+
104
+ After changing [`patterns.md`](patterns.md), run from the repo root:
105
+
106
+ ```bash
107
+ python scripts/sync_semgrep.py
108
+ ```
109
+
110
+ ## Workflow: Recon → Scan → Verify
111
+
112
+ ### 1) Recon
113
+ - Map entrypoints, data flows, and trust boundaries for this stack.
114
+ - Identify which metrics in [`patterns.md`](patterns.md) apply to the code under review.
115
+
116
+ ### 2) Scan
117
+ - Run Semgrep with `semgrep-rules/<skill>.yaml` (generated) and correlate with Anti-Patterns.
118
+ - Eliminate findings that cannot bind to a metric row.
119
+
120
+ ### 3) Verify
121
+ - Confirm markers or scanner hits for touched IDs in the gold testbed when adding metrics.
122
+ - Emit findings as `Vulnerable: <PREFIX>-<NNN>` in written reviews.
123
+
@@ -0,0 +1,58 @@
1
+ | ID | Название метрики | Anti-Pattern (Vulnerable Code/YAML) | Safe-Pattern (Remediation) | Stack | Источник fix_template | Exploit scenario |
2
+ |---|---|---|---|---|---|---|
3
+ | PY-100 | Fail-Open Auth (env token) | `if token == os.getenv("CHAT_TOKEN")` | Fail-closed: проверять `None`, валидировать секрет, использовать constant-time compare. | Python | Access Control SAR | Use strict Pydantic BaseModel schemas for input/output, including response_model and field allowlists. | Атакующий доставляет входные данные, соответствующие anti-pattern; реальный ущерб зависит от приёмника (sink), конфигурации и границ доверия. |
4
+ | PY-105 | BOLA in Django queryset | `return Message.objects.all()` | Ограничивать `queryset` по `request.user`/tenant policy. | Python | Access Control SAR | Use strict Pydantic BaseModel schemas for input/output, including response_model and field allowlists. | Атакующий доставляет входные данные, соответствующие anti-pattern; реальный ущерб зависит от приёмника (sink), конфигурации и границ доверия. |
5
+ | NJS-009 | JWT verify without strict policy | `jwt.verify(token, secret)` | Явный `algorithms` allowlist + проверки `iss/aud/exp/nbf`. | Node.js/JavaScript | JWT Governance | Validate data with Zod and sanitize DOM/HTML sinks with DOMPurify before rendering. | Атакующий доставляет входные данные, соответствующие anti-pattern; реальный ущерб зависит от приёмника (sink), конфигурации и границ доверия. |
6
+ | NJS-016 | Missing ownership check (IDOR/BOLA) | `repo.findById(req.params.id)` | Проверять `resource.ownerId == req.user.id` до выдачи объекта. | Node.js/JavaScript | OWASP API1 | Validate data with Zod and sanitize DOM/HTML sinks with DOMPurify before rendering. | Атакующий доставляет входные данные, соответствующие anti-pattern; реальный ущерб зависит от приёмника (sink), конфигурации и границ доверия. |
7
+ | NJS-024 | Weak session cookie policy | `res.cookie("sid", sid)` | `httpOnly`, `secure`, `sameSite`, rotation, revoke on logout. | Node.js/JavaScript | Session Hardening | Validate data with Zod and sanitize DOM/HTML sinks with DOMPurify before rendering. | Атакующий доставляет входные данные, соответствующие anti-pattern; реальный ущерб зависит от приёмника (sink), конфигурации и границ доверия. |
8
+ | NJS-026 | Mass Assignment | `User.create(req.body)` | DTO/allowlist полей, блок системных атрибутов. | Node.js/JavaScript | OWASP Mass Assignment | Validate data with Zod and sanitize DOM/HTML sinks with DOMPurify before rendering. | Атакующий доставляет входные данные, соответствующие anti-pattern; реальный ущерб зависит от приёмника (sink), конфигурации и границ доверия. |
9
+ | PY-011 | JWT algorithm confusion | `decode(token, key)` without allowlist | Фиксированный список алгоритмов и строгая валидация claims. | Python | Auth Baseline | Use strict Pydantic BaseModel schemas for input/output, including response_model and field allowlists. | Атакующий доставляет входные данные, соответствующие anti-pattern; реальный ущерб зависит от приёмника (sink), конфигурации и границ доверия. |
10
+ | PY-013 | ORM mass assignment | `Model(**request.json())` | Явная схема input + whitelist map. | Python | AuthZ Baseline | Use strict Pydantic BaseModel schemas for input/output, including response_model and field allowlists. | Атакующий доставляет входные данные, соответствующие anti-pattern; реальный ущерб зависит от приёмника (sink), конфигурации и границ доверия. |
11
+ | FTS-018 | Hidden UI Auth Bypass | `display:none` вместо server-side ACL | Enforce authorization на backend, не в UI. | Node.js/JavaScript | Client Auth Safety | Validate data with Zod and sanitize DOM/HTML sinks with DOMPurify before rendering. | Атакующий доставляет входные данные, соответствующие anti-pattern; реальный ущерб зависит от приёмника (sink), конфигурации и границ доверия. |
12
+ | FTS-019 | Loose comparison in access checks | `role == "admin"` | Использовать `===`/strict types в auth ветках. | Node.js/JavaScript | JS Auth Safety | Validate data with Zod and sanitize DOM/HTML sinks with DOMPurify before rendering. | Атакующий доставляет входные данные, соответствующие anti-pattern; реальный ущерб зависит от приёмника (sink), конфигурации и границ доверия. |
13
+ | APP-100 | Duplicate token issuance in parallel flow | Повторная выдача токена на один challenge | Вводить idempotency-key и single-flight для token issue. | Application | Architecture Risks | Вводить idempotency-key и single-flight для token issue. | Атакующий доставляет входные данные, соответствующие anti-pattern; реальный ущерб зависит от приёмника (sink), конфигурации и границ доверия. |
14
+ | APP-101 | Missing client timeout policy | HTTP-клиент без `timeout` | Обязательный timeout + retry budget + circuit breaker. | Platform/API | Architecture Risks | Обязательный timeout + retry budget + circuit breaker. | Атакующий доставляет входные данные, соответствующие anti-pattern; реальный ущерб зависит от приёмника (sink), конфигурации и границ доверия. |
15
+ | APP-102 | Fail-open fallback on auth provider error | `except: allow()` | Fail-closed при ошибке внешнего IdP. | Application | Architecture Risks | Fail-closed при ошибке внешнего IdP. | Атакующий доставляет входные данные, соответствующие anti-pattern; реальный ущерб зависит от приёмника (sink), конфигурации и границ доверия. |
16
+ | APP-103 | Missing token replay binding | Токен не связан с устройством/контекстом | Привязка токена к nonce/device/session fingerprint. | Application | Architecture Risks | Привязка токена к nonce/device/session fingerprint. | Атакующий доставляет входные данные, соответствующие anti-pattern; реальный ущерб зависит от приёмника (sink), конфигурации и границ доверия. |
17
+ | APP-104 | Missing MFA enforcement on critical action | Step-up не проверяется | Обязательный MFA gate для high-risk операций. | Application | Architecture Risks | Обязательный MFA gate для high-risk операций. | Атакующий доставляет входные данные, соответствующие anti-pattern; реальный ущерб зависит от приёмника (sink), конфигурации и границ доверия. |
18
+ | APP-105 | Admin action without re-auth | Долгая сессия без повторной верификации | Re-auth/step-up перед привилегированными операциями. | Application | Architecture Risks | Re-auth/step-up перед привилегированными операциями. | Атакующий доставляет входные данные, соответствующие anti-pattern; реальный ущерб зависит от приёмника (sink), конфигурации и границ доверия. |
19
+ | APP-106 | Broad role wildcard in policy | `role in ["*"]` | Явный least-privilege allowlist ролей. | Application | Architecture Risks | Явный least-privilege allowlist ролей. | Атакующий доставляет входные данные, соответствующие anti-pattern; реальный ущерб зависит от приёмника (sink), конфигурации и границ доверия. |
20
+ | APP-107 | Static service token reuse | Один service-token для разных сервисов | Scope-bound short-lived tokens per service. | Application | Architecture Risks | Scope-bound short-lived tokens per service. | Атакующий доставляет входные данные, соответствующие anti-pattern; реальный ущерб зависит от приёмника (sink), конфигурации и границ доверия. |
21
+ | APP-108 | Missing session revocation propagation | Logout не инвалидирует downstream-сессии | Central revocation + backchannel logout. | Application | Architecture Risks | Central revocation + backchannel logout. | Атакующий доставляет входные данные, соответствующие anti-pattern; реальный ущерб зависит от приёмника (sink), конфигурации и границ доверия. |
22
+ | APP-109 | Privileged action via GET | Изменение состояния через GET endpoint | Использовать POST/PUT/PATCH + CSRF guards. | Application | Architecture Risks | Использовать POST/PUT/PATCH + CSRF guards. | Атакующий доставляет входные данные, соответствующие anti-pattern; реальный ущерб зависит от приёмника (sink), конфигурации и границ доверия. |
23
+ | APP-110 | Missing authz check in background worker | Worker выполняет команду без ACL | Проверять subject/scope до исполнения job. | Application | Architecture Risks | Проверять subject/scope до исполнения job. | Атакующий доставляет входные данные, соответствующие anti-pattern; реальный ущерб зависит от приёмника (sink), конфигурации и границ доверия. |
24
+ | APP-111 | Weak API key rotation policy | Неограниченный lifetime ключей | Ротация по SLA + автоотзыв компрометированных ключей. | Application | Architecture Risks | Ротация по SLA + автоотзыв компрометированных ключей. | Атакующий доставляет входные данные, соответствующие anti-pattern; реальный ущерб зависит от приёмника (sink), конфигурации и границ доверия. |
25
+ | APP-112 | No lockout on auth brute force | Бесконечные попытки входа | Rate-limit + progressive delay + lockout. | Application | Architecture Risks | Rate-limit + progressive delay + lockout. | Атакующий доставляет входные данные, соответствующие anti-pattern; реальный ущерб зависит от приёмника (sink), конфигурации и границ доверия. |
26
+ | APP-113 | No tenant isolation in access token | token не содержит tenant context | Включать tenant claim + enforce в policy layer. | Application | Architecture Risks | Включать tenant claim + enforce в policy layer. | Атакующий доставляет входные данные, соответствующие anti-pattern; реальный ущерб зависит от приёмника (sink), конфигурации и границ доверия. |
27
+ | APP-114 | Missing auth audit trail | Нет событий login/privilege escalation | Централизованный security audit log. | Application | Architecture Risks | Централизованный security audit log. | Атакующий доставляет входные данные, соответствующие anti-pattern; реальный ущерб зависит от приёмника (sink), конфигурации и границ доверия. |
28
+ | APP-115 | Insecure impersonation flow | Админ-имперсонация без traceability | Signed delegation token + bounded TTL + audit. | Application | Architecture Risks | Signed delegation token + bounded TTL + audit. | Атакующий доставляет входные данные, соответствующие anti-pattern; реальный ущерб зависит от приёмника (sink), конфигурации и границ доверия. |
29
+ | APP-116 | Silent token refresh failures | Ошибки refresh маскируются | Явная обработка ошибок + forced re-auth. | Application | Architecture Risks | Явная обработка ошибок + forced re-auth. | Атакующий доставляет входные данные, соответствующие anti-pattern; реальный ущерб зависит от приёмника (sink), конфигурации и границ доверия. |
30
+ | APP-117 | No anti-automation controls on auth APIs | Нет device/risk checks | Risk-based controls, captcha/behavioral checks. | Application | Architecture Risks | Risk-based controls, captcha/behavioral checks. | Атакующий доставляет входные данные, соответствующие anti-pattern; реальный ущерб зависит от приёмника (sink), конфигурации и границ доверия. |
31
+ | APP-118 | Missing consent boundary for delegated scopes | Делегированные scope без подтверждения | Явный consent prompt + least-scope default. | Application | Architecture Risks | Явный consent prompt + least-scope default. | Атакующий доставляет входные данные, соответствующие anti-pattern; реальный ущерб зависит от приёмника (sink), конфигурации и границ доверия. |
32
+ | APP-119 | Auth cache poisoning risk | Кэш auth-решений без key scoping | Cache key по subject+scope+tenant+ttl. | Application | Architecture Risks | Cache key по subject+scope+tenant+ttl. | Атакующий доставляет входные данные, соответствующие anti-pattern; реальный ущерб зависит от приёмника (sink), конфигурации и границ доверия. |
33
+ | PY-010 | Insecure random for security tokens | `random.random()` for token | Использовать `secrets` module или `os.urandom`. | Python | Python secrets guidance | Use strict Pydantic BaseModel schemas for input/output, including response_model and field allowlists. | Атакующий доставляет входные данные, соответствующие anti-pattern; реальный ущерб зависит от приёмника (sink), конфигурации и границ доверия. |
34
+ | PY-012 | SQL string interpolation in execute | `session.execute(f"SELECT * FROM t WHERE id={id}")` | Использовать bind parameters / ORM expressions. | Python | CWE-89 | Use strict Pydantic BaseModel schemas for input/output, including response_model and field allowlists. | Атакующий доставляет входные данные, соответствующие anti-pattern; реальный ущерб зависит от приёмника (sink), конфигурации и границ доверия. |
35
+ | PY-017 | Missing rate limit on sensitive endpoints | `@app.post("/login")` without limiter | Добавлять rate limits/bruteforce protection на auth routes. | Python | OWASP API4 | Use strict Pydantic BaseModel schemas for input/output, including response_model and field allowlists. | Атакующий доставляет входные данные, соответствующие anti-pattern; реальный ущерб зависит от приёмника (sink), конфигурации и границ доверия. |
36
+ | PY-023 | Playwright context isolation missing per session | `browser.new_page()` reused globally | Создавать новый `browser.new_context()` для каждой сессии/tenant. | Python | Playwright isolation | Use strict Pydantic BaseModel schemas for input/output, including response_model and field allowlists. | Атакующий доставляет входные данные, соответствующие anti-pattern; реальный ущерб зависит от приёмника (sink), конфигурации и границ доверия. |
37
+ | PY-026 | Sensitive data in logs | `logger.info("token=%s", token)` | Маскировать секреты, использовать structured redaction policy. | Python | OWASP Logging | Use strict Pydantic BaseModel schemas for input/output, including response_model and field allowlists. | Атакующий доставляет входные данные, соответствующие anti-pattern; реальный ущерб зависит от приёмника (sink), конфигурации и границ доверия. |
38
+ | PY-028 | Missing CSRF on state-changing form endpoints | state change endpoint without CSRF check | Включать CSRF protection для cookie-authenticated flows. | Python | OWASP CSRF | Use strict Pydantic BaseModel schemas for input/output, including response_model and field allowlists. | Атакующий доставляет входные данные, соответствующие anti-pattern; реальный ущерб зависит от приёмника (sink), конфигурации и границ доверия. |
39
+ | DJA-007 | Insecure Cookie Flags (SESSION/CSRF) | `SESSION_COOKIE_SECURE = False`<br>`CSRF_COOKIE_SECURE = False` | `SESSION_COOKIE_SECURE = True`<br>`SESSION_COOKIE_HTTPONLY = True`<br>`CSRF_COOKIE_SECURE = True` | Python | `CWE-614` | Use strict Pydantic BaseModel schemas for input/output, including response_model and field allowlists. | Атакующий доставляет входные данные, соответствующие anti-pattern; реальный ущерб зависит от приёмника (sink), конфигурации и границ доверия. |
40
+ | DJA-012 | Unsafe Session Serializer: `PickleSerializer` | `SESSION_SERIALIZER = "django.contrib.sessions.serializers.PickleSerializer"` | `SESSION_SERIALIZER = "django.contrib.sessions.serializers.JSONSerializer"` | Python | `CWE-502` | Use strict Pydantic BaseModel schemas for input/output, including response_model and field allowlists. | Атакующий доставляет входные данные, соответствующие anti-pattern; реальный ущерб зависит от приёмника (sink), конфигурации и границ доверия. |
41
+ | DJA-014 | Weak password hasher | `PASSWORD_HASHERS = ["django.contrib.auth.hashers.MD5PasswordHasher"]` | `PASSWORD_HASHERS = ["django.contrib.auth.hashers.Argon2PasswordHasher", "django.contrib.auth.hashers.BCryptSHA256PasswordHasher"]` | Python | `CWE-330` | Use strict Pydantic BaseModel schemas for input/output, including response_model and field allowlists. | Атакующий доставляет входные данные, соответствующие anti-pattern; реальный ущерб зависит от приёмника (sink), конфигурации и границ доверия. |
42
+ | MOB-010 | Hardcoded Tokens in Debug Logs | `if (kDebugMode) {`<br>` print('token - $token');`<br>`}` | Исключить вывод токенов даже в debug-режиме, применять редактирование/маскирование чувствительных данных в логах. | Flutter | Silk Mobile SAR | Исключить вывод токенов даже в debug-режиме, применять редактирование/маскирование чувствительных данных в логах. | Атакующий доставляет входные данные, соответствующие anti-pattern; реальный ущерб зависит от приёмника (sink), конфигурации и границ доверия. |
43
+ | DSK-105 | Insecure IPC channel for sensitive actions | `ipcMain.on("export-secrets", (event, payload) => { ... })` | Для чувствительных операций использовать `ipcMain.handle` + строгую валидацию payload и проверку источника/role. | Electron/Desktop | Insight SAR | Для чувствительных операций использовать `ipcMain.handle` + строгую валидацию payload и проверку источника/role. | Атакующий доставляет входные данные, соответствующие anti-pattern; реальный ущерб зависит от приёмника (sink), конфигурации и границ доверия. |
44
+ | NJS-032 | Insecure JWT Secret Storage via direct env read | `const secret = process.env.JWT_SECRET` | Получать JWT secrets через Secret Manager/Vault/KMS abstraction с ротацией и аудитом доступа, не читать напрямую в runtime logic. | Node.js/JavaScript | JWT Secret Management | Validate data with Zod and sanitize DOM/HTML sinks with DOMPurify before rendering. | Атакующий доставляет входные данные, соответствующие anti-pattern; реальный ущерб зависит от приёмника (sink), конфигурации и границ доверия. |
45
+ | NJS-033 | Weak mTLS/TLS config with `rejectUnauthorized: false` | `https.request({ rejectUnauthorized: false })` | Всегда включать валидацию сертификатов, использовать trust store/pinning и запретить insecure TLS overrides в production. | Node.js/JavaScript | TLS/mTLS Hardening | Validate data with Zod and sanitize DOM/HTML sinks with DOMPurify before rendering. | Атакующий доставляет входные данные, соответствующие anti-pattern; реальный ущерб зависит от приёмника (sink), конфигурации и границ доверия. |
46
+ | FTS-002 | Insecure Client Storage: sensitive tokens/data in web storage | `localStorage.setItem("jwt", token)`<br>`sessionStorage.setItem("snils", value)` | Хранить access/session данные в `httpOnly` cookies с `Secure`/`SameSite`, не сохранять JWT/ПДн/секреты в JS-readable storage. | Node.js/JavaScript | OWASP ASVS Session Management | Validate data with Zod and sanitize DOM/HTML sinks with DOMPurify before rendering. | Атакующий доставляет входные данные, соответствующие anti-pattern; реальный ущерб зависит от приёмника (sink), конфигурации и границ доверия. |
47
+ | FTS-003 | Sensitive Console Logging in production builds | `console.log("token", token)`<br>`console.error("user profile", profile)` | Запретить вывод чувствительных данных в `console.*` на проде; использовать redaction и build-time stripping логов. | Node.js/JavaScript | OWASP Logging Cheat Sheet | Validate data with Zod and sanitize DOM/HTML sinks with DOMPurify before rendering. | Атакующий доставляет входные данные, соответствующие anti-pattern; реальный ущерб зависит от приёмника (sink), конфигурации и границ доверия. |
48
+ | FTS-005 | Client-Side Logic Bypass: critical checks only in frontend | `if (user.role === "admin") price = 0`<br>`if (clientAmount < limit) approve()` | Критичную бизнес-логику (цены, лимиты, ACL) дублировать и enforce на backend/API, фронтенд использовать только как UX слой. | Node.js/JavaScript | OWASP Top 10 A04 Insecure Design | Validate data with Zod and sanitize DOM/HTML sinks with DOMPurify before rendering. | Атакующий доставляет входные данные, соответствующие anti-pattern; реальный ущерб зависит от приёмника (sink), конфигурации и границ доверия. |
49
+ | FTS-014 | Insecure Pseudo-Random for security tokens | `const token = Math.random().toString(36)` | Для токенов/идентификаторов использовать `window.crypto.getRandomValues()` и криптографически стойкие генераторы. | Node.js/JavaScript | Web Crypto API Guidance | Validate data with Zod and sanitize DOM/HTML sinks with DOMPurify before rendering. | Атакующий доставляет входные данные, соответствующие anti-pattern; реальный ущерб зависит от приёмника (sink), конфигурации и границ доверия. |
50
+ | CWE-755-PY | Fail-Open Error Handling in auth-critical Python paths | `def verify_token(token):`<br>` try:`<br>` return decode_token(token)`<br>` except Exception:`<br>` logger.error("auth failed")`<br>` return True` | Для auth/authorization функций использовать fail-closed: после исключения немедленно `raise`/`return False`, без продолжения выполнения критического кода. | Python | CWE Compliance | Use strict Pydantic BaseModel schemas for input/output, including response_model and field allowlists. | Атакующий доставляет входные данные, соответствующие anti-pattern; реальный ущерб зависит от приёмника (sink), конфигурации и границ доверия. |
51
+ | CWE-384-PY | Session Fixation in custom Python auth views | `login(request, user)` без `request.session.cycle_key()`<br>`# no rotate_token(request)` | После успешной аутентификации выполнять `session.cycle_key()` и `rotate_token(request)` для инвалидизации старого session ID. | Python | CWE Compliance - Logic/Resources | Use strict Pydantic BaseModel schemas for input/output, including response_model and field allowlists. | Атакующий доставляет входные данные, соответствующие anti-pattern; реальный ущерб зависит от приёмника (sink), конфигурации и границ доверия. |
52
+ | CWE-613-PY | Insufficient Session Expiration in Python auth flows | `SESSION_COOKIE_AGE = 60*60*24*30`<br>`# no idle timeout / absolute timeout` | Ограничить TTL сессии, вводить idle/absolute timeout и принудительный re-auth для чувствительных операций. | Python | CWE Final Certification | Use strict Pydantic BaseModel schemas for input/output, including response_model and field allowlists. | Атакующий доставляет входные данные, соответствующие anti-pattern; реальный ущерб зависит от приёмника (sink), конфигурации и границ доверия. |
53
+ | CWE-770-PY | Missing API Rate Limiting for auth/critical endpoints (Python) | `@app.post("/login")` без limiter/throttle | Включить rate limiting (per-IP/per-user), burst control и lockout policy на критичных endpoint-ах. | Python | CWE Final Certification | Use strict Pydantic BaseModel schemas for input/output, including response_model and field allowlists. | Атакующий доставляет входные данные, соответствующие anti-pattern; реальный ущерб зависит от приёмника (sink), конфигурации и границ доверия. |
54
+ | CWE-770-JS | Missing API Rate Limiting in Node auth routes | `app.post("/login", handler)` без limiter middleware | Добавить `express-rate-limit`/аналог, ограничивать частоту и вводить progressive delays. | Node.js/JavaScript | CWE Final Certification | Validate data with Zod and sanitize DOM/HTML sinks with DOMPurify before rendering. | Атакующий доставляет входные данные, соответствующие anti-pattern; реальный ущерб зависит от приёмника (sink), конфигурации и границ доверия. |
55
+ | CWE-20-ORM-MASS-ASSIGN | ORM Mass Assignment via full payload object without explicit whitelist | `Model(**request.json)`<br>`Model.create(req.body)` | Для create/update использовать явный whitelist полей (DTO/pick), блокировать системные/привилегированные атрибуты и валидировать типы. | Universal | CWE Final Certification | Для create/update использовать явный whitelist полей (DTO/pick), блокировать системные/привилегированные атрибуты и валидировать типы. | Атакующий доставляет входные данные, соответствующие anti-pattern; реальный ущерб зависит от приёмника (sink), конфигурации и границ доверия. |
56
+ | CWE-287-KEYCLOAK-JWT-AUD-ISS | Missing `aud`/`iss` validation in Keycloak JWT verification (`python-jose`) | `jwt.decode(token, key, algorithms=["RS256"])` без `audience`/`issuer` | При проверке Keycloak JWT всегда валидировать `aud` и `iss` (expected realm issuer), отклонять токены с несовпадающими claims. | Python/Keycloak | CWE Final Certification | Use strict Pydantic BaseModel schemas for input/output, including response_model and field allowlists. | Атакующий доставляет входные данные, соответствующие anti-pattern; реальный ущерб зависит от приёмника (sink), конфигурации и границ доверия. |
57
+ | CWE-613-KEYCLOAK-SESSION-CHECKS | Weak session/token lifetime checks in Keycloak integration | Проверка JWT без контроля `exp/nbf` и политики сессии realm/client | Валидация времени жизни токена (`exp/nbf`), короткие TTL, rotation и принудительная ревокация при logout/компрометации. | Python/Keycloak | CWE Final Certification | Use strict Pydantic BaseModel schemas for input/output, including response_model and field allowlists. | Атакующий доставляет входные данные, соответствующие anti-pattern; реальный ущерб зависит от приёмника (sink), конфигурации и границ доверия. |
58
+ | CWE-862-NEXTJS-SERVER-ACTION | Missing authorization checks in Next.js Server Actions (`'use server'`) | `\"use server\"` функция без `getServerSession(...)`/`auth()` в начале | В каждом Server Action выполнять проверку аутентификации/авторизации в начале функции и fail-closed при отсутствии валидной сессии. | Node.js/Next.js 14 | CWE Final Certification | Validate data with Zod and sanitize DOM/HTML sinks with DOMPurify before rendering. | Атакующий доставляет входные данные, соответствующие anti-pattern; реальный ущерб зависит от приёмника (sink), конфигурации и границ доверия. |
@@ -0,0 +1,36 @@
1
+ {
2
+ "skill_id": "domain-access-management",
3
+ "name": "Domain Access Management",
4
+ "activation_triggers": [
5
+ "fail-open-auth",
6
+ "bola-owner-check",
7
+ "session-cookie-policy",
8
+ "jwt-claim-validation",
9
+ "app-auth-architecture"
10
+ ],
11
+ "relevant_extensions": [
12
+ ".py",
13
+ ".js",
14
+ ".ts",
15
+ ".json"
16
+ ],
17
+ "tools": [
18
+ "semgrep",
19
+ "syft",
20
+ "trufflehog"
21
+ ],
22
+ "rules_path": "core/skills/domain-access-management/patterns.md",
23
+ "few_shot_examples": "core/gold-standard-testbed/gap_fill_vulnerable.py",
24
+ "mitigation_logic": {
25
+ "BOLA": {
26
+ "exception_rule": "Если в endpoint-коде реализована явная Ownership-проверка (сравнение user_id из токена и owner_id целевого объекта), риск BOLA считается закрытым.",
27
+ "status_override": "OK",
28
+ "validation_requirements": [
29
+ "Идентификатор субъекта извлекается из верифицированного токена/контекста сессии.",
30
+ "Перед доступом к объекту выполняется прямое условие равенства user_id == owner_id (или эквивалентная deny-by-default проверка)."
31
+ ],
32
+ "rationale": "Объектный доступ ограничен владельцем ресурса, что исключает горизонтальную эскалацию привилегий по IDOR/BOLA сценарию."
33
+ }
34
+ },
35
+ "security_priority": 9
36
+ }
@@ -0,0 +1,98 @@
1
+ # Domain Data Privacy
2
+
3
+ ## Stack overview
4
+
5
+ PII and secret leakage controls across logs, traces, browser storage, and runtime diagnostics.
6
+
7
+ ## Top threats
8
+
9
+ - **Validate data with Zod and sanitize DOM/HTML sinks with DOMPurify before rendering.**: 19 metrics (`FTS-002`, `FTS-003`, `FTS-008`, `NJS-010`)
10
+ - **Use strict Pydantic BaseModel schemas for input/output, including response_model and field allowlists.**: 17 metrics (`PY-002`, `PY-009`, `PY-026`, `DJA-008`)
11
+ - **Use using/try-finally and safe .NET APIs; enforce strict allowlists for untrusted input.**: 3 metrics (`CWE-798-CSH-CONFIG-SECRETS`, `CWE-384-CSH-STATIC-TOKEN-CONTEXT`, `CWE-532-CSH-OFFICE-PII-LOG`)
12
+ - **Sanitization pipeline до отправки в telemetry backend.**: 1 metrics (`LOG-012`)
13
+ - **Включить `window.setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE)` для защиты экрана от скриншотов и записи.**: 1 metrics (`MOB-021`)
14
+ - **Маскирование ПДн и policy-based log redaction.**: 1 metrics (`RRC-001`)
15
+ - **Не передавать секреты в query string; использовать Authorization header/body и redaction policy для логов/телеметрии.**: 1 metrics (`CWE-359-AXIOS-PARAMS-LEAK`)
16
+ - **Перед логированием принудительно заменять/экранировать `\r` и `\n` (например, `\\r`/`\\n`), применять centralized log sanitizer.**: 1 metrics (`CWE-117-UNIVERSAL-CRLF`)
17
+ - **Передавать секреты через Secret Manager/ESO/Vault, исключать plaintext ENV в Docker/K8s manifests.**: 1 metrics (`CWE-312-ENV`)
18
+ - **Хранить ключи только во внешнем secret manager/env, маскировать в логах и исключать из репозитория/trace output.**: 1 metrics (`CWE-200-OPENROUTER-APIKEY-LEAK`)
19
+
20
+ ## Pattern catalog
21
+
22
+ Complete Anti-Pattern / Safe-Pattern definitions live in [`patterns.md`](patterns.md). The table below is a **table of contents** by metric ID.
23
+
24
+ | ID | Metric | Stack |
25
+ |---|---|---|
26
+ | `FTS-002` | Sensitive data in client storage | Validate data with Zod and sanitize DOM/HTML sinks with DOMPurify before rendering. |
27
+ | `FTS-003` | Sensitive console logging | Validate data with Zod and sanitize DOM/HTML sinks with DOMPurify before rendering. |
28
+ | `FTS-008` | Source-map data exposure | Validate data with Zod and sanitize DOM/HTML sinks with DOMPurify before rendering. |
29
+ | `PY-002` | Error detail leakage | Use strict Pydantic BaseModel schemas for input/output, including response_model and field allowlists. |
30
+ | `PY-009` | Hardcoded secret in code | Use strict Pydantic BaseModel schemas for input/output, including response_model and field allowlists. |
31
+ | `PY-026` | Secrets in logs | Use strict Pydantic BaseModel schemas for input/output, including response_model and field allowlists. |
32
+ | `NJS-010` | Stacktrace leakage in API | Validate data with Zod and sanitize DOM/HTML sinks with DOMPurify before rendering. |
33
+ | `NJS-035` | Sensitive data retained in memory | Validate data with Zod and sanitize DOM/HTML sinks with DOMPurify before rendering. |
34
+ | `RRC-001` | PII leakage in logs (152-FZ) | Маскирование ПДн и policy-based log redaction. |
35
+ | `LOG-012` | PII/secret leakage in observability | Sanitization pipeline до отправки в telemetry backend. |
36
+ | `DJA-008` | Hardcoded Secret Key | Use strict Pydantic BaseModel schemas for input/output, including response_model and field allowlists. |
37
+ | `DJA-010` | Verbose error leakage to client | Use strict Pydantic BaseModel schemas for input/output, including response_model and field allowlists. |
38
+ | `DJA-015` | Unsafe logout redirect | Use strict Pydantic BaseModel schemas for input/output, including response_model and field allowlists. |
39
+ | `DJA-018` | Missing `LoginRequiredMixin` on CBV | Use strict Pydantic BaseModel schemas for input/output, including response_model and field allowlists. |
40
+ | `MOB-021` | UI Privacy Missing FLAG_SECURE | Включить `window.setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE)` для защиты экрана от скриншотов и записи. |
41
+ | `NJS-005` | Missing process crash guards for async/runtime failures | Validate data with Zod and sanitize DOM/HTML sinks with DOMPurify before rendering. |
42
+ | `NJS-019` | Abuse of process.env directly in business logic | Validate data with Zod and sanitize DOM/HTML sinks with DOMPurify before rendering. |
43
+ | `NJS-034` | Unsafe stream piping without error handlers | Validate data with Zod and sanitize DOM/HTML sinks with DOMPurify before rendering. |
44
+ | `FTS-017` | Unsafe Message Parsing in message handlers | Validate data with Zod and sanitize DOM/HTML sinks with DOMPurify before rendering. |
45
+ | `FTS-020` | Unhandled Async Errors in Promise/async flows | Validate data with Zod and sanitize DOM/HTML sinks with DOMPurify before rendering. |
46
+ | `CWE-327-PY` | Weak Hash Algorithms in Python (MD5/SHA1) | Use strict Pydantic BaseModel schemas for input/output, including response_model and field allowlists. |
47
+ | `CWE-328-PY` | Weak Crypto Mode (ECB) in Python | Use strict Pydantic BaseModel schemas for input/output, including response_model and field allowlists. |
48
+ | `CWE-338-PY` | Predictable Random for tokens/passwords in Python | Use strict Pydantic BaseModel schemas for input/output, including response_model and field allowlists. |
49
+ | `CWE-327-JS` | Weak Hash/Cipher in Node.js crypto | Validate data with Zod and sanitize DOM/HTML sinks with DOMPurify before rendering. |
50
+ | `CWE-338-JS` | Predictable Random for session IDs in JavaScript | Validate data with Zod and sanitize DOM/HTML sinks with DOMPurify before rendering. |
51
+ | `CWE-200-PY` | Information Disclosure via hardcoded internal/Sheets URLs | Use strict Pydantic BaseModel schemas for input/output, including response_model and field allowlists. |
52
+ | `CWE-200-JS` | Source leak via sensitive fields in model toString | Validate data with Zod and sanitize DOM/HTML sinks with DOMPurify before rendering. |
53
+ | `CWE-117-PY` | Log Injection in Python logging with unsanitized user input | Use strict Pydantic BaseModel schemas for input/output, including response_model and field allowlists. |
54
+ | `CWE-117-JS` | Log Injection in JS/Node logs | Validate data with Zod and sanitize DOM/HTML sinks with DOMPurify before rendering. |
55
+ | `CWE-404-JS` | Resource Leak with stream handles in Node.js | Validate data with Zod and sanitize DOM/HTML sinks with DOMPurify before rendering. |
56
+ | `CWE-312-JS` | Cleartext token storage in browser localStorage | Validate data with Zod and sanitize DOM/HTML sinks with DOMPurify before rendering. |
57
+ | `CWE-312-PY` | Cleartext secret/password in Python settings | Use strict Pydantic BaseModel schemas for input/output, including response_model and field allowlists. |
58
+ | `CWE-532-PY` | Sensitive data written to logs in plaintext | Use strict Pydantic BaseModel schemas for input/output, including response_model and field allowlists. |
59
+ | `CWE-312-ENV` | Cleartext secrets in environment/Docker configuration | Передавать секреты через Secret Manager/ESO/Vault, исключать plaintext ENV в Docker/K8s manifests. |
60
+ | `CWE-532-PY-DECORATOR` | PII leak in Python decorator-based logging | Use strict Pydantic BaseModel schemas for input/output, including response_model and field allowlists. |
61
+ | `CWE-117-UNIVERSAL-CRLF` | Log Injection via unsanitized CRLF in user-controlled log fields | Перед логированием принудительно заменять/экранировать `\r` и `\n` (например, `\\r`/`\\n`), применять centralized log sanitizer. |
62
+ | `CWE-74-PY-LDAP` | LDAP Injection in Python (`ldap3`) filter construction | Use strict Pydantic BaseModel schemas for input/output, including response_model and field allowlists. |
63
+ | `CWE-74-JS-LDAP` | LDAP Injection in Node.js (`ldapjs`) filter concatenation | Validate data with Zod and sanitize DOM/HTML sinks with DOMPurify before rendering. |
64
+ | `CWE-359-AXIOS-PARAMS-LEAK` | Sensitive data exposure via Axios `params` query string (`token/password/secret`) | Не передавать секреты в query string; использовать Authorization header/body и redaction policy для логов/телеметрии. |
65
+ | `CWE-524-AXIOS-CACHE-AUTH` | Missing `Cache-Control: no-store` on Axios GET to `/api/user/*` or `/api/auth/*` | Validate data with Zod and sanitize DOM/HTML sinks with DOMPurify before rendering. |
66
+ | `CWE-200-NEXTJS-CLIENT-ENV` | Secret env leak: server-side env vars used in `use client` components | Validate data with Zod and sanitize DOM/HTML sinks with DOMPurify before rendering. |
67
+ | `CWE-200-OPENROUTER-APIKEY-LEAK` | Hardcoded OpenRouter/OpenAI API keys in code/logs | Хранить ключи только во внешнем secret manager/env, маскировать в логах и исключать из репозитория/trace output. |
68
+ | `CWE-922-FASTAPI-HEADER-LOG` | Sensitive headers (`Authorization`, `Set-Cookie`) logged by request middleware | Use strict Pydantic BaseModel schemas for input/output, including response_model and field allowlists. |
69
+ | `CWE-798-CSH-CONFIG-SECRETS` | Hardcoded API keys/passwords in `.config`, `Settings.settings`, `.resx` for C# desktop ... | Use using/try-finally and safe .NET APIs; enforce strict allowlists for untrusted input. |
70
+ | `CWE-384-CSH-STATIC-TOKEN-CONTEXT` | Session fixation risk via `public static` token/user context fields in VSTO classes | Use using/try-finally and safe .NET APIs; enforce strict allowlists for untrusted input. |
71
+ | `CWE-532-CSH-OFFICE-PII-LOG` | PII leakage: logging Office object properties (`MailItem.SenderEmailAddress`, `Document... | Use using/try-finally and safe .NET APIs; enforce strict allowlists for untrusted input. |
72
+
73
+ ## Verification
74
+
75
+ **Verification:** Check the gold testbed file(s) below for `Vulnerable: <ID>` markers (static Semgrep + `detection-matrix.md` ground truth).
76
+
77
+ - [`gold-standard-testbed/gap_fill_vulnerable.py`](../gold-standard-testbed/gap_fill_vulnerable.py)
78
+
79
+ After changing [`patterns.md`](patterns.md), run from the repo root:
80
+
81
+ ```bash
82
+ python scripts/sync_semgrep.py
83
+ ```
84
+
85
+ ## Workflow: Recon → Scan → Verify
86
+
87
+ ### 1) Recon
88
+ - Map entrypoints, data flows, and trust boundaries for this stack.
89
+ - Identify which metrics in [`patterns.md`](patterns.md) apply to the code under review.
90
+
91
+ ### 2) Scan
92
+ - Run Semgrep with `semgrep-rules/<skill>.yaml` (generated) and correlate with Anti-Patterns.
93
+ - Eliminate findings that cannot bind to a metric row.
94
+
95
+ ### 3) Verify
96
+ - Confirm markers or scanner hits for touched IDs in the gold testbed when adding metrics.
97
+ - Emit findings as `Vulnerable: <PREFIX>-<NNN>` in written reviews.
98
+