Coverage for app/roles.py: 100%

15 statements  

« prev     ^ index     » next       coverage.py v7.14.1, created at 2026-10-31 11:18 +0000

1"""The platform roles an ID token carries (docs/system/security/auth-flow.md). 

2 

3An Auth0 post-login Action puts the roles assigned to the user in Auth0 into 

4one custom claim (``settings.AUTH0_ROLES_CLAIM``). svc-auth keeps them on the 

5session, svc-bff carries them to svc-core in the internal token, and svc-core 

6decides what each one unlocks. This module only reads the claim: it never 

7grants anything. 

8 

9A token without the claim says nothing about roles, which is not the same as 

10a token that says "none" — svc-core changes a user's roles only on the 

11second. So :func:`roles_from` answers ``None`` for a missing claim and a list 

12(perhaps empty) for one that is there. 

13""" 

14 

15from __future__ import annotations 

16 

17from typing import Any, Mapping 

18 

19from app.config import settings 

20 

21#: More than a person could hold; a claim past it is cut, never refused. 

22MAX_ROLES = 20 

23#: An Auth0 role name is short; a longer value is no role of ours. 

24MAX_ROLE_LENGTH = 64 

25 

26 

27def roles_from(payload: Mapping[str, Any]) -> list[str] | None: 

28 """The roles in a decoded ID token, sorted and distinct, or ``None`` when 

29 the token does not carry the claim.""" 

30 if settings.AUTH0_ROLES_CLAIM not in payload: 

31 return None 

32 claim = payload.get(settings.AUTH0_ROLES_CLAIM) 

33 if isinstance(claim, str): 

34 claim = [claim] 

35 if not isinstance(claim, (list, tuple)): 

36 return [] 

37 roles = { 

38 value.strip() 

39 for value in claim 

40 if isinstance(value, str) and 0 < len(value.strip()) <= MAX_ROLE_LENGTH 

41 } 

42 return sorted(roles)[:MAX_ROLES]