pyceo/ceo_common/model/HTTPClient.py

80 lines
2.8 KiB
Python
Raw Normal View History

2021-08-25 22:19:18 -04:00
import flask
2021-08-28 23:09:02 -04:00
from flask import g
2021-07-24 17:09:10 -04:00
import gssapi
import requests
from requests_gssapi import HTTPSPNEGOAuth
from zope import component
from zope.interface import implementer
from ceo_common.interfaces import IConfig, IHTTPClient, IKerberosService
2021-07-24 17:09:10 -04:00
@implementer(IHTTPClient)
class HTTPClient:
def __init__(self):
# Determine how to connect to other ceod instances
cfg = component.getUtility(IConfig)
if cfg.get('ceod_use_https'):
self.scheme = 'https'
else:
self.scheme = 'http'
self.ceod_port = cfg.get('ceod_port')
2021-08-03 19:19:33 -04:00
self.base_domain = cfg.get('base_domain')
2021-07-24 17:09:10 -04:00
2021-08-28 23:09:02 -04:00
def request(self, method: str, host: str, path: str, **kwargs):
2021-08-21 02:27:33 -04:00
# always use the FQDN
if '.' not in host:
host = host + '.' + self.base_domain
2021-08-23 09:59:01 -04:00
2021-08-28 23:09:02 -04:00
if method == 'GET':
need_auth = path.startswith('/api/members') or \
path.startswith('/api/cloud')
2021-08-28 23:09:02 -04:00
delegate = False
else:
need_auth = True
delegate = True
2021-08-23 09:59:01 -04:00
# SPNEGO
2021-08-28 23:09:02 -04:00
if need_auth:
spnego_kwargs = {
'opportunistic_auth': True,
'target_name': gssapi.Name('ceod/' + host),
}
if flask.has_request_context():
2021-08-28 23:09:02 -04:00
# This is reached when we are the server and the client has
# forwarded their credentials to us.
token = None
if g.get('need_admin_creds', False):
# Some Kerberos bindings in some programming languages can't
# perform delegation, so use the admin creds here.
token = component.getUtility(IKerberosService).get_admin_creds_token()
elif 'client_token' in g:
token = g.client_token
if token is not None:
spnego_kwargs['creds'] = gssapi.Credentials(token=token)
2021-08-28 23:09:02 -04:00
elif delegate:
# This is reached when we are the client and we want to
# forward our credentials to the server.
spnego_kwargs['delegate'] = True
auth = HTTPSPNEGOAuth(**spnego_kwargs)
else:
auth = None
2021-08-23 09:59:01 -04:00
2021-07-24 17:09:10 -04:00
return requests.request(
method,
2021-08-28 23:09:02 -04:00
f'{self.scheme}://{host}:{self.ceod_port}{path}',
2021-08-25 22:19:18 -04:00
auth=auth, **kwargs,
2021-07-24 17:09:10 -04:00
)
2021-08-28 23:09:02 -04:00
def get(self, host: str, path: str, **kwargs):
return self.request('GET', host, path, **kwargs)
2021-08-23 09:59:01 -04:00
2021-08-28 23:09:02 -04:00
def post(self, host: str, path: str, **kwargs):
return self.request('POST', host, path, **kwargs)
2021-07-24 17:09:10 -04:00
2021-08-28 23:09:02 -04:00
def patch(self, host: str, path: str, **kwargs):
return self.request('PATCH', host, path, **kwargs)
2021-07-24 17:09:10 -04:00
2021-08-28 23:09:02 -04:00
def delete(self, host: str, path: str, **kwargs):
return self.request('DELETE', host, path, **kwargs)