Style the profile page, and drop the step before writing

Two bugs, both mine.

The profile page arrived unstyled because its CSS was in a <style>
block. default-src 'self' covers style-src, 'self' does not permit
inline, so the browser dropped the whole block without a word — the
photo loaded because img-src allows same-origin, which is what made the
screenshot look like a half-working page rather than a blocked one. The
third time this policy has silently made something inert, after two
rounds of inline event handlers. Moved to static/profile.css, where the
policy allows it, and test_templates.py now fails on an inline <style>
the way it already does on an inline onclick.

Private messages had an "Abrir conversación" button that created an
empty conversation and sent you to a page where you then had to type. It
bought nothing and littered the inbox with rows reading "Sin mensajes
todavía" for people nobody had written to. A conversation is now
addressed by the person — /privados/con/<member_id> — and the page
always carries the history and the box together. The row is created by
the first message, not by looking at somebody's name.

That also makes the access rule structural instead of checked. Every
lookup is scoped to the member doing the looking, so there is no query
that could return somebody else's correspondence, and the two helpers
that took a conversation id are gone. A third person opening the same
URL now sees their own empty conversation, which the tests assert
directly rather than asserting a 404.

281 tests.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NizVpJ2dwzCbjCrTLCjeHn
This commit is contained in:
Claude 2026-09-29 14:16:25 +00:00
parent 6acc8922b1
commit 63dd19e451
No known key found for this signature in database
7 changed files with 333 additions and 200 deletions

View File

@ -25,34 +25,6 @@ bp = Blueprint("messages", __name__)
BODY_MAX = 20_000 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: def blocked_between(a: int, b: int) -> bool:
"""A block in either direction stops both directions.""" """A block in either direction stops both directions."""
return get_db().execute( return get_db().execute(
@ -63,6 +35,18 @@ def blocked_between(a: int, b: int) -> bool:
).fetchone() is not None ).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: def conversation_with(other_id: int) -> int:
"""The conversation between the signed-in member and `other_id`, made if """The conversation between the signed-in member and `other_id`, made if
it does not exist yet.""" it does not exist yet."""
@ -151,34 +135,71 @@ def inbox():
excerpt=lambda text: (text or "")[:120]) excerpt=lambda text: (text or "")[:120])
@bp.route("/privados/nueva", methods=["POST"]) @bp.route("/privados/con")
@login_required @login_required
def start(): def pick():
"""The member comes from the form, not the path, so the select can post """The select posts here as a plain GET and is sent on to the conversation.
straight here. A path parameter would need JavaScript to rewrite the
action, and the Content-Security-Policy makes inline handlers silently A form cannot put its own value into a path, and rewriting the action with
inert — a class of bug this codebase has already paid for once.""" JavaScript is not available: the Content-Security-Policy has no
member_id = request.form.get("member_id", type=int) 'unsafe-inline', so an inline handler is ignored without a word. One tiny
if member_id is None or member_id == g.member["id"]: 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/<int:member_id>", 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) abort(400)
target = get_db().execute( other = get_db().execute(
"""SELECT * FROM members """SELECT * FROM members
WHERE id = ? AND active = 1 AND role IN ('owner', 'admin', 'user')""", WHERE id = ? AND active = 1 AND role IN ('owner', 'admin', 'user')""",
(member_id,), (member_id,),
).fetchone() ).fetchone()
if target is None: if other is None:
abort(404) abort(404)
if blocked_between(g.member["id"], member_id): blocked = blocked_between(g.member["id"], member_id)
if blocked and request.method == "POST":
abort(403) abort(403)
return redirect(url_for("messages.conversation",
conversation_id=conversation_with(member_id)))
@bp.route("/privados/<int:conversation_id>")
@login_required
def conversation(conversation_id: int):
_mine_or_404(conversation_id)
db = get_db() db = get_db()
conversation_id = existing_conversation(member_id)
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( rows = db.execute(
"""SELECT m.*, a.display_name AS author """SELECT m.*, a.display_name AS author
FROM messages m JOIN members a ON a.id = m.author_id FROM messages m JOIN members a ON a.id = m.author_id
@ -186,55 +207,19 @@ def conversation(conversation_id: int):
ORDER BY m.created_at""", ORDER BY m.created_at""",
(conversation_id,), (conversation_id,),
).fetchall() ).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( db.execute(
"""UPDATE conversation_members SET last_read_at = datetime('now') """UPDATE conversation_members SET last_read_at = datetime('now')
WHERE conversation_id = ? AND member_id = ?""", WHERE conversation_id = ? AND member_id = ?""",
(conversation_id, g.member["id"]), (conversation_id, g.member["id"]),
) )
other = _other_party(conversation_id)
return render_template( return render_template(
"conversation.html", conversation_id=conversation_id, messages=rows, "conversation.html", other=other, messages=rows, to_html=to_html,
other=other, to_html=to_html,
images=uploads.for_messages([row["id"] for row in rows]), images=uploads.for_messages([row["id"] for row in rows]),
blocked=other is not None and blocked_between(g.member["id"], other["id"]), blocked=blocked,
) )
@bp.route("/privados/<int:conversation_id>/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(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))
cursor = get_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.conversation", conversation_id=conversation_id) + "#final")
@bp.route("/privados/bloquear/<int:member_id>", methods=["POST"]) @bp.route("/privados/bloquear/<int:member_id>", methods=["POST"])
@login_required @login_required
def block(member_id: int): def block(member_id: int):

View File

@ -0,0 +1,88 @@
/* The public profile page at vienalatina.com/su-nombre.
*
* A separate file rather than a <style> block in the template, and that is not
* a matter of taste. The Content-Security-Policy in app.py is
* `default-src 'self'` with no 'unsafe-inline', so a browser silently ignores
* an inline <style> — the page arrives in Times New Roman with blue links and
* nothing in the console explains why. Served from /comunidad/static/ it is
* same-origin, allowed, and the policy keeps its teeth.
*
* The colours are repeated from themes/vienalatina/assets/css/main.css rather
* than shared with it: Hugo fingerprints its stylesheet, so there is no stable
* URL to link to. If the brand changes there, change it here. A deliberate
* duplicate, said out loud.
*/
:root {
--brand: #c0391c;
--ink: #2b2320;
--muted: #6b5f59;
--surface: #fffaf6;
--line: #e7dcd4;
--radius: 12px;
}
* { box-sizing: border-box; }
body {
margin: 0;
background: var(--surface);
color: var(--ink);
font: 1rem/1.65 system-ui, -apple-system, "Segoe UI", sans-serif;
}
.wrap { max-width: 42rem; margin: 0 auto; padding: 2.5rem 1rem 4rem; }
a { color: var(--brand); }
.home {
display: inline-block;
margin-bottom: 2rem;
font-size: .9rem;
text-decoration: none;
}
.head { display: flex; gap: 1.25rem; align-items: center; flex-wrap: wrap; }
/* Bounded on both axes: a photo straight off a phone is several thousand
pixels wide, and without this it pushes the name off the screen. */
.photo {
width: 104px;
height: 104px;
border-radius: 50%;
object-fit: cover;
border: 1px solid var(--line);
}
h1 { margin: 0; font-size: 1.7rem; line-height: 1.2; }
.bio { margin-top: 1.75rem; }
.bio :first-child { margin-top: 0; }
.bio img { max-width: 100%; height: auto; border-radius: var(--radius); }
ul.links {
list-style: none;
padding: 0;
margin: 1.75rem 0 0;
display: flex;
flex-wrap: wrap;
gap: .5rem;
}
ul.links a {
display: inline-block;
padding: .4rem .8rem;
background: #fff;
border: 1px solid var(--line);
border-radius: 999px;
text-decoration: none;
font-size: .9rem;
}
footer {
margin-top: 3rem;
padding-top: 1.25rem;
border-top: 1px solid var(--line);
color: var(--muted);
font-size: .85rem;
}

View File

@ -1,10 +1,10 @@
{% extends "base.html" %} {% extends "base.html" %}
{% from "_attachments.html" import attachments %} {% from "_attachments.html" import attachments %}
{% block title %}{{ other.display_name if other else 'Conversación' }}{% endblock %} {% block title %}{{ other.display_name }}{% endblock %}
{% block main %} {% block main %}
<div class="feed-head"> <div class="feed-head">
<h1>{{ other.display_name if other else 'Miembro eliminado' }}</h1> <h1>{{ other.display_name }}</h1>
<a class="linkish" href="{{ url_for('messages.inbox') }}">Volver</a> <a class="linkish" href="{{ url_for('messages.inbox') }}">Volver</a>
</div> </div>
@ -16,13 +16,13 @@
<div class="prose">{{ to_html(m.body_md) }}</div> <div class="prose">{{ to_html(m.body_md) }}</div>
{{ attachments(images.get(m.id, [])) }} {{ attachments(images.get(m.id, [])) }}
</article> </article>
{% else %}
<p class="muted">Todavía no os habéis escrito. Empieza abajo.</p>
{% endfor %} {% endfor %}
<span id="final"></span> <span id="final"></span>
{% if other is none %} {% if blocked %}
<p class="muted">Esta persona ya no está en la comunidad.</p>
{% elif blocked %}
<p class="muted"> <p class="muted">
Hay un bloqueo entre vosotros, así que ninguno de los dos puede escribir. Hay un bloqueo entre vosotros, así que ninguno de los dos puede escribir.
</p> </p>
@ -34,11 +34,14 @@
Si el bloqueo lo puso la otra persona, esto no lo quita. Si el bloqueo lo puso la otra persona, esto no lo quita.
</p> </p>
{% else %} {% else %}
{# Always on this page, under the history. There is no separate step to "open"
a conversation: arriving at somebody's name is opening it, and nothing is
created in the database until the first message is actually sent. #}
<form class="card" method="post" enctype="multipart/form-data" <form class="card" method="post" enctype="multipart/form-data"
action="{{ url_for('messages.send', conversation_id=conversation_id) }}"> action="{{ url_for('messages.talk', member_id=other.id) }}">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}"> <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
<label for="body">Mensaje</label> <label for="body">Mensaje</label>
<textarea id="body" name="body" rows="4" <textarea id="body" name="body" rows="4" autofocus
placeholder="Se puede usar Markdown: **negrita**, listas, enlaces."></textarea> placeholder="Se puede usar Markdown: **negrita**, listas, enlaces."></textarea>
<label for="pictures">Imágenes <span class="muted small">(opcional)</span></label> <label for="pictures">Imágenes <span class="muted small">(opcional)</span></label>

View File

@ -7,15 +7,16 @@
</div> </div>
{% if people %} {% if people %}
<form class="card" method="post" action="{{ url_for('messages.start') }}"> {# GET, not POST: choosing somebody to write to is navigation, not a change.
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}"> It also means no conversation is created just because a name was picked. #}
<form class="card" method="get" action="{{ url_for('messages.pick') }}">
<label for="para">Escribir a</label> <label for="para">Escribir a</label>
<select id="para" name="member_id"> <select id="para" name="member_id">
{% for person in people %} {% for person in people %}
<option value="{{ person.id }}">{{ person.display_name }}</option> <option value="{{ person.id }}">{{ person.display_name }}</option>
{% endfor %} {% endfor %}
</select> </select>
<button class="btn" type="submit">Abrir conversación</button> <button class="btn" type="submit">Escribir</button>
</form> </form>
{% endif %} {% endif %}
@ -25,7 +26,7 @@
{% for c in conversations %} {% for c in conversations %}
<article class="card"> <article class="card">
<a class="card__title" href="{{ url_for('messages.conversation', conversation_id=c.id) }}"> <a class="card__title" href="{{ url_for('messages.talk', member_id=c.other_id) }}">
{{ c.other_name }} {{ c.other_name }}
{% if c.unread %}<span class="tag">{{ c.unread }}</span>{% endif %} {% if c.unread %}<span class="tag">{{ c.unread }}</span>{% endif %}
</a> </a>

View File

@ -1,11 +1,10 @@
{# A page on the PUBLIC site, so it does not extend base.html — that is the {# A page on the PUBLIC site, so it does not extend base.html — that is the
members-area chrome, with its navigation and its "Área privada" footer. members-area chrome, with its navigation and its "Área privada" footer.
The colours are repeated here rather than shared. Hugo fingerprints its Its styling lives in static/profile.css and NOT in a <style> block here.
stylesheet, so the app cannot link to it and get a stable URL; this is the The Content-Security-Policy has no 'unsafe-inline', so an inline block is
same problem the Gitea theme has. Source of truth is ignored by the browser without a word, and the page arrives looking like
themes/vienalatina/assets/css/main.css — if the brand changes there, change 1996. test_templates.py fails the build if one reappears. #}
it here too. A deliberate duplicate, said out loud. #}
<!DOCTYPE html> <!DOCTYPE html>
<html lang="es"> <html lang="es">
<head> <head>
@ -13,31 +12,7 @@
<meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="viewport" content="width=device-width, initial-scale=1">
<title>{{ member.display_name }} — Viena Latina</title> <title>{{ member.display_name }} — Viena Latina</title>
<meta name="description" content="{{ (member.bio or '')[:150] }}"> <meta name="description" content="{{ (member.bio or '')[:150] }}">
<style> <link rel="stylesheet" href="{{ url_for('static', filename='profile.css') }}">
:root { --brand:#c0391c; --ink:#2b2320; --muted:#6b5f59;
--surface:#fffaf6; --line:#e7dcd4; --radius:12px; }
* { box-sizing:border-box; }
body { margin:0; background:var(--surface); color:var(--ink);
font:1rem/1.65 system-ui,-apple-system,"Segoe UI",sans-serif; }
.wrap { max-width:42rem; margin:0 auto; padding:2.5rem 1rem 4rem; }
a { color:var(--brand); }
.home { display:inline-block; margin-bottom:2rem; font-size:.9rem;
text-decoration:none; }
.head { display:flex; gap:1.25rem; align-items:center; flex-wrap:wrap; }
.photo { width:104px; height:104px; border-radius:50%; object-fit:cover;
border:1px solid var(--line); }
h1 { margin:0; font-size:1.7rem; line-height:1.2; }
.bio { margin-top:1.75rem; }
.bio :first-child { margin-top:0; }
.bio img { max-width:100%; height:auto; border-radius:var(--radius); }
ul.links { list-style:none; padding:0; margin:1.75rem 0 0;
display:flex; flex-wrap:wrap; gap:.5rem; }
ul.links a { display:inline-block; padding:.4rem .8rem; background:#fff;
border:1px solid var(--line); border-radius:999px;
text-decoration:none; font-size:.9rem; }
footer { margin-top:3rem; padding-top:1.25rem; border-top:1px solid var(--line);
color:var(--muted); font-size:.85rem; }
</style>
</head> </head>
<body> <body>
<div class="wrap"> <div class="wrap">

View File

@ -1,8 +1,12 @@
"""Private messages, unread marks and blocking. """Private messages, unread marks and blocking.
The access rule is membership of the conversation, and it is worth testing A conversation is addressed by the person, not by an id: `/privados/con/<id>`
from the outside rather than trusting the query: the failure mode is not an is "what I have said to them and they to me", and it exists as a page before it
error, it is somebody quietly reading correspondence that is not theirs. 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 from __future__ import annotations
@ -10,63 +14,122 @@ from __future__ import annotations
import io import io
from pathlib import Path from pathlib import Path
PNG = b"\x89PNG\r\n\x1a\n" + b"\x00" * 64 PNG = b"\x89PNG\r\n\x1a\n" + b"\x00" * 64
def conversation_between(client, post, a, b, sign_in): def talk(member_id: int) -> str:
sign_in(a) return f"/comunidad/privados/con/{member_id}"
response = post("/comunidad/privados/nueva", {"member_id": str(b)})
return int(response.headers["Location"].rstrip("/").rsplit("/", 1)[1])
# --- who may read what ---------------------------------------------------- # --- who may read what ----------------------------------------------------
def test_a_stranger_cannot_read_a_conversation(client, post, make_member, sign_in): def test_a_third_person_sees_their_own_empty_conversation(
"""404 rather than 403, deliberately: a member who is not in a conversation client, post, make_member, sign_in):
should not be able to tell it apart from one that does not exist.""" """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/<jose>` 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") 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")) 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): def test_writing_to_somebody_does_not_join_you_to_their_other_conversations(
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(
client, db, post, make_member, sign_in): client, db, post, make_member, sign_in):
maria, jose = make_member("maria"), make_member("jose") maria, jose = make_member("maria"), make_member("jose")
first = conversation_between(client, post, maria, jose, sign_in) sign_in(maria)
second = conversation_between(client, post, maria, jose, sign_in) 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 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 --------------------------------------------------------------- # --- unread ---------------------------------------------------------------
def test_unread_is_per_member_and_clears_on_reading(client, post, make_member, sign_in): def test_unread_is_per_member_and_clears_on_reading(client, post, make_member, sign_in):
maria, jose = make_member("maria"), make_member("jose") maria, jose = make_member("maria"), make_member("jose")
conversation = conversation_between(client, post, maria, jose, sign_in) sign_in(maria)
post(f"/comunidad/privados/{conversation}/enviar", {"body": "¿Vienes?"}) post(talk(jose), {"body": "¿Vienes?"})
badge = '<span class="tag">1</span>' badge = '<span class="tag">1</span>'
@ -76,7 +139,7 @@ def test_unread_is_per_member_and_clears_on_reading(client, post, make_member, s
sign_in(jose) sign_in(jose)
assert badge in client.get("/comunidad/privados").get_data(as_text=True) 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) 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 leaves the blocker able to keep writing, which is a megaphone, not a
safety feature.""" safety feature."""
maria, jose = make_member("maria"), make_member("jose") 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", assert post(talk(jose), {"body": "Otra cosa"}).status_code == 403 # …and maria too
{"body": "Otra cosa"}).status_code == 403 # …and maria too
sign_in(jose) sign_in(jose)
assert post(f"/comunidad/privados/{conversation}/enviar", assert post(talk(maria), {"body": "¿Hola?"}).status_code == 403
{"body": "¿Hola?"}).status_code == 403
def test_a_block_is_enforced_in_the_handler_not_the_template( 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 """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.""" keeps the old page open, or crafts the request, meets the same refusal."""
maria, jose = make_member("maria"), make_member("jose") maria, jose = make_member("maria"), make_member("jose")
conversation = conversation_between(client, post, maria, jose, sign_in)
sign_in(jose) sign_in(jose)
post(f"/comunidad/privados/bloquear/{maria}") post(f"/comunidad/privados/bloquear/{maria}")
sign_in(maria) # never reloaded the page, still has the form sign_in(maria) # never reloaded the page, still has the form
assert post(f"/comunidad/privados/{conversation}/enviar", assert post(talk(jose), {"body": "Hola"}).status_code == 403
{"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): client, post, make_member, sign_in):
maria, jose = make_member("maria"), make_member("jose") maria, jose = make_member("maria"), make_member("jose")
sign_in(maria) sign_in(maria)
post(talk(jose), {"body": "Antes del bloqueo"})
post(f"/comunidad/privados/bloquear/{jose}") post(f"/comunidad/privados/bloquear/{jose}")
sign_in(jose) body = client.get(talk(jose)).get_data(as_text=True)
assert post("/comunidad/privados/nueva", {"member_id": str(maria)}).status_code == 403 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): 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 """The board's pictures are for every member. These are not, and being
signed in is nowhere near enough of a check.""" signed in is nowhere near enough of a check."""
maria, jose = make_member("maria"), make_member("jose") maria, jose = make_member("maria"), make_member("jose")
conversation = conversation_between(client, post, maria, jose, sign_in) sign_in(maria)
post(f"/comunidad/privados/{conversation}/enviar", post(talk(jose), {"body": "Mira", "pictures": (io.BytesIO(PNG), "foto.png")},
{"body": "Mira", "pictures": (io.BytesIO(PNG), "foto.png")},
content_type="multipart/form-data") content_type="multipart/form-data")
name = db.execute("SELECT stored_name FROM attachments").fetchone()["stored_name"] 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): 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") maria, jose = make_member("maria"), make_member("jose")
conversation = conversation_between(client, post, maria, jose, sign_in) sign_in(maria)
post(f"/comunidad/privados/{conversation}/enviar", {"body": " "}) post(talk(jose), {"body": " "})
assert db.execute("SELECT COUNT(*) AS n FROM messages").fetchone()["n"] == 0 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 -------------------------------------------------------------- # --- 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 two-party exchange has no remainder to preserve, and keeping half of
somebody's erased correspondence is what erasure exists to prevent.""" somebody's erased correspondence is what erasure exists to prevent."""
maria, jose = make_member("maria"), make_member("jose") maria, jose = make_member("maria"), make_member("jose")
conversation = conversation_between(client, post, maria, jose, sign_in) sign_in(maria)
post(f"/comunidad/privados/{conversation}/enviar", post(talk(jose), {"body": "Privado", "pictures": (io.BytesIO(PNG), "f.png")},
{"body": "Privado", "pictures": (io.BytesIO(PNG), "f.png")},
content_type="multipart/form-data") content_type="multipart/form-data")
name = db.execute("SELECT stored_name FROM attachments").fetchone()["stored_name"] name = db.execute("SELECT stored_name FROM attachments").fetchone()["stored_name"]

View File

@ -26,6 +26,26 @@ def test_no_inline_event_handlers(template):
assert not found, f"{template.name} has inline handler(s): {found}" 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 <style>. The browser drops the whole block without a word, and the
page arrives in Times New Roman with blue links — which is exactly how the
public profile page shipped. Put it in static/ and link it, where the
policy allows it and the browser caches it.
"""
# Comments stripped first: profile.html explains in a Jinja comment why it
# has no <style> block, and a guard that trips on its own documentation is
# a guard people delete.
html = JINJA_COMMENT.sub("", template.read_text(encoding="utf-8"))
assert "<style" not in html, (
f"{template.name} has an inline <style> block, which the CSP ignores. "
"Move it to apps/board/static/ and link it with url_for('static', …)."
)
@pytest.mark.parametrize("template", TEMPLATES, ids=lambda p: p.name) @pytest.mark.parametrize("template", TEMPLATES, ids=lambda p: p.name)
def test_every_post_form_carries_a_csrf_token(template): def test_every_post_form_carries_a_csrf_token(template):
"""The hook in app.py rejects a POST without one, so a form that forgets it """The hook in app.py rejects a POST without one, so a form that forgets it