Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 11 additions & 4 deletions python-phoenixdb/phoenixdb/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,6 @@
# limitations under the License.
import sys

import gssapi

from phoenixdb import errors, types
from phoenixdb.avatica import AvaticaClient
from phoenixdb.connection import Connection
Expand All @@ -24,8 +22,6 @@

from requests.auth import HTTPBasicAuth, HTTPDigestAuth

from requests_gssapi import HTTPSPNEGOAuth

if sys.version_info.major == 3:
from urllib.parse import urlencode, urlparse, urlunparse, parse_qs
else:
Expand Down Expand Up @@ -127,6 +123,17 @@ def connect(url, max_retries=None, auth=None, authentication=None, avatica_user=


def _get_SPNEGOAuth():
if sys.platform == 'win32':
try:
from phoenixdb.sspi_auth import HTTPSPNEGOAuthSSPI
except ImportError:
# pyspnego needs Python 3.8+, fall back to requests_gssapi below
pass
else:
return HTTPSPNEGOAuthSSPI()

import gssapi
from requests_gssapi import HTTPSPNEGOAuth
try:
spnego = gssapi.mechs.Mechanism.from_sasl_name("SPNEGO")
except AttributeError:
Expand Down
87 changes: 87 additions & 0 deletions python-phoenixdb/phoenixdb/sspi_auth.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""SPNEGO authentication for requests on Windows.

Uses pyspnego, which goes through the native SSPI (and so the logged on user's
LSA Kerberos tickets) on Windows, so no MIT Kerberos installation is needed.
"""

import base64
import re
from urllib.parse import urlparse

from requests.auth import AuthBase

try:
import spnego
except OSError as e:
# pyspnego only catches ImportError around its optional gssapi import. A gssapi
# package installed without MIT Kerberos for Windows raises OSError instead.
raise RuntimeError(
"pyspnego could not be imported because the installed 'gssapi' package is "
"broken (%s). SSPI does not need it: run 'pip uninstall gssapi requests-gssapi'."
% e) from e

_NEGOTIATE_RE = re.compile(r'(?:^|,)\s*Negotiate\s*([^,]*)', re.IGNORECASE)


def _negotiate_token(response):
match = _NEGOTIATE_RE.search(response.headers.get('www-authenticate', ''))
if match is None:
return None
token = match.group(1).strip()
return base64.b64decode(token) if token else b''


class HTTPSPNEGOAuthSSPI(AuthBase):
"""Opportunistic SPNEGO ("Negotiate") authentication, like
requests_gssapi.HTTPSPNEGOAuth(opportunistic_auth=True) with mutual
authentication disabled."""

def __init__(self, service='HTTP'):
self.service = service

def _new_context(self, url):
return spnego.client(hostname=urlparse(url).hostname, service=self.service,
protocol='negotiate')

def __call__(self, r):
ctx = self._new_context(r.url)
r.headers['Authorization'] = 'Negotiate ' + base64.b64encode(ctx.step()).decode()
r.register_hook('response', self._handle_401(ctx))
return r

def _handle_401(self, ctx):
def handle(response, **kwargs):
if response.status_code != 401 or getattr(response.request, '_spnego_retried', False):
return response
in_token = _negotiate_token(response)
if not in_token or ctx.complete:
# The server rejected the token outright, retrying won't help
return response

# Multi-leg exchange: answer the server's challenge on the same connection
response.content
response.close()
prep = response.request.copy()
prep.headers['Authorization'] = 'Negotiate ' + \
base64.b64encode(ctx.step(in_token)).decode()
prep._spnego_retried = True
new_response = response.connection.send(prep, **kwargs)
new_response.history.append(response)
new_response.request = prep
return new_response
return handle
3 changes: 2 additions & 1 deletion python-phoenixdb/requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,5 @@
#
protobuf>=3.0.0
requests
requests-gssapi
requests-gssapi; sys_platform != "win32"
pyspnego; sys_platform == "win32"
5 changes: 4 additions & 1 deletion python-phoenixdb/setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@ def readme():
]
if sys.version_info < (3,8):
install_requires.append('requests-gssapi<1.3.0')
elif sys.platform == 'win32':
install_requires.append('pyspnego')
else:
install_requires.append('requests-gssapi')
if sys.version_info < (3,6):
Expand All @@ -53,7 +55,8 @@ def readme():
install_requires=[
'protobuf>=3.0.0',
'requests',
'requests-gssapi; python_version>="3.8.0"',
'requests-gssapi; python_version>="3.8.0" and sys_platform!="win32"',
'pyspnego; python_version>="3.8.0" and sys_platform=="win32"',
'requests-gssapi<1.3.0; python_version<"3.8.0"',
'gssapi<1.6.0; python_version<"3.6.0"',
]
Expand Down