Add safe external draft update API
Some checks failed
Deploy Dzen assistant / deploy (push) Failing after 0s
Some checks failed
Deploy Dzen assistant / deploy (push) Failing after 0s
This commit is contained in:
parent
5ebc63dfe9
commit
367e772e65
5 changed files with 384 additions and 3 deletions
|
|
@ -17,7 +17,7 @@ from urllib.parse import urlparse
|
|||
|
||||
from fastapi import APIRouter, Body, Depends, File, HTTPException, Query, Request, UploadFile, WebSocket, WebSocketDisconnect
|
||||
from fastapi.responses import HTMLResponse, RedirectResponse, Response
|
||||
from pydantic import BaseModel
|
||||
from pydantic import BaseModel, ConfigDict
|
||||
from sqlalchemy import func, select
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from sqlalchemy.orm import Session
|
||||
|
|
@ -126,6 +126,17 @@ class DraftCreateIn(BaseModel):
|
|||
ctaHtml: str | None = None
|
||||
|
||||
|
||||
class DraftUpdateIn(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
title: str | None = None
|
||||
slug: str | None = None
|
||||
lead: str | None = None
|
||||
bodyHtml: str | None = None
|
||||
featureImageUrl: str | None = None
|
||||
ctaHtml: str | None = None
|
||||
|
||||
|
||||
class ChatIn(BaseModel):
|
||||
message: str
|
||||
|
||||
|
|
@ -439,6 +450,63 @@ def get_api_draft(
|
|||
return draft_api_payload(session, article, settings)
|
||||
|
||||
|
||||
@router.patch("/api/v1/drafts/{article_id}")
|
||||
def update_api_draft(
|
||||
article_id: int,
|
||||
payload: DraftUpdateIn,
|
||||
request: Request,
|
||||
session: Session = Depends(get_session),
|
||||
settings: Settings = Depends(get_settings),
|
||||
) -> dict[str, Any]:
|
||||
require_draft_api_key(request, session)
|
||||
article = session.get(Article, article_id)
|
||||
if not article or article.status == "rejected":
|
||||
raise HTTPException(status_code=404, detail="Черновик не найден.")
|
||||
if article.status != "draft" or article.published_at is not None:
|
||||
raise HTTPException(status_code=409, detail="Изменять можно только неопубликованные черновики.")
|
||||
|
||||
supplied_fields = payload.model_fields_set
|
||||
if not supplied_fields:
|
||||
raise HTTPException(status_code=422, detail="Нужно передать хотя бы одно поле для обновления.")
|
||||
if any(getattr(payload, field) is None for field in supplied_fields):
|
||||
raise HTTPException(status_code=422, detail="Поля обновления не могут иметь значение null.")
|
||||
|
||||
title = payload.title.strip() if "title" in supplied_fields else article.title
|
||||
if "title" in supplied_fields and not title:
|
||||
raise HTTPException(status_code=422, detail="Поле title обязательно.")
|
||||
updated_slug = article.slug
|
||||
if "slug" in supplied_fields:
|
||||
updated_slug = normalize_article_slug(payload.slug)
|
||||
if session.scalar(select(Article.id).where(Article.slug == updated_slug, Article.id != article.id)):
|
||||
raise HTTPException(status_code=409, detail="Slug уже используется.")
|
||||
article.slug = updated_slug
|
||||
if "featureImageUrl" in supplied_fields:
|
||||
feature_image_url = payload.featureImageUrl.strip()
|
||||
if feature_image_url and not re.match(r"^(https?://|/media/)", feature_image_url, flags=re.I):
|
||||
raise HTTPException(status_code=422, detail="featureImageUrl должен быть HTTPS-адресом или локальным /media/ URL.")
|
||||
article.feature_image_url = feature_image_url
|
||||
if "title" in supplied_fields:
|
||||
article.title = title
|
||||
if "lead" in supplied_fields:
|
||||
article.lead = sanitize_article_editor_html(payload.lead)
|
||||
if "bodyHtml" in supplied_fields:
|
||||
article.body_html = strip_leading_duplicate_title(sanitize_article_editor_html(payload.bodyHtml), title)
|
||||
if "ctaHtml" in supplied_fields:
|
||||
article.cta_html = sanitize_article_editor_html(payload.ctaHtml)
|
||||
|
||||
try:
|
||||
session.commit()
|
||||
except IntegrityError:
|
||||
session.rollback()
|
||||
if "slug" in supplied_fields and session.scalar(
|
||||
select(Article.id).where(Article.slug == updated_slug, Article.id != article.id)
|
||||
):
|
||||
raise HTTPException(status_code=409, detail="Slug уже используется.")
|
||||
raise
|
||||
session.refresh(article)
|
||||
return draft_api_payload(session, article, settings)
|
||||
|
||||
|
||||
@router.get("/feed")
|
||||
def feed(session: Session = Depends(get_session), settings: Settings = Depends(get_settings)) -> Response:
|
||||
return Response(build_feed_xml(session, settings), media_type="application/rss+xml; charset=utf-8")
|
||||
|
|
|
|||
|
|
@ -1,8 +1,8 @@
|
|||
# API создания черновиков
|
||||
# API работы с черновиками
|
||||
|
||||
## Назначение
|
||||
|
||||
API предназначен для внешнего ИИ или другого автоматизированного сервиса, который должен передать в Дзен-ассистент готовый материал и получить новый черновик статьи. Публикация в RSS через этот API не выполняется: черновик всегда нужно проверить и опубликовать из админки.
|
||||
API предназначен для внешнего ИИ или другого автоматизированного сервиса, который должен передать в Дзен-ассистент готовый материал, получить новый черновик статьи или безопасно обновить редакционные поля уже существующего неопубликованного черновика. Публикация в RSS через этот API не выполняется: черновик всегда нужно проверить и опубликовать отдельно.
|
||||
|
||||
Базовый адрес production:
|
||||
|
||||
|
|
@ -161,3 +161,28 @@ curl 'https://dzen.nstarikov.ru/api/v1/drafts/321' \
|
|||
```
|
||||
|
||||
Каждый элемент содержит `title`, `lead`, `bodyHtml`, `ctaHtml`, `contentHtml`, `editableHtml`, статус, URL, обложку и объект `video` с названием, ссылкой, длительностью и датой исходного ролика. Эти маршруты доступны только по API-ключу и не изменяют черновики.
|
||||
|
||||
## Обновление существующего черновика
|
||||
|
||||
Для частичного обновления редакционных полей используйте:
|
||||
|
||||
```http
|
||||
PATCH /api/v1/drafts/{id}
|
||||
Content-Type: application/json
|
||||
Authorization: Bearer dzen_draft_...
|
||||
```
|
||||
|
||||
Можно передать любое непустое сочетание полей `title`, `slug`, `lead`, `bodyHtml`, `featureImageUrl` и `ctaHtml`:
|
||||
|
||||
```json
|
||||
{
|
||||
"lead": "<p>Обновлённый лид.</p>",
|
||||
"bodyHtml": "<h2>Раздел</h2><p>Обновлённый текст.</p>",
|
||||
"featureImageUrl": "https://dzen.nstarikov.ru/media/uploads/20261018/cover.jpg",
|
||||
"ctaHtml": "<p>Подпись.</p>"
|
||||
}
|
||||
```
|
||||
|
||||
Маршрут работает только для материала со статусом `draft` и пустым `publishedAt`. Он не принимает и не меняет статус, дату публикации, расписание, связь с исходным роликом или другие служебные поля. Неизвестные поля, пустое тело и явные `null` возвращают `422`; попытка изменить опубликованный или иной нечерновой материал возвращает `409`.
|
||||
|
||||
Успешный ответ содержит полный объект черновика. После изменения интеграция должна прочитать материал ещё раз через `GET /api/v1/drafts/{id}` и проверить заголовок, slug, видео, `status=draft`, `publishedAt=null`, обложку и итоговый HTML.
|
||||
|
|
|
|||
56
docs/superpowers/plans/2026-10-18-draft-update-api.md
Normal file
56
docs/superpowers/plans/2026-10-18-draft-update-api.md
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
# External Draft Update API Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Add a documented, authenticated PATCH endpoint that changes only editorial fields on existing unpublished drafts.
|
||||
|
||||
**Architecture:** Extend the existing FastAPI `/api/v1/drafts` router with one Pydantic input model and one guarded handler. Reuse current sanitizers, slug normalization, API authentication, persistence, and response serialization so update behavior cannot diverge from creation behavior.
|
||||
|
||||
**Tech Stack:** Python, FastAPI, Pydantic, SQLAlchemy, unittest/TestClient, Forgejo Actions, Docker Compose.
|
||||
|
||||
---
|
||||
|
||||
### Task 1: Specify update behavior with tests
|
||||
|
||||
**Files:**
|
||||
- Modify: `tests/test_draft_api.py`
|
||||
|
||||
- [ ] Add a helper that creates a video-linked draft and returns its identifiers.
|
||||
- [ ] Add a test that PATCHes editorial fields and verifies the returned payload, sanitized HTML, updated cover, preserved `video.id`, preserved `status=draft`, and `publishedAt=null`.
|
||||
- [ ] Add tests for empty payload (`422`), wrong key (`401`), missing article (`404`), published/non-draft article (`409`), duplicate slug (`409`), invalid cover URL (`422`), and forbidden unknown fields (`422`).
|
||||
- [ ] Run `python -m unittest tests.test_draft_api -v` and verify the new tests fail because PATCH is not implemented.
|
||||
|
||||
### Task 2: Implement the guarded PATCH endpoint
|
||||
|
||||
**Files:**
|
||||
- Modify: `app/routes.py`
|
||||
|
||||
- [ ] Add `DraftUpdateIn` with optional editorial fields and `model_config = ConfigDict(extra="forbid")`.
|
||||
- [ ] Add `PATCH /api/v1/drafts/{article_id}` after the existing GET detail route.
|
||||
- [ ] Authenticate with `require_draft_api_key` and reject missing/rejected, non-draft, or published records before mutation.
|
||||
- [ ] Reject an empty update and apply the create endpoint's validation, slug normalization, HTML sanitation, and duplicate-title stripping only to supplied fields.
|
||||
- [ ] Commit once, roll back on `IntegrityError`, refresh, and return `draft_api_payload`.
|
||||
- [ ] Run `python -m unittest tests.test_draft_api -v` and verify every draft API test passes.
|
||||
|
||||
### Task 3: Document and validate the contract
|
||||
|
||||
**Files:**
|
||||
- Modify: `docs/draft-api.md`
|
||||
- Modify: `/Users/dima/.codex/skills/dzen-assistant-api/SKILL.md`
|
||||
- Modify: `/Users/dima/.codex/skills/dzen-assistant-api/references/api-contract.md`
|
||||
|
||||
- [ ] Document allowed fields, draft-only guards, status codes, and explicit non-capabilities.
|
||||
- [ ] Run `python -m unittest discover -s tests -v`.
|
||||
- [ ] Run `git diff --check` and inspect the scoped diff.
|
||||
|
||||
### Task 4: Deploy and prove the production boundary
|
||||
|
||||
**Files:**
|
||||
- Commit only the scoped application, tests, docs, and skill updates.
|
||||
|
||||
- [ ] Push `main` so the existing Forgejo workflow deploys API, worker, and beat.
|
||||
- [ ] Poll `https://dzen.nstarikov.ru/health` and `/openapi.json` until PATCH appears on `/api/v1/drafts/{article_id}`.
|
||||
- [ ] Read drafts 508–510 before mutation and record title, slug, video ID, status, and published date.
|
||||
- [ ] PATCH only `lead`, `bodyHtml`, `ctaHtml`, and `featureImageUrl` using the prepared editorial payload and uploaded covers.
|
||||
- [ ] Read drafts 508–510 back and verify unchanged title, slug, video ID, `status=draft`, `publishedAt=null`, one `[[VK_VIDEO]]` marker, one rendered iframe, exact cover URL, internal Dzen links, opinion block, and signature link.
|
||||
|
||||
39
docs/superpowers/specs/2026-10-18-draft-update-api-design.md
Normal file
39
docs/superpowers/specs/2026-10-18-draft-update-api-design.md
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
# External Draft Update API Design
|
||||
|
||||
## Goal
|
||||
|
||||
Allow trusted integrations to update editorial fields of an existing unpublished Dzen Assistant draft through the documented `/api/v1` contract, without granting publication, deletion, scheduling, status, or video-association capabilities.
|
||||
|
||||
## Endpoint
|
||||
|
||||
`PATCH /api/v1/drafts/{article_id}` uses the existing global draft API key and returns the same complete draft payload as the create/read endpoints.
|
||||
|
||||
The request may contain any non-empty subset of:
|
||||
|
||||
- `title`
|
||||
- `slug`
|
||||
- `lead`
|
||||
- `bodyHtml`
|
||||
- `featureImageUrl`
|
||||
- `ctaHtml`
|
||||
|
||||
Unknown fields remain rejected by Pydantic. An empty object returns `422`.
|
||||
|
||||
## Safety boundaries
|
||||
|
||||
- Only articles with `status == "draft"` and `published_at is None` may be updated.
|
||||
- The endpoint never accepts or mutates `status`, `publishedAt`, `videoId`, `createdAt`, or publication/scheduling fields.
|
||||
- Missing or rejected articles return `404`.
|
||||
- A non-draft or already-published article returns `409`.
|
||||
- Title, slug, image URL, and HTML use the same normalization and sanitization rules as draft creation.
|
||||
- A slug already owned by another article returns `409`.
|
||||
- The existing `video_id` relationship remains unchanged.
|
||||
|
||||
## Data flow
|
||||
|
||||
The handler authenticates the API key, loads the article, applies guard clauses, validates only supplied fields, sanitizes HTML, commits one transaction, refreshes the record, and returns `draft_api_payload`. `IntegrityError` is rolled back and mapped to a deterministic slug conflict when applicable.
|
||||
|
||||
## Verification
|
||||
|
||||
Unit tests cover authentication, partial updates, HTML sanitization, invalid and duplicate slugs, invalid cover URLs, empty payloads, rejection of published/non-draft articles, and preservation of video/status/publication fields. Production verification checks OpenAPI exposure, performs read-back around the three intended draft updates, and confirms each remains a draft with its original video and one rendered VK iframe.
|
||||
|
||||
|
|
@ -1,4 +1,5 @@
|
|||
import unittest
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi.testclient import TestClient
|
||||
|
|
@ -56,6 +57,29 @@ class DraftApiTest(unittest.TestCase):
|
|||
"ctaHtml": "",
|
||||
}
|
||||
|
||||
def create_video_draft(self, *, slug: str = "draft-from-video") -> tuple[int, int]:
|
||||
with Session(self.engine) as session:
|
||||
video = Video(
|
||||
external_id=f"vk-{slug}",
|
||||
source_url="https://vkvideo.ru/video-1_123",
|
||||
title="Исходный ролик",
|
||||
duration_seconds=321,
|
||||
)
|
||||
session.add(video)
|
||||
session.flush()
|
||||
article = Article(
|
||||
video_id=video.id,
|
||||
slug=slug,
|
||||
title="Черновик из ролика",
|
||||
lead="<p>Вступление.</p>",
|
||||
body_html="<h2>Раздел</h2><p>Текст.</p>",
|
||||
cta_html="",
|
||||
status="draft",
|
||||
)
|
||||
session.add(article)
|
||||
session.commit()
|
||||
return article.id, video.id
|
||||
|
||||
def test_creates_draft_with_exact_requested_slug(self):
|
||||
response = self.client.post(
|
||||
"/api/v1/drafts",
|
||||
|
|
@ -192,6 +216,175 @@ class DraftApiTest(unittest.TestCase):
|
|||
self.assertIn('src="https://vkvideo.ru/video_ext.php?oid=-1&id=2"', sanitized)
|
||||
self.assertNotIn("example.com", sanitized)
|
||||
|
||||
def test_updates_editorial_fields_and_preserves_draft_video_boundary(self):
|
||||
article_id, video_id = self.create_video_draft()
|
||||
|
||||
response = self.client.patch(
|
||||
f"/api/v1/drafts/{article_id}",
|
||||
json={
|
||||
"title": " Новый заголовок ",
|
||||
"slug": " New-Draft-Slug ",
|
||||
"lead": '<p>Новый лид.</p><script>alert("x")</script>',
|
||||
"bodyHtml": (
|
||||
"<h1>Новый заголовок</h1>"
|
||||
'<p>Новый текст.</p><iframe src="https://example.com/embed"></iframe>'
|
||||
),
|
||||
"featureImageUrl": "/media/covers/new-cover.jpg",
|
||||
"ctaHtml": '<p>Подпись.</p><script>alert("x")</script>',
|
||||
},
|
||||
headers=self.headers,
|
||||
)
|
||||
|
||||
self.assertEqual(response.status_code, 200)
|
||||
data = response.json()
|
||||
self.assertEqual(data["title"], "Новый заголовок")
|
||||
self.assertEqual(data["slug"], "new-draft-slug")
|
||||
self.assertEqual(data["featureImageUrl"], "/media/covers/new-cover.jpg")
|
||||
self.assertEqual(data["lead"], "<p>Новый лид.</p>")
|
||||
self.assertNotIn("<h1", data["bodyHtml"])
|
||||
self.assertIn("Новый текст.", data["bodyHtml"])
|
||||
self.assertNotIn("example.com", data["bodyHtml"])
|
||||
self.assertEqual(data["ctaHtml"], "<p>Подпись.</p>")
|
||||
self.assertEqual(data["video"]["id"], video_id)
|
||||
self.assertEqual(data["status"], "draft")
|
||||
self.assertIsNone(data["publishedAt"])
|
||||
|
||||
with Session(self.engine) as session:
|
||||
article = session.get(Article, article_id)
|
||||
self.assertEqual(article.video_id, video_id)
|
||||
self.assertEqual(article.status, "draft")
|
||||
self.assertIsNone(article.published_at)
|
||||
|
||||
def test_update_rejects_empty_payload(self):
|
||||
article_id, _ = self.create_video_draft()
|
||||
|
||||
response = self.client.patch(f"/api/v1/drafts/{article_id}", json={}, headers=self.headers)
|
||||
|
||||
self.assertEqual(response.status_code, 422)
|
||||
|
||||
def test_update_rejects_explicit_null(self):
|
||||
article_id, _ = self.create_video_draft()
|
||||
|
||||
response = self.client.patch(
|
||||
f"/api/v1/drafts/{article_id}",
|
||||
json={"lead": None},
|
||||
headers=self.headers,
|
||||
)
|
||||
|
||||
self.assertEqual(response.status_code, 422)
|
||||
|
||||
def test_update_changes_only_supplied_fields(self):
|
||||
article_id, video_id = self.create_video_draft()
|
||||
|
||||
response = self.client.patch(
|
||||
f"/api/v1/drafts/{article_id}",
|
||||
json={"lead": "<p>Только новый лид.</p>"},
|
||||
headers=self.headers,
|
||||
)
|
||||
|
||||
self.assertEqual(response.status_code, 200)
|
||||
data = response.json()
|
||||
self.assertEqual(data["lead"], "<p>Только новый лид.</p>")
|
||||
self.assertEqual(data["title"], "Черновик из ролика")
|
||||
self.assertEqual(data["slug"], "draft-from-video")
|
||||
self.assertEqual(data["bodyHtml"], "<h2>Раздел</h2><p>Текст.</p>")
|
||||
self.assertEqual(data["video"]["id"], video_id)
|
||||
self.assertEqual(data["status"], "draft")
|
||||
self.assertIsNone(data["publishedAt"])
|
||||
|
||||
def test_update_rejects_invalid_api_key(self):
|
||||
article_id, _ = self.create_video_draft()
|
||||
|
||||
response = self.client.patch(
|
||||
f"/api/v1/drafts/{article_id}",
|
||||
json={"lead": "<p>Новый лид.</p>"},
|
||||
headers={"Authorization": "Bearer wrong"},
|
||||
)
|
||||
|
||||
self.assertEqual(response.status_code, 401)
|
||||
|
||||
def test_update_missing_article_returns_not_found(self):
|
||||
response = self.client.patch(
|
||||
"/api/v1/drafts/999999",
|
||||
json={"lead": "<p>Новый лид.</p>"},
|
||||
headers=self.headers,
|
||||
)
|
||||
|
||||
self.assertEqual(response.status_code, 404)
|
||||
|
||||
def test_update_rejected_article_returns_not_found(self):
|
||||
article_id, _ = self.create_video_draft()
|
||||
with Session(self.engine) as session:
|
||||
article = session.get(Article, article_id)
|
||||
article.status = "rejected"
|
||||
session.commit()
|
||||
|
||||
response = self.client.patch(
|
||||
f"/api/v1/drafts/{article_id}",
|
||||
json={"lead": "<p>Новый лид.</p>"},
|
||||
headers=self.headers,
|
||||
)
|
||||
|
||||
self.assertEqual(response.status_code, 404)
|
||||
|
||||
def test_update_rejects_published_or_non_draft_article(self):
|
||||
for status, published_at in (
|
||||
("published", None),
|
||||
("draft", datetime.now(timezone.utc)),
|
||||
("processing", None),
|
||||
):
|
||||
with self.subTest(status=status, published_at=published_at):
|
||||
article_id, _ = self.create_video_draft(slug=f"guarded-{status}-{bool(published_at)}")
|
||||
with Session(self.engine) as session:
|
||||
article = session.get(Article, article_id)
|
||||
article.status = status
|
||||
article.published_at = published_at
|
||||
session.commit()
|
||||
|
||||
response = self.client.patch(
|
||||
f"/api/v1/drafts/{article_id}",
|
||||
json={"lead": "<p>Новый лид.</p>"},
|
||||
headers=self.headers,
|
||||
)
|
||||
|
||||
self.assertEqual(response.status_code, 409)
|
||||
|
||||
def test_update_rejects_duplicate_slug(self):
|
||||
article_id, _ = self.create_video_draft(slug="first-draft")
|
||||
self.create_video_draft(slug="occupied-slug")
|
||||
|
||||
response = self.client.patch(
|
||||
f"/api/v1/drafts/{article_id}",
|
||||
json={"slug": "occupied-slug"},
|
||||
headers=self.headers,
|
||||
)
|
||||
|
||||
self.assertEqual(response.status_code, 409)
|
||||
self.assertEqual(response.json()["detail"], "Slug уже используется.")
|
||||
|
||||
def test_update_rejects_invalid_cover_url(self):
|
||||
article_id, _ = self.create_video_draft()
|
||||
|
||||
response = self.client.patch(
|
||||
f"/api/v1/drafts/{article_id}",
|
||||
json={"featureImageUrl": "javascript:alert(1)"},
|
||||
headers=self.headers,
|
||||
)
|
||||
|
||||
self.assertEqual(response.status_code, 422)
|
||||
|
||||
def test_update_rejects_unknown_or_forbidden_fields(self):
|
||||
article_id, _ = self.create_video_draft()
|
||||
|
||||
for payload in ({"status": "published"}, {"videoId": None}, {"unknown": "value"}):
|
||||
with self.subTest(payload=payload):
|
||||
response = self.client.patch(
|
||||
f"/api/v1/drafts/{article_id}",
|
||||
json=payload,
|
||||
headers=self.headers,
|
||||
)
|
||||
self.assertEqual(response.status_code, 422)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
|
|
|||
Loading…
Reference in a new issue