Files
2026-09-09 14:13:44 +02:00

120 lines
5.8 KiB
Python

import importlib.util
from pathlib import Path
import tempfile
import json
from urllib.parse import urlsplit, parse_qs
import shutil
import subprocess
import unittest
spec = importlib.util.spec_from_file_location('patch', Path(__file__).resolve().parents[1] / 'scripts/logout_patch.py')
patch = importlib.util.module_from_spec(spec)
spec.loader.exec_module(patch)
FIXTURE = """text: gettext('Logout'),
handler: function () {
PVE.data.ResourceStore.loadData([], false);
me.showLogin();
cleanup();
},"""
class LogoutTests(unittest.TestCase):
def test_two_host_redirect_chain(self):
endpoints = ['https://9.99.30.11:8443/realms/main.heim.lan/protocol/openid-connect/logout',
'https://keycloak.service.heim.lan:8443/realms/main.heim.lan/protocol/openid-connect/logout']
plan = patch.logout_plan(endpoints, 'PVE-SERVER', 'https://192.168.1.231:8006/')
first = urlsplit(plan['url'])
self.assertEqual(first.hostname, '9.99.30.11')
next_url = parse_qs(first.query)['post_logout_redirect_uri'][0]
self.assertIn(next_url, plan['allowed_redirects'])
second = urlsplit(next_url)
self.assertEqual(second.hostname, 'keycloak.service.heim.lan')
self.assertEqual(parse_qs(second.query)['post_logout_redirect_uri'], ['https://192.168.1.231:8006/'])
self.assertEqual(len(plan['allowed_redirects']), 2)
for endpoints_bad in ([], endpoints * 2, [endpoints[0]] * 2, ['http://kc/logout'],
['https://kc/logout?next=bad'], ['https://kc/not-logout']):
with self.assertRaises(ValueError):
patch.logout_plan(endpoints_bad, 'PVE-SERVER', 'https://pve/')
def test_lifecycle_and_update(self):
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
target = root / 'bundle.js'
target.write_text(FIXTURE)
args = dict(target=target, directory=root / 'state', enabled=True,
version='pve-manager/9.0.0/test', realm='main.heim.lan',
endpoint='https://kc:8443/realms/main/protocol/openid-connect/logout',
client='PVE-SERVER', redirect='https://ts01:8006/')
self.assertTrue(patch.apply(**args))
self.assertFalse(patch.apply(**args))
self.assertIn('pveIdmUser.endsWith', target.read_text())
self.assertLess(target.read_text().index('me.showLogin();'), target.read_text().index('window.setTimeout'))
args['client'] = 'OTHER'
self.assertTrue(patch.apply(**args))
self.assertTrue(patch.apply(target, root / 'state', False))
self.assertEqual(target.read_text(), FIXTURE)
self.assertFalse(patch.apply(target, root / 'state', False))
patch.apply(**args)
# Package update replaced the entire file; rollback must not downgrade it.
target.write_text(FIXTURE + '\n// new package')
self.assertFalse(patch.apply(target, root / 'state', False))
self.assertTrue(patch.apply(**args))
self.assertTrue(patch.apply(target, root / 'state', False))
self.assertEqual(target.read_text(), FIXTURE + '\n// new package')
def test_unknown_code_rejected(self):
for text in ('unknown', FIXTURE + FIXTURE):
with self.assertRaises(ValueError):
patch.render(text, 'realm', 'https://kc/logout', 'client', 'https://pve/')
def test_tamper_rejected(self):
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
target = root / 'bundle.js'
target.write_text(FIXTURE)
patch.apply(target, root / 'state', True, 'pve-manager/9.1/x', 'realm',
'https://kc/logout', 'client', 'https://pve/')
target.write_text(target.read_text() + '// manual edit')
with self.assertRaises(ValueError):
patch.apply(target, root / 'state', False)
@unittest.skipUnless(shutil.which('node'), 'Node.js not installed')
def test_browser_handler_order_and_realm(self):
code = patch.render(FIXTURE, 'main.heim.lan', 'https://kc/logout', 'PVE-SERVER', 'https://ts01:8006/')
javascript = r"""
const vm = require('vm');
const source = CODE;
for (const user of ['alice@main.heim.lan', 'root@pam']) {
const events = []; const timers = [];
const context = {URL, gettext: x => x,
Proxmox: {UserName: user},
PVE: {data: {ResourceStore: {loadData: () => events.push('clear')}}},
me: {showLogin: () => { events.push('local'); context.Proxmox.UserName = null; }},
cleanup: () => events.push('cleanup'),
window: {setTimeout: f => timers.push(f), location: {assign: u => events.push(u)}}};
vm.runInNewContext('({' + source + '}).handler()', context);
if (events.join(',') !== 'clear,local,cleanup') throw Error('Local cleanup/order failed');
timers.forEach(f => f());
if (user === 'root@pam' && events.length !== 3) throw Error('PAM redirected');
if (user.startsWith('alice')) {
const url = new URL(events[3]);
if (url.origin !== 'https://kc' || url.searchParams.get('client_id') !== 'PVE-SERVER'
|| url.searchParams.get('post_logout_redirect_uri') !== 'https://ts01:8006/') throw Error('Wrong redirect');
}
}
""".replace('CODE', json.dumps(code))
subprocess.run([shutil.which('node'), '-e', javascript], check=True, capture_output=True)
def test_wrong_version_no_write(self):
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
target = root / 'bundle.js'
target.write_text(FIXTURE)
with self.assertRaises(ValueError):
patch.apply(target, root / 'state', True, 'pve-manager/10.0/x')
self.assertEqual(target.read_text(), FIXTURE)
if __name__ == '__main__':
unittest.main()