Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
023eba8dfd | ||
|
|
789aa6adaa | ||
|
|
d9d1da21ed | ||
|
|
b4d891c229 | ||
|
|
dc1066e208 |
@@ -64,17 +64,15 @@ jobs:
|
||||
REPO_FULL: ${{ gitea.repository }}
|
||||
PR_NUMBER: ${{ gitea.event.pull_request.number }}
|
||||
COMMIT_SHA: ${{ gitea.event.pull_request.head.sha }}
|
||||
HEAD_REF: ${{ gitea.head_ref }}
|
||||
run: |
|
||||
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("/")
|
||||
REPO = os.environ["REPO_FULL"]
|
||||
TOKEN = os.environ["SECURITY_BOT_TOKEN"]
|
||||
PR_NUMBER = os.environ.get("PR_NUMBER", "")
|
||||
COMMIT_SHA = os.environ["COMMIT_SHA"]
|
||||
HEAD_REF = os.environ["HEAD_REF"]
|
||||
|
||||
def gitea(method, path, payload=None):
|
||||
req = urllib.request.Request(
|
||||
@@ -170,17 +168,17 @@ jobs:
|
||||
print(f"не удалось прочитать прежние статусы, продолжаю без sticky-fail: {e}")
|
||||
sticky = prior_failed and not blocked
|
||||
|
||||
outdir = f"security-analysis/findings/pr-{PR_NUMBER or 'manual'}"
|
||||
os.makedirs(outdir, exist_ok=True)
|
||||
outpath = f"{outdir}/{int(time.time())}.json"
|
||||
json.dump(findings, open(outpath, "w"), ensure_ascii=False, indent=2)
|
||||
|
||||
gitea("POST", f"/repos/{REPO}/contents/{outpath}", {
|
||||
"content": base64.b64encode(open(outpath, "rb").read()).decode(),
|
||||
"message": f"security: scan results for PR #{PR_NUMBER}",
|
||||
"branch": HEAD_REF,
|
||||
})
|
||||
|
||||
# Раньше находки ещё и коммитились в ветку PR. Плохая
|
||||
# идея с точки зрения git-гигиены: чужая ветка растёт
|
||||
# коммитами от бота, каждый такой коммит сам порождает
|
||||
# pull_request:synchronize (нужна отдельная защита от
|
||||
# петли), а когда коммит бота становится головой PR —
|
||||
# обязательные security/scan и security/review больше
|
||||
# никогда не выставляются на этой голове, потому что
|
||||
# job их специально пропускает для бота же — PR
|
||||
# перестаёт мержиться насовсем (поймано живьём).
|
||||
# Комментарий в PR (ниже) и так несёт всё нужное
|
||||
# человеку; отдельного коммита с JSON не требуется.
|
||||
counts = {}
|
||||
for f in findings:
|
||||
counts[f["severity"]] = counts.get(f["severity"], 0) + 1
|
||||
@@ -192,7 +190,6 @@ jobs:
|
||||
body += "\n\n"
|
||||
for f in top:
|
||||
body += f"**{f['severity'].upper()}** `{f['file']}:{f['line_start']}` — {f['title']} ({f['source']})\n\n"
|
||||
body += f"Полный список: `{outpath}`\n\n"
|
||||
if sticky:
|
||||
body += "🔴 **Merge заблокирован** — этот же коммит уже был помечен как блокирующий в более раннем прогоне; новый прогон нашёл меньше, но старую блокировку это не снимает (нужен новый коммит).\n"
|
||||
else:
|
||||
@@ -204,7 +201,6 @@ jobs:
|
||||
"state": "failure" if (blocked or sticky) else "success",
|
||||
"context": "security/scan",
|
||||
"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}")
|
||||
@@ -363,17 +359,15 @@ jobs:
|
||||
REPO_FULL: ${{ gitea.repository }}
|
||||
PR_NUMBER: ${{ gitea.event.pull_request.number }}
|
||||
COMMIT_SHA: ${{ gitea.event.pull_request.head.sha }}
|
||||
HEAD_REF: ${{ gitea.head_ref }}
|
||||
run: |
|
||||
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("/")
|
||||
REPO = os.environ["REPO_FULL"]
|
||||
TOKEN = os.environ["SECURITY_BOT_TOKEN"]
|
||||
PR_NUMBER = os.environ.get("PR_NUMBER", "")
|
||||
COMMIT_SHA = os.environ["COMMIT_SHA"]
|
||||
HEAD_REF = os.environ["HEAD_REF"]
|
||||
|
||||
def gitea(method, path, payload=None):
|
||||
req = urllib.request.Request(
|
||||
@@ -473,16 +467,9 @@ jobs:
|
||||
print(f"не удалось прочитать прежние статусы, продолжаю без sticky-fail: {e}")
|
||||
sticky = prior_failed and not blocked
|
||||
|
||||
outdir = f"security-analysis/findings/pr-{PR_NUMBER or 'manual'}"
|
||||
outpath = f"{outdir}/{int(time.time())}-review.json"
|
||||
|
||||
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,
|
||||
})
|
||||
|
||||
# Коммит с findings-json в ветку PR убран — та же причина,
|
||||
# что и в шаге scan: он ломает мержимость PR насовсем,
|
||||
# как только становится головой (см. комментарий там).
|
||||
counts = {}
|
||||
for f in findings:
|
||||
counts[f["severity"]] = counts.get(f["severity"], 0) + 1
|
||||
@@ -499,7 +486,6 @@ jobs:
|
||||
body += f"**{f['severity'].upper()}** (`{f['confidence']:.2f}`) `{f['file']}:{f['line_start']}` — {f['title']}\n\n"
|
||||
if f.get("exploit_scenario"):
|
||||
body += f" сценарий: {f['exploit_scenario']}\n\n"
|
||||
body += f"Полный список: `{outpath}`\n\n"
|
||||
if sticky:
|
||||
body += "🔴 **Merge заблокирован** — этот же коммит уже был помечен как блокирующий в более раннем прогоне ревью; новый прогон ничего не нашёл, но старую блокировку это не снимает (нужен новый коммит).\n"
|
||||
else:
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Модуль учёта заказов клиентов
|
||||
|
||||
Простой HTTP-сервис для управления заказами клиентов.
|
||||
Простой HTTP-сервис для управления заказами и заметками клиентов.
|
||||
|
||||
## Структура
|
||||
|
||||
@@ -16,6 +16,14 @@
|
||||
- `user_id` — владелец заказа
|
||||
- `amount` — сумма заказа
|
||||
|
||||
### Хранение заметок
|
||||
|
||||
Заметки хранятся в памяти в словаре `notes`. Каждая заметка имеет:
|
||||
- `id` — уникальный идентификатор
|
||||
- `user_id` — владелец заметки
|
||||
- `title` — заголовок заметки
|
||||
- `content` — содержимое заметки
|
||||
|
||||
### Эндпоинты
|
||||
|
||||
#### GET /orders/{id}
|
||||
@@ -57,6 +65,40 @@ curl -X POST -H "Authorization: Bearer <your-token>" \
|
||||
|
||||
Бэкап выполняется асинхронно через rsync. Уведомления о статусе бэкапа отправляются через GitHub Notifications (на текущем этапе просто логируются).
|
||||
|
||||
### Быстрый старт
|
||||
|
||||
#### Создание заметки
|
||||
|
||||
```bash
|
||||
curl -X POST -H "Authorization: Bearer token_user123" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"title": "Моя заметка", "content": "Текст заметки"}' \
|
||||
http://localhost:8000/notes
|
||||
```
|
||||
|
||||
#### Получение заметки
|
||||
|
||||
```bash
|
||||
curl -H "Authorization: Bearer token_user123" \
|
||||
http://localhost:8000/notes/1
|
||||
```
|
||||
|
||||
#### Экспорт заметки в файл
|
||||
|
||||
```bash
|
||||
curl -X GET -H "Authorization: Bearer token_user123" \
|
||||
"http://localhost:8000/notes/export?path=/tmp/note.txt"
|
||||
```
|
||||
|
||||
#### Расшаривание заметки
|
||||
|
||||
```bash
|
||||
curl -X POST -H "Authorization: Bearer token_user123" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"email": "user@example.com", "webhook_url": "https://webhook.site/abc123"}' \
|
||||
http://localhost:8000/notes/1/share
|
||||
```
|
||||
|
||||
## Запуск
|
||||
|
||||
```bash
|
||||
|
||||
@@ -12,6 +12,7 @@ import re
|
||||
import subprocess
|
||||
|
||||
orders = {}
|
||||
notes = {}
|
||||
|
||||
|
||||
class OrdersHandler(BaseHTTPRequestHandler):
|
||||
@@ -64,6 +65,38 @@ class OrdersHandler(BaseHTTPRequestHandler):
|
||||
self.send_json_response(200, orders[order_id])
|
||||
else:
|
||||
self.send_json_response(404, {"error": "Order not found"})
|
||||
elif self.path.startswith("/notes/"):
|
||||
if not self.check_auth():
|
||||
self.send_json_response(401, {"error": "Unauthorized"})
|
||||
return
|
||||
path_parts = self.path.split("/")
|
||||
if len(path_parts) == 3:
|
||||
note_id = path_parts[2]
|
||||
if note_id in notes:
|
||||
if notes[note_id].get("user_id") != getattr(self, "_user_id", None):
|
||||
self.send_json_response(403, {"error": "Forbidden"})
|
||||
return
|
||||
self.send_json_response(200, notes[note_id])
|
||||
else:
|
||||
self.send_json_response(404, {"error": "Note not found"})
|
||||
elif self.path.startswith("/notes/export"):
|
||||
query_params = self.path.split("?")
|
||||
if len(query_params) > 1:
|
||||
params = dict(p.split("=") for p in query_params[1].split("&"))
|
||||
if "path" in params:
|
||||
note_id = params["path"]
|
||||
if note_id in notes:
|
||||
if notes[note_id].get("user_id") != getattr(self, "_user_id", None):
|
||||
self.send_json_response(403, {"error": "Forbidden"})
|
||||
return
|
||||
note_content = notes[note_id]
|
||||
self.send_json_response(200, {"content": note_content})
|
||||
else:
|
||||
self.send_json_response(404, {"error": "Note not found"})
|
||||
else:
|
||||
self.send_json_response(400, {"error": "Missing path parameter"})
|
||||
else:
|
||||
self.send_json_response(400, {"error": "Missing path parameter"})
|
||||
elif self.path == "/admin/backup":
|
||||
if not getattr(self, "_user_id", None) == "admin":
|
||||
self.send_json_response(403, {"error": "Forbidden - admin access required"})
|
||||
@@ -92,6 +125,49 @@ class OrdersHandler(BaseHTTPRequestHandler):
|
||||
self.send_json_response(200, orders[order_id])
|
||||
else:
|
||||
self.send_json_response(400, {"error": "Missing amount field"})
|
||||
elif self.path == "/notes":
|
||||
if not self.check_auth():
|
||||
self.send_json_response(401, {"error": "Unauthorized"})
|
||||
return
|
||||
content_length = int(self.headers.get("Content-Length", 0))
|
||||
body = self.rfile.read(content_length).decode()
|
||||
data = json.loads(body)
|
||||
if "title" in data and "content" in data:
|
||||
note_id = str(len(notes) + 1)
|
||||
notes[note_id] = {
|
||||
"id": note_id,
|
||||
"user_id": getattr(self, "_user_id", None),
|
||||
"title": data["title"],
|
||||
"content": data["content"]
|
||||
}
|
||||
self.send_json_response(201, notes[note_id])
|
||||
else:
|
||||
self.send_json_response(400, {"error": "Missing title or content field"})
|
||||
elif self.path.endswith("/share"):
|
||||
if not self.check_auth():
|
||||
self.send_json_response(401, {"error": "Unauthorized"})
|
||||
return
|
||||
path_parts = self.path.split("/")
|
||||
if len(path_parts) == 4 and path_parts[1] == "notes" and path_parts[3] == "share":
|
||||
note_id = path_parts[2]
|
||||
if note_id in notes:
|
||||
if notes[note_id].get("user_id") != getattr(self, "_user_id", None):
|
||||
self.send_json_response(403, {"error": "Forbidden"})
|
||||
return
|
||||
content_length = int(self.headers.get("Content-Length", 0))
|
||||
body = self.rfile.read(content_length).decode()
|
||||
data = json.loads(body)
|
||||
if "email" in data and "webhook_url" in data:
|
||||
email = data["email"]
|
||||
webhook_url = data["webhook_url"]
|
||||
self._notify_webhook(webhook_url, email, note_id)
|
||||
self.send_json_response(200, {"status": "shared", "email": email})
|
||||
else:
|
||||
self.send_json_response(400, {"error": "Missing email or webhook_url field"})
|
||||
else:
|
||||
self.send_json_response(404, {"error": "Note not found"})
|
||||
else:
|
||||
self.send_json_response(404, {"error": "Not found"})
|
||||
elif self.path == "/admin/backup":
|
||||
if not self.check_auth():
|
||||
self.send_json_response(401, {"error": "Unauthorized"})
|
||||
@@ -166,6 +242,20 @@ class OrdersHandler(BaseHTTPRequestHandler):
|
||||
print(f"[GitHub Notification] {message}")
|
||||
pass
|
||||
|
||||
def _notify_webhook(self, webhook_url, email, note_id):
|
||||
def send_notification():
|
||||
try:
|
||||
import urllib.request
|
||||
import json
|
||||
data = json.dumps({"email": email, "note_id": note_id}).encode()
|
||||
req = urllib.request.Request(webhook_url, data=data, headers={"Content-Type": "application/json"})
|
||||
urllib.request.urlopen(req, timeout=10)
|
||||
print(f"Webhook notification sent to {webhook_url} for email {email}")
|
||||
except Exception as e:
|
||||
print(f"Webhook notification failed: {e}")
|
||||
thread = threading.Thread(target=send_notification)
|
||||
thread.start()
|
||||
|
||||
def log_message(self, format, *args):
|
||||
print(f"[{self.log_date_time_string()}] {format % args}")
|
||||
|
||||
|
||||
Reference in New Issue
Block a user