Anyone not signed in holds the guest role

Whether somebody with no account may see something was being answered one
feature at a time: a securesend_allow_guests setting, an enable flag per kiosk,
and very nearly a third for guides - each with its own settings page, its own
vocabulary and its own hand-written branch inside a route. Every one of them
answered a permissions question, and this app already administers permissions
per role.

So a caller with no token is not nobody: they hold the seeded `guest` role.
require_permission consults it when there is no identity, which is the entire
mechanism. The role is seeded holding NOTHING, so an upgrade opens no door; a
site opens one by ticking a box in the same grid it uses for every other role,
and closes it the same way. Revocation is read on every request rather than
cached, because taking guest access away is what somebody does the moment they
realise what they opened, and it has to bite immediately.

The redundant @jwt_required() above require_permission is gone from 184 routes.
It was belt-and-braces before; now it is actively wrong, because it refuses a
request with no token before the permission check can have an opinion, so a
grant would appear to do nothing.

What a guest may hold is bounded. Any .view or .read permission is grantable.
A WRITE has to be blessed by whoever owns it, through the new
get_guest_grantable_permissions hook (contract 0.21.0), and Secure Send is the
only case that exists: sending a password to a vendor is the one write this
product means to offer somebody who never signs in. Everything else is refused
by the API and greyed out in the grid rather than warned about - a checkbox
that quietly makes deleting an asset anonymous is not a warning anybody reads
twice. A guest write records no creator: the trail says when and from where,
never who, and that is the reason for the bar.

GE-Enforce and Slides gained read permissions so they can be opened to guests
without handing out the manage right. Their read routes accept either through
require_any_permission, so nothing an existing manager could reach has moved.

The navigation endpoint now returns only what the caller can actually reach.
Without that a signed-out visitor gets a sidebar of the whole app where every
link bounces off the login page, which reads as a broken site rather than as a
closed door. A nav item may name several permissions; holding any one is
enough, which is what GE-Enforce and Slides need now that a viewer and a
manager hold different strings.

Two things this found on the way: current_user is a LocalProxy, so
`current_user is None` is False for a request with nobody behind it - harmless
under a required JWT, an AttributeError the moment verification became
optional. And an image pasted into a guide before its first save was never
attached to it, so it was visible to editors and invisible to every reader;
saving now attaches it, and `flask guides fix-images` repairs what is stored.

The guides guest setting written earlier today is gone. Granting guides.view to
the guest role replaces it, which is the point.
This commit is contained in:
cproudlock
2026-08-27 12:51:58 -04:00
parent 8531559f22
commit 151d7c4f44
44 changed files with 783 additions and 240 deletions

View File

@@ -10,13 +10,34 @@ or not a separate @jwt_required is also present. The admin role bypasses every
permission check (see User.haspermission), so an admin never needs individual
permissions granted.
THE GUEST ROLE
Somebody with no token is not nobody: they hold the `guest` role. If that role
has been granted the permission a route asks for, the request proceeds; if it
has not - and by default it holds nothing at all - the answer is 401, exactly
as before.
This replaced a growing pile of per-feature booleans (`securesend_allow_guests`,
one per kiosk, one nearly written for guides). Every one of them answered the
same question in its own vocabulary, in its own settings page, checked by its
own hand-written branch inside a route. What a signed-out visitor may see is a
permissions question, and this app already administers permissions per role.
So: a site opens a door by ticking a box in the role grid, and a plugin needs
no code at all to participate. A feature FLAG is still a flag - whether a kiosk
screen exists at this site is not the same question as who may read it.
Usage:
@assets_bp.route('/<int:asset_id>', methods=['DELETE'])
@jwt_required()
@require_permission('assets.delete')
def delete_asset(asset_id):
...
A separate @jwt_required() above these is redundant - they verify the request
themselves - and it is actively wrong now: it refuses a request with no token
before the guest role can be consulted, so a permission granted to guests would
appear to do nothing.
"""
from functools import wraps
@@ -26,6 +47,45 @@ from flask_jwt_extended import verify_jwt_in_request, current_user, get_jwt
from shopdb.utils.responses import error_response, ErrorCodes
def currentuser():
"""The signed-in user, or None.
`current_user` is a LocalProxy: the proxy object exists whether or not
anybody is behind it, so `current_user is None` is False even for a request
with no token. Under a required JWT that never showed, because the request
was refused before reaching here. With optional verification it shows
immediately, as "'NoneType' object has no attribute 'haspermission'".
"""
try:
return current_user._get_current_object()
except Exception:
return None
def guestholds(permission_name: str) -> bool:
"""Whether the guest role has been granted this permission.
Read every time, not cached. Revoking guest access is what somebody does the
moment they realise what they opened up, and it has to bite on the very next
request - a cache keyed to the app context outlives a request whenever one
is pushed around several (which is exactly how the test client behaves, and
how the revoke test caught it). One small indexed query on the rare path is
worth more than that risk.
A site with no guest role yet - an older database, seeded before this
existed - answers no, which is the behaviour it already had.
"""
from shopdb.core.models import Role
try:
role = Role.guest()
except Exception:
# A database that cannot answer must not turn into an open door.
return False
if role is None:
return False
return any(p.name == permission_name for p in role.permissions)
def require_permission(permission_name: str):
"""Gate a route behind a single permission. Admin role bypasses.
@@ -36,10 +96,15 @@ def require_permission(permission_name: str):
def decorator(view_func):
@wraps(view_func)
def wrapper(*args, **kwargs):
# verify jwt first so current_user is loaded (idempotent if the
# route also has @jwt_required)
verify_jwt_in_request()
if current_user is None:
# Optional, so a request with no token reaches the guest check
# below rather than being refused by the JWT layer before this
# decorator can have an opinion. A request that DOES carry a token
# is still verified, and a bad one still fails here.
verify_jwt_in_request(optional=True)
user = currentuser()
if user is None:
if guestholds(permission_name):
return view_func(*args, **kwargs)
return error_response(
ErrorCodes.UNAUTHORIZED,
'Authentication required',
@@ -53,7 +118,7 @@ def require_permission(permission_name: str):
# everything), so the scope list is the real limiter - the
# admin bypass is suspended.
allowed = (permission_name in patscopes
and current_user.haspermission(permission_name))
and user.haspermission(permission_name))
if not allowed:
return error_response(
ErrorCodes.FORBIDDEN,
@@ -61,7 +126,54 @@ def require_permission(permission_name: str):
http_code=403
)
return view_func(*args, **kwargs)
if not current_user.haspermission(permission_name):
if not user.haspermission(permission_name):
return error_response(
ErrorCodes.FORBIDDEN,
'You do not have permission to perform this action',
http_code=403
)
return view_func(*args, **kwargs)
return wrapper
return decorator
def require_any_permission(*permission_names):
"""Gate a route behind ANY ONE of several permissions. Admin bypasses.
For a read that two different rights should reach. GE-Enforce and Slides
are the cases: a GET was gated on the MANAGE permission, because managing
was the only thing anybody did there. Splitting a read permission out would
have locked out every existing manager, so a read now accepts either, and
the read permission is the one a site can hand to a guest.
A scoped PAT must carry one of the names, and its owner must hold that same
one - the intersection rule of require_permission, applied per name.
"""
def decorator(view_func):
@wraps(view_func)
def wrapper(*args, **kwargs):
verify_jwt_in_request(optional=True)
user = currentuser()
if user is None:
if any(guestholds(name) for name in permission_names):
return view_func(*args, **kwargs)
return error_response(
ErrorCodes.UNAUTHORIZED,
'Authentication required',
http_code=401
)
patscopes = get_jwt().get('patscopes')
if patscopes is not None:
allowed = any(name in patscopes and user.haspermission(name)
for name in permission_names)
if not allowed:
return error_response(
ErrorCodes.FORBIDDEN,
'This API token is not scoped for this action',
http_code=403
)
return view_func(*args, **kwargs)
if not any(user.haspermission(name) for name in permission_names):
return error_response(
ErrorCodes.FORBIDDEN,
'You do not have permission to perform this action',
@@ -83,7 +195,8 @@ def require_role(rolename: str):
@wraps(view_func)
def wrapper(*args, **kwargs):
verify_jwt_in_request()
if current_user is None:
user = currentuser()
if user is None:
return error_response(
ErrorCodes.UNAUTHORIZED,
'Authentication required',
@@ -95,7 +208,7 @@ def require_role(rolename: str):
'Scoped API tokens cannot access role-gated endpoints',
http_code=403
)
if not current_user.hasrole(rolename):
if not user.hasrole(rolename):
return error_response(
ErrorCodes.FORBIDDEN,
f'{rolename.capitalize()} access required',