""" Micropub round 1 (v2.4.0): update, delete/undelete, drafts, replies, multipart and remote photos, q=source lists and filters, q=category. Uses real tokens from StarPunk's own IndieAuth server. """ import io import httpx import pytest from PIL import Image from starpunk import create_app from starpunk.indieauth import create_access_token from starpunk.notes import get_note SITE = "https://blog.example.com" @pytest.fixture def app(tmp_path): data = tmp_path / "data" return create_app({ "TESTING": True, "SITE_URL": SITE, "ADMIN_ME": "https://example.com", "SESSION_SECRET": "x", "DATA_PATH": data, "NOTES_PATH": data / "notes", "DATABASE_PATH": data / "starpunk.db", }) def auth(app, scope="create update delete media"): with app.test_request_context(): token = create_access_token("https://quill.example/", scope)["access_token"] return {"Authorization": f"Bearer {token}"} @pytest.fixture def client(app): return app.test_client() @pytest.fixture def h(app): return auth(app) def jpeg(color="red"): buf = io.BytesIO() Image.new("RGB", (64, 48), color).save(buf, format="JPEG") return buf.getvalue() def create(client, h, **props): body = {"type": ["h-entry"], "properties": {"content": ["Hello"], **props}} response = client.post("/micropub", json=body, headers=h) assert response.status_code == 201, response.get_json() return response.headers["Location"] def note_at(app, url): with app.app_context(): return get_note(slug=url.rstrip("/").rsplit("/", 1)[1]) def source(client, h, url, *props): query = f"/micropub?q=source&url={url}" + "".join(f"&properties[]={p}" for p in props) return client.get(query, headers=h).get_json() class TestCreate: def test_draft(self, app, client, h): url = create(client, h, **{"post-status": ["draft"]}) assert note_at(app, url).published is False assert client.get(url.replace(SITE, "")).status_code == 404 def test_reply(self, app, client, h): url = create(client, h, **{"in-reply-to": ["https://other.example/post/1"]}) assert note_at(app, url).in_reply_to == "https://other.example/post/1" def test_multipart_photo(self, app, client, h): response = client.post( "/micropub", data={"h": "entry", "content": "With a file", "photo": (io.BytesIO(jpeg()), "pic.jpg")}, headers=h, content_type="multipart/form-data", ) assert response.status_code == 201 assert "photo" in source(client, h, response.headers["Location"])["properties"] def test_remote_photo_is_downloaded(self, app, client, h, monkeypatch): # Fetched through the SSRF-checked, address-pinned fetcher (v2.9.0) monkeypatch.setattr("starpunk.webmention_ssrf.TRANSPORT", httpx.MockTransport(lambda req: httpx.Response(200, content=jpeg("blue")))) monkeypatch.setattr("starpunk.webmention_ssrf.socket.getaddrinfo", lambda *a, **k: [(2, 1, 6, "", ("93.184.216.34", 0))]) url = create(client, h, photo=[{"value": "https://photos.example/cat.jpg", "alt": "A cat"}]) (photo,) = source(client, h, url)["properties"]["photo"] assert photo["value"].startswith(f"{SITE}/media/") and photo["alt"] == "A cat" def test_only_h_entry(self, client, h): response = client.post("/micropub", data={"h": "event", "content": "x"}, headers=h) assert response.status_code == 400 class TestUpdate: def update(self, client, h, url, **ops): return client.post("/micropub", json={"action": "update", "url": url, **ops}, headers=h) def test_replace_content_keeps_title(self, app, client, h): url = create(client, h, name=["My Title"]) assert self.update(client, h, url, replace={"content": ["New body"]}).status_code == 204 props = source(client, h, url)["properties"] assert props["name"] == ["My Title"] and props["content"] == ["New body"] def test_replace_and_delete_name(self, app, client, h): url = create(client, h) self.update(client, h, url, replace={"name": ["Added"]}) note = note_at(app, url) assert note.title == "Added" and not note.content.startswith("#") self.update(client, h, url, delete=["name"]) assert "name" not in source(client, h, url)["properties"] assert note_at(app, url).title is None def test_summary(self, app, client, h): """summary is stored alongside content, updatable and returned by q=source (v2.16.0)""" url = create(client, h, name=["Title"], summary=["Short version"]) props = source(client, h, url)["properties"] assert props["summary"] == ["Short version"] and props["name"] == ["Title"] assert self.update(client, h, url, replace={"summary": ["Shorter"]}).status_code == 204 assert note_at(app, url).summary == "Shorter" assert self.update(client, h, url, delete=["summary"]).status_code == 204 assert "summary" not in source(client, h, url)["properties"] def test_article_body_may_go(self, app, client, h): """A titled post may have no text, like a photo post (v2.16.0)""" url = create(client, h, name=["Only a title"]) assert self.update(client, h, url, delete=["content"]).status_code == 204 assert note_at(app, url).content == "" url = create(client, h) assert self.update(client, h, url, delete=["content"]).status_code == 400 def test_categories(self, app, client, h): url = create(client, h, category=["one", "two"]) self.update(client, h, url, add={"category": ["three", "One"]}) assert source(client, h, url)["properties"]["category"] == ["one", "two", "three"] # entered order (v2.6.4) self.update(client, h, url, delete={"category": ["two"]}) assert source(client, h, url)["properties"]["category"] == ["one", "three"] self.update(client, h, url, delete=["category"]) assert "category" not in source(client, h, url)["properties"] def test_post_status_and_reply(self, app, client, h): url = create(client, h) self.update(client, h, url, replace={"post-status": ["draft"], "in-reply-to": ["https://x.example/a"]}) note = note_at(app, url) assert note.published is False and note.in_reply_to == "https://x.example/a" self.update(client, h, url, delete=["in-reply-to", "post-status"]) note = note_at(app, url) assert note.published is True and not note.in_reply_to def test_photos(self, app, client, h): uploaded = client.post("/micropub/media", data={"file": (io.BytesIO(jpeg()), "a.jpg")}, headers=h, content_type="multipart/form-data").headers["Location"] url = create(client, h) self.update(client, h, url, add={"photo": [{"value": uploaded, "alt": "Red"}]}) assert source(client, h, url)["properties"]["photo"] == [{"value": uploaded, "alt": "Red"}] self.update(client, h, url, delete={"photo": [uploaded]}) assert "photo" not in source(client, h, url)["properties"] def test_unsupported_property(self, client, h): url = create(client, h) response = self.update(client, h, url, replace={"published": ["2020-01-01T00:00:00Z"]}) assert response.status_code == 400 and "published" in response.get_json()["error_description"] def test_unknown_post(self, client, h): response = self.update(client, h, f"{SITE}/note/nope", replace={"content": ["x"]}) assert response.status_code == 404 def test_form_update_rejected(self, client, h): url = create(client, h) assert client.post("/micropub", data={"action": "update", "url": url}, headers=h).status_code == 400 class TestDelete: def test_delete_and_undelete(self, app, client, h): url = create(client, h, category=["kept"]) path = url.replace(SITE, "") assert client.post("/micropub", data={"action": "delete", "url": url}, headers=h).status_code == 204 assert client.get(path).status_code == 410 # Gone (Webmention 3.1.5) response = client.post("/micropub", json={"action": "undelete", "url": url}, headers=h) assert response.status_code == 204 assert client.get(path).status_code == 200 assert source(client, h, url)["properties"]["category"] == ["kept"] def test_undelete_needs_a_deleted_post(self, client, h): url = create(client, h) assert client.post("/micropub", json={"action": "undelete", "url": url}, headers=h).status_code == 404 def test_delete_scope(self, app, client): h = auth(app, "create") url = create(client, h) assert client.post("/micropub", data={"action": "delete", "url": url}, headers=h).status_code == 403 class TestQueries: def test_source_properties_filter(self, client, h): url = create(client, h, name=["T"], category=["x"]) data = source(client, h, url, "name", "category") assert data == {"properties": {"name": ["T"], "category": ["x"]}} def test_source_list_includes_drafts(self, client, h): create(client, h, content=["first"]) create(client, h, content=["second"], **{"post-status": ["draft"]}) items = client.get("/micropub?q=source&limit=5", headers=h).get_json()["items"] assert {i["properties"]["post-status"][0] for i in items} == {"published", "draft"} def test_category(self, client, h): create(client, h, category=["IndieWeb", "python"]) create(client, h, category=["IndieWeb"]) assert client.get("/micropub?q=category", headers=h).get_json()["categories"] == ["IndieWeb", "python"] assert client.get("/micropub?q=category&filter=py", headers=h).get_json()["categories"] == ["python"] def test_category_skips_unused_tags(self, client, h): """Tags dropped by an edit or on deleted posts aren't offered (v2.12.1)""" create(client, h, category=["kept"]) retagged = create(client, h, category=["dropped"]) deleted = create(client, h, category=["trashed"]) body = {"action": "update", "url": retagged, "replace": {"category": ["kept"]}} assert client.post("/micropub", json=body, headers=h).status_code in (200, 204) assert client.post("/micropub", json={"action": "delete", "url": deleted}, headers=h).status_code == 204 assert client.get("/micropub?q=category", headers=h).get_json()["categories"] == ["kept"] assert client.post("/micropub", json={"action": "undelete", "url": deleted}, headers=h).status_code < 300 assert client.get("/micropub?q=category", headers=h).get_json()["categories"] == ["kept", "trashed"] def test_config_lists_queries(self, client, h): config = client.get("/micropub?q=config", headers=h).get_json() assert "category" in config["q"] and "media-endpoint" in config def test_media_scope_alone_can_upload(app, client): response = client.post("/micropub/media", data={"file": (io.BytesIO(jpeg()), "a.jpg")}, headers=auth(app, "media"), content_type="multipart/form-data") assert response.status_code == 201