iot-fixturekit 0.1.0a2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,4 @@
1
+ """Experimental schema-driven fixture projection."""
2
+ from .core import FixtureError, project, build_fixture
3
+
4
+ __all__ = ["FixtureError", "project", "build_fixture"]
@@ -0,0 +1,191 @@
1
+ """Conservative fixture linting. Findings never contain matched values."""
2
+ import argparse
3
+ import json
4
+ import math
5
+ import re
6
+ import sys
7
+ from dataclasses import dataclass
8
+ from pathlib import Path
9
+
10
+ from .cli import read_json
11
+ from .policy import compile_policy
12
+
13
+ LIMIT = 8 * 1024 * 1024
14
+ MAX_DEPTH = 64
15
+ MAX_NODES = 200_000
16
+ MAX_TEXT_CHARS = LIMIT
17
+ MAX_FINDINGS = 4096
18
+ PATTERNS = {
19
+ "email": re.compile(r"(?<![A-Za-z0-9._%+-])[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b"),
20
+ "mac": re.compile(r"(?<![0-9A-Fa-f])(?:[0-9A-Fa-f]{2}:){5}[0-9A-Fa-f]{2}(?![0-9A-Fa-f])"),
21
+ "jwt": re.compile(r"(?<![A-Za-z0-9_-])eyJ[A-Za-z0-9_-]{8,}\.eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{16,}(?![A-Za-z0-9_-])"),
22
+ "private-key": re.compile(r"-----BEGIN (?:[A-Z0-9]+ )*PRIVATE KEY-----"),
23
+ }
24
+ SAFE_EMAIL = re.compile(r"[^@]+@(?:[A-Za-z0-9-]+\.)*example\.invalid$", re.I)
25
+ SENSITIVE = frozenset({
26
+ "password", "passwd", "accesstoken", "refreshtoken", "clienttoken",
27
+ "authorization", "cookie", "setcookie", "privatekey", "apikey", "token",
28
+ })
29
+ PLACEHOLDERS = ("", "<redacted>", "**REDACTED**", "__REDACTED__")
30
+ PROFILES = ("generic", "tuya", "overkiz")
31
+ # Deliberately narrow initial profile: these exact state names were observed
32
+ # in the upstream masking convention. This is not an exhaustive schema.
33
+ OVERKIZ_SENSITIVE_STATES = frozenset({
34
+ "core:SerialNumber", "core:DeviceSerialNumberState",
35
+ "core:NetworkMacState", "core:MacAddress",
36
+ "core:SSIDState", "core:NameState",
37
+ "homekit:SetupCode", "homekit:SetupPayload",
38
+ "core:LocalIPv4AddressState", "core:IPAddress",
39
+ "core:IPAddressState",
40
+ })
41
+ # Upstream string obfuscation preserves punctuation and replaces word runs.
42
+ # Allow only a restricted set of separators surrounding actual mask markers.
43
+ OVERKIZ_MASK = re.compile(r"[ *:;,/()]+")
44
+
45
+
46
+ @dataclass(frozen=True)
47
+ class Finding:
48
+ rule: str
49
+ line: int
50
+
51
+
52
+ def _safe_match(rule, value):
53
+ if rule == "email":
54
+ return SAFE_EMAIL.fullmatch(value) is not None
55
+ if rule == "mac":
56
+ return value == "00:00:00:00:00:00"
57
+ return False
58
+
59
+
60
+ def audit_text(text):
61
+ """Return rule IDs and line numbers, never source fragments."""
62
+ if not isinstance(text, str) or len(text) > MAX_TEXT_CHARS:
63
+ raise ValueError("text audit size limit")
64
+ results = set()
65
+ for line, value in enumerate(text.splitlines(), 1):
66
+ for rule, pattern in PATTERNS.items():
67
+ if any(not _safe_match(rule, m.group()) for m in pattern.finditer(value)):
68
+ results.add(Finding(rule, line))
69
+ if len(results) > MAX_FINDINGS:
70
+ raise ValueError("text audit finding limit")
71
+ return sorted(results, key=lambda f: (f.line, f.rule))
72
+
73
+
74
+ def _key(value):
75
+ return re.sub(r"[^a-z0-9]", "", value.lower())
76
+
77
+
78
+ def audit_json(data, profile="generic", *, policy=None):
79
+ """Check parsed values, including escaped JSON strings.
80
+
81
+ Line 0 denotes a structural finding, not a precise source location.
82
+ This is a heuristic, not a privacy guarantee.
83
+ """
84
+ if profile not in PROFILES:
85
+ raise ValueError("unknown profile")
86
+ findings = set()
87
+ exceptions = compile_policy(policy) if policy is not None else frozenset()
88
+ stack = [((), data, False)]
89
+ visited = 0
90
+ while stack:
91
+ path, node, is_key = stack.pop()
92
+ visited += 1
93
+ if visited > MAX_NODES or len(path) > MAX_DEPTH:
94
+ raise ValueError("JSON audit complexity limit")
95
+ if len(stack) > MAX_NODES:
96
+ raise ValueError("JSON audit complexity limit")
97
+ if isinstance(node, dict):
98
+ if len(node) > (MAX_NODES - visited - len(stack)) // 2:
99
+ raise ValueError("JSON audit complexity limit")
100
+ if profile == "overkiz":
101
+ state = node.get("name")
102
+ if isinstance(state, str) and state in OVERKIZ_SENSITIVE_STATES:
103
+ value = node.get("value")
104
+ masked = isinstance(value, str) and (
105
+ value in PLACEHOLDERS
106
+ or ("*" in value and OVERKIZ_MASK.fullmatch(value) is not None)
107
+ )
108
+ if value is not None and not masked:
109
+ findings.add(Finding("overkiz-unmasked-state", 0))
110
+ for key, value in node.items():
111
+ if not isinstance(key, str):
112
+ raise ValueError("non-string JSON object key")
113
+ if _key(key) in SENSITIVE and value is not None and value not in PLACEHOLDERS:
114
+ findings.add(Finding("sensitive-field", 0))
115
+ stack.append((path + (key,), key, True))
116
+ stack.append((path + (key,), value, False))
117
+ elif isinstance(node, list):
118
+ if len(node) > MAX_NODES - visited - len(stack):
119
+ raise ValueError("JSON audit complexity limit")
120
+ stack.extend((path + (index,), item, False) for index, item in enumerate(node))
121
+ elif isinstance(node, str):
122
+ # Reject lone surrogates rather than treating an unencodable file as clean.
123
+ node.encode("utf-8")
124
+ findings.update(
125
+ Finding(f.rule, 0) for f in audit_text(node)
126
+ if is_key or (path, f.rule, node) not in exceptions
127
+ )
128
+ elif type(node) is float and not math.isfinite(node):
129
+ raise ValueError("non-finite JSON value")
130
+ elif node is not None and type(node) not in (bool, int, float):
131
+ raise ValueError("unsupported JSON value")
132
+ if profile == "tuya":
133
+ if not isinstance(data, dict):
134
+ findings.add(Finding("tuya-shape", 0))
135
+ else:
136
+ if any(k in data for k in ("id", "terminal_id", "home_assistant")):
137
+ findings.add(Finding("tuya-forbidden-root", 0))
138
+ if not all(isinstance(data.get(k), str) and data[k] for k in ("category", "product_id")):
139
+ findings.add(Finding("tuya-shape", 0))
140
+ status = data.get("status", {})
141
+ if not isinstance(status, dict):
142
+ findings.add(Finding("tuya-status-shape", 0))
143
+ elif status.get("device_info") not in (None, ""):
144
+ findings.add(Finding("tuya-device-info", 0))
145
+ return sorted(findings, key=lambda f: f.rule)
146
+
147
+
148
+ def audit_file(path, profile="generic", *, policy=None):
149
+ """Audit a bounded local file with the same rules for CLI and integrations."""
150
+ path = Path(path)
151
+ if path.suffix.lower() in (".json", ".har"):
152
+ return audit_json(read_json(path), profile, policy=policy)
153
+ if profile != "generic" or policy is not None:
154
+ raise ValueError("profile or policy requires JSON")
155
+ with path.open("rb") as handle:
156
+ raw = handle.read(LIMIT + 1)
157
+ if len(raw) > LIMIT:
158
+ raise ValueError("size limit")
159
+ return audit_text(raw.decode("utf-8"))
160
+
161
+
162
+ def main(argv=None):
163
+ parser = argparse.ArgumentParser(description="Local fixture lint; no matched values in output")
164
+ parser.add_argument("files", nargs="+")
165
+ parser.add_argument("--profile", choices=PROFILES, default="generic")
166
+ parser.add_argument("--policy", help="explicit JSON placeholder policy")
167
+ args = parser.parse_args(argv)
168
+ try:
169
+ policy = read_json(args.policy) if args.policy is not None else None
170
+ if args.policy is not None:
171
+ compile_policy(policy)
172
+ except (OSError, ValueError, TypeError, RecursionError):
173
+ print('{"error":"invalid-placeholder-policy"}')
174
+ return 2
175
+ result = 0
176
+ for index, name in enumerate(args.files, 1):
177
+ try:
178
+ findings = audit_file(name, args.profile, policy=policy)
179
+ print(json.dumps({"file_index": index, "findings": [
180
+ {"rule": f.rule, "line": f.line} for f in findings
181
+ ]}, sort_keys=True))
182
+ if findings:
183
+ result = max(result, 1)
184
+ except (OSError, ValueError, TypeError, RecursionError):
185
+ print(json.dumps({"file_index": index, "error": "unreadable-or-invalid"}))
186
+ result = 2
187
+ return result
188
+
189
+
190
+ if __name__ == "__main__":
191
+ sys.exit(main())
iot_fixturekit/cli.py ADDED
@@ -0,0 +1,57 @@
1
+ import argparse
2
+ import json
3
+ import math
4
+ import sys
5
+ from pathlib import Path
6
+
7
+ from .core import FixtureError, build_fixture
8
+
9
+
10
+ def _reject_constant(_):
11
+ raise FixtureError("non-finite JSON value")
12
+
13
+
14
+ def _finite_float(value):
15
+ result = float(value)
16
+ if not math.isfinite(result):
17
+ raise FixtureError("non-finite JSON value")
18
+ return result
19
+
20
+
21
+ def _unique_object(pairs):
22
+ result = {}
23
+ for key, value in pairs:
24
+ if key in result:
25
+ raise FixtureError("duplicate JSON key")
26
+ result[key] = value
27
+ return result
28
+
29
+
30
+ def read_json(path):
31
+ with Path(path).open("rb") as handle:
32
+ raw = handle.read(8 * 1024 * 1024 + 1)
33
+ if len(raw) > 8 * 1024 * 1024:
34
+ raise FixtureError("input exceeds size limit")
35
+ return json.loads(raw, parse_constant=_reject_constant, parse_float=_finite_float,
36
+ object_pairs_hook=_unique_object)
37
+
38
+
39
+ def main(argv=None):
40
+ parser = argparse.ArgumentParser(description="Project diagnostic JSON into a fixture")
41
+ parser.add_argument("input")
42
+ parser.add_argument("--policy", required=True)
43
+ parser.add_argument("--profile", required=True)
44
+ args = parser.parse_args(argv)
45
+ try:
46
+ fixture = build_fixture(read_json(args.input), read_json(args.policy), profile=args.profile)
47
+ output = json.dumps(fixture, sort_keys=True, indent=2, allow_nan=False)
48
+ except (OSError, ValueError, RecursionError, TypeError):
49
+ # Do not expose raw values, file paths, or malformed policy details.
50
+ print("fixture rejected; inspect input and policy locally", file=sys.stderr)
51
+ return 2
52
+ print(output)
53
+ return 0
54
+
55
+
56
+ if __name__ == "__main__":
57
+ raise SystemExit(main())
iot_fixturekit/core.py ADDED
@@ -0,0 +1,118 @@
1
+ """Explicit projection, not a general-purpose PII detector."""
2
+ import math
3
+ import re
4
+
5
+
6
+ class FixtureError(ValueError):
7
+ """Input or policy violates the declared fixture contract."""
8
+
9
+
10
+ _RULE_KEYS = {
11
+ "object": {"type", "fields"},
12
+ "array": {"type", "items", "max_items"},
13
+ "enum": {"type", "values"},
14
+ "boolean": {"type"},
15
+ "integer": {"type", "min", "max"},
16
+ "number": {"type", "min", "max"},
17
+ }
18
+
19
+
20
+ def _validate_rule(rule):
21
+ """Validate the entire declared tree, even branches with no input items."""
22
+ pending = [(rule, 0)]
23
+ visited = 0
24
+ while pending:
25
+ current, depth = pending.pop()
26
+ visited += 1
27
+ if depth > 64 or visited > 10000:
28
+ raise FixtureError("policy complexity limit")
29
+ if not isinstance(current, dict):
30
+ raise FixtureError("invalid policy")
31
+ kind = current.get("type")
32
+ if not isinstance(kind, str) or kind not in _RULE_KEYS or set(current) - _RULE_KEYS[kind]:
33
+ raise FixtureError("unsupported policy")
34
+ if kind == "object":
35
+ fields = current.get("fields")
36
+ if not isinstance(fields, dict) or not all(isinstance(k, str) for k in fields):
37
+ raise FixtureError("invalid object policy")
38
+ if len(fields) + len(pending) + visited > 10000:
39
+ raise FixtureError("policy complexity limit")
40
+ pending.extend((child, depth + 1) for child in fields.values())
41
+ elif kind == "array":
42
+ limit = current.get("max_items", 1000)
43
+ if type(limit) is not int or not 0 <= limit <= 10000 or "items" not in current:
44
+ raise FixtureError("invalid array policy")
45
+ pending.append((current["items"], depth + 1))
46
+ elif kind == "enum":
47
+ options = current.get("values")
48
+ if not isinstance(options, list) or not options or not all(isinstance(v, str) for v in options):
49
+ raise FixtureError("invalid enum policy")
50
+ elif kind in ("integer", "number"):
51
+ low, high = current.get("min"), current.get("max")
52
+ if any(type(v) not in (int, float) or (type(v) is float and not math.isfinite(v))
53
+ for v in (low, high)) or low > high:
54
+ raise FixtureError("numeric bounds required")
55
+
56
+
57
+ def project(value, rule):
58
+ """Project JSON values using explicit object, list and scalar rules.
59
+
60
+ Unknown object keys are omitted. Strings are never retained unless they
61
+ match an explicit enum. Numeric values can still be sensitive; reviewers
62
+ must assess the field semantics before selecting a policy.
63
+ """
64
+ _validate_rule(rule)
65
+ return _project(value, rule)
66
+
67
+
68
+ def _project(value, rule):
69
+ kind = rule["type"]
70
+ if kind == "object":
71
+ fields = rule.get("fields")
72
+ if not isinstance(value, dict) or not isinstance(fields, dict):
73
+ raise FixtureError("expected object")
74
+ # Every selected field is required; never silently drop malformed data.
75
+ if not all(isinstance(k, str) and k in value for k in fields):
76
+ raise FixtureError("missing selected field")
77
+ return {k: _project(value[k], child) for k, child in fields.items()}
78
+ if kind == "array":
79
+ limit = rule.get("max_items", 1000)
80
+ if type(limit) is not int or not 0 <= limit <= 10000:
81
+ raise FixtureError("invalid array limit")
82
+ if not isinstance(value, list) or len(value) > limit or "items" not in rule:
83
+ raise FixtureError("invalid array")
84
+ return [_project(item, rule["items"]) for item in value]
85
+ if kind == "enum":
86
+ options = rule.get("values")
87
+ if not isinstance(options, list) or not options or not all(
88
+ isinstance(item, str) for item in options
89
+ ):
90
+ raise FixtureError("invalid enum policy")
91
+ if not isinstance(value, str) or value not in options:
92
+ raise FixtureError("unexpected enum value")
93
+ return value
94
+ if kind == "boolean":
95
+ if type(value) is not bool:
96
+ raise FixtureError("expected boolean")
97
+ return value
98
+ if kind == "integer":
99
+ if type(value) is not int:
100
+ raise FixtureError("expected integer")
101
+ elif type(value) not in (float, int) or (
102
+ type(value) is float and not math.isfinite(value)
103
+ ):
104
+ raise FixtureError("expected finite number")
105
+ low, high = rule.get("min"), rule.get("max")
106
+ if any(type(x) not in (int, float) or (type(x) is float and not math.isfinite(x))
107
+ for x in (low, high)) or low > high:
108
+ raise FixtureError("numeric bounds required")
109
+ if not low <= value <= high:
110
+ raise FixtureError("number outside policy bounds")
111
+ return value
112
+
113
+
114
+ def build_fixture(value, policy, *, profile):
115
+ """Build a versioned deterministic fixture envelope."""
116
+ if not isinstance(profile, str) or not re.fullmatch(r"[a-z][a-z0-9_-]{0,63}", profile):
117
+ raise FixtureError("invalid profile")
118
+ return {"schema_version": 1, "profile": profile, "data": project(value, policy)}
@@ -0,0 +1,39 @@
1
+ """Strict, explicit fixture placeholder policy. Policies require human review."""
2
+ import re
3
+
4
+ _MAC = re.compile(r"(?:[0-9A-Fa-f]{2}:){5}[0-9A-Fa-f]{2}")
5
+ MAX_RULES = 128
6
+
7
+
8
+ def compile_policy(document):
9
+ """Return exact (typed JSON path, rule, full value) triples.
10
+
11
+ Version 1 only recognizes colon-delimited MAC placeholders. No wildcards,
12
+ regex allowlists, credential exemptions, or global disable switches.
13
+ """
14
+ if not isinstance(document, dict) or set(document) != {"version", "placeholders"}:
15
+ raise ValueError("invalid placeholder policy")
16
+ if type(document["version"]) is not int or document["version"] != 1:
17
+ raise ValueError("unsupported policy version")
18
+ entries = document["placeholders"]
19
+ if not isinstance(entries, list) or len(entries) > MAX_RULES:
20
+ raise ValueError("invalid placeholder list")
21
+ result = set()
22
+ for entry in entries:
23
+ if not isinstance(entry, dict) or set(entry) != {"path", "rule", "value"}:
24
+ raise ValueError("invalid placeholder entry")
25
+ path, rule, value = entry["path"], entry["rule"], entry["value"]
26
+ if not isinstance(path, list) or not 1 <= len(path) <= 32:
27
+ raise ValueError("invalid placeholder path")
28
+ if not all((type(p) is str and 0 < len(p) <= 256) or
29
+ (type(p) is int and 0 <= p <= 1000000) for p in path):
30
+ raise ValueError("invalid path segment")
31
+ if any(p in ("*", "**") for p in path):
32
+ raise ValueError("wildcard not supported")
33
+ if rule != "mac" or not isinstance(value, str) or not _MAC.fullmatch(value):
34
+ raise ValueError("unsupported placeholder rule or value")
35
+ item = (tuple(path), rule, value)
36
+ if item in result:
37
+ raise ValueError("duplicate placeholder")
38
+ result.add(item)
39
+ return frozenset(result)
@@ -0,0 +1,26 @@
1
+ """Optional pytest fixture, using the same audit as the command line."""
2
+ import pytest
3
+
4
+ from .audit import audit_file
5
+ from .cli import read_json
6
+ from .policy import compile_policy
7
+
8
+
9
+ def check_fixture(path, *, profile="generic", policy_path=None):
10
+ """Assert a candidate has no known findings; never report matched values."""
11
+ try:
12
+ policy = read_json(policy_path) if policy_path is not None else None
13
+ if policy_path is not None:
14
+ compile_policy(policy)
15
+ findings = audit_file(path, profile, policy=policy)
16
+ except (OSError, ValueError, TypeError, RecursionError):
17
+ pytest.fail("fixture audit: unreadable or invalid input", pytrace=False)
18
+ if findings:
19
+ rules = ", ".join(sorted({finding.rule for finding in findings}))
20
+ pytest.fail(f"fixture audit findings: {rules}", pytrace=False)
21
+
22
+
23
+ @pytest.fixture
24
+ def iot_fixture_check():
25
+ """Return the callable check_fixture(path, profile=..., policy_path=...)."""
26
+ return check_fixture
iot_fixturekit/tuya.py ADDED
@@ -0,0 +1,86 @@
1
+ """Local Tuya diagnostics conversion; output requires human privacy review."""
2
+ import argparse
3
+ import copy
4
+ import json
5
+ import re
6
+ import sys
7
+ from pathlib import Path
8
+
9
+ from .audit import audit_json
10
+ from .cli import read_json
11
+ from .core import FixtureError
12
+
13
+ CATEGORY = re.compile(r"[a-z][a-z0-9]{0,31}")
14
+ PRODUCT = re.compile(r"[A-Za-z0-9]{1,64}")
15
+ FORBIDDEN = ("id", "terminal_id", "home_assistant")
16
+
17
+
18
+ class AuditRejected(FixtureError):
19
+ """Candidate failed heuristic checks."""
20
+
21
+ def __init__(self, findings):
22
+ self.rules = tuple(sorted({finding.rule for finding in findings}))
23
+ super().__init__("candidate rejected by fixture audit")
24
+
25
+
26
+ def convert_diagnostics(document):
27
+ """Return (filename, candidate), without mutating input.
28
+
29
+ Implements the documented Tuya fixture extraction rules. Unknown datapoints
30
+ are preserved for functional compatibility and may contain private data.
31
+ A successful audit is not a privacy guarantee; review locally.
32
+ """
33
+ if not isinstance(document, dict) or not isinstance(document.get("data"), dict):
34
+ raise FixtureError("expected diagnostics data object")
35
+ candidate = copy.deepcopy(document["data"])
36
+ for key in FORBIDDEN:
37
+ candidate.pop(key, None)
38
+ category = candidate.get("category")
39
+ product = candidate.get("product_id")
40
+ if not isinstance(category, str) or not CATEGORY.fullmatch(category):
41
+ raise FixtureError("invalid category")
42
+ if not isinstance(product, str) or not PRODUCT.fullmatch(product):
43
+ raise FixtureError("invalid product id")
44
+ if "status" in candidate:
45
+ if not isinstance(candidate["status"], dict):
46
+ raise FixtureError("invalid status object")
47
+ if "device_info" in candidate["status"]:
48
+ candidate["status"]["device_info"] = ""
49
+ findings = audit_json(candidate, "tuya")
50
+ if findings:
51
+ raise AuditRejected(findings)
52
+ # Catch non-JSON and non-finite values before exposing the candidate.
53
+ json.dumps(candidate, allow_nan=False)
54
+ return f"{category}_{product}.json", candidate
55
+
56
+
57
+ def main(argv=None):
58
+ parser = argparse.ArgumentParser(description="Convert Tuya diagnostics to a local review candidate")
59
+ parser.add_argument("input")
60
+ parser.add_argument("--output-dir", required=True, help="existing local review directory")
61
+ args = parser.parse_args(argv)
62
+ try:
63
+ filename, candidate = convert_diagnostics(read_json(args.input))
64
+ payload = (json.dumps(candidate, indent=2, ensure_ascii=False, allow_nan=False) + "\n").encode("utf-8")
65
+ target = Path(args.output_dir) / filename
66
+ # Exclusive creation with restrictive permissions. Never replace existing files.
67
+ import os
68
+ fd = os.open(target, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
69
+ try:
70
+ with os.fdopen(fd, "wb") as handle:
71
+ handle.write(payload)
72
+ except BaseException:
73
+ target.unlink(missing_ok=True)
74
+ raise
75
+ except AuditRejected as exc:
76
+ print(json.dumps({"status": "rejected", "rules": exc.rules}), file=sys.stderr)
77
+ return 1
78
+ except (OSError, ValueError, TypeError, RecursionError):
79
+ print('{"status":"invalid-or-unwritable"}', file=sys.stderr)
80
+ return 2
81
+ print('{"status":"candidate-written","manual_review_required":true}')
82
+ return 0
83
+
84
+
85
+ if __name__ == "__main__":
86
+ sys.exit(main())
@@ -0,0 +1,237 @@
1
+ Metadata-Version: 2.4
2
+ Name: iot-fixturekit
3
+ Version: 0.1.0a2
4
+ Summary: Local-first, schema-driven IoT diagnostic fixture tooling
5
+ License-Expression: Apache-2.0
6
+ Project-URL: Homepage, https://github.com/FlyzDev/fixturekit
7
+ Project-URL: Issues, https://github.com/FlyzDev/fixturekit/issues
8
+ Requires-Python: >=3.9
9
+ Description-Content-Type: text/markdown
10
+ License-File: LICENSE
11
+ Provides-Extra: pytest
12
+ Requires-Dist: pytest>=7; extra == "pytest"
13
+ Dynamic: license-file
14
+
15
+ # IoT FixtureKit
16
+
17
+ **Experimental local-first tooling for converting IoT diagnostics into
18
+ reproducible test fixtures.** No network access, no telemetry, no automatic uploads.
19
+
20
+ Home Assistant integration authors frequently need real device behavior to
21
+ write regression tests. Different projects maintain their own diagnostic-to-fixture
22
+ workflows. This experiment tests whether an explicit projection engine can reduce
23
+ that maintenance without replacing their existing protocol libraries or tests.
24
+
25
+ **Alpha preview (0.1.0a2).** Independent security review is pending.
26
+ No privacy certification or upstream endorsement is claimed.
27
+
28
+ ## Install the published alpha
29
+
30
+ In a virtual environment (Python 3.9+):
31
+
32
+ python -m pip install "https://github.com/FlyzDev/fixturekit/releases/download/v0.1.0a2/iot_fixturekit-0.1.0a2-py3-none-any.whl"
33
+
34
+ [Release files and SHA256 checksums](https://github.com/FlyzDev/fixturekit/releases/tag/v0.1.0a2).
35
+ PyPI publication is pending. The optional pytest integration can be installed
36
+ with the corresponding direct reference:
37
+
38
+ python -m pip install "iot-fixturekit[pytest] @ https://github.com/FlyzDev/fixturekit/releases/download/v0.1.0a2/iot_fixturekit-0.1.0a2-py3-none-any.whl"
39
+
40
+ ## Start here
41
+
42
+ See [QUICKSTART.md](QUICKSTART.md) for installation and the five-minute local
43
+ consumer demo; see [CONTRIBUTING.md](CONTRIBUTING.md) for pilot feedback.
44
+
45
+ ## Run the synthetic demo
46
+
47
+ Python 3.9+; no runtime dependencies.
48
+
49
+ PYTHONPATH=src python3 -m iot_fixturekit.cli examples/synthetic-diagnostics.json --policy examples/synthetic-policy.json --profile demo
50
+
51
+ PYTHONPATH=src python3 -m unittest discover -s tests -v
52
+
53
+ Unknown object fields are excluded. Selected strings must match declared enum
54
+ values. Numbers require explicit bounds. Invalid input is rejected.
55
+ The complete projection policy is validated before use, even for empty arrays.
56
+ Policies are limited to 64 nested levels and 10,000 rules.
57
+ The output is versioned and deterministic.
58
+
59
+ ## Important security boundary
60
+
61
+ This is NOT a complete anonymizer, secret scanner, or privacy guarantee.
62
+ A poorly designed policy can retain sensitive values, keys or measurements.
63
+ Review policy semantics and output locally before sharing. Do not commit raw
64
+ diagnostics, credentials, real device identifiers or customer data. No live
65
+ device adapters are implemented yet. All examples are synthetic.
66
+
67
+ ## Pilot validation
68
+
69
+ Start with maintainer-approved, narrowly scoped adapters for existing fixture
70
+ workflows. Do not request upstream adoption until compatibility and maintenance
71
+ benefit have been demonstrated. Research notes are maintained separately in the repository.
72
+
73
+ ## Fixture audit (experimental)
74
+
75
+ Run on an already-reviewed candidate fixture, not as a replacement for redaction:
76
+
77
+ PYTHONPATH=src python3 -m iot_fixturekit.audit --profile tuya examples/synthetic-tuya-fixture.json
78
+
79
+ Generic mode checks JSON/HAR structures and plain-text patterns (including XML).
80
+ Tuya mode additionally checks selected requirements documented by Tuya Device
81
+ Handlers. Reports contain file ordinals, rule IDs and line numbers (0 for JSON
82
+ structural checks), not paths or matched values. Exit 0 means no findings, 1
83
+ means findings, 2 means an input error. A clean result does NOT certify privacy.
84
+ Unknown secrets, encoded strings, device identifiers and context-specific
85
+ sensitive measurements may remain. Generic mode does not parse XML or JSONL
86
+ structurally. No upstream adoption is claimed.
87
+
88
+ ## Tuya diagnostics adapter (experimental)
89
+
90
+ Create a **local review candidate**, not a publication-ready fixture:
91
+
92
+ mkdir -p raw/review
93
+ PYTHONPATH=src python3 -m iot_fixturekit.tuya examples/synthetic-tuya-diagnostics.json --output-dir raw/review
94
+
95
+ The adapter follows the documented Tuya Device Handlers extraction convention:
96
+ it selects the diagnostics data object, drops account-specific root keys,
97
+ blanks device_info, preserves functional datapoints and preserves the case of
98
+ the product ID. Filename components are restricted to safe alphanumeric forms.
99
+ The candidate is audited before writing, created with exclusive access (no
100
+ overwrite) and restrictive POSIX permissions. Review every field manually
101
+ before sharing; unknown datapoints, device names, timestamps and encoded values
102
+ may still contain personal data. The CLI never prints candidate values.
103
+ Exit 1 indicates audit findings; exit 2 indicates invalid input or write failure.
104
+ The ignored raw/ folder is recommended for private local work.
105
+
106
+ ## Pytest integration
107
+
108
+ Install the package with its optional pytest extra. The pytest entry point
109
+ automatically registers the callable fixture:
110
+
111
+ ```python
112
+ def test_device_fixture(iot_fixture_check):
113
+ iot_fixture_check("tests/fixtures/device.json", profile="tuya")
114
+ ```
115
+
116
+ Use the default generic profile for other devices. Explicitly parametrize the
117
+ files you want checked; there is no automatic repository-wide scanning.
118
+ The plugin uses the same file audit as the CLI and reports only rule IDs.
119
+ Avoid pytest options or custom plugins that dump sensitive local variables.
120
+
121
+ ## Pre-commit integration
122
+
123
+ For a local checkout of the package, use a local hook after installing it in
124
+ the environment running pre-commit:
125
+
126
+ ```yaml
127
+ repos:
128
+ - repo: local
129
+ hooks:
130
+ - id: iot-fixture-audit
131
+ name: Audit IoT test fixtures
132
+ entry: iot-fixture-audit
133
+ language: system
134
+ types: [text]
135
+ files: '(^|/)(fixtures|golden)/.*\.(json|har|xml|jsonl|log|txt)$'
136
+ ```
137
+
138
+ Consumers can also use the public hook pinned to the alpha release:
139
+
140
+ ```yaml
141
+ repos:
142
+ - repo: https://github.com/FlyzDev/fixturekit
143
+ rev: v0.1.0a2
144
+ hooks:
145
+ - id: iot-fixture-audit
146
+ ``` Restrict the file
147
+ pattern to reviewed fixture directories; use separate hooks with
148
+ `args: [--profile, tuya]` where appropriate. No findings is not a privacy
149
+ guarantee, and a hook is not a substitute for human review.
150
+
151
+ ## Project-specific placeholder policies (experimental)
152
+
153
+ Some libraries intentionally preserve synthetic MAC addresses in test fixtures.
154
+ Use an explicitly reviewed JSON policy, such as
155
+ `examples/synthetic-placeholder-policy.json`, with the audit CLI:
156
+
157
+ iot-fixture-audit --policy examples/synthetic-placeholder-policy.json tests/fixtures/device.json
158
+
159
+ Pytest accepts the same file through `policy_path`; pre-commit can pass
160
+ `args: [--policy, path/to/policy.json]` on a JSON-only hook.
161
+ For Python callers, pass the parsed policy via the keyword-only `policy`
162
+ argument to `audit_json` or `audit_file`.
163
+
164
+ Version 1 supports exact typed JSON paths and exact full colon-delimited MAC
165
+ placeholder values only. Integer path segments select array indexes; strings
166
+ select object keys. No wildcard or regex exemptions, no credential-rule
167
+ exemptions, and no exemption of object keys or Tuya structural checks.
168
+ Policies are opt-in; the Tuya conversion CLI retains its original strict audit.
169
+ Text formats do not accept policies. Keep policy files human-reviewed and use
170
+ only known synthetic values, never actual device addresses. A policy is not
171
+ evidence that a fixture is safe to publish.
172
+
173
+ Audit inputs are limited to 8 MiB per file, 64 nested path segments and
174
+ 200,000 visited JSON nodes (including object keys). The JSON audit rejects
175
+ non-finite numbers, unsupported Python values and unpaired Unicode surrogates.
176
+ These are defensive limits, not a complete resource-isolation guarantee.
177
+
178
+ Text audit additionally limits input to 8,388,608 characters and output to
179
+ 4,096 distinct line/rule findings per audit_text call. Exceeding a limit
180
+ is an input error, never a clean scan. Email and JWT matching starts at
181
+ token boundaries to avoid repeatedly scanning long runs of punctuation
182
+ or token characters. These heuristics can miss unusual or embedded values.
183
+
184
+ ## License
185
+
186
+ Apache License 2.0. See LICENSE.
187
+
188
+ ## Tuya loader compatibility pilot
189
+
190
+ A generated synthetic fixture was successfully loaded by the pinned upstream
191
+ Tuya Device Handlers test helper using the published alpha. See
192
+ [the reproducible pilot](examples/pilot/TUYA.md) for the exact scope and checks.
193
+
194
+ ## Overkiz profile (experimental)
195
+
196
+ The opt-in JSON profile checks selected exact state names for unmasked
197
+ values, including serial numbers, network identifiers and HomeKit setup
198
+ states. It recognizes limited mask-only strings and explicit redaction
199
+ placeholders; it does not validate all Overkiz fields or prove privacy.
200
+ Use the upstream obfuscator first. Generic mode is unchanged.
201
+
202
+ iot-fixture-audit --profile overkiz tests/fixtures/setup/device.json
203
+
204
+ Pytest accepts profile="overkiz", and JSON pre-commit hooks can pass
205
+ args: [--profile, overkiz]. MAC placeholder exceptions do not suppress
206
+ semantic state findings. This profile is included in the 0.1.0a2 alpha.
207
+
208
+ ## Overkiz post-obfuscation pilot
209
+
210
+ The published alpha was tested as an additional non-mutating check after
211
+ the pinned pyoverkiz obfuscator. See [the pilot and its known gap](examples/pilot/OVERKIZ.md).
212
+
213
+ ## Synthetic consumer pilot
214
+
215
+ The examples/pilot directory illustrates a fixture convention used by a
216
+ device library: a fixed synthetic Wi-Fi MAC placeholder at status.wifi.mac.
217
+ The example is independently constructed, incomplete and not an upstream
218
+ fixture or a compatibility guarantee.
219
+
220
+ After installing the package in a separate project, a JSON-only pre-commit
221
+ hook can pass the checked-in policy path as an argument:
222
+
223
+ ```yaml
224
+ repos:
225
+ - repo: local
226
+ hooks:
227
+ - id: fixturekit
228
+ name: FixtureKit audit
229
+ entry: iot-fixture-audit
230
+ language: system
231
+ args: [--policy, examples/pilot/shelly-style-policy.json]
232
+ files: '^tests/fixtures/.*\.json$'
233
+ ```
234
+
235
+ Use the matching policy in pytest via policy_path. Keep policies under human
236
+ review and do not apply the exception globally. This supplements, rather
237
+ than replaces, device-library redactors. See the four pilot integration tests.
@@ -0,0 +1,13 @@
1
+ iot_fixturekit/__init__.py,sha256=sMC9Cy4JtRNYOTbftCgeUjp7JLgOzlBaPXj5XzCERL8,164
2
+ iot_fixturekit/audit.py,sha256=enhvQFz12E5MTfVsk6hUcIz8AnHbCZWP6maQgoRlQC8,8093
3
+ iot_fixturekit/cli.py,sha256=_GQjH4YzEucUy9hrNtCE_7p1q1pK3s0GSsG1BS1B9TU,1704
4
+ iot_fixturekit/core.py,sha256=lZFVmhONR1Er27K5oyc2VC9Wlv6kP6ymigFpS6W6YDI,5057
5
+ iot_fixturekit/policy.py,sha256=prJJaJ1YSiPSO58DxMVO_Rl-CTUqXGNPaKLlA7oI4-c,1859
6
+ iot_fixturekit/pytest_plugin.py,sha256=0J4MAJDbU-l-PMSqbgYOthhvntYQcBFPXocExfX4ypw,998
7
+ iot_fixturekit/tuya.py,sha256=UlRyqV69jlJg70P9lWcxPl9dCs-rsnp3MKUtY1cmdb4,3398
8
+ iot_fixturekit-0.1.0a2.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
9
+ iot_fixturekit-0.1.0a2.dist-info/METADATA,sha256=05DOoRXrk4Q4gkU7UzTMxLWTAKGQrNhWhPJs36qd7rI,10275
10
+ iot_fixturekit-0.1.0a2.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
11
+ iot_fixturekit-0.1.0a2.dist-info/entry_points.txt,sha256=bikH9KKpBVjU3A8jfBO6YUTc__rsLH7eOyIKPVOmbmk,207
12
+ iot_fixturekit-0.1.0a2.dist-info/top_level.txt,sha256=vQmS5ZkgJrsoAxg40BDSwNCEadqtN2Ml0xxbo3WvSpU,15
13
+ iot_fixturekit-0.1.0a2.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,7 @@
1
+ [console_scripts]
2
+ iot-fixture-audit = iot_fixturekit.audit:main
3
+ iot-fixture-tuya = iot_fixturekit.tuya:main
4
+ iot-fixturekit = iot_fixturekit.cli:main
5
+
6
+ [pytest11]
7
+ iot_fixturekit = iot_fixturekit.pytest_plugin
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1 @@
1
+ iot_fixturekit