318 lines
23 KiB
Python
318 lines
23 KiB
Python
#!/usr/bin/env python3
|
|
"""Actual TLS mock IdP + native server + existing dev PostgreSQL, no approvals/VM effects.
|
|
|
|
Only creates/removes its own identity/membership and separate login role fixture.
|
|
No direct API/DB approval is performed. Requires normal migrations already applied.
|
|
"""
|
|
import base64
|
|
import datetime
|
|
import hashlib
|
|
import http.client
|
|
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import secrets
|
|
import shutil
|
|
import socket
|
|
import ssl
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
import threading
|
|
import time
|
|
import urllib.parse
|
|
import uuid
|
|
from cryptography import x509
|
|
from cryptography.hazmat.primitives import hashes, serialization
|
|
from cryptography.hazmat.primitives.asymmetric import padding, rsa
|
|
from cryptography.x509.oid import NameOID
|
|
|
|
ROOT = Path(__file__).resolve().parents[2]
|
|
STAGE = 'initial setup'
|
|
sys.path.insert(0, str(ROOT / 'tests'))
|
|
from local_integration import sql, STATE, CA, A, B
|
|
|
|
|
|
def encoded(value):
|
|
return base64.urlsafe_b64encode(value).decode().rstrip('=')
|
|
|
|
|
|
def private(path, data):
|
|
path.write_bytes(data if isinstance(data, bytes) else data.encode())
|
|
path.chmod(0o600)
|
|
return str(path)
|
|
|
|
|
|
def quiet(args, **kwargs):
|
|
result = subprocess.run(args, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, **kwargs)
|
|
if result.returncode:
|
|
raise RuntimeError('private subprocess failed')
|
|
|
|
|
|
class Idp:
|
|
def __init__(self, folder):
|
|
self.lock = threading.Lock()
|
|
self.key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
|
|
self.kid = 'initial'
|
|
self.subject = 'synthetic-oidc-' + uuid.uuid4().hex
|
|
self.codes, self.requests = {}, {}
|
|
self.jwks, self.exchanges = 0, 0
|
|
self.bad_nonce = False
|
|
ca_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
|
|
name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, 'Isolated OIDC mock CA')])
|
|
now = datetime.datetime.now(datetime.timezone.utc)
|
|
ca = (x509.CertificateBuilder().subject_name(name).issuer_name(name).public_key(ca_key.public_key())
|
|
.serial_number(x509.random_serial_number()).not_valid_before(now-datetime.timedelta(minutes=1))
|
|
.not_valid_after(now+datetime.timedelta(days=1)).add_extension(x509.BasicConstraints(ca=True,path_length=0),critical=True)
|
|
.sign(ca_key,hashes.SHA256()))
|
|
leaf_key = rsa.generate_private_key(public_exponent=65537,key_size=2048)
|
|
leaf = (x509.CertificateBuilder().subject_name(x509.Name([x509.NameAttribute(NameOID.COMMON_NAME,'localhost')]))
|
|
.issuer_name(name).public_key(leaf_key.public_key()).serial_number(x509.random_serial_number())
|
|
.not_valid_before(now-datetime.timedelta(minutes=1)).not_valid_after(now+datetime.timedelta(days=1))
|
|
.add_extension(x509.SubjectAlternativeName([x509.DNSName('localhost')]),critical=False)
|
|
.add_extension(x509.ExtendedKeyUsage([x509.oid.ExtendedKeyUsageOID.SERVER_AUTH]),critical=False).sign(ca_key,hashes.SHA256()))
|
|
self.ca = private(folder/'mock-ca.pem',ca.public_bytes(serialization.Encoding.PEM))
|
|
cert = private(folder/'mock.pem',leaf.public_bytes(serialization.Encoding.PEM))
|
|
key = private(folder/'mock.key',leaf_key.private_bytes(serialization.Encoding.PEM,serialization.PrivateFormat.PKCS8,serialization.NoEncryption()))
|
|
idp = self
|
|
|
|
class Handler(BaseHTTPRequestHandler):
|
|
def log_message(self, *_): pass
|
|
def respond(self, status, value=None, location=None, html=None):
|
|
body = html.encode() if html else json.dumps(value or {}).encode()
|
|
self.send_response(status)
|
|
self.send_header('Content-Type','text/html' if html else 'application/json')
|
|
self.send_header('Content-Length',str(len(body)))
|
|
self.send_header('Cache-Control','no-store')
|
|
if location: self.send_header('Location',location)
|
|
self.end_headers();self.wfile.write(body)
|
|
def do_GET(self):
|
|
u = urllib.parse.urlsplit(self.path)
|
|
if u.path == '/.well-known/openid-configuration':
|
|
self.respond(200,{'issuer':idp.issuer,'authorization_endpoint':idp.issuer+'authorize','token_endpoint':idp.issuer+'token','jwks_uri':idp.issuer+'jwks','response_types_supported':['code'],'id_token_signing_alg_values_supported':['RS256'],'code_challenge_methods_supported':['S256'],'token_endpoint_auth_methods_supported':['client_secret_post']})
|
|
elif u.path == '/jwks':
|
|
with idp.lock:
|
|
idp.jwks += 1
|
|
key = idp.key.public_key().public_numbers()
|
|
self.respond(200,{'keys':[{'kty':'RSA','alg':'RS256','use':'sig','kid':idp.kid,'n':encoded(key.n.to_bytes((key.n.bit_length()+7)//8,'big')),'e':encoded(key.e.to_bytes(3,'big'))}]})
|
|
elif u.path == '/authorize':
|
|
q = dict(urllib.parse.parse_qsl(u.query))
|
|
if q.get('client_id')!='rmm-browser' or q.get('redirect_uri')!=idp.redirect or q.get('code_challenge_method')!='S256': return self.respond(400)
|
|
request_id = secrets.token_hex(24)
|
|
with idp.lock: idp.requests[request_id] = q
|
|
self.respond(200,html=f'<h1>SIMULATED local OIDC test principal, no human acceptance</h1><form action="/approve" method="post"><input type="hidden" name="request" value="{request_id}"><button>Authorize simulated test login</button></form>')
|
|
else: self.respond(404)
|
|
def do_POST(self):
|
|
size = int(self.headers.get('Content-Length','0'))
|
|
if size>16384: return self.respond(413)
|
|
q = dict(urllib.parse.parse_qsl(self.rfile.read(size).decode()))
|
|
if self.path == '/approve':
|
|
with idp.lock:
|
|
request = idp.requests.pop(q.get('request'),None)
|
|
if request is None: return self.respond(400)
|
|
code = secrets.token_hex(32); idp.codes[code] = request
|
|
return self.respond(303,location=idp.redirect+'?'+urllib.parse.urlencode({'code':code,'state':request['state']}))
|
|
if self.path != '/token': return self.respond(404)
|
|
with idp.lock:
|
|
idp.exchanges += 1
|
|
request = idp.codes.pop(q.get('code'),None)
|
|
if request is None or q.get('client_secret')!=idp.secret or q.get('redirect_uri')!=idp.redirect or q.get('client_id')!='rmm-browser' or q.get('grant_type')!='authorization_code' or encoded(hashlib.sha256(q.get('code_verifier','').encode()).digest())!=request['code_challenge']: return self.respond(400)
|
|
value = idp.token(aud='rmm-browser',typ='JWT',nonce='invalid' if idp.bad_nonce else request['nonce'])
|
|
self.respond(200,{'id_token':value,'token_type':'Bearer','access_token':'unused'})
|
|
|
|
self.server = ThreadingHTTPServer(('127.0.0.1',0),Handler)
|
|
self.issuer = f'https://localhost:{self.server.server_port}/'
|
|
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER);ctx.load_cert_chain(cert,key)
|
|
self.server.socket = ctx.wrap_socket(self.server.socket,server_side=True)
|
|
self.thread = threading.Thread(target=self.server.serve_forever,daemon=True);self.thread.start()
|
|
self.secret = secrets.token_hex(32)
|
|
def token(self, aud='https://rmm.example/mcp', typ='at+jwt', **overrides):
|
|
claims = {'iss':self.issuer,'sub':self.subject,'aud':aud,'exp':int(time.time())+300,'iat':int(time.time()),'nbf':int(time.time())-1,'jti':uuid.uuid4().hex,'client_id':'rmm-mcp','scope':'inventory:read operations:read plans:approve'}
|
|
claims.update(overrides)
|
|
header = {'alg':'RS256','kid':self.kid,'typ':typ}
|
|
body = encoded(json.dumps(header,separators=(',',':')).encode())+'.'+encoded(json.dumps(claims,separators=(',',':')).encode())
|
|
return body+'.'+encoded(self.key.sign(body.encode(),padding.PKCS1v15(),hashes.SHA256()))
|
|
|
|
|
|
def main():
|
|
global STAGE
|
|
env = {}
|
|
for line in (STATE/'.env').read_text().splitlines():
|
|
if line and not line.startswith('#'):
|
|
name,value=line.split('=',1);env[name]=value
|
|
result = subprocess.run(['docker','inspect','--format','{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}','rust-discovery-dev-postgres-1'],capture_output=True,text=True,check=True)
|
|
address = result.stdout.strip()
|
|
socket.inet_aton(address)
|
|
role = 'oidc_test_' + secrets.token_hex(8)
|
|
password = secrets.token_hex(32)
|
|
principal = None
|
|
process = None
|
|
idp = None
|
|
state_key_ref = None
|
|
assertions = 0
|
|
def check(value, label):
|
|
nonlocal assertions
|
|
if not value: raise RuntimeError(label)
|
|
assertions += 1;print('PASS',label)
|
|
with tempfile.TemporaryDirectory(prefix='oidc-server-',dir=STATE) as folder_name:
|
|
folder = Path(folder_name);folder.chmod(0o700)
|
|
try:
|
|
idp = Idp(folder)
|
|
with socket.socket() as sock:
|
|
sock.bind(('127.0.0.1',0));port=sock.getsockname()[1]
|
|
origin = f'https://rmm-dev.internal:{port}'
|
|
idp.redirect = origin+'/auth/oidc/callback'
|
|
principal = 'oidc:'+hashlib.sha256(json.dumps([idp.issuer,idp.subject],separators=(',',':')).encode()).hexdigest()
|
|
# Only identity routing/membership fixtures; never authorization/job writes.
|
|
sql(f"CREATE ROLE {role} LOGIN PASSWORD '{password}' NOSUPERUSER NOBYPASSRLS; GRANT USAGE ON SCHEMA rmm_oidc_auth TO {role}; GRANT SELECT,INSERT,DELETE ON rmm_oidc_auth.login_states TO {role}; INSERT INTO oidc_principals VALUES('{principal}','{idp.issuer}','{idp.subject}',ARRAY['{A}']::uuid[],false); INSERT INTO memberships VALUES('{A}','{principal}','human',ARRAY['inventory:read','operations:read','plans:approve'],NULL);")
|
|
app = urllib.parse.urlsplit(env['DATABASE_URL'])
|
|
def database_url(user, pwd): return urllib.parse.urlunsplit(('postgres',f'{user}:{pwd}@{address}:5432','/rmm','',''))
|
|
cfg = {'issuer':idp.issuer,'browser_client_id':'rmm-browser','client_secret_ref':private(folder/'client-secret',idp.secret),'redirect_uri':idp.redirect,'mcp_audience':'https://rmm.example/mcp','mcp_client_ids':['rmm-mcp'],'auth_database_url_ref':private(folder/'auth-db',database_url(role,password)),'state_key_ref':private(folder/'state-key',encoded(secrets.token_bytes(32))),'extra_ca_file':idp.ca,'testsimulation':True}
|
|
config = private(folder/'oidc.json',json.dumps(cfg))
|
|
state_key_ref = cfg['state_key_ref']
|
|
server_env = dict(os.environ)
|
|
server_env.update(env)
|
|
server_env.update(RMM_PROFILE='development',RMM_DEV_AUTH='true',DATABASE_URL=database_url(app.username,app.password),RMM_TLS_DIR=str(STATE/'pki'),RMM_JOB_KEY_FILE=str(STATE/'jobs/ed25519.pem'),RMM_WEB_DIR=str(ROOT/'web/dist'),RMM_UI_ORIGIN=origin,RMM_OIDC_CONFIG_FILE=config,RMM_LISTEN_ADDR=f'127.0.0.1:{port}',RMM_SERVER_ROLE='api')
|
|
for name in ('RUST_LOG','RUST_BACKTRACE'): server_env.pop(name,None)
|
|
def start():
|
|
nonlocal process
|
|
process=subprocess.Popen([str(ROOT/'target/debug/rmm-server')],env=server_env,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
|
|
for _ in range(100):
|
|
if process.poll() is not None: raise RuntimeError('configured server failed startup')
|
|
try:
|
|
if request('/healthz')[0]==200:return
|
|
except (OSError,ssl.SSLError):pass
|
|
time.sleep(.1)
|
|
raise RuntimeError('configured server did not become ready')
|
|
def request(path, method='GET', body=None, headers=None):
|
|
connection=http.client.HTTPSConnection('rmm-dev.internal',port,context=ssl.create_default_context(cafile=str(CA)),timeout=15)
|
|
def connect():
|
|
connection.sock=connection._context.wrap_socket(socket.create_connection(('127.0.0.1',port),timeout=15),server_hostname='rmm-dev.internal')
|
|
connection.connect=connect
|
|
h=dict(headers or {})
|
|
if body is not None:h['Content-Type']='application/json'
|
|
connection.request(method,path,body=None if body is None else json.dumps(body),headers=h)
|
|
response=connection.getresponse();items=response.getheaders();status=response.status
|
|
if 'text/event-stream' in response.getheader('Content-Type',''):
|
|
data=b''
|
|
while True:
|
|
line=response.readline()
|
|
if not line:break
|
|
if line.startswith(b'data:') and line[5:].strip():
|
|
value=json.loads(line[5:])
|
|
if 'result' in value or 'error' in value:
|
|
data=json.dumps(value).encode();break
|
|
else:data=response.read()
|
|
connection.close()
|
|
return status,items,data
|
|
def flow():
|
|
status,headers,_=request('/auth/oidc/login');check(status==303,'configured login starts real OIDC flow')
|
|
h=dict(headers);binding=h['set-cookie'].split(';')[0]
|
|
q=dict(urllib.parse.parse_qsl(urllib.parse.urlsplit(h['location']).query))
|
|
with idp.lock:
|
|
code=secrets.token_hex(32);idp.codes[code]=q
|
|
return '/auth/oidc/callback?'+urllib.parse.urlencode({'code':code,'state':q['state']}),binding
|
|
STAGE = 'configured native server startup'
|
|
start()
|
|
STAGE = 'HTTP OIDC contracts'
|
|
check(json.loads(request('/auth/config')[2])['oidc_login_url']=='/auth/oidc/login','UI discovery exposes nonempty OIDC login URL')
|
|
callback,binding=flow()
|
|
check(request(callback,headers={'Cookie':'__Host-rmm_oidc_binding=wrong'})[0]==401,'wrong binding rejected without burning correct state')
|
|
status,headers,_=request(callback,headers={'Cookie':binding})
|
|
check(status==303,'real token exchange validates signature nonce and PKCE')
|
|
cookies=[v.split(';')[0] for k,v in headers if k.lower()=='set-cookie' and v.startswith('__Host-rmm_session=')]
|
|
cookie=cookies[0]
|
|
check(request(callback,headers={'Cookie':binding})[0]==401,'consumed callback state cannot be replayed')
|
|
status,_,raw=request('/auth/session',headers={'Cookie':cookie});session=json.loads(raw)
|
|
check(status==200 and session['principal']==principal and session['testsimulation'] is True,'OIDC identity uses stable mapped principal and explicit dev simulation')
|
|
csrf={'Cookie':cookie,'Origin':origin,'X-CSRF-Token':session['csrf_token']}
|
|
check(request('/auth/logout','POST',{},headers={'Cookie':cookie})[0]==403,'OIDC cookie mutations require Origin and CSRF')
|
|
access=idp.token()
|
|
bearer={'Authorization':'Bearer '+access}
|
|
check(request(f'/api/v1/tenants/{A}/devices',headers=bearer)[0]==200,'resource JWT combines scopes with current persistent membership')
|
|
check(request(f'/api/v1/tenants/{B}/devices',headers=bearer)[0]==404,'foreign tenant uses same not-found boundary')
|
|
approval=f'/api/v1/tenants/{A}/operation-plans/{uuid.uuid4()}/authorizations'
|
|
check(request(approval,'POST',{'plan_hash':'0'*64},headers={**csrf,**bearer})[0]==403,'bearer cannot borrow valid browser cookie to approve even with membership and scope')
|
|
for token,label,expected in [(idp.token(aud='rmm-browser',typ='JWT'),'ID token',401),(idp.token(aud='rmm-browser'),'browser audience access token',401),(idp.token(iss='https://attacker.example/'),'wrong issuer',401),(idp.token(exp=int(time.time())-30),'expired token',401),(idp.token(scope='operations:read'),'missing scope',403),(idp.token(sub='unmapped-subject'),'unmapped identity',403)]:
|
|
check(request(f'/api/v1/tenants/{A}/devices',headers={'Authorization':'Bearer '+token})[0]==expected,label+' rejected')
|
|
oldkid=idp.kid;idp.kid='unknown-kid'
|
|
unknown=idp.token();idp.kid=oldkid
|
|
check(request(f'/api/v1/tenants/{A}/devices',headers={'Authorization':'Bearer '+unknown})[0]==401,'unknown kid rejected')
|
|
with idp.lock:idp.key=rsa.generate_private_key(public_exponent=65537,key_size=2048);idp.kid='rotated'
|
|
time.sleep(1.1)
|
|
check(request(f'/api/v1/tenants/{A}/devices',headers={'Authorization':'Bearer '+idp.token()})[0]==200,'real JWKS rotation refreshes configured issuer keys')
|
|
mcp={'Authorization':'Bearer '+idp.token(),'Accept':'application/json, text/event-stream','MCP-Protocol-Version':'2025-11-25'}
|
|
initialize={'jsonrpc':'2.0','id':1,'method':'initialize','params':{'protocolVersion':'2025-11-25','capabilities':{},'clientInfo':{'name':'oidc-test','version':'1'}}}
|
|
status,headers,_=request('/mcp','POST',initialize,headers=mcp)
|
|
check(status==200,'real MCP transport accepts targeted OAuth JWT')
|
|
session_id = next((v for k,v in headers if k.lower()=='mcp-session-id'),None)
|
|
if session_id:mcp['Mcp-Session-Id']=session_id
|
|
check(request('/mcp','POST',{'jsonrpc':'2.0','method':'notifications/initialized'},headers=mcp)[0]==202,'OIDC MCP initialized lifecycle')
|
|
call={'jsonrpc':'2.0','id':2,'method':'tools/call','params':{'name':'inventory.list_devices','arguments':{'tenant_id':A}}}
|
|
def result_json(raw):
|
|
text=raw.decode()
|
|
if text.startswith('event:') or text.startswith('data:'):
|
|
text=next(line[5:].strip() for line in text.splitlines() if line.startswith('data:'))
|
|
return json.loads(text)
|
|
status,_,raw=request('/mcp','POST',call,headers=mcp)
|
|
check(status==200 and not result_json(raw)['result'].get('isError',False),'actual OIDC MCP inventory tool uses current scoped identity')
|
|
restricted={**mcp,'Authorization':'Bearer '+idp.token(scope='operations:read')}
|
|
status,_,raw=request('/mcp','POST',call,headers=restricted)
|
|
check(status==200 and result_json(raw)['result'].get('isError',False),'MCP tool rejects insufficient access scope despite membership')
|
|
sql(f"UPDATE memberships SET revoked_at=now() WHERE principal='{principal}';")
|
|
check(request(f'/api/v1/tenants/{A}/devices',headers={'Authorization':'Bearer '+idp.token()})[0]==403 and request('/auth/session',headers={'Cookie':cookie})[0]==403,'membership revocation immediately affects JWT and browser session')
|
|
sql(f"UPDATE memberships SET revoked_at=NULL WHERE principal='{principal}'; UPDATE oidc_principals SET disabled=true WHERE principal='{principal}';")
|
|
check(request(f'/api/v1/tenants/{A}/devices',headers={'Authorization':'Bearer '+idp.token()})[0]==403,'disabled persistent external identity is denied')
|
|
sql(f"UPDATE oidc_principals SET disabled=false WHERE principal='{principal}';")
|
|
check(request('/mcp','POST',initialize,headers={'Authorization':'Bearer '+idp.token(aud='rmm-browser',typ='JWT'),'Accept':'application/json, text/event-stream'})[0]==401,'MCP rejects browser ID token')
|
|
check(request('/auth/logout','POST',{},headers=csrf)[0]==204 and request('/auth/session',headers={'Cookie':cookie})[0]==401,'local logout invalidates opaque RMM session')
|
|
idp.bad_nonce=True
|
|
callback,binding=flow()
|
|
check(request(callback,headers={'Cookie':binding})[0]==401,'nonce mismatch rejects signed ID token')
|
|
idp.bad_nonce=False
|
|
callback,binding=flow()
|
|
with idp.lock:
|
|
for value in idp.codes.values():value['code_challenge']='invalid-pkce'
|
|
check(request(callback,headers={'Cookie':binding})[0]==401,'provider-enforced PKCE failure rejects callback')
|
|
# Isolated real-browser truststore: never disable TLS or modify host roots.
|
|
home=folder/'browser-home';nss=home/'.pki/nssdb';nss.mkdir(parents=True,mode=0o700)
|
|
cache=ROOT/'web/node_modules/.cache'
|
|
certutil=shutil.which('certutil') or str(cache/'nss-tools/root/usr/bin/certutil')
|
|
quiet([certutil,'-N','-d','sql:'+str(nss),'--empty-password'])
|
|
for label,path in [('RMM server CA',str(CA)),('OIDC ephemeral CA',idp.ca)]:quiet([certutil,'-A','-d','sql:'+str(nss),'-n',label,'-t','C,,','-i',path])
|
|
browser_env={k:v for k,v in os.environ.items() if k not in ('DEBUG','PWDEBUG','NODE_DEBUG','RUST_LOG')}
|
|
browser_env.update(PLAYWRIGHT_BROWSERS_PATH=str(cache/'playwright-browsers'),RMM_OIDC_TEST_BROWSER_HOME=str(home),RMM_OIDC_TEST_ORIGIN=origin,RMM_OIDC_TEST_PRINCIPAL=principal)
|
|
STAGE = 'isolated Chromium OIDC flow'
|
|
quiet(['node',str(ROOT/'tests/oidc/browser.cjs')],env=browser_env,timeout=90)
|
|
check(True,'real Chromium UI OIDC authorization and cross-site callback, verified TLS and logout passed')
|
|
check(sql(f"SELECT count(*) FROM authorizations WHERE principal='{principal}';")=='0','no direct API/DB or browser plan authorization performed')
|
|
process.terminate();process.wait(timeout=10);process=None
|
|
cfg['testsimulation']=False;private(folder/'oidc.json',json.dumps(cfg))
|
|
server_env.update(RMM_PROFILE='production',RMM_DEV_AUTH='false')
|
|
for name in ('RMM_VIEWER_A','RMM_VIEWER_B','RMM_DEV_USERNAME','RMM_DEV_PASSWORD','RMM_OPERATOR_A','RMM_OPERATOR_B'):server_env.pop(name,None)
|
|
STAGE = 'configured production profile'
|
|
start()
|
|
STAGE = 'production dev-route denial'
|
|
check(request('/auth/dev/login','POST',{},headers={'Origin':origin})[0]==404,'configured production OIDC starts while dev login stays disabled')
|
|
STAGE = 'production non-simulated session'
|
|
callback,binding=flow()
|
|
status,headers,_=request(callback,headers={'Cookie':binding})
|
|
cookies=[v.split(';')[0] for k,v in headers if k.lower()=='set-cookie' and v.startswith('__Host-rmm_session=')]
|
|
check(status==303 and json.loads(request('/auth/session',headers={'Cookie':cookies[0]})[2])['testsimulation'] is False,'production OIDC session is non-simulated by server configuration, no role/group auto-grant')
|
|
print(f'OIDC server integration: {assertions} assertions passed; actual mock TLS/PG/Chromium only, no external IdP or production acceptance')
|
|
finally:
|
|
if process is not None:
|
|
process.terminate();process.wait(timeout=10)
|
|
if idp is not None:idp.server.shutdown();idp.server.server_close()
|
|
if principal is not None:
|
|
if state_key_ref is not None:
|
|
sql("DELETE FROM rmm_oidc_auth.login_states WHERE encryption_key_ref='"+state_key_ref.replace("'","''")+"';")
|
|
sql(f"DELETE FROM memberships WHERE principal='{principal}'; DELETE FROM oidc_principals WHERE principal='{principal}'; DROP OWNED BY {role}; DROP ROLE IF EXISTS {role};")
|
|
|
|
|
|
if __name__=='__main__':
|
|
try:main()
|
|
except Exception:
|
|
print('FAIL OIDC integration: '+STAGE+' (private details suppressed)',file=sys.stderr);sys.exit(1)
|