Add optional permission scopes to API tokens
A token may carry a scopes list: it then grants only those permissions, intersected with what the owner holds at use time, with the admin role bypass suspended and role-gated routes denied - a scoped token from an admin account is genuinely limited. Scope ceiling enforced at create/update too (only permissions the owner holds; 400 lists violations) and the picker only offers what you hold. Token management itself now requires the new apitokens.create permission (admin by default, grantable via roles). Unscoped tokens keep the exact prior act-as-owner behavior; imports need an unscoped admin token. Migration 7d22. 756 tests pass; live-verified scoped 201/403 matrix. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
@@ -11,11 +11,40 @@ from flask_jwt_extended import jwt_required, current_user
|
||||
from shopdb.extensions import db
|
||||
from shopdb.core.models import ApiToken, AuditLog
|
||||
from shopdb.utils.responses import success_response, error_response, ErrorCodes
|
||||
from shopdb.utils.authz import require_permission
|
||||
from shopdb.utils.import_mode import parse_import_datetime
|
||||
|
||||
apitokens_bp = Blueprint('apitokens', __name__)
|
||||
|
||||
|
||||
def _validate_scopes(scopes, owner):
|
||||
"""Validate a scopes payload against the token OWNER. Return
|
||||
(scopelist_or_none, error_response); the second is None when valid.
|
||||
|
||||
scopes may be None/absent (unscoped) or a list of permission names. Every
|
||||
name must exist in the catalog AND be held by the owner (the scope ceiling):
|
||||
a token can never grant more than its owner holds. Admins hold everything.
|
||||
"""
|
||||
if scopes is None:
|
||||
return None, None
|
||||
if not isinstance(scopes, list) or not all(isinstance(s, str) for s in scopes):
|
||||
return None, error_response(
|
||||
ErrorCodes.VALIDATION_ERROR,
|
||||
'scopes must be a list of permission names')
|
||||
unknown = ApiToken.unknown_scope_names(scopes)
|
||||
if unknown:
|
||||
return None, error_response(
|
||||
ErrorCodes.VALIDATION_ERROR,
|
||||
'Unknown permission names: ' + ', '.join(unknown))
|
||||
# Scope ceiling: the owner must actually hold each scoped permission.
|
||||
disallowed = [n for n in scopes if not owner.haspermission(n)]
|
||||
if disallowed:
|
||||
return None, error_response(
|
||||
ErrorCodes.VALIDATION_ERROR,
|
||||
'Permissions not held by the token owner: ' + ', '.join(disallowed))
|
||||
return scopes, None
|
||||
|
||||
|
||||
@apitokens_bp.route('', methods=['GET'])
|
||||
@jwt_required()
|
||||
def list_apitokens():
|
||||
@@ -40,8 +69,13 @@ def list_apitokens():
|
||||
|
||||
@apitokens_bp.route('', methods=['POST'])
|
||||
@jwt_required()
|
||||
@require_permission('apitokens.create')
|
||||
def create_apitoken():
|
||||
"""Create a token for the caller. Returns the full secret ONCE."""
|
||||
"""Create a token for the caller. Returns the full secret ONCE.
|
||||
|
||||
Optional scopes limit the token to a subset of the caller's own
|
||||
permissions; absent/null means an unscoped token acting as the caller.
|
||||
"""
|
||||
data = request.get_json() or {}
|
||||
|
||||
name = (data.get('name') or '').strip()
|
||||
@@ -55,6 +89,10 @@ def create_apitoken():
|
||||
return error_response(ErrorCodes.VALIDATION_ERROR,
|
||||
'expiresat is not a valid date/datetime')
|
||||
|
||||
scopelist, scope_error = _validate_scopes(data.get('scopes'), current_user)
|
||||
if scope_error is not None:
|
||||
return scope_error
|
||||
|
||||
secret = ApiToken.generate_secret()
|
||||
token = ApiToken(
|
||||
userid=current_user.userid,
|
||||
@@ -63,6 +101,7 @@ def create_apitoken():
|
||||
tokenhash=ApiToken.hash_secret(secret),
|
||||
expiresat=expiresat,
|
||||
)
|
||||
token.scopelist = scopelist
|
||||
db.session.add(token)
|
||||
db.session.flush()
|
||||
|
||||
@@ -79,8 +118,14 @@ def create_apitoken():
|
||||
|
||||
@apitokens_bp.route('/<int:tokenid>', methods=['PUT'])
|
||||
@jwt_required()
|
||||
@require_permission('apitokens.create')
|
||||
def update_apitoken(tokenid: int):
|
||||
"""Rename or deactivate a token. Own token, or any if admin."""
|
||||
"""Rename, rescope, or deactivate a token. Own token, or any if admin.
|
||||
|
||||
Scopes are validated against the token OWNER's permissions (the ceiling),
|
||||
not the editor's - so an admin rescoping someone else's token still cannot
|
||||
grant that owner more than the owner holds.
|
||||
"""
|
||||
token = db.session.get(ApiToken, tokenid)
|
||||
if token is None:
|
||||
return error_response(ErrorCodes.NOT_FOUND, 'Token not found', http_code=404)
|
||||
@@ -97,6 +142,11 @@ def update_apitoken(tokenid: int):
|
||||
token.name = newname
|
||||
if 'isactive' in data:
|
||||
token.isactive = bool(data['isactive'])
|
||||
if 'scopes' in data:
|
||||
scopelist, scope_error = _validate_scopes(data.get('scopes'), token.user)
|
||||
if scope_error is not None:
|
||||
return scope_error
|
||||
token.scopelist = scopelist
|
||||
|
||||
db.session.commit()
|
||||
return success_response(token.to_dict(), message='Token updated')
|
||||
@@ -104,6 +154,7 @@ def update_apitoken(tokenid: int):
|
||||
|
||||
@apitokens_bp.route('/<int:tokenid>', methods=['DELETE'])
|
||||
@jwt_required()
|
||||
@require_permission('apitokens.create')
|
||||
def revoke_apitoken(tokenid: int):
|
||||
"""Revoke (deactivate) a token. Own token, or any if admin."""
|
||||
token = db.session.get(ApiToken, tokenid)
|
||||
|
||||
Reference in New Issue
Block a user