usb-claim-audit 0.1.0__tar.gz

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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 usb-claim-audit contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,2 @@
1
+ include README.md LICENSE
2
+ recursive-include tests *.py *.md .env
@@ -0,0 +1,133 @@
1
+ Metadata-Version: 2.4
2
+ Name: usb-claim-audit
3
+ Version: 0.1.0
4
+ Summary: Offline static audit of documented wired device claims
5
+ Author: usb-claim-audit contributors
6
+ License: MIT
7
+ Requires-Python: >=3.9
8
+ Description-Content-Type: text/markdown
9
+ License-File: LICENSE
10
+ Dynamic: license-file
11
+
12
+ # usb-claim-audit
13
+
14
+ Version 0.1.0. An offline static checker comparing documented wired device
15
+ capabilities with provider-resolved discovery calls in Python source.
16
+ Audited source is parsed with AST and never executed. No runtime dependencies.
17
+ Python 3.9 or newer is required. This machine has only `python3`.
18
+
19
+ ```sh
20
+ python3 -m pip install .
21
+ usb-claim-audit /path/to/project
22
+ python3 -m usb_claim_audit /path/to/project --json
23
+ python3 -m usb_claim_audit /path/to/project --verbose --ignore 'docs/archive/*'
24
+ python3 -m usb_claim_audit /path/to/project --fail-on MEDIUM
25
+ python3 -m usb_claim_audit --version
26
+ python3 -m unittest discover
27
+ python3 -m build
28
+ ```
29
+
30
+ Root README.md and Markdown under any docs path component are scanned.
31
+ Fenced blocks are excluded; inline code counts. Paragraph lines are joined,
32
+ case is folded, contractions expanded, hyphens replaced with spaces, and
33
+ whitespace collapsed. Exact word boundaries apply; longer negative spans are
34
+ removed before positive matching. The complete vocabulary follows.
35
+
36
+ ```text
37
+ connects to usb devices
38
+ connect to usb devices
39
+ connects via usb
40
+ connect via usb
41
+ connects over usb
42
+ connect over usb
43
+ reads from usb devices
44
+ read from usb devices
45
+ writes to usb devices
46
+ write to usb devices
47
+ reads data from usb devices
48
+ read data from usb devices
49
+ writes data to usb devices
50
+ write data to usb devices
51
+ transfers files over usb
52
+ transfer files over usb
53
+ transfers data over usb
54
+ transfer data over usb
55
+ transfers files via usb
56
+ transfer files via usb
57
+ detects usb devices
58
+ detect usb devices
59
+ lists usb devices
60
+ list usb devices
61
+ finds usb devices
62
+ find usb devices
63
+ communicates over usb
64
+ communicate over usb
65
+ communicates via usb
66
+ communicate via usb
67
+ controls usb devices
68
+ control usb devices
69
+ supports usb devices
70
+ usb device support
71
+ usb connectivity
72
+ supports usb
73
+ usb support
74
+ uses usb
75
+ use usb
76
+ does not connect to usb devices
77
+ does not connect via usb
78
+ does not connect over usb
79
+ does not read from usb devices
80
+ does not write to usb devices
81
+ does not transfer files over usb
82
+ does not transfer data over usb
83
+ does not detect usb devices
84
+ does not list usb devices
85
+ does not communicate over usb
86
+ does not communicate via usb
87
+ does not support usb devices
88
+ does not support usb
89
+ does not use usb
90
+ usb connectivity not supported
91
+ usb not supported
92
+ no usb support
93
+ without usb support
94
+ no usb connectivity
95
+ without usb connectivity
96
+ no usb
97
+ without usb
98
+ ```
99
+
100
+ `documented-usb-claim-false` is HIGH without production evidence and MEDIUM
101
+ when evidence occurs only in test source. The following rule is HIGH when
102
+ production evidence contradicts the documentation:
103
+
104
+ ```text
105
+ documented-no-usb-claim-false
106
+ ```
107
+ Each family
108
+ produces at most one finding. Default failure threshold is HIGH; MEDIUM can
109
+ be selected. JSON contains verdict, findings (rule, severity, message), and
110
+ scanned count. Exit codes are 0 for PASS, 2 for FAIL, and 1 for usage errors.
111
+ MEDIUM findings remain visible even when the verdict is PASS.
112
+
113
+ ## Limitations
114
+
115
+ Only the exact vocabulary in the fenced block constitutes claims. A bare
116
+ protocol word, chapter title, dependency name, or instruction asking the user
117
+ to attach a cable or plug in a device does not qualify. Charging, serial
118
+ ports, printing, and file export descriptions do not qualify either.
119
+
120
+ Imports, strings, comments, docstrings, unbound transfers, logging functions,
121
+ and web route decorators are insufficient. System device listing helpers
122
+ launched through subprocess are excluded: shell command names in strings
123
+ are not evidence. Discovery through pyusb's core find function counts by
124
+ itself, including aliased imports, bound handles, and chained transfers.
125
+ This checks source fingerprints, not successful hardware access, permissions,
126
+ reachability, or whether a discovery returns a device. Syntax-invalid files
127
+ provide no evidence. Dynamic imports and runtime rebinding are not resolved.
128
+
129
+ Production scanning excludes tests, test-named modules, fixtures, docs,
130
+ examples, and symlinks. Test evidence only affects the MEDIUM variant.
131
+ Environment files are never opened. A positive claim without source is HIGH;
132
+ an absence claim without source is consistent. With no claim, the audit passes
133
+ regardless of source evidence. Ignore globs match paths relative to the root.
@@ -0,0 +1,122 @@
1
+ # usb-claim-audit
2
+
3
+ Version 0.1.0. An offline static checker comparing documented wired device
4
+ capabilities with provider-resolved discovery calls in Python source.
5
+ Audited source is parsed with AST and never executed. No runtime dependencies.
6
+ Python 3.9 or newer is required. This machine has only `python3`.
7
+
8
+ ```sh
9
+ python3 -m pip install .
10
+ usb-claim-audit /path/to/project
11
+ python3 -m usb_claim_audit /path/to/project --json
12
+ python3 -m usb_claim_audit /path/to/project --verbose --ignore 'docs/archive/*'
13
+ python3 -m usb_claim_audit /path/to/project --fail-on MEDIUM
14
+ python3 -m usb_claim_audit --version
15
+ python3 -m unittest discover
16
+ python3 -m build
17
+ ```
18
+
19
+ Root README.md and Markdown under any docs path component are scanned.
20
+ Fenced blocks are excluded; inline code counts. Paragraph lines are joined,
21
+ case is folded, contractions expanded, hyphens replaced with spaces, and
22
+ whitespace collapsed. Exact word boundaries apply; longer negative spans are
23
+ removed before positive matching. The complete vocabulary follows.
24
+
25
+ ```text
26
+ connects to usb devices
27
+ connect to usb devices
28
+ connects via usb
29
+ connect via usb
30
+ connects over usb
31
+ connect over usb
32
+ reads from usb devices
33
+ read from usb devices
34
+ writes to usb devices
35
+ write to usb devices
36
+ reads data from usb devices
37
+ read data from usb devices
38
+ writes data to usb devices
39
+ write data to usb devices
40
+ transfers files over usb
41
+ transfer files over usb
42
+ transfers data over usb
43
+ transfer data over usb
44
+ transfers files via usb
45
+ transfer files via usb
46
+ detects usb devices
47
+ detect usb devices
48
+ lists usb devices
49
+ list usb devices
50
+ finds usb devices
51
+ find usb devices
52
+ communicates over usb
53
+ communicate over usb
54
+ communicates via usb
55
+ communicate via usb
56
+ controls usb devices
57
+ control usb devices
58
+ supports usb devices
59
+ usb device support
60
+ usb connectivity
61
+ supports usb
62
+ usb support
63
+ uses usb
64
+ use usb
65
+ does not connect to usb devices
66
+ does not connect via usb
67
+ does not connect over usb
68
+ does not read from usb devices
69
+ does not write to usb devices
70
+ does not transfer files over usb
71
+ does not transfer data over usb
72
+ does not detect usb devices
73
+ does not list usb devices
74
+ does not communicate over usb
75
+ does not communicate via usb
76
+ does not support usb devices
77
+ does not support usb
78
+ does not use usb
79
+ usb connectivity not supported
80
+ usb not supported
81
+ no usb support
82
+ without usb support
83
+ no usb connectivity
84
+ without usb connectivity
85
+ no usb
86
+ without usb
87
+ ```
88
+
89
+ `documented-usb-claim-false` is HIGH without production evidence and MEDIUM
90
+ when evidence occurs only in test source. The following rule is HIGH when
91
+ production evidence contradicts the documentation:
92
+
93
+ ```text
94
+ documented-no-usb-claim-false
95
+ ```
96
+ Each family
97
+ produces at most one finding. Default failure threshold is HIGH; MEDIUM can
98
+ be selected. JSON contains verdict, findings (rule, severity, message), and
99
+ scanned count. Exit codes are 0 for PASS, 2 for FAIL, and 1 for usage errors.
100
+ MEDIUM findings remain visible even when the verdict is PASS.
101
+
102
+ ## Limitations
103
+
104
+ Only the exact vocabulary in the fenced block constitutes claims. A bare
105
+ protocol word, chapter title, dependency name, or instruction asking the user
106
+ to attach a cable or plug in a device does not qualify. Charging, serial
107
+ ports, printing, and file export descriptions do not qualify either.
108
+
109
+ Imports, strings, comments, docstrings, unbound transfers, logging functions,
110
+ and web route decorators are insufficient. System device listing helpers
111
+ launched through subprocess are excluded: shell command names in strings
112
+ are not evidence. Discovery through pyusb's core find function counts by
113
+ itself, including aliased imports, bound handles, and chained transfers.
114
+ This checks source fingerprints, not successful hardware access, permissions,
115
+ reachability, or whether a discovery returns a device. Syntax-invalid files
116
+ provide no evidence. Dynamic imports and runtime rebinding are not resolved.
117
+
118
+ Production scanning excludes tests, test-named modules, fixtures, docs,
119
+ examples, and symlinks. Test evidence only affects the MEDIUM variant.
120
+ Environment files are never opened. A positive claim without source is HIGH;
121
+ an absence claim without source is consistent. With no claim, the audit passes
122
+ regardless of source evidence. Ignore globs match paths relative to the root.
@@ -0,0 +1,18 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "usb-claim-audit"
7
+ version = "0.1.0"
8
+ description = "Offline static audit of documented wired device claims"
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ license = {text = "MIT"}
12
+ authors = [{name = "usb-claim-audit contributors"}]
13
+
14
+ [project.scripts]
15
+ usb-claim-audit = "usb_claim_audit.__main__:main"
16
+
17
+ [tool.setuptools.packages.find]
18
+ include = ["usb_claim_audit*"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
File without changes
@@ -0,0 +1,12 @@
1
+ """Reusable fixture builders."""
2
+ from pathlib import Path
3
+
4
+
5
+ def populate(root, docs="connects to usb devices", source="pass", name="app.py"):
6
+ root = Path(root)
7
+ (root / "README.md").write_text(docs)
8
+ if source is not None:
9
+ path = root / name
10
+ path.parent.mkdir(parents=True, exist_ok=True)
11
+ path.write_text(source)
12
+ return root
@@ -0,0 +1 @@
1
+ # marker only; never read
@@ -0,0 +1 @@
1
+ connects to usb devices
@@ -0,0 +1 @@
1
+ pass
@@ -0,0 +1 @@
1
+ connects to usb devices
@@ -0,0 +1,2 @@
1
+ from usb.core import find
2
+ find(idVendor=0x1234)
@@ -0,0 +1 @@
1
+ no usb support
@@ -0,0 +1,2 @@
1
+ import usb.core
2
+ usb.core.find()
@@ -0,0 +1 @@
1
+ connects to usb devices
@@ -0,0 +1,2 @@
1
+ from usb.core import find
2
+ find()
@@ -0,0 +1,286 @@
1
+ """Specification coverage, with separate cases for every claim phrase."""
2
+ import builtins
3
+ import json
4
+ import re
5
+ import subprocess
6
+ import tempfile
7
+ import unittest
8
+ from pathlib import Path
9
+ from unittest.mock import patch
10
+ from usb_claim_audit.audit import audit, claims, evidence
11
+ from usb_claim_audit.phrases import USB, NOUSB
12
+ from tests.cases import populate
13
+
14
+ ROOT = Path(__file__).resolve().parents[1]
15
+ FIXTURES = ROOT / 'tests' / 'fixtures'
16
+
17
+
18
+ class AuditTests(unittest.TestCase):
19
+ def result(self, docs='connects to usb devices', source='pass', name='app.py'):
20
+ with tempfile.TemporaryDirectory() as tmp:
21
+ return audit(populate(tmp, docs, source, name))
22
+
23
+ def assert_high(self, result, rule='documented-usb-claim-false'):
24
+ self.assertEqual(result['verdict'], 'FAIL')
25
+ self.assertEqual(len(result['findings']), 1)
26
+ self.assertEqual(result['findings'][0]['severity'], 'HIGH')
27
+ self.assertEqual(result['findings'][0]['rule'], rule)
28
+
29
+ def cli(self, *args):
30
+ return subprocess.run(['python3', '-m', 'usb_claim_audit', *map(str, args)], capture_output=True, text=True)
31
+
32
+ def test_good_find(self):
33
+ self.assertEqual(audit(FIXTURES / 'good')['findings'], [])
34
+
35
+ def test_good_attribute(self):
36
+ self.assertEqual(self.result(source='import usb.core\nusb.core.find()')['findings'], [])
37
+
38
+ def test_good_alias(self):
39
+ self.assertEqual(self.result(source='import usb.core as core\ncore.find()')['findings'], [])
40
+
41
+ def test_good_bound_read(self):
42
+ self.assertEqual(self.result(source='from usb.core import find\ndev=find()\ndev.read(1, 8)')['findings'], [])
43
+
44
+ def test_good_bound_write(self):
45
+ self.assertEqual(self.result(source='from usb.core import find\ndev=find()\ndev.write(1, b"x")')['findings'], [])
46
+
47
+ def test_good_ctrl_transfer(self):
48
+ self.assertEqual(self.result(source='from usb.core import find\ndev=find()\ndev.ctrl_transfer(0, 1)')['findings'], [])
49
+
50
+ def test_good_chained(self):
51
+ self.assertEqual(self.result(source='import usb.core\nusb.core.find().read(1, 8)')['findings'], [])
52
+
53
+ def test_bad(self):
54
+ self.assert_high(audit(FIXTURES / 'bad'))
55
+ self.assertEqual(self.cli(FIXTURES / 'bad').returncode, 2)
56
+
57
+ def test_import_only(self):
58
+ self.assert_high(self.result(source='import usb'))
59
+
60
+ def test_core_import_only(self):
61
+ self.assert_high(self.result(source='import usb.core'))
62
+
63
+ def test_unbound(self):
64
+ self.assert_high(self.result(source='dev.read(1, 8)'))
65
+
66
+ def test_strings(self):
67
+ self.assert_high(self.result(source='VENDOR="usb 0x1234:0x5678"'))
68
+
69
+ def test_subprocess(self):
70
+ self.assert_high(self.result(source='import subprocess\nsubprocess.run(["lsusb"])'))
71
+
72
+ def test_subprocess_other(self):
73
+ self.assert_high(self.result(source='import subprocess\nsubprocess.run(["usb-devices"])'))
74
+
75
+ def test_serial(self):
76
+ self.assert_high(self.result(source='import serial\nserial.Serial("/dev/ttyUSB0")'))
77
+
78
+ def test_testonly(self):
79
+ result = audit(FIXTURES / 'testonly')
80
+ self.assertEqual(result['verdict'], 'PASS')
81
+ self.assertEqual(len(result['findings']), 1)
82
+ self.assertEqual(result['findings'][0]['severity'], 'MEDIUM')
83
+ self.assertEqual(result['findings'][0]['rule'], 'documented-usb-claim-false')
84
+ self.assertEqual(self.cli(FIXTURES / 'testonly').returncode, 0)
85
+ self.assertEqual(self.cli(FIXTURES / 'testonly', '--fail-on', 'MEDIUM').returncode, 2)
86
+
87
+ def test_no_usb(self):
88
+ self.assert_high(audit(FIXTURES / 'no-usb'), 'documented-no-usb-claim-false')
89
+ self.assertEqual(self.cli(FIXTURES / 'no-usb').returncode, 2)
90
+
91
+ def test_no_claim(self):
92
+ self.assertEqual(self.result('Device utility', 'import usb.core\nusb.core.find()')['findings'], [])
93
+
94
+ def test_user_instruction(self):
95
+ self.assertEqual(self.result('Plug in the usb device first. Connect the usb cable before starting.')['findings'], [])
96
+
97
+ def test_bare_word(self):
98
+ self.assertEqual(self.result('# USB')['findings'], [])
99
+
100
+ def test_fenced(self):
101
+ self.assertEqual(self.result('```text\nconnects via usb\n```')['findings'], [])
102
+
103
+ def test_inline(self):
104
+ self.assert_high(self.result('Tool `connects via usb` today.'))
105
+
106
+ def test_negation(self):
107
+ self.assertEqual(self.result('does not connect via usb')['findings'], [])
108
+
109
+ def test_no_source_positive(self):
110
+ self.assert_high(self.result(source=None))
111
+
112
+ def test_no_source_negative(self):
113
+ self.assertEqual(self.result('no usb', None)['findings'], [])
114
+
115
+ def test_self_audit(self):
116
+ self.assertEqual(claims((ROOT / 'README.md').read_text()), (False, False))
117
+ self.assertEqual(audit(ROOT)['findings'], [])
118
+ self.assertEqual(self.cli(ROOT).returncode, 0)
119
+
120
+ def test_cli_version(self):
121
+ proc = self.cli('--version')
122
+ self.assertEqual(proc.returncode, 0)
123
+ self.assertEqual(proc.stdout.strip(), '0.1.0')
124
+
125
+ def test_cli_json(self):
126
+ proc = self.cli(FIXTURES / 'bad', '--json')
127
+ self.assertEqual(proc.returncode, 2)
128
+ self.assert_high(json.loads(proc.stdout))
129
+
130
+ def test_cli_bad_path(self):
131
+ self.assertEqual(self.cli(ROOT / 'nonexistent').returncode, 1)
132
+
133
+ def test_cli_bad_option(self):
134
+ self.assertEqual(self.cli('--nonexistent').returncode, 1)
135
+
136
+ def test_ignore(self):
137
+ with tempfile.TemporaryDirectory() as tmp:
138
+ root = populate(tmp, 'Utility', 'pass')
139
+ (root / 'docs').mkdir()
140
+ (root / 'docs' / 'claim.md').write_text('connect via usb')
141
+ self.assertEqual(self.cli(root, '--ignore', 'docs/*.md').returncode, 0)
142
+ self.assertEqual(self.cli(root).returncode, 2)
143
+
144
+ def test_verbose(self):
145
+ proc = self.cli(FIXTURES / 'good', '--verbose')
146
+ self.assertEqual(proc.returncode, 0)
147
+ self.assertIn('Scanned', proc.stdout)
148
+
149
+ def test_packaging(self):
150
+ project = (ROOT / 'pyproject.toml').read_text()
151
+ self.assertIn('usb-claim-audit = "usb_claim_audit.__main__:main"', project)
152
+ self.assertIn('version = "0.1.0"', project)
153
+ self.assertIn('requires-' + 'py' + 'thon = ">=3.9"', project)
154
+ self.assertIn('MIT License', (ROOT / 'LICENSE').read_text())
155
+ self.assertTrue((ROOT / 'README.md').is_file())
156
+ self.assertIn('recursive-include tests *.py *.md .env', (ROOT / 'MANIFEST.in').read_text())
157
+ self.assertTrue((FIXTURES / '.env').is_file())
158
+
159
+ def test_no_bare_interpreter_commands(self):
160
+ forbidden = r'\b' + 'py' + r'thon\b'
161
+ for base in ('usb_claim_audit', 'tests'):
162
+ for path in (ROOT / base).rglob('*.py'):
163
+ self.assertIsNone(re.search(forbidden, path.read_text()), str(path))
164
+ for line in (ROOT / 'README.md').read_text().splitlines():
165
+ self.assertIsNone(re.search(forbidden, line, re.IGNORECASE) if line.lstrip().startswith(('py' + 'thon', '$ ', '>>>')) else None)
166
+
167
+ def test_no_secret_literals(self):
168
+ secret = re.compile(r'(?:AKIA[0-9A-Z]{16}|ghp_[A-Za-z0-9]{36}|-----BEGIN ' + r'(?:RSA |OPENSSH )?PRIVATE KEY-----)')
169
+ for path in ROOT.rglob('*'):
170
+ if path.is_file() and path.suffix in {'.py', '.md', '.toml'} and not any(p in {'dist', 'build', '.venv'} for p in path.parts):
171
+ self.assertIsNone(secret.search(path.read_text()), str(path))
172
+
173
+ def test_env_never_opened(self):
174
+ original = builtins.open
175
+ original_path = Path.open
176
+ def guarded(file, *args, **kwargs):
177
+ self.assertNotEqual(Path(file).name, '.env')
178
+ return original(file, *args, **kwargs)
179
+ def guarded_path(path, *args, **kwargs):
180
+ self.assertNotEqual(path.name, '.env')
181
+ return original_path(path, *args, **kwargs)
182
+ with patch('builtins.open', guarded), patch.object(Path, 'open', guarded_path):
183
+ self.assertEqual(audit(FIXTURES)['findings'], [])
184
+
185
+ def test_more_import_aliases(self):
186
+ for source in ['from usb import core as c\nc.find()', 'from usb.core import find as f\nf()', 'import usb as u\nu.core.find()', 'from usb import core\ncore.find()']:
187
+ with self.subTest(source=source):
188
+ self.assertTrue(evidence(source))
189
+
190
+ def test_self_attribute_configuration(self):
191
+ self.assertTrue(evidence('from usb.core import find\nself.dev=find()\nself.dev.set_configuration()'))
192
+
193
+ def test_bare_find(self):
194
+ self.assertFalse(evidence('def find(): return 1\nfind()'))
195
+
196
+ def test_logging_connect(self):
197
+ self.assert_high(self.result(source='def connect():\n print("usb")\n return True'))
198
+
199
+ def test_decorator(self):
200
+ self.assert_high(self.result(source='@app.get("/usb")\ndef route(): return "usb"'))
201
+
202
+ def test_comments_docstrings(self):
203
+ self.assertFalse(evidence('# usb.core.find()\n"""usb.core.find()"""'))
204
+
205
+ def test_scope_exclusions(self):
206
+ for name in ['fixtures/app.py', 'docs/app.py', 'examples/app.py']:
207
+ with self.subTest(name=name):
208
+ self.assert_high(self.result(source='import usb.core\nusb.core.find()', name=name))
209
+ for name in ['test_device.py', 'device_test.py']:
210
+ with self.subTest(name=name):
211
+ self.assertEqual(self.result(source='import usb.core\nusb.core.find()', name=name)['findings'][0]['severity'], 'MEDIUM')
212
+
213
+ def test_symlinks(self):
214
+ with tempfile.TemporaryDirectory() as tmp, tempfile.TemporaryDirectory() as other:
215
+ root = populate(tmp)
216
+ target = Path(other) / 'device.py'
217
+ target.write_text('import usb.core\nusb.core.find()')
218
+ (root / 'device.py').symlink_to(target)
219
+ (root / 'linked').symlink_to(other, target_is_directory=True)
220
+ self.assert_high(audit(root))
221
+
222
+ def test_docs_scope(self):
223
+ with tempfile.TemporaryDirectory() as tmp:
224
+ root = populate(tmp, 'Utility')
225
+ (root / 'other.md').write_text('connect via usb')
226
+ self.assertEqual(audit(root)['findings'], [])
227
+ path = root / 'nested' / 'docs' / 'deep' / 'claim.md'
228
+ path.parent.mkdir(parents=True)
229
+ path.write_text('connect via usb')
230
+ self.assert_high(audit(root))
231
+
232
+ def test_test_docs_negative(self):
233
+ with tempfile.TemporaryDirectory() as tmp:
234
+ root = populate(tmp, 'Utility', 'import usb.core\nusb.core.find()')
235
+ path = root / 'tests' / 'docs' / 'claim.md'
236
+ path.parent.mkdir(parents=True)
237
+ path.write_text('no usb')
238
+ self.assert_high(audit(root), 'documented-no-usb-claim-false')
239
+
240
+ def test_normalization(self):
241
+ self.assertEqual(claims('CONNECTS-TO\nUSB DEVICES'), (True, False))
242
+ self.assertEqual(claims("doesn't connect via usb"), (False, True))
243
+ self.assertEqual(claims('reconnect via usbs'), (False, False))
244
+ self.assertEqual(claims('connect via\n\nusb'), (False, False))
245
+
246
+ def test_both_families_max_two(self):
247
+ result = self.result('connect via usb. supports usb. no usb. without usb.')
248
+ self.assert_high(result)
249
+ result = self.result('connect via usb. no usb.', 'import usb.core\nusb.core.find()')
250
+ self.assert_high(result, 'documented-no-usb-claim-false')
251
+
252
+ def test_unreadable_root(self):
253
+ with tempfile.TemporaryDirectory() as tmp:
254
+ root = Path(tmp)
255
+ root.chmod(0)
256
+ try:
257
+ self.assertEqual(self.cli(root).returncode, 1)
258
+ finally:
259
+ root.chmod(0o700)
260
+
261
+ def test_tilde_fence(self):
262
+ self.assertEqual(claims('~~~text\nconnect via usb\n~~~'), (False, False))
263
+
264
+ def test_invalid_source(self):
265
+ self.assert_high(self.result(source='import usb.core\nusb.core.find('))
266
+
267
+
268
+ def positive_test(phrase):
269
+ def run(self):
270
+ self.assertEqual(claims(phrase), (True, False))
271
+ self.assert_high(self.result(phrase))
272
+ return run
273
+
274
+
275
+ def negative_test(phrase):
276
+ def run(self):
277
+ self.assertEqual(claims(phrase), (False, True))
278
+ self.assertEqual(self.result(phrase)['findings'], [])
279
+ self.assert_high(self.result(phrase, 'import usb.core\nusb.core.find()'), 'documented-no-usb-claim-false')
280
+ return run
281
+
282
+
283
+ for index, phrase in enumerate(USB):
284
+ setattr(AuditTests, 'test_positive_phrase_%02d' % index, positive_test(phrase))
285
+ for index, phrase in enumerate(NOUSB):
286
+ setattr(AuditTests, 'test_negative_phrase_%02d' % index, negative_test(phrase))
@@ -0,0 +1,2 @@
1
+ """Static wired device claim auditing."""
2
+ __version__ = "0.1.0"
@@ -0,0 +1,38 @@
1
+ """Command line interface."""
2
+ import argparse
3
+ import json
4
+ import sys
5
+ from . import __version__
6
+ from .audit import audit
7
+
8
+
9
+ def main():
10
+ parser = argparse.ArgumentParser(description="Audit documented wired device claims against Python source.")
11
+ parser.add_argument("root")
12
+ parser.add_argument("--json", action="store_true")
13
+ parser.add_argument("--verbose", action="store_true")
14
+ parser.add_argument("--ignore", action="append", default=[])
15
+ parser.add_argument("--fail-on", choices=("HIGH", "MEDIUM"), default="HIGH")
16
+ parser.add_argument("--version", action="version", version=__version__)
17
+ try:
18
+ args = parser.parse_args()
19
+ except SystemExit as exc:
20
+ return 1 if exc.code == 2 else exc.code
21
+ try:
22
+ result = audit(args.root, args.ignore, args.fail_on)
23
+ except (OSError, ValueError) as exc:
24
+ print(str(exc), file=sys.stderr)
25
+ return 1
26
+ if args.json:
27
+ print(json.dumps(result))
28
+ else:
29
+ print(result["verdict"])
30
+ for finding in result["findings"]:
31
+ print("{severity} {rule}: {message}".format(**finding))
32
+ if args.verbose:
33
+ print("Scanned {} files".format(result["scanned"]))
34
+ return 2 if result["verdict"] == "FAIL" else 0
35
+
36
+
37
+ if __name__ == "__main__":
38
+ sys.exit(main())
@@ -0,0 +1,96 @@
1
+ """Offline document and AST analysis; audited code is never executed."""
2
+ import ast
3
+ import fnmatch
4
+ import re
5
+ from pathlib import Path
6
+ from .phrases import USB, NOUSB
7
+
8
+
9
+ def pattern(phrases):
10
+ return re.compile(r"\b(?:" + "|".join(re.escape(p) for p in sorted(phrases, key=len, reverse=True)) + r")\b")
11
+
12
+
13
+ def claims(text):
14
+ lines = []
15
+ fence = None
16
+ for line in text.splitlines():
17
+ match = re.match(r"^\s{0,3}(`{3,}|~{3,})", line)
18
+ if fence:
19
+ if match and match[1][0] == fence[0] and len(match[1]) >= len(fence) and not line[match.end():].strip():
20
+ fence = None
21
+ lines.append("")
22
+ elif match:
23
+ fence = match[1]
24
+ lines.append("")
25
+ else:
26
+ lines.append(line)
27
+ positive = negative = False
28
+ for paragraph in re.split(r"\n\s*\n", "\n".join(lines)):
29
+ normalized = re.sub(r"\s+", " ", paragraph.lower().replace("n't", " not").replace("-", " "))
30
+ negative |= bool(pattern(NOUSB).search(normalized))
31
+ normalized = pattern(NOUSB).sub(" ", normalized)
32
+ positive |= bool(pattern(USB).search(normalized))
33
+ return positive, negative
34
+
35
+
36
+ def evidence(source):
37
+ try:
38
+ tree = ast.parse(source)
39
+ except (SyntaxError, ValueError):
40
+ return False
41
+ aliases = {}
42
+ for node in ast.walk(tree):
43
+ if isinstance(node, ast.Import):
44
+ for item in node.names:
45
+ if item.name == "usb" or item.name.startswith("usb."):
46
+ aliases[item.asname or item.name.split(".")[0]] = item.name if item.asname else "usb"
47
+ elif isinstance(node, ast.ImportFrom) and node.module and (node.module == "usb" or node.module.startswith("usb.")):
48
+ for item in node.names:
49
+ aliases[item.asname or item.name] = node.module + "." + item.name
50
+ def resolve(node):
51
+ if isinstance(node, ast.Name):
52
+ return aliases.get(node.id, "")
53
+ if isinstance(node, ast.Attribute):
54
+ base = resolve(node.value)
55
+ return base + "." + node.attr if base else ""
56
+ return ""
57
+ # Discovery itself is evidence, including every bound or chained route.
58
+ return any(isinstance(n, ast.Call) and resolve(n.func) == "usb.core.find" for n in ast.walk(tree))
59
+
60
+
61
+ def audit(root, ignore=(), fail_on="HIGH"):
62
+ root = Path(root)
63
+ if not root.is_dir():
64
+ raise ValueError("root must be a readable directory")
65
+ if root.stat().st_mode & 0o444 == 0 or root.stat().st_mode & 0o111 == 0:
66
+ raise ValueError("root must be a readable directory")
67
+ positive = negative = prod = test = False
68
+ scanned = 0
69
+ for path in sorted(root.rglob("*")):
70
+ rel = path.relative_to(root)
71
+ if path.is_symlink() or any((root / Path(*rel.parts[:i])).is_symlink() for i in range(1, len(rel.parts))):
72
+ continue
73
+ if any(fnmatch.fnmatch(rel.as_posix(), glob) for glob in ignore):
74
+ continue
75
+ if not path.is_file():
76
+ continue
77
+ if path.suffix.lower() == ".md" and (rel.as_posix() == "README.md" or "docs" in rel.parts[:-1]):
78
+ a, b = claims(path.read_text(encoding="utf-8"))
79
+ positive |= a
80
+ negative |= b
81
+ scanned += 1
82
+ if path.suffix == ".py":
83
+ if any(p in {"fixtures", "docs", "examples"} for p in rel.parts[:-1]):
84
+ continue
85
+ is_test = "tests" in rel.parts[:-1] or path.name.startswith("test_") or path.name.endswith("_test.py")
86
+ found = evidence(path.read_text(encoding="utf-8"))
87
+ test |= found and is_test
88
+ prod |= found and not is_test
89
+ scanned += 1
90
+ findings = []
91
+ if positive and not prod:
92
+ findings.append(dict(rule="documented-usb-claim-false", severity="MEDIUM" if test else "HIGH", message="Documented wired device capability lacks production evidence."))
93
+ if negative and prod:
94
+ findings.append(dict(rule="documented-no-usb-claim-false", severity="HIGH", message="Documented absence conflicts with production discovery evidence."))
95
+ failed = any(f["severity"] == "HIGH" or fail_on == "MEDIUM" for f in findings)
96
+ return dict(verdict="FAIL" if failed else "PASS", findings=findings, scanned=scanned)
@@ -0,0 +1,3 @@
1
+ """Exact normalized claim vocabulary."""
2
+ USB = ('connects to usb devices', 'connect to usb devices', 'connects via usb', 'connect via usb', 'connects over usb', 'connect over usb', 'reads from usb devices', 'read from usb devices', 'writes to usb devices', 'write to usb devices', 'reads data from usb devices', 'read data from usb devices', 'writes data to usb devices', 'write data to usb devices', 'transfers files over usb', 'transfer files over usb', 'transfers data over usb', 'transfer data over usb', 'transfers files via usb', 'transfer files via usb', 'detects usb devices', 'detect usb devices', 'lists usb devices', 'list usb devices', 'finds usb devices', 'find usb devices', 'communicates over usb', 'communicate over usb', 'communicates via usb', 'communicate via usb', 'controls usb devices', 'control usb devices', 'supports usb devices', 'usb device support', 'usb connectivity', 'supports usb', 'usb support', 'uses usb', 'use usb')
3
+ NOUSB = ('does not connect to usb devices', 'does not connect via usb', 'does not connect over usb', 'does not read from usb devices', 'does not write to usb devices', 'does not transfer files over usb', 'does not transfer data over usb', 'does not detect usb devices', 'does not list usb devices', 'does not communicate over usb', 'does not communicate via usb', 'does not support usb devices', 'does not support usb', 'does not use usb', 'usb connectivity not supported', 'usb not supported', 'no usb support', 'without usb support', 'no usb connectivity', 'without usb connectivity', 'no usb', 'without usb')
@@ -0,0 +1,133 @@
1
+ Metadata-Version: 2.4
2
+ Name: usb-claim-audit
3
+ Version: 0.1.0
4
+ Summary: Offline static audit of documented wired device claims
5
+ Author: usb-claim-audit contributors
6
+ License: MIT
7
+ Requires-Python: >=3.9
8
+ Description-Content-Type: text/markdown
9
+ License-File: LICENSE
10
+ Dynamic: license-file
11
+
12
+ # usb-claim-audit
13
+
14
+ Version 0.1.0. An offline static checker comparing documented wired device
15
+ capabilities with provider-resolved discovery calls in Python source.
16
+ Audited source is parsed with AST and never executed. No runtime dependencies.
17
+ Python 3.9 or newer is required. This machine has only `python3`.
18
+
19
+ ```sh
20
+ python3 -m pip install .
21
+ usb-claim-audit /path/to/project
22
+ python3 -m usb_claim_audit /path/to/project --json
23
+ python3 -m usb_claim_audit /path/to/project --verbose --ignore 'docs/archive/*'
24
+ python3 -m usb_claim_audit /path/to/project --fail-on MEDIUM
25
+ python3 -m usb_claim_audit --version
26
+ python3 -m unittest discover
27
+ python3 -m build
28
+ ```
29
+
30
+ Root README.md and Markdown under any docs path component are scanned.
31
+ Fenced blocks are excluded; inline code counts. Paragraph lines are joined,
32
+ case is folded, contractions expanded, hyphens replaced with spaces, and
33
+ whitespace collapsed. Exact word boundaries apply; longer negative spans are
34
+ removed before positive matching. The complete vocabulary follows.
35
+
36
+ ```text
37
+ connects to usb devices
38
+ connect to usb devices
39
+ connects via usb
40
+ connect via usb
41
+ connects over usb
42
+ connect over usb
43
+ reads from usb devices
44
+ read from usb devices
45
+ writes to usb devices
46
+ write to usb devices
47
+ reads data from usb devices
48
+ read data from usb devices
49
+ writes data to usb devices
50
+ write data to usb devices
51
+ transfers files over usb
52
+ transfer files over usb
53
+ transfers data over usb
54
+ transfer data over usb
55
+ transfers files via usb
56
+ transfer files via usb
57
+ detects usb devices
58
+ detect usb devices
59
+ lists usb devices
60
+ list usb devices
61
+ finds usb devices
62
+ find usb devices
63
+ communicates over usb
64
+ communicate over usb
65
+ communicates via usb
66
+ communicate via usb
67
+ controls usb devices
68
+ control usb devices
69
+ supports usb devices
70
+ usb device support
71
+ usb connectivity
72
+ supports usb
73
+ usb support
74
+ uses usb
75
+ use usb
76
+ does not connect to usb devices
77
+ does not connect via usb
78
+ does not connect over usb
79
+ does not read from usb devices
80
+ does not write to usb devices
81
+ does not transfer files over usb
82
+ does not transfer data over usb
83
+ does not detect usb devices
84
+ does not list usb devices
85
+ does not communicate over usb
86
+ does not communicate via usb
87
+ does not support usb devices
88
+ does not support usb
89
+ does not use usb
90
+ usb connectivity not supported
91
+ usb not supported
92
+ no usb support
93
+ without usb support
94
+ no usb connectivity
95
+ without usb connectivity
96
+ no usb
97
+ without usb
98
+ ```
99
+
100
+ `documented-usb-claim-false` is HIGH without production evidence and MEDIUM
101
+ when evidence occurs only in test source. The following rule is HIGH when
102
+ production evidence contradicts the documentation:
103
+
104
+ ```text
105
+ documented-no-usb-claim-false
106
+ ```
107
+ Each family
108
+ produces at most one finding. Default failure threshold is HIGH; MEDIUM can
109
+ be selected. JSON contains verdict, findings (rule, severity, message), and
110
+ scanned count. Exit codes are 0 for PASS, 2 for FAIL, and 1 for usage errors.
111
+ MEDIUM findings remain visible even when the verdict is PASS.
112
+
113
+ ## Limitations
114
+
115
+ Only the exact vocabulary in the fenced block constitutes claims. A bare
116
+ protocol word, chapter title, dependency name, or instruction asking the user
117
+ to attach a cable or plug in a device does not qualify. Charging, serial
118
+ ports, printing, and file export descriptions do not qualify either.
119
+
120
+ Imports, strings, comments, docstrings, unbound transfers, logging functions,
121
+ and web route decorators are insufficient. System device listing helpers
122
+ launched through subprocess are excluded: shell command names in strings
123
+ are not evidence. Discovery through pyusb's core find function counts by
124
+ itself, including aliased imports, bound handles, and chained transfers.
125
+ This checks source fingerprints, not successful hardware access, permissions,
126
+ reachability, or whether a discovery returns a device. Syntax-invalid files
127
+ provide no evidence. Dynamic imports and runtime rebinding are not resolved.
128
+
129
+ Production scanning excludes tests, test-named modules, fixtures, docs,
130
+ examples, and symlinks. Test evidence only affects the MEDIUM variant.
131
+ Environment files are never opened. A positive claim without source is HIGH;
132
+ an absence claim without source is consistent. With no claim, the audit passes
133
+ regardless of source evidence. Ignore globs match paths relative to the root.
@@ -0,0 +1,25 @@
1
+ LICENSE
2
+ MANIFEST.in
3
+ README.md
4
+ pyproject.toml
5
+ tests/__init__.py
6
+ tests/cases.py
7
+ tests/test_audit.py
8
+ tests/fixtures/.env
9
+ tests/fixtures/bad/README.md
10
+ tests/fixtures/bad/app.py
11
+ tests/fixtures/good/README.md
12
+ tests/fixtures/good/app.py
13
+ tests/fixtures/no-usb/README.md
14
+ tests/fixtures/no-usb/app.py
15
+ tests/fixtures/testonly/README.md
16
+ tests/fixtures/testonly/tests/test_device.py
17
+ usb_claim_audit/__init__.py
18
+ usb_claim_audit/__main__.py
19
+ usb_claim_audit/audit.py
20
+ usb_claim_audit/phrases.py
21
+ usb_claim_audit.egg-info/PKG-INFO
22
+ usb_claim_audit.egg-info/SOURCES.txt
23
+ usb_claim_audit.egg-info/dependency_links.txt
24
+ usb_claim_audit.egg-info/entry_points.txt
25
+ usb_claim_audit.egg-info/top_level.txt
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ usb-claim-audit = usb_claim_audit.__main__:main
@@ -0,0 +1 @@
1
+ usb_claim_audit