Coverage for app / services / rules / redaction.py: 95%

19 statements  

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

1""" 

2The PII redaction a rule asks for, keyed for this deployment. 

3 

4``pii`` is the detection engine and holds no configuration — svc-ai carries 

5the same file. This is where svc-core supplies what it needs: the placeholder 

6key, derived from ``INTERNAL_JWT_SECRET`` (the secret svc-ai derives the same 

7key from, so a value redacted in either service gets the same placeholder), 

8and the owner placeholders are keyed to, which the rule engine puts on the 

9context it hands actions. 

10""" 

11 

12from __future__ import annotations 

13 

14import logging 

15from functools import lru_cache 

16from typing import Any 

17 

18from app.services.rules import pii 

19 

20logger = logging.getLogger(__name__) 

21 

22#: Context key under which the rule engine hands redaction actions the user 

23#: placeholders are keyed to. Namespaced so it can never collide with a 

24#: registered condition field. 

25OWNER_CONTEXT_KEY = "__pii_owner__" 

26 

27 

28@lru_cache(maxsize=1) 

29def placeholder_key() -> bytes: 

30 """This deployment's placeholder key. Read once: rotating the secret 

31 takes a restart, like everything else that reads it.""" 

32 from app.common.settings import get_settings 

33 

34 return pii.placeholder_key(get_settings().INTERNAL_JWT_SECRET) 

35 

36 

37def redactor(kinds: Any = None, owner: str | None = None) -> pii.Redactor: 

38 """A redactor for ``kinds`` (a rule's ``kinds`` parameter, as stored) whose 

39 placeholders are keyed to ``owner``.""" 

40 chosen, unknown = pii.parse_kinds(kinds) 

41 if unknown: 

42 logger.warning( 

43 "PII rule names kinds the detectors do not know (%s) — ignored", 

44 ", ".join(unknown), 

45 ) 

46 return pii.Redactor(chosen, key=placeholder_key(), owner=owner) 

47 

48 

49def for_action(config: dict[str, Any], context: dict[str, Any]) -> pii.Redactor: 

50 """The redactor one action block asks for, in one evaluation's context.""" 

51 owner = context.get(OWNER_CONTEXT_KEY) or context.get("user_id") 

52 return redactor(config.get("kinds"), str(owner) if owner else None)