
Using IBeforeTraverseEvent as a roadblock
Closing a Plone site to anonymous visitors with one traversal subscriber, and why the check has to wait for authentication.
The new plone.org is being built in the open, and it has two preproduction stacks. Testers need to use them. Search engines, scrapers and curious visitors should not.
Until now, the gate was HTTP basic auth on the frontend, configured in Traefik. It works, but it is a second login that knows nothing about Plone. Our testers already have an account: they sign in through the community identity provider. The proxy cannot see that account, so everyone shared one more password.
What I wanted was simpler: if Plone knows who you are, come in. If it doesn't, stop. And do it in one place, for every path under the site, with or without ++api++.
The trick itself is not new. I first wrote it back in 2017, to block access to an internal knowledge base at Briefy, a startup where I was CTO at the time. Bringing it to a Plone 6 site with a Volto frontend took a few adjustments, and those are most of this post.
The hook
Zope gives us a rich and comprehensive event system. Objects are created, modified, moved and removed, workflow transitions happen, users log in, requests start and end, and each of these moments is an event any package can subscribe to. That is what makes solutions like this one small: there is no need to patch the publisher or wrap the application, only to pick the right event and listen to it.
The right event here is IBeforeTraverseEvent. Zope fires it when the publisher is about to traverse into a site, and the Plone site root is one. Register a subscriber for the site root and you get called for every request that goes through the site:
<subscriber
for="plone.base.interfaces.IPloneSiteRoot
zope.traversing.interfaces.IBeforeTraverseEvent"
handler=".traversal.roadblock"
/>Note what it is registered for: the site root, not INavigationRoot, and not every object. It runs once per request, not once per path segment. Paths outside the Plone site, such as the Zope root, are not touched.
The catch: it is too early
The tempting version checks api.user.is_anonymous() inside the subscriber and raises. It does not work, because the event fires during traversal, and Zope authenticates the user after traversal. At that point, everyone looks anonymous.
The fix is to not decide yet. The subscriber only schedules a callback with request.post_traverse, which the publisher runs once traversal and authentication are done:
def roadblock(obj, event):
if not settings.ENABLE_ROADBLOCK:
return
request = event.request
try:
request.post_traverse(reject_anonymous, (obj, request))
except RuntimeError:
# Not inside publishing traversal: nothing is being published.
return
def reject_anonymous(portal, request):
if not api.user.is_anonymous():
return
if first_segment(portal, request) in ANON_ALLOW_LISTED:
return
raise Unauthorized("Anonymous rejected")Raising Unauthorized gives the client a 401, as JSON under ++api++. No redirect, no fiddling with the response.
The RuntimeError is there because the event is not only fired by the publisher. plone.app.testing notifies it on its test request while setting up the environment, and scripts can do the same. Outside publishing, post_traverse refuses with "may only be called during publishing traversal", and the right answer is to do nothing: nothing is being published.
The roadblock is switched on by an environment variable, ENABLE_ROADBLOCK, read once at startup into a setting. Both preproduction stacks set it, and the same change removes the Traefik basic auth it replaces. Without it, the subscriber returns at once.
The allow-list
A wall with no door is not useful. An anonymous visitor must still be able to load the frontend and log in, so a few names are allowed through:
ANON_ALLOW_LISTED = frozenset((
"@site",
"@workflow",
"@login",
"@login-providers",
"@identity-callback",
))That is what Volto needs, with the pas.plugins.identity login, to show the login page and complete a sign-in. It is a list for this site, not a universal one: magic links and email confirmation, for example, are not on it.
The check looks at the first path segment under the site:
IGNORED_SEGMENTS = frozenset(("++api++", "index_html"))
def first_segment(portal, request):
portal_path = portal.getPhysicalPath()
physical_path = request.physicalPathFromURL(request["URL"])
names = [
name
for name in physical_path[len(portal_path):]
if name not in IGNORED_SEGMENTS
]
return names[0] if names else ""Two lines in that function exist because the first version of the port got them wrong.
What the port got wrong
- ++api++ is a segment. Volto calls /Plone/++api++/@site. If ++api++ is not skipped, the first segment is always ++api++, nothing matches the allow-list, and nobody can even reach @login. The site was perfectly closed, including to the people who were supposed to open it.
- The site root has no segment. GET /Plone, or /Plone/index_html, leaves nothing after the site path. Taking the first item of an empty list is an IndexError, which is a 500. Now it returns an empty string, which is not on the list, so the request is blocked, as it should be.
- Prefixes are not names. Matching with startswith let @login-anything through. An exact match on a frozenset does not. It also means @login-providers has to be listed on its own, because Volto's login page calls it.
A few more things are worth knowing, even if they are not bugs. An unknown name gives a 404, not a 401, because traversal fails before the post-traverse callback runs. Behind the virtual host rewrite Traefik does for the API, the check behaves the same, because it works on the physical path, not on the URL the browser saw. And the subscriber reads settings.ENABLE_ROADBLOCK through the module on every request: from settings import ENABLE_ROADBLOCK would freeze the value at import time, and the tests could not switch the roadblock on and off.
Tests
The tests use pytest-plone, which brings Plone's test layers to pytest as fixtures. Two of them do most of the work here: functional_portal, a site served by a real WSGI server, and request_factory, which builds HTTP sessions against it, anonymous by default or with a role, through ++api++ by default or not. The project adds two fixtures of its own: page, a published Document, and roadblock, which switches the setting on and off:
@pytest.fixture
def roadblock(monkeypatch):
def func(enabled: bool) -> None:
monkeypatch.setattr(settings, "ENABLE_ROADBLOCK", enabled)
return func
class TestRoadblockEnabled:
@pytest.fixture(autouse=True)
def _setup(self, roadblock, page):
roadblock(True)
@pytest.mark.parametrize("path,api", BLOCKED)
def test_anonymous_blocked(self, request_factory, path, api):
session = request_factory(api=api)
assert _get(session, path) == 401
@pytest.mark.parametrize("path,api", BLOCKED)
def test_manager_reaches(self, request_factory, path, api):
session = request_factory(role="Manager", api=api)
assert _get(session, path) == 200BLOCKED holds (path, through ++api++) pairs: the site root, the page, @navigation, @breadcrumbs and @search. _get sends a GET without following redirects and returns the status code. The monkeypatch reaches the server because the test WSGI server runs in the same process as the test. A twin class, with the roadblock off, asserts that an anonymous visitor gets 200 on the same pairs, and another test checks that every allowed name answers the same with the roadblock on or off.
Some cases cannot be shown over HTTP, because traversal answers 404 first: @login-anything, @site-anything and @sit. Those are tested by calling reject_anonymous directly, with pytest-plone's integration portal and http_request fixtures, after logout().
If you want to test behind the virtual host rewrite, add a Virtual Host Monster to the app and commit first. Without it, /VirtualHostBase/… is a plain 404, and you will spend a while wondering why.
Wrapping up
The idea is small enough to copy into any Plone 6 site that needs a staging gate: one subscriber, one callback, one list of doors. The part to remember is the timing. IBeforeTraverseEvent tells you where the request is going. Only post_traverse can tell you who is asking.