Add invocation-scoped TLS verification bypass for self-signed servers
This commit is contained in:
1 parent
7fa71eceb1
commit
59ab4c5b26
9 files changed
+206
-15
No files matched your search
+153
@@ -0,0 +1,153 @@
|
||||
"""Synthetic self-signed HTTPS tests; never disable verification for real services.
|
||||
|
||||
Set PAGES_CLI_TEST_BINARY to run subprocess tests against the packaged executable.
|
||||
"""
|
||||
import contextlib
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import runpy
|
||||
import ssl
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import unittest
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from unittest.mock import patch
|
||||
|
||||
m=runpy.run_path(str(Path(__file__).with_name('pages')))
|
||||
Client,Failure=m['Client'],m['Failure']
|
||||
|
||||
|
||||
class TLSTests(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.temp=tempfile.TemporaryDirectory()
|
||||
cls.addClassCleanup(cls.temp.cleanup)
|
||||
cls.cert=Path(cls.temp.name)/'cert.pem'
|
||||
cls.key=Path(cls.temp.name)/'key.pem'
|
||||
subprocess.run(['openssl','req','-x509','-newkey','rsa:2048','-nodes',
|
||||
'-keyout',str(cls.key),'-out',str(cls.cert),'-days','1',
|
||||
'-subj','/CN=localhost','-addext','subjectAltName=DNS:localhost'],
|
||||
check=True,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL,timeout=30)
|
||||
|
||||
def setUp(self):
|
||||
self.calls=[]
|
||||
calls=self.calls
|
||||
self.token='synthetic_tls_session_'+'x'*40
|
||||
token=self.token
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
def log_message(self,*args):pass
|
||||
def reply(self,data):
|
||||
self.send_response(200);self.send_header('Content-Type','application/json');self.end_headers()
|
||||
self.wfile.write(json.dumps(data).encode())
|
||||
def do_GET(self):
|
||||
calls.append((self.path,self.headers.get('Authorization')))
|
||||
if self.path.startswith('/redirect'):
|
||||
self.send_response(302);self.send_header('Location','/destination');self.end_headers();return
|
||||
self.reply({'items':[{'uuid':'synthetic-task','title':'TLS task','status':'todo'}]})
|
||||
def do_POST(self):
|
||||
self.rfile.read(int(self.headers.get('Content-Length',0)))
|
||||
calls.append((self.path,self.headers.get('Authorization')))
|
||||
if self.path=='/_/auth/login':
|
||||
self.reply({'access_token':token,'token_type':'Bearer','expires_in':3600})
|
||||
elif self.path=='/_/auth/cli/start':
|
||||
self.reply({'device_code':'D'*43,'verification_uri':'/_/auth/cli/verify?request='+'R'*43,'user_code':'ABCD-1234','expires_in':300,'interval':5})
|
||||
elif self.path=='/_/auth/cli/token':
|
||||
self.reply({'access_token':token,'token_type':'Bearer','expires_in':3600,'username':'synthetic'})
|
||||
elif self.path=='/_/auth/logout':self.reply({})
|
||||
else:self.send_error(404)
|
||||
self.server=ThreadingHTTPServer(('127.0.0.1',0),Handler)
|
||||
context=ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
|
||||
context.load_cert_chain(self.cert,self.key)
|
||||
self.server.socket=context.wrap_socket(self.server.socket,server_side=True)
|
||||
self.thread=threading.Thread(target=self.server.serve_forever,daemon=True);self.thread.start()
|
||||
self.base=f'https://localhost:{self.server.server_port}'
|
||||
self.environment=patch.dict(os.environ,{'NO_PROXY':'localhost,127.0.0.1','no_proxy':'localhost,127.0.0.1'})
|
||||
self.environment.start()
|
||||
|
||||
def tearDown(self):
|
||||
self.environment.stop()
|
||||
self.server.shutdown();self.server.server_close();self.thread.join()
|
||||
|
||||
def test_default_rejects_and_bypass_does_not_change_global_policy(self):
|
||||
default_context=ssl._create_default_https_context
|
||||
with self.assertRaises(Failure):Client(self.base,self.token).json('/first')
|
||||
self.assertEqual(self.calls,[])
|
||||
self.assertIn('items',Client(self.base,self.token,insecure=True).json('/explicit'))
|
||||
self.assertEqual(self.calls,[('/explicit','Bearer '+self.token)])
|
||||
with self.assertRaises(Failure):Client(self.base,self.token).json('/default-again')
|
||||
self.assertEqual(len(self.calls),1)
|
||||
self.assertIs(ssl._create_default_https_context,default_context)
|
||||
|
||||
def test_hostname_verification_and_secure_trusted_certificate(self):
|
||||
# Trust our synthetic CA, but its certificate covers localhost, not 127.0.0.1.
|
||||
with patch.dict(os.environ,{'SSL_CERT_FILE':str(self.cert)}):
|
||||
self.assertIn('items',Client(self.base).json('/trusted'))
|
||||
wrong_host=self.base.replace('localhost','127.0.0.1')
|
||||
with self.assertRaises(Failure):Client(wrong_host).json('/wrong-host')
|
||||
self.assertIn('items',Client(wrong_host,insecure=True).json('/explicit-wrong-host'))
|
||||
self.assertEqual([p for p,_ in self.calls],['/trusted','/explicit-wrong-host'])
|
||||
|
||||
def test_bypass_does_not_allow_redirects_or_remote_http(self):
|
||||
with self.assertRaises(Failure) as caught:Client(self.base,self.token,insecure=True).json('/redirect')
|
||||
self.assertEqual(caught.exception.status,302)
|
||||
self.assertEqual(self.calls,[('/redirect','Bearer '+self.token)])
|
||||
with self.assertRaises(Failure):Client('http://example.invalid',insecure=True)
|
||||
|
||||
def test_edit_language_override_preserves_tls_policy(self):
|
||||
for insecure in (False,True):
|
||||
client=Client(self.base,self.token,insecure=insecure)
|
||||
received=[]
|
||||
def editor(editing,*args):received.append(editing)
|
||||
with patch.dict(m['execute'].__globals__,{'editor':editor}):
|
||||
m['execute'](client,type('Profile',(),{'data':{}})(),['edit','/test','--lang','ja'])
|
||||
self.assertEqual(received[0].insecure,insecure)
|
||||
self.assertEqual(received[0].lang,'ja')
|
||||
|
||||
def test_login_commands_shell_logout_and_non_persistence(self):
|
||||
binary=os.environ.get('PAGES_CLI_TEST_BINARY')
|
||||
command=[str(Path(binary).resolve())] if binary else [sys.executable,str(Path(__file__).with_name('pages'))]
|
||||
with tempfile.TemporaryDirectory() as config:
|
||||
env={**os.environ,'XDG_CONFIG_HOME':config}
|
||||
def run(*args,stdin='',ok=True):
|
||||
r=subprocess.run(command+list(args),input=stdin,text=True,capture_output=True,env=env,timeout=20)
|
||||
self.assertEqual(r.returncode==0,ok,(args,r.stderr))
|
||||
self.assertNotIn(self.token,r.stdout+r.stderr)
|
||||
return r
|
||||
run('configure','--origin',self.base,'--username','synthetic')
|
||||
run('login',stdin='test-password\n',ok=False)
|
||||
self.assertEqual(self.calls,[])
|
||||
r=run('--insecure','login',stdin='test-password\n')
|
||||
self.assertIn('WARNING: --insecure',r.stderr)
|
||||
self.assertEqual(r.stderr.count('WARNING:'),1)
|
||||
self.assertNotIn('WARNING:',r.stdout)
|
||||
run('task','list',ok=False)
|
||||
r=run('-k','task','list')
|
||||
self.assertIn('TLS task',r.stdout)
|
||||
r=run('-k','shell',stdin='task list\nexit\n')
|
||||
self.assertIn('TLS task',r.stdout)
|
||||
self.assertEqual(r.stderr.count('WARNING:'),1)
|
||||
for path in Path(config).rglob('*.json'):
|
||||
self.assertNotIn('insecure',path.read_text())
|
||||
self.assertNotIn('verify_tls',path.read_text())
|
||||
run('logout',ok=False)
|
||||
self.assertIn('token',json.loads((Path(config)/'pages-cli/sessions/default.json').read_text()))
|
||||
run('-k','logout')
|
||||
self.assertNotIn('token',json.loads((Path(config)/'pages-cli/sessions/default.json').read_text()))
|
||||
run('-k','configure',ok=False)
|
||||
|
||||
def test_oidc_client_uses_explicit_tls_context(self):
|
||||
client=Client(self.base,insecure=True)
|
||||
with patch.object(m['webbrowser'],'open') as browser,contextlib.redirect_stdout(io.StringIO()) as out:
|
||||
_,username=client.login_oidc(no_browser=True,sleep=lambda _:None)
|
||||
browser.assert_not_called()
|
||||
self.assertEqual(username,'synthetic')
|
||||
self.assertEqual(client.token,self.token)
|
||||
self.assertNotIn(self.token,out.getvalue())
|
||||
self.assertEqual([p for p,_ in self.calls],['/_/auth/cli/start','/_/auth/cli/token'])
|
||||
|
||||
|
||||
if __name__=='__main__':unittest.main()
|
||||
Reference in new issue
Block a user