"""Redaction for the Codex rollout cleaning pipeline. Design ------ * All finders run on the ORIGINAL text and return spans (start, end, kind, replacement). Overlaps are resolved left-to-right (earliest start wins, then longest), so every replacement has exact offsets in the redacted text. That is what lets the pipeline log only replacements that survive tool-output truncation. * Finders are linear-time: nothing starts with an unbounded character class followed by a distant anchor (e.g. e-mail search is anchored on '@', not on the local part). * A second "verification" loop re-scans the redacted text with the *secret* finders and re-applies them if anything is left (belt and braces). * Nothing here ever writes an original value anywhere; callers only receive sha256 digests. """ import hashlib import re SECRET = "" EMAIL = "" IP = "" # ----------------------------------------------------------------------------- secrets _PEM_FULL = re.compile( r"-----BEGIN [A-Z0-9 ]*PRIVATE KEY(?: BLOCK)?-----[\s\S]{0,20000}?-----END [A-Z0-9 ]*PRIVATE KEY(?: BLOCK)?-----" ) # Unterminated block (output was cut or the END line was lost): redact BEGIN line + base64 body. _PEM_OPEN = re.compile( r"-----BEGIN [A-Z0-9 ]*PRIVATE KEY(?: BLOCK)?-----(?:[A-Za-z0-9+/=\s]|\\n|\\r){0,8000}" ) # Token patterns are applied exactly as written in the task spec (no left word-boundary), so a plain grep for the # same regex over the output finds nothing. Matches that are glued to a preceding word character (for example the # "sk-" inside a hyphenated file name such as "...task-board-...") are logged with kind suffix ":embedded_in_word" # so the collateral can be audited from redactions.jsonl. _AKIA = re.compile(r"AKIA[0-9A-Z]{16}") _GH = re.compile(r"gh[pousr]_[A-Za-z0-9]{20,}") # ghp_ (+ gho_/ghu_/ghs_/ghr_) _GH_PAT = re.compile(r"github_pat_[A-Za-z0-9_]{20,}") _SK = re.compile(r"sk-[A-Za-z0-9_-]{20,}") _BEARER = re.compile( r"(?i)\bAuthorization\s*[:=]\s*\\*[\"']?\s*Bearer\s+(?P[A-Za-z0-9._~+/=-]{8,})" ) # key = value secrets. password|passwd|token|api_key|apikey|secret, optionally prefixed # (access_token, client_secret, x-api-key, DB_PASSWORD ...) but NOT suffixed (token_count, secrets...) _KV = re.compile( r"(?i)(?(?:[A-Za-z0-9]+[_.-])*(?:password|passwd|token|api[_-]?key|apikey|secret))" r"(?![A-Za-z0-9])\\*[\"']?[ \t]*(?::|=(?!=))[ \t]*\\*(?:" r"(?P[\"'])(?P[^\"'\r\n\\]{3,200})\\*(?P=q)" r"|(?P[^\s\"'\\,;&(){}\[\]<>|`]{6,200}))" ) _IDENT = re.compile(r"^[A-Za-z_][A-Za-z_]*$") # code identifier with no digits: not a literal secret _HEX = re.compile(r"^0[xX][0-9A-Fa-f]+$") # decompiler metadata tokens: "// Token: 0x06000001" _DOTTED = re.compile(r"^[A-Za-z_]\w*(?:\.[A-Za-z_]\w*)+$") # member access: this.token_value (JWTs are far longer) def _kv_value_ok(val, quoted): if not val or val[0] in "$%<{(@#*": return False if val.lower() in ("null", "none", "true", "false", "undefined", "nullptr", "redacted"): return False if quoted: return True if _IDENT.match(val) or _HEX.match(val): return False if len(val) <= 64 and _DOTTED.match(val): return False return True # ----------------------------------------------------------------------------- e-mail _EMAIL_LOCAL = re.compile(r"[A-Za-z0-9._%+-]+$") _EMAIL_DOMAIN = re.compile(r"[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*\.([A-Za-z]{2,})") # TLD-looking file extensions: icon@2x.png, foo@bar.cpp ... are not mail addresses. _FILE_EXT = frozenset( "png jpg jpeg gif svg webp bmp ico tga dds tif tiff psd bin dll exe lib obj asm so dylib pdb log xml yml yaml " "html htm css js ts json txt md c h cc cpp hpp cs py rs go java rb php sh bat ps1 cmd csv tsv bk2 bik bik2 " "mp4 mkv avi mov wav mp3 ogg zip rar 7z gz tar".split() ) def _find_emails(text): out = [] i = text.find("@") n = len(text) while i != -1: # local part: walk left (bounded) j = i lo = max(0, i - 64) while j > lo and text[j - 1] in "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789._%+-": j -= 1 local = text[j:i] if local and any(ch.isalnum() for ch in local): m = _EMAIL_DOMAIN.match(text, i + 1) if m and m.group(1).lower() not in _FILE_EXT: out.append((j, m.end(), "email", EMAIL)) i = text.find("@", i + 1) return out # ----------------------------------------------------------------------------- windows user paths _SYSTEM_PROFILES = frozenset(("public", "default", "default user", "all users", "user", "defaultuser0")) _WIN_USER = re.compile( r"(?P[A-Za-z]:)(?P\\{1,8}|/{1,2})(?i:Users)(?P\\{1,8}|/{1,2})(?P[^\\/\s\"'<>|:*?,;(){}\[\]`]+)" ) _UNIX_USER = re.compile( r"(?/mnt/[a-z]|/[a-z])/(?i:Users)/(?P[^\\/\s\"'<>|:*?,;(){}\[\]`]+)" ) def _find_user_paths(text): out = [] if "sers" not in text and "SERS" not in text: return out for m in _WIN_USER.finditer(text): name = m.group("name") if name.lower() in _SYSTEM_PROFILES: continue rep = f"{m.group('drive')}{m.group('s1')}Users{m.group('s2')}user" out.append((m.start(), m.end(), "win_user_path", rep)) for m in _UNIX_USER.finditer(text): name = m.group("name") if name.lower() in _SYSTEM_PROFILES: continue out.append((m.start(), m.end(), "win_user_path_posix", f"{m.group('pre')}/Users/user")) return out # ----------------------------------------------------------------------------- OneDrive organisation names # Work/school OneDrive folders are named "OneDrive - " and are followed by a path separator, # e.g. "D:\OneDrive - Some School\Documents". The organisation identifies the account owner, so it is masked. # The generic consumer folder "OneDrive - Personal" is not an organisation and is kept. ORG = "" _ONEDRIVE_ORG = re.compile(r"(?<=OneDrive - )(?P[^\\/\r\n\"<>|:*?]{1,80}?)(?=\\|/)") _ONEDRIVE_KEEP = frozenset(("personal",)) def _find_onedrive_org(text): out = [] if "OneDrive - " not in text: return out for m in _ONEDRIVE_ORG.finditer(text): if m.group("org").strip().lower() in _ONEDRIVE_KEEP: continue out.append((m.start("org"), m.end("org"), "onedrive_org", ORG)) return out # ----------------------------------------------------------------------------- IPv4 _OCT = r"(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)" _IPV4 = re.compile(rf"(? 0 and (text[start - 1].isalnum() or text[start - 1] in "_-") else "" def _find_secrets(text): out = [] if "-----BEGIN" in text: for m in _PEM_FULL.finditer(text): out.append((m.start(), m.end(), "secret:pem_private_key", SECRET)) for m in _PEM_OPEN.finditer(text): out.append((m.start(), m.end(), "secret:pem_private_key", SECRET)) if "AKIA" in text: for m in _AKIA.finditer(text): out.append((m.start(), m.end(), "secret:aws_access_key" + _emb(text, m.start()), SECRET)) if "gh" in text: for m in _GH.finditer(text): out.append((m.start(), m.end(), "secret:github_token" + _emb(text, m.start()), SECRET)) if "github_pat_" in text: for m in _GH_PAT.finditer(text): out.append((m.start(), m.end(), "secret:github_pat" + _emb(text, m.start()), SECRET)) if "sk-" in text: for m in _SK.finditer(text): out.append((m.start(), m.end(), "secret:sk_key" + _emb(text, m.start()), SECRET)) if "earer" in text: for m in _BEARER.finditer(text): v = m.group("val") if v[0] in "$%<{": continue out.append((m.start("val"), m.end("val"), "secret:bearer_token", SECRET)) low = text.lower() if ("password" in low) or ("passwd" in low) or ("token" in low) or ("secret" in low) or ("apikey" in low) or ("api_key" in low) or ("api-key" in low): for m in _KV.finditer(text): if m.group("q"): s, e, val, quoted = m.start("qval"), m.end("qval"), m.group("qval"), True else: s, e, val, quoted = m.start("bval"), m.end("bval"), m.group("bval"), False if not _kv_value_ok(val, quoted): continue kname = re.sub(r"[^a-z]", "", m.group("key").lower().split("_")[-1].split("-")[-1].split(".")[-1]) out.append((s, e, "secret:kv:" + (kname or "key"), SECRET)) return out def _resolve(spans): """Earliest start wins; at equal start the longer span wins. Overlapping losers are dropped.""" spans.sort(key=lambda s: (s[0], -(s[1] - s[0]))) kept = [] last_end = -1 for s in spans: if s[0] >= last_end: kept.append(s) last_end = s[1] return kept def _sha(s): return hashlib.sha256(s.encode("utf-8", "surrogatepass")).hexdigest() def redact_text(text): """Redact `text`. Returns (new_text, events) where events is a list of (start, end, kind, sha256_of_original, replacement) with start/end in *new_text* coordinates.""" if not text: return text, [] spans = _find_secrets(text) + _find_emails(text) + _find_user_paths(text) + _find_onedrive_org(text) + _find_ips(text) if not spans: return text, [] kept = _resolve(spans) pieces = [] events = [] pos = 0 out_len = 0 for s, e, kind, rep in kept: seg = text[pos:s] pieces.append(seg) out_len += len(seg) events.append((out_len, out_len + len(rep), kind, _sha(text[s:e]), rep)) pieces.append(rep) out_len += len(rep) pos = e pieces.append(text[pos:]) new = "".join(pieces) # Verification loop: a secret-class match must never survive. for _ in range(3): left = _find_secrets(new) if not left: break left = _resolve(left) pieces = [] pos = 0 shift_events = [] for s, e, kind, rep in left: pieces.append(new[pos:s]) pieces.append(rep) shift_events.append((s, e, kind, _sha(new[s:e]), rep)) pos = e pieces.append(new[pos:]) new = "".join(pieces) # offsets of earlier events can shift; recompute coarsely by dropping offsets (rare path) events = [(-1, -1, k, h, r) for (_, _, k, h, r) in events] + [(-1, -1, k, h, r) for (_, _, k, h, r) in shift_events] return new, events def redact_json_leaves(obj, sink): """Redact every string leaf of a parsed JSON value. `sink` receives (kind, sha, replacement) tuples. Returns (new_obj, changed).""" if isinstance(obj, str): new, ev = redact_text(obj) for (_, _, k, h, r) in ev: sink.append((k, h, r)) return new, bool(ev) if isinstance(obj, list): changed = False res = [] for x in obj: y, c = redact_json_leaves(x, sink) res.append(y) changed = changed or c return res, changed if isinstance(obj, dict): changed = False res = {} for k, v in obj.items(): y, c = redact_json_leaves(v, sink) res[k] = y changed = changed or c return res, changed return obj, False # ----------------------------------------------------------------------------- validation regexes # Plain (un-boundaried) secret regexes used by the *validation* step, deliberately broader than the # redaction finders so that a miss caused by a boundary rule is still surfaced. VALIDATION_REGEXES = { "AKIA": re.compile(r"AKIA[0-9A-Z]{16}"), "ghp_": re.compile(r"ghp_[A-Za-z0-9]{20,}"), "github_pat_": re.compile(r"github_pat_[A-Za-z0-9_]{20,}"), "sk-": re.compile(r"sk-[A-Za-z0-9_-]{20,}"), "PEM PRIVATE KEY": re.compile(r"-----BEGIN [A-Z0-9 ]*PRIVATE KEY"), "Authorization: Bearer": re.compile(r"(?i)Authorization\s*[:=]\s*\\*[\"']?\s*Bearer\s+(?!)[A-Za-z0-9._~+/=-]{8,}"), } # ----------------------------------------------------------------------------- phone-like candidates # Reported, never redacted. PHONE_RE = re.compile( r"(?