Compare commits

...
Author SHA1 Message Date
testclient-admin 34b28b6d19 security-analysis/policy.yml: low блокирует merge
security/scan 0 findings, 0 blocking
security / scan (pull_request) Successful in 53s
security/review 0 findings, 0 blocking
security / review (pull_request) Successful in 1m24s
security / deep-audit (pull_request) Skipped
2026-09-01 06:29:03 +00:00
testclient-admin 801bdafc91 Merge pull request 'Add Level 0 + Level 1 + Level 2 security scanning' (#19) from add-security-scanning into main
Reviewed-on: testclient-admin/playground#19
2026-08-25 07:34:16 +00:00
testclient-admin 90c797e500 Level 0: security scanning for pull requests
security/scan 0 findings, 0 blocking
security / scan (pull_request) Successful in 1m5s
security/review 0 findings, 0 blocking
security / review (pull_request) Successful in 1m24s
security / deep-audit (pull_request) Skipped
2026-08-25 07:16:05 +00:00
testclient-admin 023f6c016a Level 0: security scanning for pull requests 2026-08-25 07:16:04 +00:00
testclient-admin 97f18a399b Level 0: security scanning for pull requests 2026-08-25 07:16:03 +00:00
testclient-admin 789aa6adaa Merge pull request 'Add Level 0 + Level 1 + Level 2 security scanning' (#16) from add-security-scanning into main
Reviewed-on: testclient-admin/playground#16
2026-08-25 04:03:04 +00:00
testclient-admin d9d1da21ed Level 0: security scanning for pull requests
security/scan 3 findings, 3 blocking
security / scan (pull_request) Failing after 56s
security/review 0 findings, 0 blocking
security / review (pull_request) Successful in 1m27s
security / deep-audit (pull_request) Skipped
2026-08-25 03:08:09 +00:00
testclient-admin b4d891c229 Level 0: security scanning for pull requests 2026-08-25 03:08:08 +00:00
testclient-admin dc1066e208 Level 0: security scanning for pull requests 2026-08-25 03:08:07 +00:00
2 changed files with 45 additions and 35 deletions
+40 -31
View File
@@ -49,7 +49,30 @@ jobs:
curl -sSL -o /tmp/gitleaks.tar.gz \ curl -sSL -o /tmp/gitleaks.tar.gz \
"https://github.com/gitleaks/gitleaks/releases/download/v8.30.1/gitleaks_8.30.1_linux_${GL_ARCH}.tar.gz" "https://github.com/gitleaks/gitleaks/releases/download/v8.30.1/gitleaks_8.30.1_linux_${GL_ARCH}.tar.gz"
tar -xzf /tmp/gitleaks.tar.gz -C /usr/local/bin gitleaks tar -xzf /tmp/gitleaks.tar.gz -C /usr/local/bin gitleaks
gitleaks detect --source=. --report-format json --report-path /tmp/gitleaks.json --exit-code 0 -v || true
# curl-auth-header — дефолтное правило gitleaks, ловит ЛЮБОЙ
# "curl -H \"Authorization: Bearer ...\"" по форме, не по
# содержимому. Подтверждено живьём на нескольких клиентских
# README: ни одна формулировка примера (одинаковый токен,
# разные токены, плейсхолдер в угловых скобках) не проходит
# — а HIGH-находка блокирует мерж навсегда, потому что
# документация с примером curl-запроса есть почти у любого
# проекта с API. Точечно исключаем только эту находку на
# markdown-файлах; остальные правила (реальные секреты по
# энтропии/префиксам) продолжают действовать и там.
cat > /tmp/.gitleaks.toml <<'GLCFG'
[extend]
useDefault = true
[[rules]]
id = "curl-auth-header"
[rules.allowlist]
paths = ['''(?i)\.md$''']
GLCFG
gitleaks detect --source=. --config=/tmp/.gitleaks.toml \
--report-format json --report-path /tmp/gitleaks.json --exit-code 0 -v || true
[ -f /tmp/gitleaks.json ] || echo '[]' > /tmp/gitleaks.json [ -f /tmp/gitleaks.json ] || echo '[]' > /tmp/gitleaks.json
- name: semgrep (SAST) - name: semgrep (SAST)
@@ -64,17 +87,15 @@ jobs:
REPO_FULL: ${{ gitea.repository }} REPO_FULL: ${{ gitea.repository }}
PR_NUMBER: ${{ gitea.event.pull_request.number }} PR_NUMBER: ${{ gitea.event.pull_request.number }}
COMMIT_SHA: ${{ gitea.event.pull_request.head.sha }} COMMIT_SHA: ${{ gitea.event.pull_request.head.sha }}
HEAD_REF: ${{ gitea.head_ref }}
run: | run: |
python3 <<'PYEOF' python3 <<'PYEOF'
import base64, json, os, sys, time, urllib.error, urllib.request import json, os, sys, time, urllib.error, urllib.request
SERVER = os.environ["GITEA_SERVER"].rstrip("/") SERVER = os.environ["GITEA_SERVER"].rstrip("/")
REPO = os.environ["REPO_FULL"] REPO = os.environ["REPO_FULL"]
TOKEN = os.environ["SECURITY_BOT_TOKEN"] TOKEN = os.environ["SECURITY_BOT_TOKEN"]
PR_NUMBER = os.environ.get("PR_NUMBER", "") PR_NUMBER = os.environ.get("PR_NUMBER", "")
COMMIT_SHA = os.environ["COMMIT_SHA"] COMMIT_SHA = os.environ["COMMIT_SHA"]
HEAD_REF = os.environ["HEAD_REF"]
def gitea(method, path, payload=None): def gitea(method, path, payload=None):
req = urllib.request.Request( req = urllib.request.Request(
@@ -170,17 +191,17 @@ jobs:
print(f"не удалось прочитать прежние статусы, продолжаю без sticky-fail: {e}") print(f"не удалось прочитать прежние статусы, продолжаю без sticky-fail: {e}")
sticky = prior_failed and not blocked sticky = prior_failed and not blocked
outdir = f"security-analysis/findings/pr-{PR_NUMBER or 'manual'}" # Раньше находки ещё и коммитились в ветку PR. Плохая
os.makedirs(outdir, exist_ok=True) # идея с точки зрения git-гигиены: чужая ветка растёт
outpath = f"{outdir}/{int(time.time())}.json" # коммитами от бота, каждый такой коммит сам порождает
json.dump(findings, open(outpath, "w"), ensure_ascii=False, indent=2) # pull_request:synchronize (нужна отдельная защита от
# петли), а когда коммит бота становится головой PR —
gitea("POST", f"/repos/{REPO}/contents/{outpath}", { # обязательные security/scan и security/review больше
"content": base64.b64encode(open(outpath, "rb").read()).decode(), # никогда не выставляются на этой голове, потому что
"message": f"security: scan results for PR #{PR_NUMBER}", # job их специально пропускает для бота же — PR
"branch": HEAD_REF, # перестаёт мержиться насовсем (поймано живьём).
}) # Комментарий в PR (ниже) и так несёт всё нужное
# человеку; отдельного коммита с JSON не требуется.
counts = {} counts = {}
for f in findings: for f in findings:
counts[f["severity"]] = counts.get(f["severity"], 0) + 1 counts[f["severity"]] = counts.get(f["severity"], 0) + 1
@@ -192,7 +213,6 @@ jobs:
body += "\n\n" body += "\n\n"
for f in top: for f in top:
body += f"**{f['severity'].upper()}** `{f['file']}:{f['line_start']}` — {f['title']} ({f['source']})\n\n" body += f"**{f['severity'].upper()}** `{f['file']}:{f['line_start']}` — {f['title']} ({f['source']})\n\n"
body += f"Полный список: `{outpath}`\n\n"
if sticky: if sticky:
body += "🔴 **Merge заблокирован** — этот же коммит уже был помечен как блокирующий в более раннем прогоне; новый прогон нашёл меньше, но старую блокировку это не снимает (нужен новый коммит).\n" body += "🔴 **Merge заблокирован** — этот же коммит уже был помечен как блокирующий в более раннем прогоне; новый прогон нашёл меньше, но старую блокировку это не снимает (нужен новый коммит).\n"
else: else:
@@ -204,7 +224,6 @@ jobs:
"state": "failure" if (blocked or sticky) else "success", "state": "failure" if (blocked or sticky) else "success",
"context": "security/scan", "context": "security/scan",
"description": (f"{len(findings)} findings, {len(blocking)} blocking" + (" (sticky: prior run flagged this commit)" if sticky else "")), "description": (f"{len(findings)} findings, {len(blocking)} blocking" + (" (sticky: prior run flagged this commit)" if sticky else "")),
"target_url": f"{SERVER}/{REPO}/src/branch/{HEAD_REF}/{outpath}",
}) })
print(f"findings: {len(findings)}, blocking: {len(blocking)}, sticky: {sticky}") print(f"findings: {len(findings)}, blocking: {len(blocking)}, sticky: {sticky}")
@@ -363,17 +382,15 @@ jobs:
REPO_FULL: ${{ gitea.repository }} REPO_FULL: ${{ gitea.repository }}
PR_NUMBER: ${{ gitea.event.pull_request.number }} PR_NUMBER: ${{ gitea.event.pull_request.number }}
COMMIT_SHA: ${{ gitea.event.pull_request.head.sha }} COMMIT_SHA: ${{ gitea.event.pull_request.head.sha }}
HEAD_REF: ${{ gitea.head_ref }}
run: | run: |
python3 <<'PYEOF2' python3 <<'PYEOF2'
import base64, json, os, sys, time, urllib.error, urllib.request import json, os, sys, time, urllib.error, urllib.request
SERVER = os.environ["GITEA_SERVER"].rstrip("/") SERVER = os.environ["GITEA_SERVER"].rstrip("/")
REPO = os.environ["REPO_FULL"] REPO = os.environ["REPO_FULL"]
TOKEN = os.environ["SECURITY_BOT_TOKEN"] TOKEN = os.environ["SECURITY_BOT_TOKEN"]
PR_NUMBER = os.environ.get("PR_NUMBER", "") PR_NUMBER = os.environ.get("PR_NUMBER", "")
COMMIT_SHA = os.environ["COMMIT_SHA"] COMMIT_SHA = os.environ["COMMIT_SHA"]
HEAD_REF = os.environ["HEAD_REF"]
def gitea(method, path, payload=None): def gitea(method, path, payload=None):
req = urllib.request.Request( req = urllib.request.Request(
@@ -473,16 +490,9 @@ jobs:
print(f"не удалось прочитать прежние статусы, продолжаю без sticky-fail: {e}") print(f"не удалось прочитать прежние статусы, продолжаю без sticky-fail: {e}")
sticky = prior_failed and not blocked sticky = prior_failed and not blocked
outdir = f"security-analysis/findings/pr-{PR_NUMBER or 'manual'}" # Коммит с findings-json в ветку PR убран — та же причина,
outpath = f"{outdir}/{int(time.time())}-review.json" # что и в шаге scan: он ломает мержимость PR насовсем,
# как только становится головой (см. комментарий там).
if findings:
gitea("POST", f"/repos/{REPO}/contents/{outpath}", {
"content": base64.b64encode(json.dumps(findings, ensure_ascii=False, indent=2).encode()).decode(),
"message": f"security: AI review results for PR #{PR_NUMBER}",
"branch": HEAD_REF,
})
counts = {} counts = {}
for f in findings: for f in findings:
counts[f["severity"]] = counts.get(f["severity"], 0) + 1 counts[f["severity"]] = counts.get(f["severity"], 0) + 1
@@ -499,7 +509,6 @@ jobs:
body += f"**{f['severity'].upper()}** (`{f['confidence']:.2f}`) `{f['file']}:{f['line_start']}` — {f['title']}\n\n" body += f"**{f['severity'].upper()}** (`{f['confidence']:.2f}`) `{f['file']}:{f['line_start']}` — {f['title']}\n\n"
if f.get("exploit_scenario"): if f.get("exploit_scenario"):
body += f" сценарий: {f['exploit_scenario']}\n\n" body += f" сценарий: {f['exploit_scenario']}\n\n"
body += f"Полный список: `{outpath}`\n\n"
if sticky: if sticky:
body += "🔴 **Merge заблокирован** — этот же коммит уже был помечен как блокирующий в более раннем прогоне ревью; новый прогон ничего не нашёл, но старую блокировку это не снимает (нужен новый коммит).\n" body += "🔴 **Merge заблокирован** — этот же коммит уже был помечен как блокирующий в более раннем прогоне ревью; новый прогон ничего не нашёл, но старую блокировку это не снимает (нужен новый коммит).\n"
else: else:
+5 -4
View File
@@ -1,7 +1,8 @@
# Какие находки блокируют merge. Читает security.yml на каждом
# скане; отсутствие файла — те же значения по умолчанию.
security: security:
block_on: block_on:
- critical - critical
- high - high
- low
min_confidence: 0.7 min_confidence: 0.7
scan_enabled: true
review_enabled: true