bluetooth-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.
- bluetooth_claim_audit-0.1.0/LICENSE +21 -0
- bluetooth_claim_audit-0.1.0/MANIFEST.in +3 -0
- bluetooth_claim_audit-0.1.0/PKG-INFO +136 -0
- bluetooth_claim_audit-0.1.0/README.md +126 -0
- bluetooth_claim_audit-0.1.0/bluetooth_claim_audit/__init__.py +2 -0
- bluetooth_claim_audit-0.1.0/bluetooth_claim_audit/__main__.py +3 -0
- bluetooth_claim_audit-0.1.0/bluetooth_claim_audit/audit.py +190 -0
- bluetooth_claim_audit-0.1.0/bluetooth_claim_audit/phrases.py +3 -0
- bluetooth_claim_audit-0.1.0/bluetooth_claim_audit.egg-info/PKG-INFO +136 -0
- bluetooth_claim_audit-0.1.0/bluetooth_claim_audit.egg-info/SOURCES.txt +25 -0
- bluetooth_claim_audit-0.1.0/bluetooth_claim_audit.egg-info/dependency_links.txt +1 -0
- bluetooth_claim_audit-0.1.0/bluetooth_claim_audit.egg-info/entry_points.txt +2 -0
- bluetooth_claim_audit-0.1.0/bluetooth_claim_audit.egg-info/top_level.txt +1 -0
- bluetooth_claim_audit-0.1.0/pyproject.toml +17 -0
- bluetooth_claim_audit-0.1.0/setup.cfg +4 -0
- bluetooth_claim_audit-0.1.0/tests/__init__.py +0 -0
- bluetooth_claim_audit-0.1.0/tests/cases.py +47 -0
- bluetooth_claim_audit-0.1.0/tests/fixtures/.env +1 -0
- bluetooth_claim_audit-0.1.0/tests/fixtures/bad/README.md +1 -0
- bluetooth_claim_audit-0.1.0/tests/fixtures/bad/app.py +1 -0
- bluetooth_claim_audit-0.1.0/tests/fixtures/good/README.md +1 -0
- bluetooth_claim_audit-0.1.0/tests/fixtures/good/app.py +2 -0
- bluetooth_claim_audit-0.1.0/tests/fixtures/no-bluetooth/README.md +1 -0
- bluetooth_claim_audit-0.1.0/tests/fixtures/no-bluetooth/app.py +2 -0
- bluetooth_claim_audit-0.1.0/tests/fixtures/testonly/README.md +1 -0
- bluetooth_claim_audit-0.1.0/tests/fixtures/testonly/tests/test_device.py +2 -0
- bluetooth_claim_audit-0.1.0/tests/test_audit.py +173 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 bluetooth-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,136 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: bluetooth-claim-audit
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Offline static audit of wireless device documentation against source
|
|
5
|
+
License: MIT
|
|
6
|
+
Requires-Python: >=3.9
|
|
7
|
+
Description-Content-Type: text/markdown
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Dynamic: license-file
|
|
10
|
+
|
|
11
|
+
# bluetooth-claim-audit
|
|
12
|
+
|
|
13
|
+
Version 0.1.0. Python >=3.9. MIT licensed. No runtime dependencies.
|
|
14
|
+
|
|
15
|
+
Checks documented wireless device claims against Python AST evidence offline.
|
|
16
|
+
Audited source is never executed. Environment files are never opened.
|
|
17
|
+
|
|
18
|
+
```sh
|
|
19
|
+
python3 -m pip install .
|
|
20
|
+
bluetooth-claim-audit path/to/project --json
|
|
21
|
+
python3 -m bluetooth_claim_audit path/to/project --verbose
|
|
22
|
+
python3 -m unittest discover
|
|
23
|
+
python3 -m build
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
Root README.md and Markdown beneath any docs directory supply claims. Fenced
|
|
27
|
+
code is excluded; inline code counts. Matching lowercases, expands n't, replaces
|
|
28
|
+
hyphens with spaces, joins paragraph lines, and applies word boundaries.
|
|
29
|
+
Negative spans are removed before positive matching. Exact templates follow:
|
|
30
|
+
|
|
31
|
+
```text
|
|
32
|
+
connects to bluetooth devices
|
|
33
|
+
connect to bluetooth devices
|
|
34
|
+
connects to ble devices
|
|
35
|
+
connect to ble devices
|
|
36
|
+
connects via bluetooth
|
|
37
|
+
connect via bluetooth
|
|
38
|
+
connects over bluetooth
|
|
39
|
+
connect over bluetooth
|
|
40
|
+
pairs with bluetooth devices
|
|
41
|
+
pair with bluetooth devices
|
|
42
|
+
discovers bluetooth devices
|
|
43
|
+
discover bluetooth devices
|
|
44
|
+
discovers ble devices
|
|
45
|
+
discover ble devices
|
|
46
|
+
scans for bluetooth devices
|
|
47
|
+
scan for bluetooth devices
|
|
48
|
+
finds bluetooth devices
|
|
49
|
+
find bluetooth devices
|
|
50
|
+
sends data over bluetooth
|
|
51
|
+
send data over bluetooth
|
|
52
|
+
sends data via bluetooth
|
|
53
|
+
send data via bluetooth
|
|
54
|
+
transfers files over bluetooth
|
|
55
|
+
transfer files over bluetooth
|
|
56
|
+
transfers data over bluetooth
|
|
57
|
+
transfer data over bluetooth
|
|
58
|
+
communicates over bluetooth
|
|
59
|
+
communicate over bluetooth
|
|
60
|
+
communicates via bluetooth
|
|
61
|
+
communicate via bluetooth
|
|
62
|
+
supports bluetooth low energy
|
|
63
|
+
bluetooth low energy support
|
|
64
|
+
bluetooth file transfer
|
|
65
|
+
bluetooth data transfer
|
|
66
|
+
bluetooth connectivity
|
|
67
|
+
supports bluetooth
|
|
68
|
+
bluetooth support
|
|
69
|
+
supports ble
|
|
70
|
+
ble support
|
|
71
|
+
ble connectivity
|
|
72
|
+
uses bluetooth
|
|
73
|
+
use bluetooth
|
|
74
|
+
does not connect to bluetooth devices
|
|
75
|
+
does not connect via bluetooth
|
|
76
|
+
does not connect over bluetooth
|
|
77
|
+
does not pair with bluetooth devices
|
|
78
|
+
does not discover bluetooth devices
|
|
79
|
+
does not scan for bluetooth devices
|
|
80
|
+
does not send data over bluetooth
|
|
81
|
+
does not transfer files over bluetooth
|
|
82
|
+
does not communicate over bluetooth
|
|
83
|
+
does not communicate via bluetooth
|
|
84
|
+
does not support bluetooth low energy
|
|
85
|
+
does not support bluetooth
|
|
86
|
+
does not support ble
|
|
87
|
+
does not use bluetooth
|
|
88
|
+
bluetooth connectivity not supported
|
|
89
|
+
bluetooth not supported
|
|
90
|
+
ble not supported
|
|
91
|
+
no bluetooth support
|
|
92
|
+
without bluetooth support
|
|
93
|
+
no bluetooth connectivity
|
|
94
|
+
without bluetooth connectivity
|
|
95
|
+
no bluetooth
|
|
96
|
+
without bluetooth
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
At most one finding per family is emitted. The positive rule is
|
|
100
|
+
`documented-bluetooth-claim-false`: HIGH without production evidence, MEDIUM
|
|
101
|
+
when evidence occurs only in tests. The negative rule is
|
|
102
|
+
|
|
103
|
+
```text
|
|
104
|
+
documented-no-bluetooth-claim-false
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
This rule is HIGH when production evidence exists.
|
|
108
|
+
No claim means PASS. Without source, positive claims fail and negative ones pass.
|
|
109
|
+
Default threshold HIGH reports MEDIUM without failing; `--fail-on MEDIUM`
|
|
110
|
+
fails on either severity. Exit codes: 0 PASS, 2 FAIL, 1 usage or root error.
|
|
111
|
+
`--json` emits verdict and findings (rule, severity, message); `--verbose`
|
|
112
|
+
adds scanned-file counts. Repeat `--ignore GLOB` to exclude relative paths.
|
|
113
|
+
`--version` prints 0.1.0. Both entry points accept these options.
|
|
114
|
+
|
|
115
|
+
## Evidence and scope
|
|
116
|
+
|
|
117
|
+
Provider imports and aliases are resolved within each module for bleak,
|
|
118
|
+
pybluez's bluetooth module, socket, and bluepy.btle. Discovery, bound client
|
|
119
|
+
connection, GATT operations, bound pybluez socket send/receive, native sockets
|
|
120
|
+
with an explicit wireless address family, and bluepy scans are recognized.
|
|
121
|
+
Assignments to names and self attributes and chained construction are supported.
|
|
122
|
+
Imports, object construction alone, strings, comments and docstrings do not count.
|
|
123
|
+
Production excludes tests, test filenames, fixtures, docs and examples;
|
|
124
|
+
symlink files and directories are skipped. Test evidence can only lower the
|
|
125
|
+
positive finding to MEDIUM. Documentation location does not soften the negative rule.
|
|
126
|
+
|
|
127
|
+
## Limitations
|
|
128
|
+
|
|
129
|
+
Only the exact templates above count. A bare wireless technology name, user
|
|
130
|
+
instructions for phone setup, headset audio routing, wired/USB/plain network
|
|
131
|
+
links and file exports are outside this audit's dimension. System wireless
|
|
132
|
+
helpers invoked by subprocess are not recognized; shell command strings alone
|
|
133
|
+
are not evidence. Analysis is static and module local, with no runtime reachability,
|
|
134
|
+
inter-module binding, dynamic import or general data-flow proof. Syntax errors
|
|
135
|
+
are reported as warnings and yield no evidence for that file. A PASS is a
|
|
136
|
+
consistency result for these templates and routes, not a hardware test.
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
# bluetooth-claim-audit
|
|
2
|
+
|
|
3
|
+
Version 0.1.0. Python >=3.9. MIT licensed. No runtime dependencies.
|
|
4
|
+
|
|
5
|
+
Checks documented wireless device claims against Python AST evidence offline.
|
|
6
|
+
Audited source is never executed. Environment files are never opened.
|
|
7
|
+
|
|
8
|
+
```sh
|
|
9
|
+
python3 -m pip install .
|
|
10
|
+
bluetooth-claim-audit path/to/project --json
|
|
11
|
+
python3 -m bluetooth_claim_audit path/to/project --verbose
|
|
12
|
+
python3 -m unittest discover
|
|
13
|
+
python3 -m build
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
Root README.md and Markdown beneath any docs directory supply claims. Fenced
|
|
17
|
+
code is excluded; inline code counts. Matching lowercases, expands n't, replaces
|
|
18
|
+
hyphens with spaces, joins paragraph lines, and applies word boundaries.
|
|
19
|
+
Negative spans are removed before positive matching. Exact templates follow:
|
|
20
|
+
|
|
21
|
+
```text
|
|
22
|
+
connects to bluetooth devices
|
|
23
|
+
connect to bluetooth devices
|
|
24
|
+
connects to ble devices
|
|
25
|
+
connect to ble devices
|
|
26
|
+
connects via bluetooth
|
|
27
|
+
connect via bluetooth
|
|
28
|
+
connects over bluetooth
|
|
29
|
+
connect over bluetooth
|
|
30
|
+
pairs with bluetooth devices
|
|
31
|
+
pair with bluetooth devices
|
|
32
|
+
discovers bluetooth devices
|
|
33
|
+
discover bluetooth devices
|
|
34
|
+
discovers ble devices
|
|
35
|
+
discover ble devices
|
|
36
|
+
scans for bluetooth devices
|
|
37
|
+
scan for bluetooth devices
|
|
38
|
+
finds bluetooth devices
|
|
39
|
+
find bluetooth devices
|
|
40
|
+
sends data over bluetooth
|
|
41
|
+
send data over bluetooth
|
|
42
|
+
sends data via bluetooth
|
|
43
|
+
send data via bluetooth
|
|
44
|
+
transfers files over bluetooth
|
|
45
|
+
transfer files over bluetooth
|
|
46
|
+
transfers data over bluetooth
|
|
47
|
+
transfer data over bluetooth
|
|
48
|
+
communicates over bluetooth
|
|
49
|
+
communicate over bluetooth
|
|
50
|
+
communicates via bluetooth
|
|
51
|
+
communicate via bluetooth
|
|
52
|
+
supports bluetooth low energy
|
|
53
|
+
bluetooth low energy support
|
|
54
|
+
bluetooth file transfer
|
|
55
|
+
bluetooth data transfer
|
|
56
|
+
bluetooth connectivity
|
|
57
|
+
supports bluetooth
|
|
58
|
+
bluetooth support
|
|
59
|
+
supports ble
|
|
60
|
+
ble support
|
|
61
|
+
ble connectivity
|
|
62
|
+
uses bluetooth
|
|
63
|
+
use bluetooth
|
|
64
|
+
does not connect to bluetooth devices
|
|
65
|
+
does not connect via bluetooth
|
|
66
|
+
does not connect over bluetooth
|
|
67
|
+
does not pair with bluetooth devices
|
|
68
|
+
does not discover bluetooth devices
|
|
69
|
+
does not scan for bluetooth devices
|
|
70
|
+
does not send data over bluetooth
|
|
71
|
+
does not transfer files over bluetooth
|
|
72
|
+
does not communicate over bluetooth
|
|
73
|
+
does not communicate via bluetooth
|
|
74
|
+
does not support bluetooth low energy
|
|
75
|
+
does not support bluetooth
|
|
76
|
+
does not support ble
|
|
77
|
+
does not use bluetooth
|
|
78
|
+
bluetooth connectivity not supported
|
|
79
|
+
bluetooth not supported
|
|
80
|
+
ble not supported
|
|
81
|
+
no bluetooth support
|
|
82
|
+
without bluetooth support
|
|
83
|
+
no bluetooth connectivity
|
|
84
|
+
without bluetooth connectivity
|
|
85
|
+
no bluetooth
|
|
86
|
+
without bluetooth
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
At most one finding per family is emitted. The positive rule is
|
|
90
|
+
`documented-bluetooth-claim-false`: HIGH without production evidence, MEDIUM
|
|
91
|
+
when evidence occurs only in tests. The negative rule is
|
|
92
|
+
|
|
93
|
+
```text
|
|
94
|
+
documented-no-bluetooth-claim-false
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
This rule is HIGH when production evidence exists.
|
|
98
|
+
No claim means PASS. Without source, positive claims fail and negative ones pass.
|
|
99
|
+
Default threshold HIGH reports MEDIUM without failing; `--fail-on MEDIUM`
|
|
100
|
+
fails on either severity. Exit codes: 0 PASS, 2 FAIL, 1 usage or root error.
|
|
101
|
+
`--json` emits verdict and findings (rule, severity, message); `--verbose`
|
|
102
|
+
adds scanned-file counts. Repeat `--ignore GLOB` to exclude relative paths.
|
|
103
|
+
`--version` prints 0.1.0. Both entry points accept these options.
|
|
104
|
+
|
|
105
|
+
## Evidence and scope
|
|
106
|
+
|
|
107
|
+
Provider imports and aliases are resolved within each module for bleak,
|
|
108
|
+
pybluez's bluetooth module, socket, and bluepy.btle. Discovery, bound client
|
|
109
|
+
connection, GATT operations, bound pybluez socket send/receive, native sockets
|
|
110
|
+
with an explicit wireless address family, and bluepy scans are recognized.
|
|
111
|
+
Assignments to names and self attributes and chained construction are supported.
|
|
112
|
+
Imports, object construction alone, strings, comments and docstrings do not count.
|
|
113
|
+
Production excludes tests, test filenames, fixtures, docs and examples;
|
|
114
|
+
symlink files and directories are skipped. Test evidence can only lower the
|
|
115
|
+
positive finding to MEDIUM. Documentation location does not soften the negative rule.
|
|
116
|
+
|
|
117
|
+
## Limitations
|
|
118
|
+
|
|
119
|
+
Only the exact templates above count. A bare wireless technology name, user
|
|
120
|
+
instructions for phone setup, headset audio routing, wired/USB/plain network
|
|
121
|
+
links and file exports are outside this audit's dimension. System wireless
|
|
122
|
+
helpers invoked by subprocess are not recognized; shell command strings alone
|
|
123
|
+
are not evidence. Analysis is static and module local, with no runtime reachability,
|
|
124
|
+
inter-module binding, dynamic import or general data-flow proof. Syntax errors
|
|
125
|
+
are reported as warnings and yield no evidence for that file. A PASS is a
|
|
126
|
+
consistency result for these templates and routes, not a hardware test.
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
"""Documentation matching and module-local static provider evidence."""
|
|
2
|
+
import argparse
|
|
3
|
+
import ast
|
|
4
|
+
import fnmatch
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
import re
|
|
9
|
+
import sys
|
|
10
|
+
|
|
11
|
+
from . import __version__
|
|
12
|
+
from .phrases import BLUETOOTH, NOBLUETOOTH
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def normalize(text):
|
|
16
|
+
return re.sub(r'\s+', ' ', text.lower().replace("n't", ' not').replace('-', ' '))
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def claims(text):
|
|
20
|
+
paragraphs = []
|
|
21
|
+
lines = []
|
|
22
|
+
fence = None
|
|
23
|
+
for line in text.splitlines():
|
|
24
|
+
match = re.match(r'^\s{0,3}(`{3,}|~{3,})(.*)$', line)
|
|
25
|
+
if fence:
|
|
26
|
+
if match and match[1][0] == fence[0] and len(match[1]) >= len(fence) and not match[2].strip():
|
|
27
|
+
fence = None
|
|
28
|
+
continue
|
|
29
|
+
if match:
|
|
30
|
+
fence = match[1]
|
|
31
|
+
paragraphs.append(' '.join(lines)); lines = []
|
|
32
|
+
elif not line.strip():
|
|
33
|
+
paragraphs.append(' '.join(lines)); lines = []
|
|
34
|
+
else:
|
|
35
|
+
lines.append(line)
|
|
36
|
+
paragraphs.append(' '.join(lines))
|
|
37
|
+
positive = negative = False
|
|
38
|
+
for paragraph in paragraphs:
|
|
39
|
+
value = normalize(paragraph)
|
|
40
|
+
for phrase in sorted(NOBLUETOOTH, key=len, reverse=True):
|
|
41
|
+
value, count = re.subn(r'\b' + re.escape(phrase) + r'\b', ' ', value)
|
|
42
|
+
negative |= bool(count)
|
|
43
|
+
positive |= any(re.search(r'\b' + re.escape(p) + r'\b', value) for p in BLUETOOTH)
|
|
44
|
+
return bool(positive), bool(negative)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def evidence(source):
|
|
48
|
+
tree = ast.parse(source)
|
|
49
|
+
aliases = {}
|
|
50
|
+
for node in ast.walk(tree):
|
|
51
|
+
if isinstance(node, ast.Import):
|
|
52
|
+
for item in node.names:
|
|
53
|
+
aliases[item.asname or item.name.split('.')[0]] = item.name if item.asname else item.name.split('.')[0]
|
|
54
|
+
elif isinstance(node, ast.ImportFrom) and node.module and not node.level:
|
|
55
|
+
for item in node.names:
|
|
56
|
+
aliases[item.asname or item.name] = node.module + '.' + item.name
|
|
57
|
+
|
|
58
|
+
def path(node):
|
|
59
|
+
if isinstance(node, ast.Name):
|
|
60
|
+
return aliases.get(node.id, node.id if node.id == 'self' else '')
|
|
61
|
+
if isinstance(node, ast.Attribute):
|
|
62
|
+
base = path(node.value)
|
|
63
|
+
return base + '.' + node.attr if base else ''
|
|
64
|
+
return ''
|
|
65
|
+
|
|
66
|
+
def provider(node, module, name):
|
|
67
|
+
value = path(node)
|
|
68
|
+
return value.startswith(module + '.') and value.split('.')[-1] == name
|
|
69
|
+
|
|
70
|
+
def constructed(node):
|
|
71
|
+
if not isinstance(node, ast.Call):
|
|
72
|
+
return None
|
|
73
|
+
for module, name, kind in [('bleak', 'BleakClient', 'bleak'), ('bleak', 'BleakScanner', 'scanner'), ('bluetooth', 'BluetoothSocket', 'pybluez'), ('bluepy.btle', 'Peripheral', 'peripheral'), ('bluepy.btle', 'Scanner', 'bluepy-scanner')]:
|
|
74
|
+
if provider(node.func, module, name):
|
|
75
|
+
return kind
|
|
76
|
+
if provider(node.func, 'socket', 'socket'):
|
|
77
|
+
if any(provider(arg, 'socket', 'AF_BLUETOOTH') for arg in list(node.args) + [kw.value for kw in node.keywords]):
|
|
78
|
+
return 'socket'
|
|
79
|
+
return None
|
|
80
|
+
|
|
81
|
+
def key(node):
|
|
82
|
+
if isinstance(node, ast.Name):
|
|
83
|
+
return node.id
|
|
84
|
+
if isinstance(node, ast.Attribute) and isinstance(node.value, ast.Name) and node.value.id == 'self':
|
|
85
|
+
return 'self.' + node.attr
|
|
86
|
+
return None
|
|
87
|
+
|
|
88
|
+
bindings = {}
|
|
89
|
+
for node in ast.walk(tree):
|
|
90
|
+
if isinstance(node, (ast.Assign, ast.AnnAssign)):
|
|
91
|
+
kind = constructed(node.value)
|
|
92
|
+
targets = node.targets if isinstance(node, ast.Assign) else [node.target]
|
|
93
|
+
if kind:
|
|
94
|
+
for target in targets:
|
|
95
|
+
if key(target):
|
|
96
|
+
bindings[key(target)] = kind
|
|
97
|
+
for node in ast.walk(tree):
|
|
98
|
+
if not isinstance(node, ast.Call):
|
|
99
|
+
continue
|
|
100
|
+
if provider(node.func, 'bluetooth', 'discover_devices'):
|
|
101
|
+
return True
|
|
102
|
+
if not isinstance(node.func, ast.Attribute):
|
|
103
|
+
continue
|
|
104
|
+
receiver = node.func.value
|
|
105
|
+
method = node.func.attr
|
|
106
|
+
kind = constructed(receiver) or bindings.get(key(receiver))
|
|
107
|
+
if method in ('discover', 'find_device') and (kind == 'scanner' or provider(receiver, 'bleak', 'BleakScanner')):
|
|
108
|
+
return True
|
|
109
|
+
if method == 'scan' and (kind == 'bluepy-scanner' or provider(receiver, 'bluepy.btle', 'Scanner')):
|
|
110
|
+
return True
|
|
111
|
+
methods = {'bleak': ('connect', 'read_gatt_char', 'write_gatt_char', 'start_notify', 'stop_notify'), 'pybluez': ('connect', 'send', 'recv'), 'socket': ('connect',), 'peripheral': ('connect',)}
|
|
112
|
+
if method in methods.get(kind, ()):
|
|
113
|
+
return True
|
|
114
|
+
return False
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def audit(root, ignore=(), fail_on='HIGH'):
|
|
118
|
+
root = Path(root)
|
|
119
|
+
if not root.is_dir():
|
|
120
|
+
raise ValueError('root must be an existing readable directory')
|
|
121
|
+
positive = negative = prod = test = False
|
|
122
|
+
counts = {'documents': 0, 'sources': 0}
|
|
123
|
+
warnings = []
|
|
124
|
+
def excluded(relative):
|
|
125
|
+
return any(fnmatch.fnmatchcase(relative, pattern) for pattern in ignore)
|
|
126
|
+
def onerror(error):
|
|
127
|
+
raise error
|
|
128
|
+
for directory, dirs, files in os.walk(root, onerror=onerror, followlinks=False):
|
|
129
|
+
dirs[:] = sorted(d for d in dirs if not (Path(directory) / d).is_symlink() and not excluded((Path(directory) / d).relative_to(root).as_posix()))
|
|
130
|
+
for name in sorted(files):
|
|
131
|
+
file = Path(directory) / name
|
|
132
|
+
relative = file.relative_to(root)
|
|
133
|
+
parts = relative.parts
|
|
134
|
+
if file.is_symlink() or excluded(relative.as_posix()):
|
|
135
|
+
continue
|
|
136
|
+
if relative.as_posix() == 'README.md' or (file.suffix.lower() == '.md' and 'docs' in parts[:-1]):
|
|
137
|
+
p, n = claims(file.read_text(encoding='utf-8'))
|
|
138
|
+
positive |= p; negative |= n
|
|
139
|
+
counts['documents'] += 1
|
|
140
|
+
if file.suffix != '.py' or any(p in ('fixtures', 'docs', 'examples') for p in parts[:-1]):
|
|
141
|
+
continue
|
|
142
|
+
counts['sources'] += 1
|
|
143
|
+
try:
|
|
144
|
+
found = evidence(file.read_text(encoding='utf-8'))
|
|
145
|
+
except (SyntaxError, UnicodeError) as error:
|
|
146
|
+
warnings.append('{}: {}'.format(relative, error)); continue
|
|
147
|
+
if 'tests' in parts[:-1] or name.startswith('test_') or name.endswith('_test.py'):
|
|
148
|
+
test |= found
|
|
149
|
+
else:
|
|
150
|
+
prod |= found
|
|
151
|
+
findings = []
|
|
152
|
+
if positive and not prod:
|
|
153
|
+
findings.append({'rule': 'documented-bluetooth-claim-false', 'severity': 'MEDIUM' if test else 'HIGH', 'message': 'Device claim has only test evidence.' if test else 'Device claim lacks production evidence.'})
|
|
154
|
+
if negative and prod:
|
|
155
|
+
findings.append({'rule': 'documented-no-bluetooth-claim-false', 'severity': 'HIGH', 'message': 'Negative device claim conflicts with production evidence.'})
|
|
156
|
+
failed = any(f['severity'] == 'HIGH' or fail_on == 'MEDIUM' for f in findings)
|
|
157
|
+
return {'verdict': 'FAIL' if failed else 'PASS', 'findings': findings, 'warnings': warnings, 'counts': counts}
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
class Parser(argparse.ArgumentParser):
|
|
161
|
+
def error(self, message):
|
|
162
|
+
self.print_usage(sys.stderr)
|
|
163
|
+
self.exit(1, '{}: error: {}\n'.format(self.prog, message))
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def main(argv=None):
|
|
167
|
+
parser = Parser(description=__doc__)
|
|
168
|
+
parser.add_argument('root')
|
|
169
|
+
parser.add_argument('--json', action='store_true')
|
|
170
|
+
parser.add_argument('--verbose', action='store_true')
|
|
171
|
+
parser.add_argument('--ignore', action='append', default=[])
|
|
172
|
+
parser.add_argument('--fail-on', choices=('HIGH', 'MEDIUM'), default='HIGH')
|
|
173
|
+
parser.add_argument('--version', action='version', version=__version__)
|
|
174
|
+
args = parser.parse_args(argv)
|
|
175
|
+
try:
|
|
176
|
+
result = audit(args.root, args.ignore, args.fail_on)
|
|
177
|
+
except (OSError, ValueError, UnicodeError) as error:
|
|
178
|
+
print(str(error), file=sys.stderr)
|
|
179
|
+
return 1
|
|
180
|
+
if args.json:
|
|
181
|
+
print(json.dumps(result))
|
|
182
|
+
else:
|
|
183
|
+
print(result['verdict'])
|
|
184
|
+
for finding in result['findings']:
|
|
185
|
+
print('{severity} {rule}: {message}'.format(**finding))
|
|
186
|
+
for warning in result['warnings']:
|
|
187
|
+
print('WARNING: ' + warning)
|
|
188
|
+
if args.verbose:
|
|
189
|
+
print(json.dumps(result['counts']))
|
|
190
|
+
return 2 if result['verdict'] == 'FAIL' else 0
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
"""Exact documentation templates."""
|
|
2
|
+
BLUETOOTH = ('connects to bluetooth devices', 'connect to bluetooth devices', 'connects to ble devices', 'connect to ble devices', 'connects via bluetooth', 'connect via bluetooth', 'connects over bluetooth', 'connect over bluetooth', 'pairs with bluetooth devices', 'pair with bluetooth devices', 'discovers bluetooth devices', 'discover bluetooth devices', 'discovers ble devices', 'discover ble devices', 'scans for bluetooth devices', 'scan for bluetooth devices', 'finds bluetooth devices', 'find bluetooth devices', 'sends data over bluetooth', 'send data over bluetooth', 'sends data via bluetooth', 'send data via bluetooth', 'transfers files over bluetooth', 'transfer files over bluetooth', 'transfers data over bluetooth', 'transfer data over bluetooth', 'communicates over bluetooth', 'communicate over bluetooth', 'communicates via bluetooth', 'communicate via bluetooth', 'supports bluetooth low energy', 'bluetooth low energy support', 'bluetooth file transfer', 'bluetooth data transfer', 'bluetooth connectivity', 'supports bluetooth', 'bluetooth support', 'supports ble', 'ble support', 'ble connectivity', 'uses bluetooth', 'use bluetooth')
|
|
3
|
+
NOBLUETOOTH = ('does not connect to bluetooth devices', 'does not connect via bluetooth', 'does not connect over bluetooth', 'does not pair with bluetooth devices', 'does not discover bluetooth devices', 'does not scan for bluetooth devices', 'does not send data over bluetooth', 'does not transfer files over bluetooth', 'does not communicate over bluetooth', 'does not communicate via bluetooth', 'does not support bluetooth low energy', 'does not support bluetooth', 'does not support ble', 'does not use bluetooth', 'bluetooth connectivity not supported', 'bluetooth not supported', 'ble not supported', 'no bluetooth support', 'without bluetooth support', 'no bluetooth connectivity', 'without bluetooth connectivity', 'no bluetooth', 'without bluetooth')
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: bluetooth-claim-audit
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Offline static audit of wireless device documentation against source
|
|
5
|
+
License: MIT
|
|
6
|
+
Requires-Python: >=3.9
|
|
7
|
+
Description-Content-Type: text/markdown
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Dynamic: license-file
|
|
10
|
+
|
|
11
|
+
# bluetooth-claim-audit
|
|
12
|
+
|
|
13
|
+
Version 0.1.0. Python >=3.9. MIT licensed. No runtime dependencies.
|
|
14
|
+
|
|
15
|
+
Checks documented wireless device claims against Python AST evidence offline.
|
|
16
|
+
Audited source is never executed. Environment files are never opened.
|
|
17
|
+
|
|
18
|
+
```sh
|
|
19
|
+
python3 -m pip install .
|
|
20
|
+
bluetooth-claim-audit path/to/project --json
|
|
21
|
+
python3 -m bluetooth_claim_audit path/to/project --verbose
|
|
22
|
+
python3 -m unittest discover
|
|
23
|
+
python3 -m build
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
Root README.md and Markdown beneath any docs directory supply claims. Fenced
|
|
27
|
+
code is excluded; inline code counts. Matching lowercases, expands n't, replaces
|
|
28
|
+
hyphens with spaces, joins paragraph lines, and applies word boundaries.
|
|
29
|
+
Negative spans are removed before positive matching. Exact templates follow:
|
|
30
|
+
|
|
31
|
+
```text
|
|
32
|
+
connects to bluetooth devices
|
|
33
|
+
connect to bluetooth devices
|
|
34
|
+
connects to ble devices
|
|
35
|
+
connect to ble devices
|
|
36
|
+
connects via bluetooth
|
|
37
|
+
connect via bluetooth
|
|
38
|
+
connects over bluetooth
|
|
39
|
+
connect over bluetooth
|
|
40
|
+
pairs with bluetooth devices
|
|
41
|
+
pair with bluetooth devices
|
|
42
|
+
discovers bluetooth devices
|
|
43
|
+
discover bluetooth devices
|
|
44
|
+
discovers ble devices
|
|
45
|
+
discover ble devices
|
|
46
|
+
scans for bluetooth devices
|
|
47
|
+
scan for bluetooth devices
|
|
48
|
+
finds bluetooth devices
|
|
49
|
+
find bluetooth devices
|
|
50
|
+
sends data over bluetooth
|
|
51
|
+
send data over bluetooth
|
|
52
|
+
sends data via bluetooth
|
|
53
|
+
send data via bluetooth
|
|
54
|
+
transfers files over bluetooth
|
|
55
|
+
transfer files over bluetooth
|
|
56
|
+
transfers data over bluetooth
|
|
57
|
+
transfer data over bluetooth
|
|
58
|
+
communicates over bluetooth
|
|
59
|
+
communicate over bluetooth
|
|
60
|
+
communicates via bluetooth
|
|
61
|
+
communicate via bluetooth
|
|
62
|
+
supports bluetooth low energy
|
|
63
|
+
bluetooth low energy support
|
|
64
|
+
bluetooth file transfer
|
|
65
|
+
bluetooth data transfer
|
|
66
|
+
bluetooth connectivity
|
|
67
|
+
supports bluetooth
|
|
68
|
+
bluetooth support
|
|
69
|
+
supports ble
|
|
70
|
+
ble support
|
|
71
|
+
ble connectivity
|
|
72
|
+
uses bluetooth
|
|
73
|
+
use bluetooth
|
|
74
|
+
does not connect to bluetooth devices
|
|
75
|
+
does not connect via bluetooth
|
|
76
|
+
does not connect over bluetooth
|
|
77
|
+
does not pair with bluetooth devices
|
|
78
|
+
does not discover bluetooth devices
|
|
79
|
+
does not scan for bluetooth devices
|
|
80
|
+
does not send data over bluetooth
|
|
81
|
+
does not transfer files over bluetooth
|
|
82
|
+
does not communicate over bluetooth
|
|
83
|
+
does not communicate via bluetooth
|
|
84
|
+
does not support bluetooth low energy
|
|
85
|
+
does not support bluetooth
|
|
86
|
+
does not support ble
|
|
87
|
+
does not use bluetooth
|
|
88
|
+
bluetooth connectivity not supported
|
|
89
|
+
bluetooth not supported
|
|
90
|
+
ble not supported
|
|
91
|
+
no bluetooth support
|
|
92
|
+
without bluetooth support
|
|
93
|
+
no bluetooth connectivity
|
|
94
|
+
without bluetooth connectivity
|
|
95
|
+
no bluetooth
|
|
96
|
+
without bluetooth
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
At most one finding per family is emitted. The positive rule is
|
|
100
|
+
`documented-bluetooth-claim-false`: HIGH without production evidence, MEDIUM
|
|
101
|
+
when evidence occurs only in tests. The negative rule is
|
|
102
|
+
|
|
103
|
+
```text
|
|
104
|
+
documented-no-bluetooth-claim-false
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
This rule is HIGH when production evidence exists.
|
|
108
|
+
No claim means PASS. Without source, positive claims fail and negative ones pass.
|
|
109
|
+
Default threshold HIGH reports MEDIUM without failing; `--fail-on MEDIUM`
|
|
110
|
+
fails on either severity. Exit codes: 0 PASS, 2 FAIL, 1 usage or root error.
|
|
111
|
+
`--json` emits verdict and findings (rule, severity, message); `--verbose`
|
|
112
|
+
adds scanned-file counts. Repeat `--ignore GLOB` to exclude relative paths.
|
|
113
|
+
`--version` prints 0.1.0. Both entry points accept these options.
|
|
114
|
+
|
|
115
|
+
## Evidence and scope
|
|
116
|
+
|
|
117
|
+
Provider imports and aliases are resolved within each module for bleak,
|
|
118
|
+
pybluez's bluetooth module, socket, and bluepy.btle. Discovery, bound client
|
|
119
|
+
connection, GATT operations, bound pybluez socket send/receive, native sockets
|
|
120
|
+
with an explicit wireless address family, and bluepy scans are recognized.
|
|
121
|
+
Assignments to names and self attributes and chained construction are supported.
|
|
122
|
+
Imports, object construction alone, strings, comments and docstrings do not count.
|
|
123
|
+
Production excludes tests, test filenames, fixtures, docs and examples;
|
|
124
|
+
symlink files and directories are skipped. Test evidence can only lower the
|
|
125
|
+
positive finding to MEDIUM. Documentation location does not soften the negative rule.
|
|
126
|
+
|
|
127
|
+
## Limitations
|
|
128
|
+
|
|
129
|
+
Only the exact templates above count. A bare wireless technology name, user
|
|
130
|
+
instructions for phone setup, headset audio routing, wired/USB/plain network
|
|
131
|
+
links and file exports are outside this audit's dimension. System wireless
|
|
132
|
+
helpers invoked by subprocess are not recognized; shell command strings alone
|
|
133
|
+
are not evidence. Analysis is static and module local, with no runtime reachability,
|
|
134
|
+
inter-module binding, dynamic import or general data-flow proof. Syntax errors
|
|
135
|
+
are reported as warnings and yield no evidence for that file. A PASS is a
|
|
136
|
+
consistency result for these templates and routes, not a hardware test.
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
MANIFEST.in
|
|
3
|
+
README.md
|
|
4
|
+
pyproject.toml
|
|
5
|
+
bluetooth_claim_audit/__init__.py
|
|
6
|
+
bluetooth_claim_audit/__main__.py
|
|
7
|
+
bluetooth_claim_audit/audit.py
|
|
8
|
+
bluetooth_claim_audit/phrases.py
|
|
9
|
+
bluetooth_claim_audit.egg-info/PKG-INFO
|
|
10
|
+
bluetooth_claim_audit.egg-info/SOURCES.txt
|
|
11
|
+
bluetooth_claim_audit.egg-info/dependency_links.txt
|
|
12
|
+
bluetooth_claim_audit.egg-info/entry_points.txt
|
|
13
|
+
bluetooth_claim_audit.egg-info/top_level.txt
|
|
14
|
+
tests/__init__.py
|
|
15
|
+
tests/cases.py
|
|
16
|
+
tests/test_audit.py
|
|
17
|
+
tests/fixtures/.env
|
|
18
|
+
tests/fixtures/bad/README.md
|
|
19
|
+
tests/fixtures/bad/app.py
|
|
20
|
+
tests/fixtures/good/README.md
|
|
21
|
+
tests/fixtures/good/app.py
|
|
22
|
+
tests/fixtures/no-bluetooth/README.md
|
|
23
|
+
tests/fixtures/no-bluetooth/app.py
|
|
24
|
+
tests/fixtures/testonly/README.md
|
|
25
|
+
tests/fixtures/testonly/tests/test_device.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
bluetooth_claim_audit
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=61"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "bluetooth-claim-audit"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Offline static audit of wireless device documentation against source"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.9"
|
|
11
|
+
license = {text = "MIT"}
|
|
12
|
+
|
|
13
|
+
[project.scripts]
|
|
14
|
+
bluetooth-claim-audit = "bluetooth_claim_audit.audit:main"
|
|
15
|
+
|
|
16
|
+
[tool.setuptools.packages.find]
|
|
17
|
+
include = ["bluetooth_claim_audit*"]
|
|
File without changes
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
GOOD = [
|
|
2
|
+
'from bleak import BleakScanner\nBleakScanner.discover()',
|
|
3
|
+
'from bleak import BleakClient\nc=BleakClient(address)\nc.connect()',
|
|
4
|
+
'import bleak as bk\nbk.BleakScanner.discover()',
|
|
5
|
+
'from bleak import BleakClient\nc=BleakClient(address)\nc.read_gatt_char(uuid)',
|
|
6
|
+
'from bluetooth import discover_devices\ndiscover_devices()',
|
|
7
|
+
'from bluetooth import BluetoothSocket\ns=BluetoothSocket()\ns.connect(address)',
|
|
8
|
+
'import socket\ns=socket.socket(socket.AF_BLUETOOTH,socket.SOCK_STREAM)\ns.connect(address)',
|
|
9
|
+
'from socket import socket, AF_BLUETOOTH\ns=socket(AF_BLUETOOTH)\ns.connect(address)',
|
|
10
|
+
'from bluepy.btle import Scanner\nScanner().scan()',
|
|
11
|
+
'from bluepy.btle import Peripheral\np=Peripheral()\np.connect(address)',
|
|
12
|
+
'from bleak.backends import BleakScanner as S\nS.find_device()',
|
|
13
|
+
'from bleak import BleakClient as C\nself.c=C(address)\nself.c.start_notify(uuid)',
|
|
14
|
+
'from bleak import BleakClient\nBleakClient(address).write_gatt_char(uuid,data)',
|
|
15
|
+
'from bleak import BleakClient\nc=BleakClient(address)\nc.stop_notify(uuid)',
|
|
16
|
+
'import bluetooth as bt\nbt.discover_devices()',
|
|
17
|
+
'from bluetooth import BluetoothSocket as S\nself.s=S()\nself.s.send(data)',
|
|
18
|
+
'import bluetooth\nbluetooth.BluetoothSocket().recv(100)',
|
|
19
|
+
'import socket as sk\nsk.socket(family=sk.AF_BLUETOOTH).connect(address)',
|
|
20
|
+
'from socket import socket as S, AF_BLUETOOTH as F\nself.s=S(F)\nself.s.connect(address)',
|
|
21
|
+
'import bluepy.btle as bt\nbt.Scanner().scan()',
|
|
22
|
+
'import bluepy.btle\nbluepy.btle.Peripheral().connect(address)',
|
|
23
|
+
'from bluepy.btle import Peripheral as P\nself.p=P()\nself.p.connect(address)',
|
|
24
|
+
]
|
|
25
|
+
BAD = [
|
|
26
|
+
'print("offline")', 'import bleak', 'import bluetooth', 'import bluepy.btle',
|
|
27
|
+
'from bleak import BleakClient\nc=BleakClient(address)',
|
|
28
|
+
'from bluetooth import BluetoothSocket\ns=BluetoothSocket()',
|
|
29
|
+
'from bluepy.btle import Peripheral\np=Peripheral()',
|
|
30
|
+
'from bleak import BleakScanner\nBleakScanner()',
|
|
31
|
+
'from bluepy.btle import Scanner\nScanner()',
|
|
32
|
+
'import socket\ns=socket.socket()\ns.connect(address)',
|
|
33
|
+
'import socket\ns=socket.socket(socket.AF_INET)\ns.connect(address)',
|
|
34
|
+
'import socket\ns=socket.socket(family)\ns.connect(address)',
|
|
35
|
+
'x.connect(address)', 'x.read_gatt_char(uuid)', 'x.send(data)',
|
|
36
|
+
'address="AA:BB:CC:DD:EE:FF bluetooth"',
|
|
37
|
+
'import subprocess\nsubprocess.run(["bluetoothctl"])',
|
|
38
|
+
'import subprocess\nsubprocess.run(["hcitool"])',
|
|
39
|
+
'import subprocess\nsubprocess.run(["hciconfig"])',
|
|
40
|
+
'def connect_device():\n print("connect")\n return True',
|
|
41
|
+
'@app.get("/connect")\ndef route():\n return True',
|
|
42
|
+
'@app.post("/connect")\ndef route():\n return True',
|
|
43
|
+
'"""BleakScanner.discover()"""',
|
|
44
|
+
'from other import BleakScanner\nBleakScanner.discover()',
|
|
45
|
+
'from other import discover_devices\ndiscover_devices()',
|
|
46
|
+
'import socket\ns=socket.socket(socket.AF_BLUETOOTH)',
|
|
47
|
+
]
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
# marker only
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
connects to bluetooth devices
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
print("offline")
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
connects to bluetooth devices
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
does not connect to bluetooth devices
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
connects to bluetooth devices
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
import contextlib
|
|
2
|
+
import io
|
|
3
|
+
import json
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
import re
|
|
6
|
+
import subprocess
|
|
7
|
+
import sys
|
|
8
|
+
import tempfile
|
|
9
|
+
import unittest
|
|
10
|
+
from unittest.mock import patch
|
|
11
|
+
|
|
12
|
+
from bluetooth_claim_audit import __version__
|
|
13
|
+
from bluetooth_claim_audit.audit import audit, claims, evidence, main
|
|
14
|
+
from bluetooth_claim_audit.phrases import BLUETOOTH, NOBLUETOOTH
|
|
15
|
+
from tests.cases import GOOD, BAD
|
|
16
|
+
|
|
17
|
+
ROOT = Path(__file__).resolve().parents[1]
|
|
18
|
+
FIXTURES = ROOT / 'tests' / 'fixtures'
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class AuditTests(unittest.TestCase):
|
|
22
|
+
def project(self, doc, code=None, filename='app.py'):
|
|
23
|
+
temp = tempfile.TemporaryDirectory(dir=ROOT)
|
|
24
|
+
self.addCleanup(temp.cleanup)
|
|
25
|
+
path = Path(temp.name)
|
|
26
|
+
(path / 'README.md').write_text(doc)
|
|
27
|
+
if code is not None:
|
|
28
|
+
file = path / filename
|
|
29
|
+
file.parent.mkdir(parents=True, exist_ok=True)
|
|
30
|
+
file.write_text(code)
|
|
31
|
+
return path
|
|
32
|
+
|
|
33
|
+
def test_fixtures(self):
|
|
34
|
+
for name, severity, rule in [('good', None, None), ('bad', 'HIGH', 'documented-bluetooth-claim-false'), ('testonly', 'MEDIUM', 'documented-bluetooth-claim-false'), ('no-bluetooth', 'HIGH', 'documented-no-bluetooth-claim-false')]:
|
|
35
|
+
with self.subTest(name=name):
|
|
36
|
+
result = audit(FIXTURES / name)
|
|
37
|
+
self.assertEqual(len(result['findings']), int(severity is not None))
|
|
38
|
+
if severity:
|
|
39
|
+
self.assertEqual(result['findings'][0]['severity'], severity)
|
|
40
|
+
self.assertEqual(result['findings'][0]['rule'], rule)
|
|
41
|
+
self.assertEqual(result['verdict'], 'FAIL' if severity == 'HIGH' else 'PASS')
|
|
42
|
+
self.assertEqual(audit(FIXTURES / 'testonly', fail_on='MEDIUM')['verdict'], 'FAIL')
|
|
43
|
+
|
|
44
|
+
def test_self_audit(self):
|
|
45
|
+
self.assertEqual(claims((ROOT / 'README.md').read_text()), (False, False))
|
|
46
|
+
self.assertEqual(audit(ROOT)['findings'], [])
|
|
47
|
+
|
|
48
|
+
def test_env_never_opened(self):
|
|
49
|
+
original = io.open
|
|
50
|
+
def guarded(file, *args, **kwargs):
|
|
51
|
+
if isinstance(file, (str, Path)) and Path(file).name == '.env':
|
|
52
|
+
self.fail('Environment marker opened')
|
|
53
|
+
return original(file, *args, **kwargs)
|
|
54
|
+
with patch('io.open', guarded):
|
|
55
|
+
self.assertTrue((FIXTURES / '.env').exists())
|
|
56
|
+
audit(ROOT)
|
|
57
|
+
audit(FIXTURES)
|
|
58
|
+
|
|
59
|
+
def test_normalization(self):
|
|
60
|
+
self.assertEqual(claims("This CONNECTS-TO\nBLUETOOTH devices."), (True, False))
|
|
61
|
+
self.assertEqual(claims("It doesn't connect via bluetooth."), (False, True))
|
|
62
|
+
self.assertEqual(claims('xconnect via bluetoothx'), (False, False))
|
|
63
|
+
self.assertEqual(claims('connect via\n\nbluetooth'), (False, False))
|
|
64
|
+
|
|
65
|
+
def test_fences_inline(self):
|
|
66
|
+
for fence in ('```', '~~~~'):
|
|
67
|
+
self.assertEqual(claims(fence+'text\n'+BLUETOOTH[0]+'\n'+fence), (False, False))
|
|
68
|
+
self.assertEqual(claims('`'+BLUETOOTH[0]+'`'), (True, False))
|
|
69
|
+
|
|
70
|
+
def test_nonclaims(self):
|
|
71
|
+
for text in ['bluetooth', 'turn on bluetooth on your phone first', 'enable bluetooth on your phone before starting', 'plays audio over bluetooth', 'listens through bluetooth headphones', 'USB link and TCP file export']:
|
|
72
|
+
self.assertEqual(audit(self.project(text))['findings'], [])
|
|
73
|
+
self.assertEqual(audit(self.project(text, GOOD[0]))['findings'], [])
|
|
74
|
+
|
|
75
|
+
def test_no_source(self):
|
|
76
|
+
self.assertEqual(audit(self.project(BLUETOOTH[0]))['findings'][0]['severity'], 'HIGH')
|
|
77
|
+
self.assertEqual(audit(self.project(NOBLUETOOTH[0]))['findings'], [])
|
|
78
|
+
|
|
79
|
+
def test_two_families_maximum(self):
|
|
80
|
+
path = self.project('\n\n'.join(BLUETOOTH + NOBLUETOOTH))
|
|
81
|
+
self.assertEqual(len(audit(path)['findings']), 1)
|
|
82
|
+
(path / 'app.py').write_text(GOOD[0])
|
|
83
|
+
self.assertEqual(len(audit(path)['findings']), 1)
|
|
84
|
+
self.assertEqual(audit(path)['findings'][0]['rule'], 'documented-no-bluetooth-claim-false')
|
|
85
|
+
|
|
86
|
+
def test_scopes(self):
|
|
87
|
+
for filename in ['tests/device.py', 'test_device.py', 'device_test.py']:
|
|
88
|
+
result = audit(self.project(BLUETOOTH[0], GOOD[0], filename))
|
|
89
|
+
self.assertEqual(result['findings'][0]['severity'], 'MEDIUM')
|
|
90
|
+
for filename in ['docs/device.py', 'examples/device.py', 'fixtures/device.py']:
|
|
91
|
+
self.assertEqual(audit(self.project(BLUETOOTH[0], GOOD[0], filename))['findings'][0]['severity'], 'HIGH')
|
|
92
|
+
|
|
93
|
+
def test_docs_and_ignore(self):
|
|
94
|
+
path = self.project('overview')
|
|
95
|
+
(path / 'nested/docs').mkdir(parents=True)
|
|
96
|
+
(path / 'nested/docs/claim.md').write_text(BLUETOOTH[0])
|
|
97
|
+
self.assertEqual(audit(path)['verdict'], 'FAIL')
|
|
98
|
+
self.assertEqual(audit(path, ['nested/docs/*.md'])['verdict'], 'PASS')
|
|
99
|
+
self.assertEqual(audit(path, ['nested'])['verdict'], 'PASS')
|
|
100
|
+
|
|
101
|
+
def test_symlinks(self):
|
|
102
|
+
path = self.project(BLUETOOTH[0])
|
|
103
|
+
(path / 'app.py').symlink_to(FIXTURES / 'good/app.py')
|
|
104
|
+
(path / 'linked').symlink_to(FIXTURES / 'good', target_is_directory=True)
|
|
105
|
+
self.assertEqual(audit(path)['verdict'], 'FAIL')
|
|
106
|
+
|
|
107
|
+
def test_cross_module(self):
|
|
108
|
+
path = self.project(BLUETOOTH[0], 'from bleak import BleakClient\nc=BleakClient(address)')
|
|
109
|
+
(path / 'second.py').write_text('c.connect(address)')
|
|
110
|
+
self.assertEqual(audit(path)['verdict'], 'FAIL')
|
|
111
|
+
|
|
112
|
+
def test_syntax_warning(self):
|
|
113
|
+
result = audit(self.project(BLUETOOTH[0], 'invalid !!!'))
|
|
114
|
+
self.assertEqual(result['verdict'], 'FAIL')
|
|
115
|
+
self.assertEqual(len(result['warnings']), 1)
|
|
116
|
+
|
|
117
|
+
def test_cli(self):
|
|
118
|
+
for argv, expected in [(['--version'], 0), (['/absent/path'], 1), ([], 1), ([str(FIXTURES/'bad'), '--fail-on', 'LOW'], 1)]:
|
|
119
|
+
with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()):
|
|
120
|
+
try:
|
|
121
|
+
code = main(argv)
|
|
122
|
+
except SystemExit as error:
|
|
123
|
+
code = error.code
|
|
124
|
+
self.assertEqual(code, expected)
|
|
125
|
+
for name, threshold, code in [('good','HIGH',0),('bad','HIGH',2),('testonly','HIGH',0),('testonly','MEDIUM',2),('no-bluetooth','HIGH',2)]:
|
|
126
|
+
proc = subprocess.run([sys.executable, '-m', 'bluetooth_claim_audit', str(FIXTURES/name), '--json', '--fail-on', threshold], capture_output=True, text=True)
|
|
127
|
+
self.assertEqual(proc.returncode, code, proc.stderr)
|
|
128
|
+
self.assertIn(json.loads(proc.stdout)['verdict'], ('PASS','FAIL'))
|
|
129
|
+
with contextlib.redirect_stdout(io.StringIO()) as output:
|
|
130
|
+
self.assertEqual(main([str(FIXTURES/'bad'), '--ignore', 'README.md', '--verbose']), 0)
|
|
131
|
+
self.assertIn('documents', output.getvalue())
|
|
132
|
+
|
|
133
|
+
def test_packaging(self):
|
|
134
|
+
self.assertEqual(__version__, '0.1.0')
|
|
135
|
+
config = (ROOT/'pyproject.toml').read_text()
|
|
136
|
+
self.assertIn('bluetooth-claim-audit = "bluetooth_claim_audit.audit:main"', config)
|
|
137
|
+
self.assertIn('requires-python = ">=3.9"', config)
|
|
138
|
+
self.assertIn('MIT License', (ROOT/'LICENSE').read_text())
|
|
139
|
+
self.assertIn('recursive-include tests', (ROOT/'MANIFEST.in').read_text())
|
|
140
|
+
for file in list((ROOT/'bluetooth_claim_audit').glob('*.py')) + [ROOT/'README.md']:
|
|
141
|
+
text = file.read_text()
|
|
142
|
+
self.assertIsNone(re.search(r'(?<![\w-])python\s+(?:-m|[^\s]*\.py)', text))
|
|
143
|
+
self.assertIsNone(re.search(r'(?:AKIA[0-9A-Z]{16}|-----BEGIN PRIVATE KEY-----)', text))
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def add_case(name, function):
|
|
147
|
+
function.__name__ = name
|
|
148
|
+
setattr(AuditTests, name, function)
|
|
149
|
+
|
|
150
|
+
for index, source in enumerate(GOOD):
|
|
151
|
+
def check(self, source=source):
|
|
152
|
+
self.assertTrue(evidence(source))
|
|
153
|
+
self.assertEqual(audit(self.project(BLUETOOTH[0], source))['findings'], [])
|
|
154
|
+
add_case('test_good_route_%02d' % index, check)
|
|
155
|
+
for index, source in enumerate(BAD):
|
|
156
|
+
def check(self, source=source):
|
|
157
|
+
self.assertFalse(evidence(source))
|
|
158
|
+
result = audit(self.project(BLUETOOTH[0], source))
|
|
159
|
+
self.assertEqual(result['verdict'], 'FAIL')
|
|
160
|
+
self.assertEqual([(f['rule'], f['severity']) for f in result['findings']], [('documented-bluetooth-claim-false', 'HIGH')])
|
|
161
|
+
add_case('test_bad_route_%02d' % index, check)
|
|
162
|
+
for index, phrase in enumerate(BLUETOOTH):
|
|
163
|
+
def check(self, phrase=phrase):
|
|
164
|
+
self.assertEqual(claims(phrase), (True, False))
|
|
165
|
+
self.assertEqual(audit(self.project(phrase))['verdict'], 'FAIL')
|
|
166
|
+
add_case('test_positive_phrase_%02d' % index, check)
|
|
167
|
+
for index, phrase in enumerate(NOBLUETOOTH):
|
|
168
|
+
def check(self, phrase=phrase):
|
|
169
|
+
self.assertEqual(claims(phrase), (False, True))
|
|
170
|
+
self.assertEqual(audit(self.project(phrase))['findings'], [])
|
|
171
|
+
result = audit(self.project(phrase, GOOD[0]))
|
|
172
|
+
self.assertEqual([(f['rule'], f['severity']) for f in result['findings']], [('documented-no-bluetooth-claim-false', 'HIGH')])
|
|
173
|
+
add_case('test_negative_phrase_%02d' % index, check)
|