Datasets:
File size: 6,195 Bytes
44a0dc8 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 | #!/usr/bin/env python3
"""Scan human-facing text for a small set of exposure-aware hard leaks."""
from __future__ import annotations
import argparse
import json
import re
import sys
from pathlib import Path
from typing import Any
EXPOSURES = ("private", "internal", "external", "public")
ALLOWED_PROFILE_KEYS = {
"profile_version",
"author_label",
"languages",
"mode_preferences",
"global_prefer",
"global_avoid",
}
PATTERNS = {
"local_path": re.compile(r"(?<![A-Za-z])[A-Za-z]:[\\/]|(?<![\w.])/(?:home|Users|tmp)/"),
"unc_path": re.compile(
r'(?<!\\)\\\\[A-Za-z0-9][A-Za-z0-9._-]*(?:\\[^\\/:*?"<>|\r\n]+)+'
),
"internal_marker": re.compile(
r"【(?:待校正|TODO|信息缺失)|(?:internal|内部)\s+(?:SOP|workflow|marker)",
re.IGNORECASE,
),
"credential_assignment": re.compile(
r"(?<![\w-])"
r"(?P<label>(?:[A-Za-z][A-Za-z0-9]*[_-]){0,2}api[_ -]?(?:key|token)|"
r"access[_ -]?token|auth[_ -]?token|refresh[_ -]?token|"
r"client[_ -]?secret|secret|token|password|passwd)"
r"(?![\w-])\s*[:=]\s*"
r"(?P<quote>[\"']?)"
r"(?P<value>[A-Za-z0-9][A-Za-z0-9_./+=:@!#$%&*?~-]{7,})"
r"(?P=quote)",
re.IGNORECASE,
),
"credential_bearer": re.compile(
r"(?<![\w-])(?P<label>authorization)\s*:\s*bearer\s+"
r"(?P<value>[A-Za-z0-9][A-Za-z0-9._~+/\-=]{7,})",
re.IGNORECASE,
),
}
EXTERNAL_ONLY_FINDINGS = {"local_path", "unc_path", "internal_marker"}
CREDENTIAL_FINDINGS = {"credential_assignment", "credential_bearer"}
NON_SECRET_VALUES = {
"authentication",
"authorization",
"changeme",
"example",
"hidden",
"masked",
"omitted",
"placeholder",
"redacted",
"your_token",
"your_token_here",
}
class CheckError(RuntimeError):
pass
def validate_profile(path: Path) -> dict[str, Any]:
profile = json.loads(path.read_text(encoding="utf-8"))
if not isinstance(profile, dict):
raise CheckError("voice profile must be a JSON object")
extra = sorted(set(profile) - ALLOWED_PROFILE_KEYS)
if extra:
raise CheckError(f"voice profile has unknown fields: {extra}")
if not isinstance(profile.get("profile_version"), str):
raise CheckError("voice profile requires string profile_version")
languages = profile.get("languages")
if (
not isinstance(languages, list)
or not languages
or not set(languages) <= {"zh-CN", "en"}
):
raise CheckError("voice profile languages must be a non-empty zh-CN/en list")
if len(languages) != len(set(languages)):
raise CheckError("voice profile languages must not contain duplicates")
if "author_label" in profile and not isinstance(profile["author_label"], str):
raise CheckError("voice profile author_label must be a string")
for field in ("global_prefer", "global_avoid"):
if field in profile and (
not isinstance(profile[field], list)
or not all(isinstance(item, str) for item in profile[field])
):
raise CheckError(f"voice profile {field} must be a string list")
preferences = profile.get("mode_preferences", {})
if not isinstance(preferences, dict):
raise CheckError("voice profile mode_preferences must be an object")
for mode, values in preferences.items():
if not isinstance(values, dict) or set(values) - {"prefer", "avoid"}:
raise CheckError(f"voice profile mode {mode} must contain prefer/avoid only")
for field, items in values.items():
if not isinstance(items, list) or not all(isinstance(item, str) for item in items):
raise CheckError(f"voice profile mode {mode}.{field} must be a string list")
return profile
def scan_text(text: str, exposure: str) -> list[dict[str, str]]:
findings: list[dict[str, str]] = []
for kind, pattern in PATTERNS.items():
if kind in EXTERNAL_ONLY_FINDINGS and exposure not in {"external", "public"}:
continue
match = next(
(
candidate
for candidate in pattern.finditer(text)
if kind not in CREDENTIAL_FINDINGS
or candidate.group("value").casefold() not in NON_SECRET_VALUES
),
None,
)
if match:
if kind == "credential_bearer":
preview = f"{match.group('label')}: Bearer [REDACTED]"
elif kind == "credential_assignment":
preview = f"{match.group('label')}=[REDACTED]"
else:
preview = match.group(0)[:80]
findings.append(
{
"kind": kind,
"severity": "P0",
"preview": preview,
}
)
return findings
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--exposure", required=True, choices=EXPOSURES)
source = parser.add_mutually_exclusive_group(required=True)
source.add_argument("--text")
source.add_argument("--file")
parser.add_argument("--voice-profile")
return parser
def main() -> int:
args = build_parser().parse_args()
try:
if args.file:
text = Path(args.file).read_text(encoding="utf-8")
else:
text = args.text
profile = validate_profile(Path(args.voice_profile)) if args.voice_profile else None
result = {
"exposure": args.exposure,
"voice_profile_loaded": profile is not None,
"findings": scan_text(text, args.exposure),
}
except (OSError, CheckError, ValueError, json.JSONDecodeError) as exc:
print(f"check: {exc}", file=sys.stderr)
return 1
print(json.dumps(result, ensure_ascii=False, indent=2))
return 2 if result["findings"] else 0
if __name__ == "__main__":
raise SystemExit(main())
|