Coverage for monitoring/auth.py: 100%

79 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-22 12:55 +0000

1"""Users, roles and tokens for the API and dashboard (V6.6.5, #350). Pure: no file, no clock, no network. 

2 

3Three roles, each including the one below it: a **viewer** reads every page; an **operator** may also lock trading on an 

4account (the manual trade lock); an **admin** may also unlock it. A user can be scoped to some accounts or to all (`*`). 

5Tokens are random (`secrets.token_urlsafe(32)`), shown once when created, and stored only as a salted PBKDF2-SHA256 hash; 

6a token is checked in constant time against every user, so the time taken says nothing about which one matched. 

7""" 

8 

9from __future__ import annotations 

10 

11import hashlib 

12import hmac 

13import re 

14import secrets 

15from collections.abc import Iterable, Mapping 

16from dataclasses import dataclass 

17from enum import IntEnum 

18from typing import Any 

19 

20__all__ = ["Role", "User", "ITERATIONS", "new_token", "new_salt", "hash_token", "make_user", "verify_token", "authorize", "parse_users", "users_document"] 

21 

22ITERATIONS = 200_000 

23_NAME_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._@-]{0,63}$") 

24 

25 

26class Role(IntEnum): 

27 """Ordered roles: a viewer reads, an operator may also lock trading, an admin may also unlock it.""" 

28 

29 VIEWER = 1 

30 OPERATOR = 2 

31 ADMIN = 3 

32 

33 @classmethod 

34 def parse(cls, text: str) -> Role: 

35 try: 

36 return cls[str(text).upper()] 

37 except KeyError: 

38 raise ValueError(f"unknown role {text!r} (viewer, operator, admin)") from None 

39 

40 

41@dataclass(frozen=True) 

42class User: 

43 """`accounts` is `("*",)` for every account, else the ids this user may act on.""" 

44 

45 name: str 

46 role: Role 

47 salt: str 

48 token_hash: str 

49 accounts: tuple[str, ...] = ("*",) 

50 

51 def may_access(self, account: str | None) -> bool: 

52 return account is None or "*" in self.accounts or account in self.accounts 

53 

54 

55def new_token() -> str: 

56 """A fresh random bearer token (32 bytes, URL-safe); shown once, stored only as a hash.""" 

57 return secrets.token_urlsafe(32) 

58 

59 

60def new_salt() -> str: 

61 """A fresh random 16-byte salt, hex-encoded.""" 

62 return secrets.token_hex(16) 

63 

64 

65def hash_token(token: str, salt: str, iterations: int = ITERATIONS) -> str: 

66 """PBKDF2-SHA256 of a token under a salt, hex-encoded.""" 

67 return hashlib.pbkdf2_hmac("sha256", str(token).encode("utf-8"), bytes.fromhex(salt), int(iterations)).hex() 

68 

69 

70def make_user(name: str, role: Role, token: str, *, accounts: Iterable[str] = ("*",), salt: str | None = None) -> User: 

71 """A user whose token is stored salted and hashed; `accounts` scopes it (`*` for all). Raises on a bad name.""" 

72 if not _NAME_RE.match(str(name)): 

73 raise ValueError(f"bad user name {name!r}") 

74 chosen = salt or new_salt() 

75 scope = tuple(sorted({str(account) for account in accounts})) or ("*",) 

76 return User(str(name), Role(role), chosen, hash_token(token, chosen), scope) 

77 

78 

79def verify_token(users: Iterable[User], token: str | None) -> User | None: 

80 """The user whose token this is, or None. Every user is checked, whatever matched first.""" 

81 if not token: 

82 return None 

83 found: User | None = None 

84 for user in users: 

85 if hmac.compare_digest(hash_token(token, user.salt), user.token_hash) and found is None: 

86 found = user 

87 return found 

88 

89 

90def authorize(user: User | None, required: Role, account: str | None = None, *, auth_required: bool) -> bool: 

91 """May `user` do something that needs `required` on `account`? With auth off, reads are open and nothing that writes 

92 is: a write always needs an authenticated user of the right role and scope.""" 

93 if not auth_required and required == Role.VIEWER: 

94 return True 

95 if user is None: 

96 return False 

97 return int(user.role) >= int(required) and user.may_access(account) 

98 

99 

100def parse_users(doc: Mapping[str, Any]) -> tuple[User, ...]: 

101 """`{"users": [{"name", "role", "salt", "token_hash", "accounts"}]}` to users. Raises ValueError on a bad or duplicate entry.""" 

102 rows = doc.get("users", []) if isinstance(doc, Mapping) else [] 

103 users: list[User] = [] 

104 seen: set[str] = set() 

105 for row in rows if isinstance(rows, list) else []: 

106 if not isinstance(row, Mapping): 

107 raise ValueError(f"a user entry must be an object, got {type(row).__name__}") 

108 name = str(row.get("name", "")) 

109 if not _NAME_RE.match(name) or name in seen: 

110 raise ValueError(f"bad or duplicate user {name!r}") 

111 seen.add(name) 

112 salt, digest = str(row.get("salt", "")), str(row.get("token_hash", "")) 

113 if not re.fullmatch(r"[0-9a-f]{32}", salt) or not re.fullmatch(r"[0-9a-f]{64}", digest): 

114 raise ValueError(f"user {name!r} has no valid salt and token hash") 

115 scope = row.get("accounts", ["*"]) 

116 # a string would iterate into characters, and "a*" into ("a", "*"): every account (V6.6.7, #363) 

117 if not isinstance(scope, list) or not all(isinstance(account, str) for account in scope): 

118 raise ValueError(f"user {name!r}: accounts must be a list of account ids") 

119 accounts = tuple(scope) or ("*",) 

120 users.append(User(name, Role.parse(str(row.get("role", "viewer"))), salt, digest, accounts)) 

121 return tuple(users) 

122 

123 

124def users_document(users: Iterable[User]) -> dict[str, Any]: 

125 """The JSON the users file holds (hashes only).""" 

126 return {"users": [{"name": user.name, "role": user.role.name.lower(), "salt": user.salt, "token_hash": user.token_hash, "accounts": list(user.accounts)} 

127 for user in users]}