#!/usr/bin/env -S uv run --script # /// script # requires-python = ">=3.12" # dependencies = [] # /// """Exercise browser authorization against the local smoke server, without tokens in output.""" import hashlib import http.client import json import re import sqlite3 import sys import urllib.parse from importlib import import_module check_csp = import_module('smoke-csp').check base, database = sys.argv[1:] origin = urllib.parse.urlsplit(base) conn = sqlite3.connect(database) def seed(name, hint='smoke.test', prompt=None): conn.execute('INSERT INTO oauth_requests (request_id,client_id,redirect_uri,scope,state,code_challenge,code_challenge_method,login_hint,expires_at,prompt) VALUES (?,?,?,?,?,?,?,?,unixepoch()+600,?)', (name, 'http://127.0.0.1:2586/oauth-client-metadata.json', 'http://127.0.0.1/callback', 'atproto', name, 'challenge', 'S256', hint, prompt)) conn.commit() return 'urn:ietf:params:oauth:request_uri:' + name def call(method, uri, fields=None, cookie=None, request_origin=base, accept=None): connection = http.client.HTTPConnection(origin.hostname, origin.port) headers = {} if accept: headers['Accept'] = accept if cookie: headers['Cookie'] = cookie body = None if fields is not None: headers['Content-Type'] = 'application/x-www-form-urlencoded' headers['Origin'] = request_origin body = urllib.parse.urlencode(fields) connection.request(method, uri, body, headers) response = connection.getresponse() result = response.status, dict(response.getheaders()), response.read().decode() connection.close() return result def page(uri, cookie=None): return call('GET', '/oauth/authorize?' + urllib.parse.urlencode({'request_uri': uri}), cookie=cookie) def cookies(headers): return {value.split('=', 1)[0]: value for name, value in headers if name.lower() == 'set-cookie'} def call_all_headers(method, uri, fields): connection = http.client.HTTPConnection(origin.hostname, origin.port) connection.request(method, uri, urllib.parse.urlencode(fields), {'Content-Type': 'application/x-www-form-urlencoded', 'Origin': base}) response = connection.getresponse() result = response.status, response.getheaders(), response.read().decode() connection.close() return result # The sign-in card never focuses a field, so the phone keyboard stays down. status, _, html = page(seed('browser-fresh', hint=None)) assert status == 200 and 'autofocus' not in html and 'autocomplete="username webauthn"' in html # Signing in is not consent: the browser is bound to this request and sent # back to the page, which then asks for consent. uri = seed('browser-two-step') status, headers, html = call_all_headers('POST', '/oauth/authorize', {'request_uri': uri, 'username': 'smoke.test', 'password': 'wrong', 'step': 'password'}) assert status == 401 and 'Wrong username or password.' in html and not cookies(headers) status, headers, _ = call_all_headers('POST', '/oauth/authorize', {'request_uri': uri, 'username': '@smoke.test', 'password': 'password'}) assert status == 303 and dict(headers)['location'].startswith('/oauth/authorize?request_uri=') assert conn.execute('SELECT sub FROM oauth_requests WHERE request_id=?', ('browser-two-step',)).fetchone()[0] is None signin = cookies(headers)['__Host-zds-signin'] for attribute in ('HttpOnly', 'Secure', 'SameSite=Lax', 'Path=/'): assert attribute in signin signin = signin.split(';')[0] status, headers, html = page(uri, signin) assert status == 200 and 'value="continue"' in html and 'name="password"' not in html assert 'Know which account is yours' in html and 'data-copy="atproto"' in html assert check_csp(headers['content-security-policy'], html) csrf = re.search(r'name="csrf" value="([^"]+)"', html)[1] assert call('POST', '/oauth/authorize', {'request_uri': seed('browser-two-step-other'), 'browser_action': 'continue', 'csrf': csrf}, signin)[0] == 403 assert call('POST', '/oauth/authorize', {'request_uri': uri, 'browser_action': 'continue', 'csrf': csrf}, signin, 'https://evil.example')[0] == 403 status, headers, _ = call('POST', '/oauth/authorize', {'request_uri': uri, 'browser_action': 'continue', 'csrf': csrf}, signin) assert status == 303 and headers['location'].startswith('http://127.0.0.1/callback?code=') assert conn.execute('SELECT sub, auth_method FROM oauth_requests WHERE request_id=?', ('browser-two-step',)).fetchone() == ('did:plc:smoketest', 'password') # A sign-in for one request does not consent for another. assert 'name="password"' in page(seed('browser-two-step-unbound'), signin)[2] status, headers, _ = call('POST', '/oauth/authorize', {'request_uri': seed('browser-cancel'), 'deny': '1'}) assert status == 303 and 'error=access_denied' in headers['location'] # The page's script posts Authorize and Deny over fetch and navigates itself, # so both also answer JSON with the redirect. status, _, body = call('POST', '/oauth/authorize', {'request_uri': seed('browser-cancel-json'), 'deny': '1'}, accept='application/json') assert status == 200 and 'error=access_denied' in json.loads(body)['redirect_uri'] json_uri = seed('browser-two-step-json') _, json_headers, _ = call_all_headers('POST', '/oauth/authorize', {'request_uri': json_uri, 'username': 'smoke.test', 'password': 'password'}) json_signin = cookies(json_headers)['__Host-zds-signin'].split(';')[0] json_csrf = re.search(r'name="csrf" value="([^"]+)"', page(json_uri, json_signin)[2])[1] status, _, body = call('POST', '/oauth/authorize', {'request_uri': json_uri, 'browser_action': 'continue', 'csrf': json_csrf}, json_signin, accept='application/json') assert status == 200 and json.loads(body)['redirect_uri'].startswith('http://127.0.0.1/callback?code=') # The page's script asks for a same-origin return page instead, which navigates # to the client on load (a tap-initiated navigation would open a universal link). page_uri = seed('browser-return-page') _, page_headers, _ = call_all_headers('POST', '/oauth/authorize', {'request_uri': page_uri, 'username': 'smoke.test', 'password': 'password'}) page_signin = cookies(page_headers)['__Host-zds-signin'].split(';')[0] page_csrf = re.search(r'name="csrf" value="([^"]+)"', page(page_uri, page_signin)[2])[1] status, _, body = call('POST', '/oauth/authorize', {'request_uri': page_uri, 'browser_action': 'continue', 'csrf': page_csrf, 'via': 'page'}, page_signin, accept='application/json') return_url = json.loads(body)['redirect_uri'] assert status == 200 and return_url.startswith('/oauth/authorize/return?request_uri=') and return_url.endswith('&outcome=granted') code = conn.execute('SELECT code FROM oauth_requests WHERE request_id=?', ('browser-return-page',)).fetchone()[0] status, headers, html = call('GET', return_url, cookie=page_signin) assert status == 200 and f'href="http://127.0.0.1/callback?code={code}&state=browser-return-page' in html and 'data-return' in html assert check_csp(headers['content-security-policy'], html) assert call('GET', return_url)[0] == 403 # A consent page restored with Back cannot issue a second code. assert call('POST', '/oauth/authorize', {'request_uri': page_uri, 'browser_action': 'continue', 'csrf': page_csrf, 'via': 'page'}, page_signin, accept='application/json')[0] == 400 conn.execute('UPDATE oauth_requests SET code = NULL WHERE request_id=?', ('browser-return-page',)) conn.commit() assert call('GET', return_url, cookie=page_signin)[0] == 410 status, _, body = call('POST', '/oauth/authorize', {'request_uri': seed('browser-return-deny'), 'deny': '1', 'via': 'page'}, accept='application/json') status, _, html = call('GET', json.loads(body)['redirect_uri']) assert status == 200 and 'error=access_denied' in html uri = seed('browser-login') fields = {'request_uri': uri, 'username': 'smoke.test', 'password': 'password', 'remember_browser': '1'} assert call('POST', '/oauth/authorize', fields, request_origin='https://evil.example')[0] == 403 status, headers, _ = call_all_headers('POST', '/oauth/authorize', fields) assert status == 303 cookie_header = cookies(headers)['__Host-zds-browser'] for attribute in ('HttpOnly', 'Secure', 'SameSite=Lax', 'Max-Age=31536000', 'Path=/'): assert attribute in cookie_header cookie = cookie_header.split(';')[0] token = cookie.split('=', 1)[1] assert conn.execute('SELECT token_hash FROM browser_sessions WHERE token_hash=?', (hashlib.sha256(token.encode()).hexdigest(),)).fetchone() assert not conn.execute('SELECT token_hash FROM browser_sessions WHERE token_hash=?', (token,)).fetchone() uri = seed('browser-consent') status, headers, html = page(uri, cookie) assert status == 200 and 'name="password"' not in html and 'value="continue"' in html assert headers['cache-control'] == 'no-store' and headers['x-frame-options'] == 'DENY' # chromium and webkit apply form-action to every hop of a form submission's # redirect chain, so 'self' would block the 303 to the client's redirect_uri assert 'form-action' not in headers['content-security-policy'] assert "frame-ancestors 'none'" in headers['content-security-policy'] assert check_csp(headers['content-security-policy'], html) csrf = re.search(r'name="csrf" value="([^"]+)"', html)[1] fields = {'request_uri': uri, 'browser_action': 'continue', 'csrf': csrf} assert call('POST', '/oauth/authorize', fields, cookie, 'https://evil.example')[0] == 403 assert call('POST', '/oauth/authorize', {**fields, 'csrf': '0'*64}, cookie)[0] == 403 assert call('POST', '/oauth/authorize', fields)[0] == 403 assert call('POST', '/oauth/authorize', fields, cookie)[0] == 303 assert conn.execute('SELECT sub FROM oauth_requests WHERE request_id=?', ('browser-consent',)).fetchone()[0] == 'did:plc:smoketest' assert 'name="password"' in page(seed('browser-forced', prompt='login'), cookie)[2] assert 'name="password"' in page(seed('browser-mismatch', hint='signup-smoke.test'), cookie)[2] assert call('POST', '/oauth/authorize', {**fields, 'request_uri': seed('browser-csrf-other')}, cookie)[0] == 403 conn.execute('UPDATE browser_sessions SET expires_at=unixepoch()-1') conn.commit() assert 'name="password"' in page(uri, cookie)[2] conn.execute('UPDATE browser_sessions SET expires_at=unixepoch()+600') conn.commit() assert call('POST', '/oauth/authorize', {**fields, 'browser_action': 'forget'}, cookie)[0] == 303 assert 'name="password"' in page(uri, cookie)[2] assert not conn.execute('SELECT 1 FROM browser_sessions').fetchone() print('browser login: two-step sign-in and consent, remembered consent, CSRF, prompt, account binding, expiry, and revocation passed')