websocket-claim-audit 0.1.0__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,190 @@
1
+ """Offline documentation and AST audit."""
2
+ import argparse
3
+ import ast
4
+ import fnmatch
5
+ import json
6
+ import re
7
+ from pathlib import Path
8
+
9
+ __version__ = '0.1.0'
10
+ WS_MODULES = {'websockets', 'websocket', 'websocket_client'}
11
+ POSITIVE = [
12
+ 'websocket support', 'web socket support', 'websocket connections',
13
+ 'web socket connections', 'websocket connection', 'web socket connection',
14
+ 'websocket server', 'web socket server', 'websocket client', 'web socket client',
15
+ 'websocket api', 'websocket endpoint', 'websocket endpoints',
16
+ 'supports websockets', 'supports web sockets', 'supports websocket',
17
+ 'support for websockets', 'support for web sockets', 'support for websocket',
18
+ 'uses websockets', 'uses web sockets', 'uses websocket',
19
+ 'using websockets', 'using web sockets', 'using websocket',
20
+ 'over websockets', 'over web sockets', 'over websocket',
21
+ 'via websockets', 'via web sockets', 'via websocket',
22
+ 'websocket based', 'websocket powered',
23
+ ]
24
+ NEGATIVE = [
25
+ 'no websocket support', 'no web socket support',
26
+ 'does not support websockets', 'does not support web sockets',
27
+ 'does not support websocket', 'does not use websockets',
28
+ 'does not use web sockets', 'does not use websocket',
29
+ 'websocket not supported', 'web socket not supported',
30
+ 'without websockets', 'without web sockets', 'without websocket',
31
+ 'no websockets', 'no web sockets', 'no websocket',
32
+ ]
33
+
34
+
35
+ def pattern(phrases):
36
+ return re.compile(r'\b(?:' + '|'.join(re.escape(p) for p in sorted(phrases, key=len, reverse=True)) + r')\b')
37
+
38
+
39
+ def claims(text):
40
+ lines = []
41
+ fence = None
42
+ for line in text.splitlines():
43
+ match = re.match(r'^\s{0,3}(`{3,}|~{3,})', line)
44
+ if fence:
45
+ if re.match(r'^\s{0,3}' + re.escape(fence[0]) + '{' + str(fence[1]) + r',}\s*$', line):
46
+ fence = None
47
+ lines.append('')
48
+ elif match:
49
+ fence = (match[1][0], len(match[1]))
50
+ lines.append('')
51
+ else:
52
+ lines.append(line)
53
+ positive = negative = False
54
+ for paragraph in re.split(r'\n\s*\n', '\n'.join(lines)):
55
+ normalized = re.sub(r'\s+', ' ', paragraph.lower().replace("n't", ' not').replace('-', ' '))
56
+ negative |= bool(pattern(NEGATIVE).search(normalized))
57
+ normalized = pattern(NEGATIVE).sub(' ', normalized)
58
+ positive |= bool(pattern(POSITIVE).search(normalized))
59
+ return positive, negative
60
+
61
+
62
+ def evidence(text):
63
+ tree = ast.parse(text)
64
+ imports = {}
65
+ for node in ast.walk(tree):
66
+ if isinstance(node, ast.Import):
67
+ for alias in node.names:
68
+ imports[alias.asname or alias.name.split('.')[0]] = alias.name
69
+ elif isinstance(node, ast.ImportFrom) and node.module and not node.level:
70
+ for alias in node.names:
71
+ imports[alias.asname or alias.name] = node.module + '.' + alias.name
72
+
73
+ def resolved(node):
74
+ if isinstance(node, ast.Name):
75
+ return imports.get(node.id, '')
76
+ if isinstance(node, ast.Attribute):
77
+ base = resolved(node.value)
78
+ return base + '.' + node.attr if base else ''
79
+ return ''
80
+
81
+ calls = [n for n in ast.walk(tree) if isinstance(n, ast.Call)]
82
+ methods = {n.func.attr for n in calls if isinstance(n.func, ast.Attribute)}
83
+ for call in calls:
84
+ func = call.func
85
+ if (isinstance(func, ast.Attribute) and isinstance(func.value, ast.Name)
86
+ and func.attr in {'serve', 'connect', 'create_connection'}
87
+ and imports.get(func.value.id, '').split('.')[0] in WS_MODULES):
88
+ return 'A'
89
+ for node in ast.walk(tree):
90
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
91
+ args = node.args.posonlyargs + node.args.args + node.args.kwonlyargs
92
+ args += [a for a in (node.args.vararg, node.args.kwarg) if a]
93
+ for arg in args:
94
+ annotation = arg.annotation
95
+ name = annotation.id if isinstance(annotation, ast.Name) else annotation.attr if isinstance(annotation, ast.Attribute) else ''
96
+ if name == 'WebSocket':
97
+ for child in ast.walk(node):
98
+ if (isinstance(child, ast.Call) and isinstance(child.func, ast.Attribute)
99
+ and child.func.attr == 'accept' and isinstance(child.func.value, ast.Name)
100
+ and child.func.value.id == arg.arg):
101
+ return 'B'
102
+ for call in calls:
103
+ name = resolved(call.func)
104
+ module, _, cls = name.rpartition('.')
105
+ root = module.split('.')[0]
106
+ if cls == 'WebSocketApp' and root in WS_MODULES and 'run_forever' in methods:
107
+ return 'C'
108
+ if cls == 'WebSocketResponse' and root == 'aiohttp' and 'prepare' in methods:
109
+ return 'C'
110
+ if cls in {'Server', 'AsyncServer'} and root == 'socketio' and methods & {'emit', 'send', 'on'}:
111
+ return 'C'
112
+ if ((cls == 'WebsocketServer' and root == 'websocket_server') or
113
+ (cls == 'SimpleWebSocketServer' and root == 'SimpleWebSocketServer')) and methods & {'serve_forever', 'run_forever'}:
114
+ return 'C'
115
+ return None
116
+
117
+
118
+ def audit(root, ignore=(), fail_on='HIGH'):
119
+ root = Path(root)
120
+ if not root.is_dir() or not root.stat().st_mode & 0o444:
121
+ raise ValueError('root must be a readable directory')
122
+ positive = negative = False
123
+ production = []
124
+ testing = []
125
+ errors = []
126
+ for path in sorted(root.rglob('*')):
127
+ if path.is_symlink() or any(parent.is_symlink() for parent in path.parents if parent != root.parent):
128
+ continue
129
+ relative = path.relative_to(root)
130
+ name = relative.as_posix()
131
+ if any(fnmatch.fnmatchcase(name, glob) for glob in ignore):
132
+ continue
133
+ if not path.is_file():
134
+ continue
135
+ if (name == 'README.md' or ('docs' in relative.parts[:-1] and path.suffix.lower() == '.md')):
136
+ p, n = claims(path.read_text(encoding='utf-8'))
137
+ positive |= p
138
+ negative |= n
139
+ if path.suffix != '.py':
140
+ continue
141
+ is_test = 'tests' in relative.parts[:-1] or path.name.startswith('test_') or path.name.endswith('_test.py')
142
+ if {'fixtures', 'docs', 'examples'} & set(relative.parts[:-1]):
143
+ continue
144
+ try:
145
+ route = evidence(path.read_text(encoding='utf-8'))
146
+ except (SyntaxError, UnicodeError) as exc:
147
+ errors.append(name + ': ' + str(exc))
148
+ continue
149
+ if route:
150
+ (testing if is_test else production).append({'path': name, 'route': route})
151
+ findings = []
152
+ if positive and not production:
153
+ findings.append({'rule': 'documented-websocket-claim-false', 'severity': 'MEDIUM' if testing else 'HIGH', 'message': 'Documented live socket link lacks production evidence.'})
154
+ if negative and production:
155
+ findings.append({'rule': 'documented-no-websocket-claim-false', 'severity': 'HIGH', 'message': 'Documented absence 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,
158
+ 'claims': {'positive': positive, 'negative': negative},
159
+ 'evidence': production, 'test_evidence': testing, 'parse_errors': errors}
160
+
161
+
162
+ def main(argv=None):
163
+ class Parser(argparse.ArgumentParser):
164
+ def error(self, message):
165
+ self.print_usage()
166
+ self.exit(1, message + '\n')
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) as exc:
178
+ parser.exit(1, str(exc) + '\n')
179
+ if args.json:
180
+ print(json.dumps(result))
181
+ else:
182
+ print(result['verdict'])
183
+ for finding in result['findings']:
184
+ print('{severity} {rule}: {message}'.format(**finding))
185
+ if args.verbose:
186
+ for item in result['evidence'] + result['test_evidence']:
187
+ print('Evidence {path}: route {route}'.format(**item))
188
+ for error in result['parse_errors']:
189
+ print('Parse error: ' + error)
190
+ return 2 if result['verdict'] == 'FAIL' else 0
@@ -0,0 +1,3 @@
1
+ from . import main
2
+
3
+ raise SystemExit(main())
@@ -0,0 +1,40 @@
1
+ Metadata-Version: 2.4
2
+ Name: websocket-claim-audit
3
+ Version: 0.1.0
4
+ Summary: Offline static audit of documented framed socket capabilities
5
+ License-Expression: MIT
6
+ Requires-Python: >=3.9
7
+ Description-Content-Type: text/markdown
8
+ License-File: LICENSE
9
+ Dynamic: license-file
10
+
11
+ # websocket-claim-audit
12
+
13
+ Offline, standard-library-only audit of documented framed socket capabilities against Python AST evidence. Version 0.1.0, Python 3.9 or later.
14
+
15
+ Install and run:
16
+
17
+ ```sh
18
+ python3 -m pip install .
19
+ websocket-claim-audit /path/to/project --json
20
+ python3 -m websocket_claim_audit /path/to/project --verbose
21
+ python3 -m unittest discover -s tests -v
22
+ python3 -m build
23
+ ```
24
+
25
+ The scanner reads root README.md and Markdown files with a docs path component. It excludes fenced blocks, counts inline code, joins paragraph lines, lowercases text, expands contractions, and converts hyphens to spaces. Negative spans are removed before positive matching. Exact word-boundary templates alone count; the complete template lists are in the package's POSITIVE and NEGATIVE constants.
26
+
27
+ Production evidence comes from alias-resolved library calls, annotated parameters that accept a channel, or paired object creation and activation calls in the same module. Source is parsed, never executed. Tests, fixtures, documentation, examples, and symlinked files are excluded from production evidence. Evidence confined to tests produces a MEDIUM finding. Environment files are never read.
28
+
29
+ Options: `--json` emits a JSON object with verdict, findings, claim flags, evidence paths and routes, and parse errors. `--verbose` lists evidence in human output. Repeat `--ignore GLOB` to exclude root-relative paths. `--fail-on HIGH` is the default; `--fail-on MEDIUM` also fails on MEDIUM findings. `--version` prints the version. Exit 0 means PASS, 2 means findings meet the threshold, and 1 means a usage or root access error.
30
+
31
+ Rule identifiers:
32
+
33
+ ```text
34
+ documented-websocket-claim-false
35
+ documented-no-websocket-claim-false
36
+ ```
37
+
38
+ ## Limitations
39
+
40
+ Only the exact phrase templates in the constants count as claims. Bare websocket, web socket, socket, live, real time, and real-time words do not count. HTTP polling, TCP sockets, HTTP hooks, and chunked output do not establish a framed socket channel. Imports, names, comments, docstrings, decorators alone, and string literals are insufficient evidence. Static patterns cannot prove runtime behavior. Paired calls need only share a module; they need not share a receiver. Invalid source is reported in parse_errors and supplies no evidence. A positive promise without source fails; a negative promise without source passes. Each family yields at most one finding. This repository deliberately describes the audit using paraphrases so its own prose contains no audited claim.
@@ -0,0 +1,8 @@
1
+ websocket_claim_audit/__init__.py,sha256=H8Su9IOxlTDCtTJgi89boecQGgSfHoSWrP4NBG0fVkc,8692
2
+ websocket_claim_audit/__main__.py,sha256=BHLi_-4Bx1gsZn-z6x7wECPn1YTxdc74y0deRea9FzY,45
3
+ websocket_claim_audit-0.1.0.dist-info/licenses/LICENSE,sha256=YkGyeCIzttB-v5pzVNJNcIb0vPhfZ1u8sLV0rWkibM4,1091
4
+ websocket_claim_audit-0.1.0.dist-info/METADATA,sha256=SLQ0JlG9RRhU0XeWLYYOitmdGs22DVuHeXJCaHw3N3k,2778
5
+ websocket_claim_audit-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
6
+ websocket_claim_audit-0.1.0.dist-info/entry_points.txt,sha256=hGjXn2SBdimrf_w7Rh0Ou_4XuIM1NDhXiSlY4wNtb58,69
7
+ websocket_claim_audit-0.1.0.dist-info/top_level.txt,sha256=wtWg8axkV7cBu4Bq-PhIV2rF0tmlBB91ZFCZAcMOjXo,22
8
+ websocket_claim_audit-0.1.0.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,2 @@
1
+ [console_scripts]
2
+ websocket-claim-audit = websocket_claim_audit:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 websocket-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 @@
1
+ websocket_claim_audit