diff --git a/apps/board/messages.py b/apps/board/messages.py index ff3eac0..05a4a05 100644 --- a/apps/board/messages.py +++ b/apps/board/messages.py @@ -25,34 +25,6 @@ bp = Blueprint("messages", __name__) BODY_MAX = 20_000 -def _other_party(conversation_id: int): - """The member on the far side, or None if they have been erased.""" - return get_db().execute( - """SELECT m.* FROM conversation_members cm - JOIN members m ON m.id = cm.member_id - WHERE cm.conversation_id = ? AND cm.member_id != ?""", - (conversation_id, g.member["id"]), - ).fetchone() - - -def _mine_or_404(conversation_id: int): - """Membership is the entire access rule, and it is checked on every hit. - - Not "does this conversation exist" — a member who is not in it must not be - able to tell the difference between a conversation that is not theirs and - one that does not exist. - """ - row = get_db().execute( - """SELECT c.* FROM conversations c - JOIN conversation_members cm ON cm.conversation_id = c.id - WHERE c.id = ? AND cm.member_id = ?""", - (conversation_id, g.member["id"]), - ).fetchone() - if row is None: - abort(404) - return row - - def blocked_between(a: int, b: int) -> bool: """A block in either direction stops both directions.""" return get_db().execute( @@ -63,6 +35,18 @@ def blocked_between(a: int, b: int) -> bool: ).fetchone() is not None +def existing_conversation(other_id: int) -> int | None: + """The conversation between us and `other_id`, or None. Creates nothing.""" + row = get_db().execute( + """SELECT a.conversation_id AS id + FROM conversation_members a + JOIN conversation_members b ON b.conversation_id = a.conversation_id + WHERE a.member_id = ? AND b.member_id = ?""", + (g.member["id"], other_id), + ).fetchone() + return row["id"] if row else None + + def conversation_with(other_id: int) -> int: """The conversation between the signed-in member and `other_id`, made if it does not exist yet.""" @@ -151,88 +135,89 @@ def inbox(): excerpt=lambda text: (text or "")[:120]) -@bp.route("/privados/nueva", methods=["POST"]) +@bp.route("/privados/con") @login_required -def start(): - """The member comes from the form, not the path, so the select can post - straight here. A path parameter would need JavaScript to rewrite the - action, and the Content-Security-Policy makes inline handlers silently - inert — a class of bug this codebase has already paid for once.""" - member_id = request.form.get("member_id", type=int) - if member_id is None or member_id == g.member["id"]: +def pick(): + """The select posts here as a plain GET and is sent on to the conversation. + + A form cannot put its own value into a path, and rewriting the action with + JavaScript is not available: the Content-Security-Policy has no + 'unsafe-inline', so an inline handler is ignored without a word. One tiny + redirect avoids the whole question. + """ + return redirect(url_for("messages.talk", + member_id=request.args.get("member_id", type=int) or 0)) + + +@bp.route("/privados/con/", methods=["GET", "POST"]) +@login_required +def talk(member_id: int): + """One page for a conversation, whether or not it exists yet. + + There used to be an "Abrir conversación" step that created an empty + conversation and sent you to it. It bought nothing — you still had to type + a message afterwards — and it littered the inbox with rows saying "Sin + mensajes todavía" for people nobody had actually written to. The + conversation is now created by the first message, not by looking at + somebody's name. + """ + if member_id == g.member["id"]: abort(400) - target = get_db().execute( + other = get_db().execute( """SELECT * FROM members WHERE id = ? AND active = 1 AND role IN ('owner', 'admin', 'user')""", (member_id,), ).fetchone() - if target is None: - abort(404) - if blocked_between(g.member["id"], member_id): - abort(403) - return redirect(url_for("messages.conversation", - conversation_id=conversation_with(member_id))) - - -@bp.route("/privados/") -@login_required -def conversation(conversation_id: int): - _mine_or_404(conversation_id) - db = get_db() - rows = db.execute( - """SELECT m.*, a.display_name AS author - FROM messages m JOIN members a ON a.id = m.author_id - WHERE m.conversation_id = ? AND m.deleted_at IS NULL - ORDER BY m.created_at""", - (conversation_id,), - ).fetchall() - - # Marked read on opening, which is what the member just did. Written before - # rendering so a slow page does not leave the badge stale. - db.execute( - """UPDATE conversation_members SET last_read_at = datetime('now') - WHERE conversation_id = ? AND member_id = ?""", - (conversation_id, g.member["id"]), - ) - - other = _other_party(conversation_id) - return render_template( - "conversation.html", conversation_id=conversation_id, messages=rows, - other=other, to_html=to_html, - images=uploads.for_messages([row["id"] for row in rows]), - blocked=other is not None and blocked_between(g.member["id"], other["id"]), - ) - - -@bp.route("/privados//enviar", methods=["POST"]) -@login_required -def send(conversation_id: int): - _mine_or_404(conversation_id) - other = _other_party(conversation_id) if other is None: - flash("Esa persona ya no está en la comunidad.", "error") - return redirect(url_for("messages.conversation", conversation_id=conversation_id)) - # Checked here and not only hidden in the template: the template is a - # courtesy, this is the rule. - if blocked_between(g.member["id"], other["id"]): + abort(404) + blocked = blocked_between(g.member["id"], member_id) + if blocked and request.method == "POST": abort(403) - body = request.form.get("body", "").strip()[:BODY_MAX] - try: - staged = uploads.stage(request.files.getlist("pictures")) - except uploads.RejectedUpload as exc: - flash(str(exc), "error") - return redirect(url_for("messages.conversation", conversation_id=conversation_id)) - if not body and not staged: - flash("Escribe algo o adjunta una imagen.", "error") - return redirect(url_for("messages.conversation", conversation_id=conversation_id)) + db = get_db() + conversation_id = existing_conversation(member_id) - cursor = get_db().execute( - "INSERT INTO messages (conversation_id, author_id, body_md) VALUES (?, ?, ?)", - (conversation_id, g.member["id"], body), + if request.method == "POST": + body = request.form.get("body", "").strip()[:BODY_MAX] + try: + staged = uploads.stage(request.files.getlist("pictures")) + except uploads.RejectedUpload as exc: + flash(str(exc), "error") + return redirect(url_for("messages.talk", member_id=member_id)) + if not body and not staged: + flash("Escribe algo o adjunta una imagen.", "error") + return redirect(url_for("messages.talk", member_id=member_id)) + + # Only now does the conversation come into being. + if conversation_id is None: + conversation_id = conversation_with(member_id) + cursor = db.execute( + "INSERT INTO messages (conversation_id, author_id, body_md) VALUES (?, ?, ?)", + (conversation_id, g.member["id"], body), + ) + uploads.save(staged, g.member["id"], message_id=cursor.lastrowid) + return redirect(url_for("messages.talk", member_id=member_id) + "#final") + + rows = [] + if conversation_id is not None: + rows = db.execute( + """SELECT m.*, a.display_name AS author + FROM messages m JOIN members a ON a.id = m.author_id + WHERE m.conversation_id = ? AND m.deleted_at IS NULL + ORDER BY m.created_at""", + (conversation_id,), + ).fetchall() + db.execute( + """UPDATE conversation_members SET last_read_at = datetime('now') + WHERE conversation_id = ? AND member_id = ?""", + (conversation_id, g.member["id"]), + ) + + return render_template( + "conversation.html", other=other, messages=rows, to_html=to_html, + images=uploads.for_messages([row["id"] for row in rows]), + blocked=blocked, ) - uploads.save(staged, g.member["id"], message_id=cursor.lastrowid) - return redirect(url_for("messages.conversation", conversation_id=conversation_id) + "#final") @bp.route("/privados/bloquear/", methods=["POST"]) diff --git a/apps/board/static/profile.css b/apps/board/static/profile.css new file mode 100644 index 0000000..5d4b7dd --- /dev/null +++ b/apps/board/static/profile.css @@ -0,0 +1,88 @@ +/* The public profile page at vienalatina.com/su-nombre. + * + * A separate file rather than a +
diff --git a/apps/board/tests/test_messages.py b/apps/board/tests/test_messages.py index da59a72..b67de82 100644 --- a/apps/board/tests/test_messages.py +++ b/apps/board/tests/test_messages.py @@ -1,8 +1,12 @@ """Private messages, unread marks and blocking. -The access rule is membership of the conversation, and it is worth testing -from the outside rather than trusting the query: the failure mode is not an -error, it is somebody quietly reading correspondence that is not theirs. +A conversation is addressed by the person, not by an id: `/privados/con/` +is "what I have said to them and they to me", and it exists as a page before it +exists as a row. That makes the access rule structural rather than checked — a +lookup is always scoped to the member doing the looking, so there is no query +that could return somebody else's correspondence. The tests below still come at +it from the outside, because the failure mode here is not an error, it is +somebody quietly reading what is not theirs. """ from __future__ import annotations @@ -10,63 +14,122 @@ from __future__ import annotations import io from pathlib import Path - PNG = b"\x89PNG\r\n\x1a\n" + b"\x00" * 64 -def conversation_between(client, post, a, b, sign_in): - sign_in(a) - response = post("/comunidad/privados/nueva", {"member_id": str(b)}) - return int(response.headers["Location"].rstrip("/").rsplit("/", 1)[1]) +def talk(member_id: int) -> str: + return f"/comunidad/privados/con/{member_id}" # --- who may read what ---------------------------------------------------- -def test_a_stranger_cannot_read_a_conversation(client, post, make_member, sign_in): - """404 rather than 403, deliberately: a member who is not in a conversation - should not be able to tell it apart from one that does not exist.""" +def test_a_third_person_sees_their_own_empty_conversation( + client, post, make_member, sign_in): + """The old design gave conversations their own ids, so this test had to + check that a stranger opening one got a 404. Addressing by person removes + the question: `/privados/con/` means *my* conversation with José, so + a third person opening the same URL sees an empty page, not this one.""" maria, jose = make_member("maria"), make_member("jose") - conversation = conversation_between(client, post, maria, jose, sign_in) + sign_in(maria) + post(talk(jose), {"body": "Algo privado"}) sign_in(make_member("curiosa")) - assert client.get(f"/comunidad/privados/{conversation}").status_code == 404 + page = client.get(talk(jose)) + + assert page.status_code == 200 + assert "Algo privado" not in page.get_data(as_text=True) -def test_a_stranger_cannot_send_into_one_either(client, post, make_member, sign_in): - maria, jose = make_member("maria"), make_member("jose") - conversation = conversation_between(client, post, maria, jose, sign_in) - - sign_in(make_member("curiosa")) - response = post(f"/comunidad/privados/{conversation}/enviar", {"body": "Hola"}) - assert response.status_code == 404 - - -def test_the_two_parties_can(client, db, post, make_member, sign_in): - maria, jose = make_member("maria"), make_member("jose") - conversation = conversation_between(client, post, maria, jose, sign_in) - post(f"/comunidad/privados/{conversation}/enviar", {"body": "Hola José"}) - - sign_in(jose) - body = client.get(f"/comunidad/privados/{conversation}").get_data(as_text=True) - assert "Hola José" in body - - -def test_opening_the_same_person_twice_reuses_the_conversation( +def test_writing_to_somebody_does_not_join_you_to_their_other_conversations( client, db, post, make_member, sign_in): maria, jose = make_member("maria"), make_member("jose") - first = conversation_between(client, post, maria, jose, sign_in) - second = conversation_between(client, post, maria, jose, sign_in) + sign_in(maria) + post(talk(jose), {"body": "Para José"}) + + curiosa = make_member("curiosa") + sign_in(curiosa) + post(talk(jose), {"body": "Para José también"}) + + # Two separate conversations, and neither shows the other's messages. + assert db.execute("SELECT COUNT(*) AS n FROM conversations").fetchone()["n"] == 2 + assert "Para José" not in client.get(talk(jose)).get_data(as_text=True).replace( + "Para José también", "") + + +def test_the_two_parties_see_it(client, post, make_member, sign_in): + maria, jose = make_member("maria"), make_member("jose") + sign_in(maria) + post(talk(jose), {"body": "Hola José"}) + + sign_in(jose) + assert "Hola José" in client.get(talk(maria)).get_data(as_text=True) + + +def test_writing_twice_reuses_the_one_conversation(client, db, post, make_member, sign_in): + maria, jose = make_member("maria"), make_member("jose") + sign_in(maria) + post(talk(jose), {"body": "Una"}) + post(talk(jose), {"body": "Dos"}) - assert first == second assert db.execute("SELECT COUNT(*) AS n FROM conversations").fetchone()["n"] == 1 + assert db.execute("SELECT COUNT(*) AS n FROM messages").fetchone()["n"] == 2 + + +# --- no ceremony before writing ------------------------------------------- + +def test_the_box_is_there_before_anything_has_been_said( + client, post, make_member, sign_in): + """There used to be an "Abrir conversación" button that created an empty + conversation and sent you to it. The page now arrives ready to type in.""" + maria, jose = make_member("maria"), make_member("jose") + sign_in(maria) + + page = client.get(talk(jose)) + + assert page.status_code == 200 + body = page.get_data(as_text=True) + assert 'name="body"' in body # the textarea, on first arrival + assert "Todavía no os habéis escrito" in body + + +def test_merely_looking_creates_nothing(client, db, make_member, sign_in): + """Otherwise the inbox fills with "Sin mensajes todavía" for every name + somebody was curious about.""" + maria, jose = make_member("maria"), make_member("jose") + sign_in(maria) + + client.get(talk(jose)) + + assert db.execute("SELECT COUNT(*) AS n FROM conversations").fetchone()["n"] == 0 + + +def test_the_picker_sends_you_straight_there(client, make_member, sign_in): + maria, jose = make_member("maria"), make_member("jose") + sign_in(maria) + + response = client.get(f"/comunidad/privados/con?member_id={jose}") + + assert response.status_code == 302 + assert response.headers["Location"].endswith(f"/privados/con/{jose}") + + +def test_you_cannot_write_to_yourself(client, make_member, sign_in): + maria = make_member("maria") + sign_in(maria) + assert client.get(talk(maria)).status_code == 400 + + +def test_you_cannot_write_to_somebody_who_is_not_a_member(client, make_member, sign_in): + sign_in(make_member("maria")) + assert client.get(talk(9999)).status_code == 404 # --- unread --------------------------------------------------------------- def test_unread_is_per_member_and_clears_on_reading(client, post, make_member, sign_in): maria, jose = make_member("maria"), make_member("jose") - conversation = conversation_between(client, post, maria, jose, sign_in) - post(f"/comunidad/privados/{conversation}/enviar", {"body": "¿Vienes?"}) + sign_in(maria) + post(talk(jose), {"body": "¿Vienes?"}) badge = '1' @@ -76,7 +139,7 @@ def test_unread_is_per_member_and_clears_on_reading(client, post, make_member, s sign_in(jose) assert badge in client.get("/comunidad/privados").get_data(as_text=True) - client.get(f"/comunidad/privados/{conversation}") # opening marks it read + client.get(talk(maria)) # opening marks it read assert badge not in client.get("/comunidad/privados").get_data(as_text=True) @@ -87,15 +150,13 @@ def test_a_block_stops_both_directions(client, post, make_member, sign_in): leaves the blocker able to keep writing, which is a megaphone, not a safety feature.""" maria, jose = make_member("maria"), make_member("jose") - conversation = conversation_between(client, post, maria, jose, sign_in) + sign_in(maria) + post(talk(jose), {"body": "Hola"}) + post(f"/comunidad/privados/bloquear/{jose}") # maria blocks jose - post(f"/comunidad/privados/bloquear/{jose}") # maria blocks jose - - assert post(f"/comunidad/privados/{conversation}/enviar", - {"body": "Otra cosa"}).status_code == 403 # …and maria too + assert post(talk(jose), {"body": "Otra cosa"}).status_code == 403 # …and maria too sign_in(jose) - assert post(f"/comunidad/privados/{conversation}/enviar", - {"body": "¿Hola?"}).status_code == 403 + assert post(talk(maria), {"body": "¿Hola?"}).status_code == 403 def test_a_block_is_enforced_in_the_handler_not_the_template( @@ -103,23 +164,24 @@ def test_a_block_is_enforced_in_the_handler_not_the_template( """The form is hidden once blocked, but hiding is a courtesy. Somebody who keeps the old page open, or crafts the request, meets the same refusal.""" maria, jose = make_member("maria"), make_member("jose") - conversation = conversation_between(client, post, maria, jose, sign_in) sign_in(jose) post(f"/comunidad/privados/bloquear/{maria}") sign_in(maria) # never reloaded the page, still has the form - assert post(f"/comunidad/privados/{conversation}/enviar", - {"body": "Hola"}).status_code == 403 + assert post(talk(jose), {"body": "Hola"}).status_code == 403 -def test_a_blocked_person_cannot_start_a_new_conversation( +def test_a_blocked_person_still_sees_the_history_but_no_box( client, post, make_member, sign_in): maria, jose = make_member("maria"), make_member("jose") sign_in(maria) + post(talk(jose), {"body": "Antes del bloqueo"}) post(f"/comunidad/privados/bloquear/{jose}") - sign_in(jose) - assert post("/comunidad/privados/nueva", {"member_id": str(maria)}).status_code == 403 + body = client.get(talk(jose)).get_data(as_text=True) + assert "Antes del bloqueo" in body + assert 'name="body"' not in body + assert "bloqueo entre vosotros" in body def test_unblocking_only_removes_your_own(client, db, post, make_member, sign_in): @@ -150,9 +212,8 @@ def test_a_picture_in_a_message_is_private_to_the_two_of_them( """The board's pictures are for every member. These are not, and being signed in is nowhere near enough of a check.""" maria, jose = make_member("maria"), make_member("jose") - conversation = conversation_between(client, post, maria, jose, sign_in) - post(f"/comunidad/privados/{conversation}/enviar", - {"body": "Mira", "pictures": (io.BytesIO(PNG), "foto.png")}, + sign_in(maria) + post(talk(jose), {"body": "Mira", "pictures": (io.BytesIO(PNG), "foto.png")}, content_type="multipart/form-data") name = db.execute("SELECT stored_name FROM attachments").fetchone()["stored_name"] @@ -167,10 +228,11 @@ def test_a_picture_in_a_message_is_private_to_the_two_of_them( def test_an_empty_message_with_no_picture_is_refused(client, db, post, make_member, sign_in): maria, jose = make_member("maria"), make_member("jose") - conversation = conversation_between(client, post, maria, jose, sign_in) - post(f"/comunidad/privados/{conversation}/enviar", {"body": " "}) + sign_in(maria) + post(talk(jose), {"body": " "}) assert db.execute("SELECT COUNT(*) AS n FROM messages").fetchone()["n"] == 0 + assert db.execute("SELECT COUNT(*) AS n FROM conversations").fetchone()["n"] == 0 # --- erasure -------------------------------------------------------------- @@ -181,9 +243,8 @@ def test_erasing_a_member_takes_their_private_messages( two-party exchange has no remainder to preserve, and keeping half of somebody's erased correspondence is what erasure exists to prevent.""" maria, jose = make_member("maria"), make_member("jose") - conversation = conversation_between(client, post, maria, jose, sign_in) - post(f"/comunidad/privados/{conversation}/enviar", - {"body": "Privado", "pictures": (io.BytesIO(PNG), "f.png")}, + sign_in(maria) + post(talk(jose), {"body": "Privado", "pictures": (io.BytesIO(PNG), "f.png")}, content_type="multipart/form-data") name = db.execute("SELECT stored_name FROM attachments").fetchone()["stored_name"] diff --git a/apps/board/tests/test_templates.py b/apps/board/tests/test_templates.py index 8174ec8..2e1755f 100644 --- a/apps/board/tests/test_templates.py +++ b/apps/board/tests/test_templates.py @@ -26,6 +26,26 @@ def test_no_inline_event_handlers(template): assert not found, f"{template.name} has inline handler(s): {found}" +@pytest.mark.parametrize("template", TEMPLATES, ids=lambda p: p.name) +def test_no_inline_style_blocks(template): + """The same policy, the same silence, a different symptom. + + `default-src 'self'` covers style-src too, and 'self' does not permit an + inline