am-freescan/scripts/verify_http_boundaries.py

107 lines
5.3 KiB
Python
Raw Normal View History

"""Read-only/invalid-input HTTP exploration against the local AM FreeScan service.
No business fixture, role, user or scanner command is created. Authenticated
requests are restricted to reads or the scanner's validation-only endpoint.
Credentials/tokens and raw response bodies are never written to the report.
"""
import json
from pathlib import Path
import urllib.error
import urllib.request
from verify_cmvr_native import Client, require
ROOT = Path(__file__).resolve().parents[1]
MISSING = '9223372036854775806'
def run():
client = Client().login()
checks = []
def check(name, method, path, *, body=None, authenticated=True,
headers=None, expected=(400, 401, 403, 404, 405, 415)):
require(method == 'GET' or not authenticated or path == '/cmvr/scanner/validate',
'Only anonymous writes or validation-only authenticated writes are permitted')
request_headers = {'tenant-id': '1', 'Accept': 'application/json'}
if authenticated:
request_headers['Authorization'] = 'Bearer ' + client._token
if body is not None:
request_headers['Content-Type'] = 'application/json'
request_headers.update(headers or {})
request = urllib.request.Request(client.base_url + '/admin-api' + path, method=method,
data=body, headers=request_headers)
try:
response = urllib.request.urlopen(request, timeout=15)
except urllib.error.HTTPError as error:
response = error
with response:
status, raw = response.status, response.read(1024 * 1024)
try:
result = json.loads(raw)
code = result.get('code')
except (ValueError, AttributeError):
code = None
ok = code in expected and status < 500
checks.append(dict(name=name, method=method, path=path, httpStatus=status,
code=code, passed=ok))
print(('PASS ' if ok else 'FAIL ') + name + ' code=' + str(code), flush=True)
anonymous = [
('GET', '/lab/master/sample/page?pageNo=1&pageSize=1'),
('GET', '/lab/task/page?pageNo=1&pageSize=1'),
('GET', '/lab/execution/page?pageNo=1&pageSize=1'),
('GET', '/lab/document/report/page?pageNo=1&pageSize=1'),
('GET', '/lab/scan-task/resource-occupations'),
('GET', '/lab/execution/scanner-view?executionId=' + MISSING),
('GET', '/cmvr/scanner/configuration'),
('GET', '/cmvr/test/inst/log/detail?instId=' + 'a' * 32),
('POST', '/cmvr/scanner/scan/start'),
('POST', '/lab/scan-task/start-unit'),
('POST', '/lab/document/report/create'),
('PUT', '/lab/scan-task/prepare'),
('DELETE', '/lab/master/sample/delete?id=' + MISSING),
]
for method, path in anonymous:
check('anonymous rejected: ' + method + ' ' + path.split('?')[0], method, path,
body=b'{}' if method in ('POST', 'PUT') else None, authenticated=False, expected=(401,))
for token in ('Bearer invalid', 'Basic Zm9vOmJhcg==', 'Bearer null'):
check('invalid authorization ' + token.split(' ')[0], 'GET', '/cmvr/scanner/configuration',
authenticated=False, headers={'Authorization': token}, expected=(401,))
for query in ('executionId=abc', 'executionId=9223372036854775808',
'executionId=', ''):
check('execution identity boundary ' + query, 'GET', '/lab/execution/scanner-view?' + query)
for query in ('afterId=-1', 'afterId=abc', 'afterId=9223372036854775808'):
check('log cursor boundary ' + query, 'GET', '/cmvr/test/inst/log/detail?instId=' + 'a' * 32 + '&' + query)
for value in ('abc', '0', '-1', '2147483648'):
check('page number boundary ' + value, 'GET', '/lab/master/sample/page?pageNo=' + value + '&pageSize=1')
for name, body in (
('malformed JSON', b'{'), ('array instead of object', b'[]'),
('unknown operation', b'{"operation":"NOT_AN_OPERATION","requestJson":"{}"}'),
('duplicate scanner JSON keys', b'{"operation":"CONNECT","requestJson":"{\\"deviceType\\":3,\\"deviceType\\":4}"}'),
('trailing scanner JSON', b'{"operation":"CONNECT","requestJson":"{} {}"}'),
('null request JSON', b'{"operation":"CONNECT","requestJson":null}'),
('object request JSON', b'{"operation":"CONNECT","requestJson":{}}'),
('array request JSON', b'{"operation":"CONNECT","requestJson":[]}'),
):
check(name, 'POST', '/cmvr/scanner/validate', body=body)
check('unsupported media type', 'POST', '/cmvr/scanner/validate', body=b'{}',
headers={'Content-Type': 'text/plain'})
check('missing scanner route', 'GET', '/cmvr/scanner/not-a-real-operation')
report = dict(passed=all(row['passed'] for row in checks), checks=checks,
failures=[row for row in checks if not row['passed']],
hardwareRequests=0, businessWrites=0)
(ROOT / '.local/http-boundary-verification.json').write_text(
json.dumps(report, ensure_ascii=False, indent=2), encoding='utf-8')
print(json.dumps(dict(passed=report['passed'], checks=len(checks),
failures=len(report['failures']))), flush=True)
return report['passed']
if __name__ == '__main__':
raise SystemExit(0 if run() else 1)