100 lines
5.7 KiB
Python
100 lines
5.7 KiB
Python
"""Authenticated native HTTP checks for the explicitly isolated synthetic public demo."""
|
|
import html
|
|
import http.client
|
|
from http.cookies import SimpleCookie
|
|
import json
|
|
from pathlib import Path
|
|
import re
|
|
import sys
|
|
import urllib.parse
|
|
|
|
|
|
class Client:
|
|
def __init__(self, identity, origin='http://127.0.0.1:49815'):
|
|
self.origin = urllib.parse.urlparse(origin)
|
|
self.cookies = {}
|
|
self.version = None
|
|
self.request('/login', inertia=False)
|
|
result = self.request('/login', 'POST', {'email': identity['email'], 'password': identity['password']}, inertia=False)
|
|
assert result['status'] in [200, 302, 303], f"Normal login failed: {result['status']}"
|
|
page = self.request('/dashboard', inertia=False)
|
|
assert page['status'] == 200 and page['page']['props']['auth']['user'] is not None, 'Normal login did not establish an authenticated session'
|
|
self.version = page['page']['version']
|
|
self.work_context = page['page']['props'].get('workContext') or {}
|
|
|
|
def request(self, path, method='GET', data=None, inertia=True, content_type=None):
|
|
context = getattr(self, 'work_context', {})
|
|
shared = path == '/' or path.startswith(('/dashboard', '/login', '/logout', '/administracao/', '/empresa', '/settings', '/contexto'))
|
|
if method == 'GET' and context.get('enforced') and not shared:
|
|
area = 'people' if path == '/pessoas' or path.startswith('/pessoas/') else 'procurement'
|
|
option = area+'.internal'
|
|
if option in context.get('available', []) and context.get('active') != option:
|
|
selected = self.request('/contexto', 'POST', {'area': area, 'option': option})
|
|
assert selected['status'] in [302, 303], 'Native explicit context selection failed'
|
|
context['active'] = option
|
|
connection = (http.client.HTTPSConnection if self.origin.scheme == 'https' else http.client.HTTPConnection)(self.origin.hostname, self.origin.port, timeout=30)
|
|
headers = {'Host': 'compras.tempo.co.mz', 'Accept': 'application/json' if method != 'GET' or inertia else 'text/html',
|
|
'Cookie': '; '.join(k+'='+v for k, v in self.cookies.items())}
|
|
if 'XSRF-TOKEN' in self.cookies:
|
|
headers['X-XSRF-TOKEN'] = urllib.parse.unquote(self.cookies['XSRF-TOKEN'])
|
|
if inertia and method == 'GET':
|
|
headers['X-Inertia'] = 'true'
|
|
if self.version: headers['X-Inertia-Version'] = self.version
|
|
body = None
|
|
if data is not None:
|
|
headers['Content-Type'] = content_type or 'application/json'
|
|
body = data if isinstance(data, bytes) else json.dumps(data)
|
|
connection.request(method, path, body, headers)
|
|
response = connection.getresponse()
|
|
for key, value in response.getheaders():
|
|
if key.lower() == 'set-cookie':
|
|
cookie = SimpleCookie(); cookie.load(value)
|
|
self.cookies.update({k: v.value for k, v in cookie.items()})
|
|
raw = response.read()
|
|
text = raw.decode('utf-8', errors='replace')
|
|
page = None
|
|
if response.getheader('Content-Type', '').startswith('application/json'):
|
|
try: page = json.loads(text)
|
|
except ValueError: pass
|
|
else:
|
|
match = re.search(r'<script data-page="app" type="application/json">([\s\S]*?)</script>', text)
|
|
if match: page = json.loads(html.unescape(match.group(1)))
|
|
result = {'status': response.status, 'page': page, 'location': response.getheader('Location'), 'text': text, 'raw': raw}
|
|
connection.close()
|
|
return result
|
|
|
|
|
|
def main():
|
|
assert sys.argv[1] == '--check-authorized-synthetic'
|
|
root = Path('/var/www/compras-deploy/releases/presentation-20261129')
|
|
assert root.exists() and 'DB_DATABASE="compras_demo_20261129"' in (root / '.env').read_text()
|
|
credentials = json.loads(Path('/root/compras-demo-access.json').read_text())
|
|
origin = sys.argv[2] if len(sys.argv) > 2 else 'http://127.0.0.1:49815'
|
|
clients = {key: Client(identity, origin) for key, identity in credentials.items()}
|
|
checks = []
|
|
routes = {
|
|
'admin': ['/dashboard', '/administracao/parametrizacao', '/pessoas', '/pessoas/relatorios', '/pessoas/relatorios?view=selections', '/relatorios'],
|
|
'requester': ['/dashboard', '/requisicoes', '/requisicoes/1'],
|
|
'procurement': ['/dashboard', '/fornecedores', '/cotacoes', '/ordens', '/ordens-operacionais', '/projectos-imobilizado',
|
|
'/compras/importacoes/12/documentos', '/compras/importacoes/12/suporte-bancario', '/compras/importacoes/12/suporte-bancario.csv',
|
|
*['/compras/importacoes/12/documentos/'+str(number) for number in range(13,18)]],
|
|
'finance': ['/dashboard', '/relatorios', '/orcamentos'],
|
|
'warehouse': ['/dashboard', '/recepcoes'],
|
|
'auditor': ['/dashboard', '/auditoria/privada'],
|
|
'direction': ['/dashboard', '/pessoas'],
|
|
}
|
|
for key, paths in routes.items():
|
|
for path in paths:
|
|
result = clients[key].request(path)
|
|
checks.append({'profile': key, 'path': path, 'status': result['status']})
|
|
errors = [check for check in checks if check['status'] != 200]
|
|
proof = {'state': 'passed' if not errors else 'failed', 'origin': origin, 'normal_login_sessions': len(clients), 'checks': checks,
|
|
'synthetic_only': True, 'authentication_shortcuts': False, 'errors': errors}
|
|
print(json.dumps(proof, indent=2))
|
|
assert not errors, 'Native route errors require diagnosis before activation'
|
|
Path('/var/www/compras-deploy/demonstration-20261129/' + ('public-http-check.json' if origin.startswith('https:') else 'staging-http-check.json')).write_text(json.dumps(proof, indent=2))
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|