micro / faisi /src /sandbox /id_mapper.py
ppJustin's picture
Add files using upload-large-folder tool
c5f5de4 verified
Raw History Blame Contribute Delete
3.84 kB
"""Private, replayable entity permutations and defensive log rendering."""
import hashlib
import random
import re
PREFIX = {"service": "SVC", "instance": "INST", "host": "HOST"}
SAFE_WORDS = frozenset("""
a an and at by for from in of on or the to with after before
aborted access address already application authentication available bad
broken cancelled client closed code connection denied disconnected
dropped duplicate empty end error exceeded exception failed failure
fatal found handshake health internal invalid io limit lost memory
missing not out overloaded packet permission pool queue rate refused
request reset resource response retry server service slow socket
status stream successful unavailable unexpected unknown warn warning
crash crashed deadline eof exhausted oom timeout timed receive read
send write operation parse protocol upstream downstream database
container process thread allocation overflow underflow restart backoff
""".split())
TOKEN = re.compile(r"[\w.-]+|[^\w\s]", re.UNICODE)
def entity_pattern(values):
names = sorted({name for name in values if name}, key=lambda name: (-len(name), name))
if not names:
return re.compile(r"(?!)")
choices = "|".join(map(re.escape, names))
return re.compile(r"(?<![A-Za-z0-9_])(?:" + choices + r")(?![A-Za-z0-9_])", re.IGNORECASE | re.ASCII)
class IdMapper:
__slots__ = ("__forward", "__reverse", "__aliases", "__pattern", "__key")
def __init__(self, entities, session_seed, case_key):
if type(session_seed) is not int or not -(2**63) <= session_seed < 2**63:
raise ValueError("invalid_session_seed")
self.__key = hashlib.blake2s(f"{case_key}\0{session_seed}".encode()).digest()
rng = random.Random(int.from_bytes(self.__key, "big"))
forward = {}
for layer, prefix in PREFIX.items():
names = sorted(name for name, kind in entities.items() if kind == layer)
rng.shuffle(names)
forward.update((name, f"{prefix}_{number:02d}") for number, name in enumerate(names, 1))
if len(forward) != len(entities):
raise ValueError("invalid_entity_layer")
self.__forward = forward
self.__reverse = {anonymous: real for real, anonymous in forward.items()}
aliases = {}
for real, anonymous in sorted(forward.items()):
aliases.setdefault(real.lower(), anonymous)
self.__aliases = aliases
self.__pattern = entity_pattern(aliases)
def _mask(self, real):
return self.__forward[real]
def _resolve(self, anonymous):
return self.__reverse.get(anonymous) if type(anonymous) is str else None
def _evidence(self, *tags):
body = "\x1f".join(tags).encode()
return "EV_" + hashlib.blake2s(body, key=self.__key, digest_size=6).hexdigest()
def _visible_text(self, message, max_chars=140):
if not message:
return ""
shown = []
previous = 0
def safe_words(fragment):
for match in TOKEN.finditer(fragment):
word = match.group().lower()
if word in SAFE_WORDS and word not in self.__aliases:
shown.append(word)
elif word not in {".", ",", ":", ";", "(", ")", "[", "]", "<", ">"}:
if not shown or shown[-1] != "<redacted>":
shown.append("<redacted>")
for match in self.__pattern.finditer(message):
safe_words(message[previous:match.start()])
shown.append(self.__aliases[match.group().lower()])
previous = match.end()
safe_words(message[previous:])
while shown and sum(len(word) + 1 for word in shown) - 1 > max_chars:
shown.pop()
return " ".join(shown)