Files
aigc-home/docs/hel-892/batch181-parameter-plan/collector.py
T

449 lines
17 KiB
Python

"""Default offline plan. Live mode requires separate service-window approval.
Response bytes live only in worker memory. Never persist raw bodies, headers,
file option strings, credentials, exception details or arbitrary node metadata.
"""
import argparse
import datetime
import hashlib
import json
import math
import multiprocessing
import re
import time
import urllib.error
import urllib.parse
import urllib.request
from pathlib import Path
DOC = Path(__file__).resolve().parent
BASE_URL = "http://192.168.200.12:8188"
CLASSES = (
"AIO_Preprocessor",
"DepthAnythingPreprocessor",
"PreviewImage",
"LoadImage",
"Canny",
"ImageStitch",
"CannyEdgePreprocessor",
"AnyLineArtPreprocessor_aux",
"LineArtPreprocessor",
"AnimeLineArtPreprocessor",
"LineartStandardPreprocessor",
"DWPreprocessor",
"AnimalPosePreprocessor",
)
RESPONSE_CAP = 131072
REQUEST_SECONDS = 6
TOTAL_SECONDS = 90
SAFE_TYPES = {
"IMAGE",
"MASK",
"STRING",
"INT",
"FLOAT",
"BOOLEAN",
"POSE_KEYPOINT",
"PROMPT",
"EXTRA_PNGINFO",
}
SENSITIVE = re.compile(r"password|secret|token|credential|api.?key|authorization|cookie", re.I)
class BoundaryError(ValueError):
pass
def canonical(value):
return json.dumps(
value, ensure_ascii=False, sort_keys=True, separators=(",", ":"), allow_nan=False
).encode()
def digest(raw):
return hashlib.sha256(raw).hexdigest()
def summary(value):
encoded = canonical(value)
return {
"redacted": True,
"canonical_value_sha256": digest(encoded),
"canonical_bytes": len(encoded),
}
def validate_request(method, url, class_name):
if class_name not in CLASSES or method != "GET":
raise BoundaryError("method_or_class_out_of_scope")
parsed = urllib.parse.urlsplit(url)
expected = BASE_URL + "/object_info/" + class_name
if url != expected or parsed.username is not None or parsed.password is not None:
raise BoundaryError("url_out_of_scope")
return url
def validate_status(status):
if 300 <= status < 400:
raise BoundaryError("redirect_rejected")
if status != 200:
raise BoundaryError("http_error")
def redact_schema(data, class_name, policy=None):
"""Export narrow structural schema; every options array is summarized, never copied."""
if class_name not in CLASSES or not isinstance(data, dict) or set(data) != {class_name}:
raise BoundaryError("missing_or_extra_class")
policy = json.loads((DOC / "redaction-policy.json").read_text()) if policy is None else policy
info = data[class_name]
if not isinstance(info, dict) or not isinstance(info.get("input"), dict):
raise BoundaryError("malformed_schema")
if info.get("name", class_name) != class_name:
raise BoundaryError("unexpected_class_identity")
output = info.get("output")
if not isinstance(output, list) or len(output) > 64:
raise BoundaryError("malformed_outputs")
clean = {"class_name": class_name, "input": {}, "output": []}
for item in output:
clean["output"].append(
item if isinstance(item, str) and item in SAFE_TYPES else summary(item)
)
for key in (
"output_node",
"has_intermediate_output",
"is_input_list",
"deprecated",
"experimental",
"dev_only",
"api_node",
):
if key in info:
if type(info[key]) is not bool:
raise BoundaryError("malformed_boolean_metadata")
clean[key] = info[key]
if "output_is_list" in info:
if (
not isinstance(info["output_is_list"], list)
or len(info["output_is_list"]) != len(output)
or any(type(x) is not bool for x in info["output_is_list"])
):
raise BoundaryError("malformed_output_list_flags")
clean["output_is_list"] = info["output_is_list"]
if "output_name" in info:
clean["output_name_summary"] = summary(info["output_name"])
if "input_order" in info:
order = info["input_order"]
if not isinstance(order, dict):
raise BoundaryError("malformed_input_order")
clean["input_order"] = {}
for category, fields in order.items():
if category not in ("required", "optional", "hidden") or not isinstance(fields, list):
raise BoundaryError("malformed_input_order")
if any(
not isinstance(x, str)
or (x not in policy[class_name]["fields"] and not SENSITIVE.search(x))
for x in fields
):
raise BoundaryError("unexpected_input_order_scope")
clean["input_order"][category] = [x for x in fields if not SENSITIVE.search(x)]
dropped_sensitive = 0
for category, fields in info["input"].items():
if category not in ("required", "optional", "hidden") or not isinstance(fields, dict):
raise BoundaryError("malformed_input_category")
clean["input"][category] = {}
for name, spec in fields.items():
if SENSITIVE.search(name):
dropped_sensitive += 1
continue
if name not in policy[class_name]["fields"]:
raise BoundaryError("unexpected_field_scope")
# Legacy hidden may be a direct string; V3 hidden is a list/tuple in JSON.
if category == "hidden" and isinstance(spec, str):
spec = [spec]
if not isinstance(spec, list) or not 1 <= len(spec) <= 2:
raise BoundaryError("malformed_input_spec")
kind = spec[0]
field = {}
if isinstance(kind, list):
field.update(type="COMBO", options_summary={"count": len(kind), **summary(kind)})
elif isinstance(kind, str) and kind in SAFE_TYPES:
field["type"] = kind
else:
field["type_summary"] = summary(kind)
config = spec[1] if len(spec) == 2 else {}
if not isinstance(config, dict):
raise BoundaryError("malformed_input_config")
for key, value in config.items():
if SENSITIVE.search(key):
dropped_sensitive += 1
elif key in ("options", "values"):
field[key + "_summary"] = {
"count": len(value) if isinstance(value, list) else None,
**summary(value),
}
elif key in ("min", "max", "step", "round", "default"):
if type(value) in (int, float, bool) and (
not isinstance(value, float) or math.isfinite(value)
):
field[key] = value
elif (
key == "default"
and isinstance(value, str)
and value == policy[class_name]["static_string_defaults"].get(name)
and name
not in (
"image",
"filename_prefix",
"ckpt_name",
"bbox_detector",
"pose_estimator",
)
):
# LoadImage defaults are never part of the approved static string set.
field[key] = value
else:
field[key + "_summary"] = summary(value)
elif (
key in ("image_upload", "optional", "advanced", "lazy", "forceInput", "rawLink")
and type(value) is bool
):
field[key] = value
# Arbitrary help text, filenames, URLs, headers and unknown metadata are dropped.
clean["input"][category][name] = field
clean["redaction"] = dict(
rule=(
"all combo arrays count/canonical SHA; known fields/types/numbers "
"and approved defaults only; metadata dropped"
),
credential_fields_removed=dropped_sensitive,
raw_http_bytes_preserved=False,
)
return clean
def process_body(raw, status, class_name, policy=None):
receipt = dict(
status=status,
received_bytes=len(raw),
response_bytes_sha256=digest(raw),
response_digest_scope="complete body"
if len(raw) <= RESPONSE_CAP
else "bounded prefix; not full body",
)
try:
validate_status(status)
if len(raw) > RESPONSE_CAP:
raise BoundaryError("response_over_cap")
try:
data = json.loads(raw, parse_constant=lambda _: (_ for _ in ()).throw(ValueError()))
except (ValueError, UnicodeError, RecursionError):
raise BoundaryError("non_json_or_malformed") from None
cleaned = redact_schema(data, class_name, policy)
encoded = canonical(cleaned)
receipt.update(
state="accepted_redacted",
redacted_schema=cleaned,
redacted_schema_sha256=digest(encoded),
redacted_bytes=len(encoded),
)
except (BoundaryError, ValueError, TypeError, OverflowError, RecursionError) as error:
receipt.update(
state="stopped",
error=str(error) if isinstance(error, BoundaryError) else "invalid_schema_value",
)
return receipt
class NoRedirect(urllib.request.HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl):
return None
def fetch_worker(pipe, class_name):
"""Called only by explicitly approved live mode. Raw response never crosses the pipe."""
url = BASE_URL + "/object_info/" + class_name
try:
validate_request("GET", url, class_name)
# Ignore environment proxy settings and disable all redirect following.
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}), NoRedirect())
request = urllib.request.Request(url, method="GET", headers={"Accept": "application/json"})
try:
response = opener.open(request, timeout=REQUEST_SECONDS)
except urllib.error.HTTPError as error:
response = error
with response:
if response.geturl() != url:
raise BoundaryError("unexpected_final_url")
raw = response.read(RESPONSE_CAP + 1)
result = process_body(raw, response.status, class_name)
except Exception as error:
result = dict(
state="stopped",
error=str(error) if isinstance(error, BoundaryError) else "transport_error",
response_bytes_sha256=None,
response_digest_scope="response not received",
)
pipe.send(result)
pipe.close()
def utc():
return datetime.datetime.now(datetime.timezone.utc)
def approval_valid(approval, now=None):
keys = {
"approved_by",
"approval_comment_id",
"user_service_window_confirmed",
"dynamic_calls_acknowledged",
"base_url",
"classes",
"starts_at_utc",
"expires_at_utc",
}
if not isinstance(approval, dict) or set(approval) != keys:
raise BoundaryError("invalid_approval_shape")
if approval["approved_by"] != "bbcc1179-3a55-48e7-a72e-c84cf79f41cb" or not re.fullmatch(
r"[a-f0-9-]{36}", approval["approval_comment_id"]
):
raise BoundaryError("approval_reference_missing")
if (
approval["user_service_window_confirmed"] is not True
or approval["dynamic_calls_acknowledged"] is not True
):
raise BoundaryError("window_not_confirmed")
if approval["base_url"] != BASE_URL or approval["classes"] != list(CLASSES):
raise BoundaryError("approval_scope_mismatch")
try:
start = datetime.datetime.fromisoformat(approval["starts_at_utc"])
end = datetime.datetime.fromisoformat(approval["expires_at_utc"])
now = utc() if now is None else now
if start.utcoffset() != datetime.timedelta(0) or end.utcoffset() != datetime.timedelta(0):
raise ValueError()
if not start <= now < end or not 0 < (end - start).total_seconds() <= 1800:
raise ValueError()
except (ValueError, TypeError):
raise BoundaryError("approval_window_invalid") from None
return end
def write_exclusive(path, raw):
with path.open("xb") as stream:
stream.write(raw)
def collect(approval_path, output):
# An approval file records a separately obtained permission.
# It does not grant permission itself.
approval = json.loads(approval_path.read_text())
expiry = approval_valid(approval)
output.mkdir(exist_ok=False)
(output / "records").mkdir()
(output / "logs").mkdir()
write_exclusive(output / "approved-scope.json", canonical(approval))
deadline = time.monotonic() + TOTAL_SECONDS
count = 0
stopped = False
for index, name in enumerate(CLASSES):
url = validate_request("GET", BASE_URL + "/object_info/" + name, name)
remaining = min(deadline - time.monotonic(), (expiry - utc()).total_seconds())
key = f"{index + 1:02d}-{name}"
record = dict(
key=key,
method="GET",
url=url,
started_at_utc=utc().isoformat(),
target_request_attempted=False,
)
if remaining <= 0:
result = dict(
state="stopped", error="total_or_window_deadline", response_bytes_sha256=None
)
else:
parent, child = multiprocessing.Pipe(duplex=False)
process = multiprocessing.Process(target=fetch_worker, args=(child, name))
process.start()
child.close()
count += 1
record["target_request_attempted"] = True
# Poll before join so bounded sanitized results cannot deadlock on pipe capacity.
if parent.poll(min(REQUEST_SECONDS, remaining)):
try:
result = parent.recv()
except EOFError:
result = dict(
state="stopped", error="worker_no_receipt", response_bytes_sha256=None
)
else:
result = dict(
state="stopped",
error="request_deadline",
response_bytes_sha256=None,
response_digest_scope="incomplete response unavailable; no synthetic digest",
)
if process.is_alive():
# Only this exact, freshly owned worker; never an executable-name kill.
process.terminate()
process.join()
parent.close()
record.update(result)
record["completed_at_utc"] = utc().isoformat()
safe_stdout = (
canonical(result["redacted_schema"]) + b"\n" if "redacted_schema" in result else b""
)
safe_stderr = (result["error"] + "\n").encode() if "error" in result else b""
record["logs"] = []
for kind, raw in (("stdout", safe_stdout), ("stderr", safe_stderr)):
path = output / "logs" / (key + "." + kind + ".txt")
write_exclusive(path, raw)
record["logs"].append(
dict(path=str(path.relative_to(output)), bytes=len(raw), sha256=digest(raw))
)
write_exclusive(output / "records" / (key + ".json"), canonical(record) + b"\n")
if result["state"] != "accepted_redacted":
stopped = True
break
write_exclusive(
output / "summary.json",
canonical(
dict(
request_attempts=count,
stopped=stopped,
raw_bodies_saved=0,
retries=0,
prompts=0,
scope="future approved definitions only",
)
),
)
return 1 if stopped else 0
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--collect", action="store_true")
parser.add_argument("--approval-file", type=Path)
parser.add_argument("--output", type=Path)
arguments = parser.parse_args()
if not arguments.collect:
if arguments.approval_file or arguments.output:
parser.error(
"plan mode takes no approval/output; redirect plan stdout with exclusive capture"
)
print((DOC / "request-plan.json").read_text(), end="")
return 0
if not arguments.approval_file or not arguments.output:
parser.error("live mode requires approval file and a new output directory")
try:
return collect(arguments.approval_file, arguments.output)
except Exception:
# Do not expose arbitrary remote values, credentials or approval content in tracebacks.
print("collection refused or failed; inspect safe exclusive receipts; no automatic retry")
return 1
if __name__ == "__main__":
raise SystemExit(main())