Skip to content
Draft
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
111 changes: 111 additions & 0 deletions mssql_python/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,103 @@ def _acquire_token(auth_type: str) -> Tuple[bytes, str]:
raise RuntimeError(f"Failed to create {credential_class.__name__}: {e}") from e


def _parse_tenant_id(sts_url: str) -> Optional[str]:
"""Extract tenant ID (GUID or domain) from a FedAuthInfo STS URL.

Expected formats:
https://login.microsoftonline.com/<tenant>/
https://login.microsoftonline.com/<tenant>/?...
https://login.microsoftonline.com/<tenant>
where <tenant> is either a GUID (e.g. ``aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee``)
or a verified domain (e.g. ``contoso.onmicrosoft.com``). Both forms are
accepted by ``azure.identity.ClientSecretCredential``.
"""
# pylint: disable=import-outside-toplevel
from urllib.parse import urlparse

try:
parsed = urlparse(sts_url)
except (ValueError, AttributeError):
return None
path = (parsed.path or "").strip("/")
if not path:
return None
first_segment = path.split("/", 1)[0]
return first_segment or None
Comment on lines +147 to +155


class ServicePrincipalAuth:
"""Builds an ``entra_id_token_factory`` callable for ActiveDirectoryServicePrincipal.

The bulkcopy path through mssql-py-core uses callback-based token
acquisition (FedAuth workflow ``0x02``) because tenant_id is only known
from the STS URL that the server returns during the TDS handshake.
"""

@staticmethod
def make_token_factory(client_id: str, client_secret: str):
"""Return a callable suitable for ``entra_id_token_factory``.

Signature: ``(spn: str, sts_url: str, auth_method: str) -> bytes``.
Returns the JWT encoded as UTF-16LE bytes (the TDS FedAuth wire format).
``ClientSecretCredential`` is constructed inside the callable so
each invocation rebuilds it; tenant is parsed from ``sts_url``
on every call rather than captured.
"""
if not client_id:
raise ValueError("ServicePrincipal auth requires a non-empty client_id (UID)")
if not client_secret:
raise ValueError("ServicePrincipal auth requires a non-empty client_secret (PWD)")

def _factory(spn: str, sts_url: str, auth_method: str) -> bytes:
# pylint: disable=import-outside-toplevel,unused-argument
try:
from azure.identity import ClientSecretCredential
from azure.core.exceptions import ClientAuthenticationError
except ImportError as e:
raise RuntimeError(
"Azure authentication libraries are not installed. "
"Please install with: pip install azure-identity azure-core"
) from e

tenant_id = _parse_tenant_id(sts_url)
if not tenant_id:
raise RuntimeError(
f"Could not extract tenant_id from STS URL: {sts_url!r}"
)

logger.info(
"ServicePrincipal token factory: acquiring token for tenant=%s, spn=%s",
tenant_id,
spn,
)
try:
credential = ClientSecretCredential(
tenant_id=tenant_id,
client_id=client_id,
client_secret=client_secret,
)
# mssql-tds passes the resource SPN; azure-identity wants a scope.
scope = spn if spn.endswith("/.default") else spn.rstrip("/") + "/.default"
token = credential.get_token(scope).token
logger.info(
"ServicePrincipal token factory: token acquired, length=%d chars",
len(token),
)
return token.encode("utf-16-le")
except ClientAuthenticationError as e:
logger.error(
"ServicePrincipal authentication failed: tenant=%s, error=%s",
tenant_id,
str(e),
)
raise RuntimeError(
f"ServicePrincipal authentication failed for tenant '{tenant_id}': {e}"
) from e

return _factory


def process_auth_parameters(parameters: List[str]) -> Tuple[List[str], Optional[str]]:
"""
Process connection parameters and extract authentication type.
Expand Down Expand Up @@ -180,6 +277,19 @@ def process_auth_parameters(parameters: List[str]) -> Tuple[List[str], Optional[
# Default authentication (uses DefaultAzureCredential)
logger.debug("process_auth_parameters: Default Azure authentication detected")
auth_type = "default"
elif value_lower == AuthType.SERVICE_PRINCIPAL.value:
# ServicePrincipal authentication. ODBC (msodbcsql 17.3+)
# handles this natively for regular queries, so leave
# auth_type=None to let ODBC own the query path.
# Bulkcopy still needs the auth type — extract_auth_type()
# propagates it as "serviceprincipal" so the bulkcopy path
# can register an entra_id_token_factory callback (Model B,
# required because tenant_id is only known from the STS URL
# that the server returns during the FedAuth handshake).
logger.debug(
"process_auth_parameters: Service principal authentication detected"
)
auth_type = None
modified_parameters.append(param)

logger.debug(
Expand Down Expand Up @@ -246,6 +356,7 @@ def extract_auth_type(connection_string: str) -> Optional[str]:
AuthType.INTERACTIVE.value: "interactive",
AuthType.DEVICE_CODE.value: "devicecode",
AuthType.DEFAULT.value: "default",
AuthType.SERVICE_PRINCIPAL.value: "serviceprincipal",
}
for part in connection_string.split(";"):
key, _, value = part.strip().partition("=")
Expand Down
1 change: 1 addition & 0 deletions mssql_python/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -337,6 +337,7 @@ class AuthType(Enum):
INTERACTIVE = "activedirectoryinteractive"
DEVICE_CODE = "activedirectorydevicecode"
DEFAULT = "activedirectorydefault"
SERVICE_PRINCIPAL = "activedirectoryserviceprincipal"


class SQLTypes:
Expand Down
70 changes: 52 additions & 18 deletions mssql_python/cursor.py
Original file line number Diff line number Diff line change
Expand Up @@ -2934,24 +2934,58 @@ def bulkcopy(
# Token acquisition — only thing cursor must handle (needs azure-identity SDK)
if self.connection._auth_type:
# Fresh token acquisition for mssql-py-core connection
from mssql_python.auth import AADAuth

try:
raw_token = AADAuth.get_raw_token(self.connection._auth_type)
except (RuntimeError, ValueError) as e:
raise RuntimeError(
f"Bulk copy failed: unable to acquire Azure AD token "
f"for auth_type '{self.connection._auth_type}': {e}"
) from e
pycore_context["access_token"] = raw_token
# Token replaces credential fields — py-core's validator rejects
# access_token combined with authentication/user_name/password.
for key in ("authentication", "user_name", "password"):
pycore_context.pop(key, None)
logger.debug(
"Bulk copy: acquired fresh Azure AD token for auth_type=%s",
self.connection._auth_type,
)
from mssql_python.auth import AADAuth, ServicePrincipalAuth

if self.connection._auth_type == "serviceprincipal":
# Model B: callback-based. tenant_id is only known from the
# STS URL the server returns mid-handshake, so we register a
# factory that py-core invokes during FedAuth (workflow 0x02).
client_id = params.get("uid", "")
client_secret = params.get("pwd", "")
if not client_id or not client_secret:
raise RuntimeError(
"Bulk copy with Authentication=ActiveDirectoryServicePrincipal "
"requires UID (client_id) and PWD (client_secret) in the "
"connection string."
)
try:
factory = ServicePrincipalAuth.make_token_factory(
client_id, client_secret
)
except (RuntimeError, ValueError) as e:
raise RuntimeError(
f"Bulk copy failed: unable to build ServicePrincipal "
f"token factory: {e}"
) from e
pycore_context["entra_id_token_factory"] = factory
# Keep authentication/user_name/password in pycore_context —
# py-core's auth validator + transformer need them to resolve
# the auth method to ActiveDirectoryServicePrincipal before
# the factory is dispatched at handshake time.
Comment on lines +2951 to +2964
Comment on lines +2960 to +2964
logger.debug(
"Bulk copy: registered ServicePrincipal token factory for client_id=%s",
client_id,
Comment on lines +2966 to +2967
)
else:
# Model A: pre-acquired token. Used for Default, DeviceCode,
# Interactive (non-Windows), and any other AD method whose
# tenant_id is discoverable client-side via Azure Identity SDK.
try:
raw_token = AADAuth.get_raw_token(self.connection._auth_type)
except (RuntimeError, ValueError) as e:
raise RuntimeError(
f"Bulk copy failed: unable to acquire Azure AD token "
f"for auth_type '{self.connection._auth_type}': {e}"
) from e
pycore_context["access_token"] = raw_token
# Token replaces credential fields — py-core's validator rejects
# access_token combined with authentication/user_name/password.
for key in ("authentication", "user_name", "password"):
pycore_context.pop(key, None)
logger.debug(
"Bulk copy: acquired fresh Azure AD token for auth_type=%s",
self.connection._auth_type,
)

pycore_connection = None
pycore_cursor = None
Expand Down
Loading
Loading