Add OIDC browser approval and PKCE session handoff for pages CLI
This commit is contained in:
1 parent
336c5790e9
commit
f188e7eac1
3 files changed
+224
-9
No files matched your search
+120
@@ -1,4 +1,5 @@
|
||||
import contextlib
|
||||
import base64
|
||||
from email.message import Message
|
||||
import hashlib
|
||||
import io
|
||||
@@ -38,6 +39,94 @@ def reply(h, status, body, mime='application/json'):
|
||||
|
||||
|
||||
class RemoteTests(unittest.TestCase):
|
||||
def test_oidc_polling_pkce_and_no_secret_output(self):
|
||||
now = [0]
|
||||
waits, calls = [], []
|
||||
started = {'device_code': 'D'*43, 'verification_uri': '/_/auth/cli/verify?request='+'R'*43,
|
||||
'user_code': 'ABCD-1234', 'expires_in': 300, 'interval': 5}
|
||||
client = Client('https://wiki.example')
|
||||
def sleep(seconds): waits.append(seconds); now[0] += seconds
|
||||
def request(route, **kwargs):
|
||||
calls.append((route, kwargs))
|
||||
if route.endswith('/start'): return started
|
||||
polls = len(calls)-1
|
||||
if polls == 1: raise Failure('pending',400,{'error':'authorization_pending'})
|
||||
if polls == 2: raise Failure('slow',400,{'error':'slow_down'})
|
||||
return {'access_token':'pw_api_'+'S'*43,'token_type':'Bearer','expires_in':3600,'username':'anya'}
|
||||
with patch.object(client,'json',side_effect=request), patch.object(m['webbrowser'],'open') as browser, contextlib.redirect_stdout(io.StringIO()) as out:
|
||||
expires, name = client.login_oidc(True,sleep=sleep,clock=lambda:now[0])
|
||||
self.assertEqual(name,'anya'); self.assertGreater(expires,time.time())
|
||||
self.assertEqual(waits,[5,5,10]); browser.assert_not_called()
|
||||
proof = calls[1][1]['form']['code_verifier']
|
||||
expected=base64.urlsafe_b64encode(hashlib.sha256(proof.encode()).digest()).decode().rstrip('=')
|
||||
self.assertEqual(calls[0][1]['form']['code_challenge'],expected)
|
||||
self.assertNotIn(proof,out.getvalue()); self.assertNotIn(started['device_code'],out.getvalue()); self.assertNotIn(client.token,out.getvalue())
|
||||
self.assertIn('ABCD-1234',out.getvalue())
|
||||
|
||||
def test_oidc_unavailable_server_explained_without_retry(self):
|
||||
for status in (404, 405, 501):
|
||||
with self.subTest(status=status):
|
||||
client = Client('https://wiki.example')
|
||||
with patch.object(client, 'json', side_effect=Failure('Not found or not readable.', status)) as api, patch.object(m['webbrowser'], 'open') as browser, contextlib.redirect_stdout(io.StringIO()) as out:
|
||||
with self.assertRaisesRegex(Failure, 'CLI OIDC login is unavailable') as caught:
|
||||
client.login_oidc(True)
|
||||
self.assertEqual(caught.exception.status, status)
|
||||
api.assert_called_once()
|
||||
browser.assert_not_called()
|
||||
self.assertEqual(out.getvalue(), '')
|
||||
self.assertEqual(client.token, '')
|
||||
|
||||
def test_oidc_disabled_and_other_start_errors(self):
|
||||
client = Client('https://wiki.example')
|
||||
with patch.object(client, 'json', side_effect=Failure('Access denied.', 403, {'error': 'oidc_disabled'})):
|
||||
with self.assertRaisesRegex(Failure, 'not enabled for this domain'):
|
||||
client.login_oidc(True)
|
||||
for error in (Failure('Connection/TLS failure.'), Failure('Access denied.', 403), Failure('Unavailable.', 503)):
|
||||
with patch.object(client, 'json', side_effect=error) as api:
|
||||
with self.assertRaises(Failure) as caught:
|
||||
client.login_oidc(True)
|
||||
self.assertIs(caught.exception, error)
|
||||
api.assert_called_once()
|
||||
|
||||
def test_oidc_rejects_external_url_and_wrong_account(self):
|
||||
client=Client('https://wiki.example')
|
||||
started={'device_code':'D'*43,'verification_uri':'https://evil.example/','user_code':'ABCD-1234','expires_in':300,'interval':5}
|
||||
with patch.object(client,'json',return_value=started),patch.object(m['webbrowser'],'open') as browser:
|
||||
with self.assertRaises(Failure): client.login_oidc()
|
||||
browser.assert_not_called()
|
||||
started['verification_uri']='/_/auth/cli/verify?request='+'R'*43
|
||||
token={'access_token':'pw_api_'+'S'*43,'token_type':'Bearer','expires_in':3600,'username':'other'}
|
||||
with patch.object(client,'json',side_effect=[started,token,{}]) as api, contextlib.redirect_stdout(io.StringIO()):
|
||||
with self.assertRaises(Failure): client.login_oidc(True,'anya',sleep=lambda _:None,clock=lambda:0)
|
||||
self.assertEqual(api.call_args.args[0],'/_/auth/logout')
|
||||
self.assertEqual(client.token,'')
|
||||
|
||||
def test_oidc_cancellation_denial_and_ambiguous_exchange(self):
|
||||
started={'device_code':'D'*43,'verification_uri':'/_/auth/cli/verify?request='+'R'*43,'user_code':'ABCD-1234','expires_in':300,'interval':5}
|
||||
for error in [Failure('denied',403,{'error':'access_denied'}),Failure('expired',400,{'error':'expired_token'}),Failure('network failure')]:
|
||||
client=Client('https://wiki.example')
|
||||
with patch.object(client,'json',side_effect=[started,error]) as api,contextlib.redirect_stdout(io.StringIO()):
|
||||
with self.assertRaises(Failure): client.login_oidc(True,sleep=lambda _:None,clock=lambda:0)
|
||||
self.assertEqual(api.call_count,2)
|
||||
client=Client('https://wiki.example')
|
||||
with patch.object(client,'json',return_value=started) as api,contextlib.redirect_stdout(io.StringIO()):
|
||||
def interrupt(_): raise KeyboardInterrupt()
|
||||
with self.assertRaises(KeyboardInterrupt): client.login_oidc(True,sleep=interrupt,clock=lambda:0)
|
||||
self.assertEqual(api.call_count,1)
|
||||
|
||||
def test_oidc_main_without_configured_username(self):
|
||||
with tempfile.TemporaryDirectory() as root, patch.dict(os.environ,{'XDG_CONFIG_HOME':root}):
|
||||
self.configure(None,'--origin','https://wiki.example')
|
||||
def login(client,*args,**kwargs): client.token='pw_api_'+'s'*43; return time.time()+600,'anya'
|
||||
with patch.object(Client,'login_oidc',login),contextlib.redirect_stdout(io.StringIO()):
|
||||
m['main'](['login','--oidc','--no-browser'])
|
||||
m['main'](['status'])
|
||||
self.configure(None,'--lang','ja')
|
||||
with Profile('default').locked() as profile:
|
||||
self.assertEqual(profile.data['username'],'anya')
|
||||
self.assertEqual(profile.data['configured_username'],'')
|
||||
with self.assertRaises(Failure): self.configure(None,'--username','other')
|
||||
|
||||
def configure(self, root, *args):
|
||||
with contextlib.redirect_stdout(io.StringIO()) as output:
|
||||
m['configure'](list(args), root)
|
||||
@@ -204,6 +293,36 @@ class RemoteTests(unittest.TestCase):
|
||||
self.assertEqual(stat.S_IMODE((directory/'recovery.json').stat().st_mode),0o600)
|
||||
|
||||
|
||||
def oidc_integration():
|
||||
fixture=json.load(sys.stdin)
|
||||
original=Client.json
|
||||
grant={}
|
||||
def capture(client,route,**kwargs):
|
||||
result=original(client,route,**kwargs)
|
||||
if route=='/_/auth/cli/start': grant.update(result)
|
||||
return result
|
||||
def browser(target,**kwargs):
|
||||
ident=m['url'].parse_qs(m['url'].urlsplit(target).query)['request'][0]
|
||||
original(Client(fixture['origin']),'/__test/cli-approve',method='POST',form={'request':ident,'code':grant['user_code']})
|
||||
return True
|
||||
with tempfile.TemporaryDirectory() as root,patch.dict(os.environ,{'XDG_CONFIG_HOME':root}),contextlib.redirect_stdout(io.StringIO()) as output:
|
||||
m['main'](['configure','--origin',fixture['origin']])
|
||||
with patch.object(Client,'json',capture),patch.object(m['webbrowser'],'open',browser): m['main'](['login','--oidc'])
|
||||
with Profile('default',root).locked() as session:
|
||||
token=session.data['token']; assert session.data['username']=='admin'
|
||||
m['main'](['ls']); m['main'](['status'])
|
||||
client=Client(fixture['origin'],token)
|
||||
state=client.snapshot('path:/editor-fixture')
|
||||
client.save(state,'# OIDC edit\n\n{{children}}\n',True)
|
||||
assert '{{children}}' in client.snapshot('path:/editor-fixture')['markdown']
|
||||
m['main'](['logout'])
|
||||
assert token not in output.getvalue()
|
||||
try: client.snapshot('path:/editor-fixture')
|
||||
except Failure as e: assert e.status in (401,403,303)
|
||||
else: raise AssertionError('revoked CLI session accepted')
|
||||
print('OIDC CLI configure/login/list/authoring/logout integration passed')
|
||||
|
||||
|
||||
def integration():
|
||||
fixture=json.load(sys.stdin)
|
||||
# Exercise the public entry point with persisted defaults, not only Client.
|
||||
@@ -261,4 +380,5 @@ def integration():
|
||||
|
||||
if __name__=='__main__':
|
||||
if sys.argv[1:] == ['--integration']: integration()
|
||||
elif sys.argv[1:] == ['--oidc-integration']: oidc_integration()
|
||||
else: unittest.main()
|
||||
Reference in new issue
Block a user