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
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,8 @@ This favors bounded validation latency over trying every idle connection during

> **`DefaultAzureCredential` is not recommended for multi-user pooling:** `ActiveDirectoryDefault` resolves to whatever ambient identity `DefaultAzureCredential` discovers (environment, managed identity, developer sign-in, etc.), which is a single process-wide identity. It is well suited to single-identity services but does **not** distinguish between end users, so pooled connections opened with it are not isolated per user. The driver emits a one-time warning in this case. For genuinely multi-user workloads, use a per-user token provider instead. (You will also see this noted in the emitted log warning.) Because a `DefaultAzureCredential` pool is keyed on the token hash rather than a stable identity, it is also **not** expiry-aware: the driver-acquired token is reused until the connection dies, so it is best suited to short-lived or single-identity use.

Raw tokens in `attrs_before[1256]` must be `bytes` or `bytearray` containing a four-byte little-endian payload length followed by the expanded token bytes (normally UTF-16LE, without a terminator). The length must exactly match a non-empty, even-length payload, and the entire buffer must fit ODBC's signed 32-bit length argument. Malformed structures, including empty buffers, raise `OperationalError` before pool checkout or passing the token to ODBC. The shared native validation also covers deferred token factories when they are invoked; it does not parse JWTs or validate credential expiry, signatures, or audiences.

### DBAPI v2.0 Compliance

The Microsoft **mssql-python** module is designed to be fully compliant with the DB API 2.0 specification. This ensures that the driver adheres to a standardized interface for database access in Python, providing consistency and reliability across different database systems. Key aspects of DBAPI v2.0 compliance include:
Expand Down
36 changes: 36 additions & 0 deletions mssql_python/pybind/connection/connection.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,33 @@
#include "logger_bridge.hpp"
#include "performance_counter.hpp"

static void validateAccessTokenStructure(const py::object& value) {
const bool isBytes = py::isinstance<py::bytes>(value);
if (!isBytes && !py::isinstance<py::bytearray>(value)) {
ThrowStdException("SQL_COPT_SS_ACCESS_TOKEN must be supplied as bytes or bytearray.");
}
const Py_ssize_t bufferSize =
isBytes ? PyBytes_GET_SIZE(value.ptr()) : PyByteArray_GET_SIZE(value.ptr());
if (bufferSize < 4 || bufferSize > std::numeric_limits<SQLINTEGER>::max()) {
ThrowStdException(
"Invalid SQL_COPT_SS_ACCESS_TOKEN structure: expected a 4-byte length "
"header and a payload that fits SQLINTEGER.");
}
const char* data =
isBytes ? PyBytes_AS_STRING(value.ptr()) : PyByteArray_AS_STRING(value.ptr());
SQLUINTEGER payloadLength = 0;
for (int i = 0; i < 4; ++i) {
payloadLength |=
static_cast<SQLUINTEGER>(static_cast<unsigned char>(data[i])) << (8 * i);
}
if (payloadLength == 0 || payloadLength % 2 != 0 ||
static_cast<size_t>(payloadLength) != static_cast<size_t>(bufferSize - 4)) {
ThrowStdException(
"Invalid SQL_COPT_SS_ACCESS_TOKEN structure: the length header must "
"match a non-empty, even-length token payload.");
}
}

static bool isPythonFinalizing() {
if (Py_IsInitialized() == 0) {
return true;
Expand Down Expand Up @@ -469,6 +496,10 @@ SQLRETURN Connection::setAttribute(SQLINTEGER attribute, py::object value, bool&
return SQL_ERROR;
}

if (attribute == SQL_COPT_SS_ACCESS_TOKEN) {
Comment thread
Copilot marked this conversation as resolved.
Resolved
validateAccessTokenStructure(value);
}

if (py::isinstance<py::int_>(value)) {
// Get the integer value
int64_t longValue;
Expand Down Expand Up @@ -920,6 +951,11 @@ ConnectionHandle::ConnectionHandle(const std::u16string& connStr, bool usePool,
const py::object& tokenFactory)
: _usePool(usePool), _connStr(connStr), _poolKey(poolKey.empty() ? connStr : poolKey) {
PERF_TIMER("ConnectionHandle::ConnectionHandle");
// Pool hits skip setAttribute(), but explicit token buffers must still be valid.
const py::int_ tokenAttribute(SQL_COPT_SS_ACCESS_TOKEN);
if (!attrsBefore.is_none() && attrsBefore.contains(tokenAttribute)) {
validateAccessTokenStructure(attrsBefore[tokenAttribute]);
}
if (_usePool) {
_conn = ConnectionPoolManager::getInstance().acquireConnection(_connStr, attrsBefore,
_poolKey, tokenFactory,
Expand Down
122 changes: 122 additions & 0 deletions tests/test_008_auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,11 @@

import pytest
import collections
import os
import platform
import subprocess
import sys
import textwrap
import threading
import warnings
from concurrent.futures import ThreadPoolExecutor
Expand Down Expand Up @@ -41,6 +44,125 @@
SAMPLE_TOKEN = secrets.token_hex(44)


@pytest.mark.parametrize("route", ["public", "native", "native_factory"])
@pytest.mark.parametrize(
"token, malformed",
[
pytest.param(b"", True, id="empty-bytes"),
pytest.param(bytearray(), True, id="empty-bytearray"),
pytest.param(b"a" * 3, True, id="truncated-header"),
pytest.param(b"a" * 16, True, id="reported-16-bytes"),
pytest.param(b"x" * 64, True, id="reported-64-bytes"),
pytest.param(bytearray(b"a" * 16), True, id="malformed-bytearray"),
pytest.param(b"\x00\x00\x00\x00", True, id="empty-payload"),
pytest.param(b"\x06\x00\x00\x00a\x00", True, id="overclaimed-payload"),
pytest.param(b"\x01\x00\x00\x00a", True, id="odd-payload"),
pytest.param(b"\x02\x00\x00\x00a\x00b\x00", True, id="trailing-payload"),
pytest.param(AADAuth.get_token_struct("opaque-not-a-jwt"), False, id="packed-opaque"),
pytest.param(AADAuth.get_token_struct("a"), False, id="packed-one-character"),
pytest.param(
bytearray(AADAuth.get_token_struct("opaque-not-a-jwt")), False, id="packed-bytearray"
),
],
)
def test_access_token_structure_in_subprocess(conn_str, route, token, malformed):
"""Exercise the real native boundary without letting a regression crash pytest."""
_run_access_token_probe(conn_str, route, token, malformed)


@pytest.mark.parametrize("route", ["public", "native"])
@pytest.mark.parametrize("token", [b"", bytearray()], ids=["bytes", "bytearray"])
def test_empty_access_token_rejected_before_pool_checkout(conn_str, route, token):
"""An explicitly empty token must not reuse a token-free pooled connection."""
_run_access_token_probe(conn_str, "pooled_" + route, token, True)


def _run_access_token_probe(conn_str, route, token, malformed):
if not conn_str:
pytest.skip("DB_CONNECTION_STRING is required for native token probes")
pooled = route.startswith("pooled_")
route = route.removeprefix("pooled_")
body = textwrap.dedent(f"""
import logging
import os
import mssql_python as ms
from mssql_python import ddbc_bindings
from mssql_python.connection import Connection
from mssql_python.connection_string_parser import _ConnectionStringParser
from mssql_python.connection_string_builder import _ConnectionStringBuilder
from mssql_python.logging import logger
from mssql_python.odbc_provider import ProviderManager

logging.disable(logging.CRITICAL)
logger.disabled = True
pooled = {pooled!r}
if pooled:
ms.pooling(max_size=1, idle_timeout=30)
else:
ms.pooling = False
parser = _ConnectionStringParser(validate_keywords=True)
params = parser._normalize_params(parser._parse(os.environ["DB_CONNECTION_STRING"]))
# The token-free pool must warm with the endpoint's normal authentication.
removed_keys = ("Driver",) if pooled else (
"Driver", "UID", "PWD", "Authentication", "Trusted_Connection"
)
for key in removed_keys:
params.pop(key, None)
connection_string = _ConnectionStringBuilder(params).build()
assert parser._normalize_params(parser._parse(connection_string)) == params
if pooled:
with ms.connect(connection_string, timeout=5) as warm:
with warm.cursor() as cursor:
cursor.execute("SELECT 1")
assert cursor.fetchone()[0] == 1
attrs = {{1256: {token!r}, ms.SQL_ATTR_LOGIN_TIMEOUT: 5}}
route = {route!r}
malformed = {malformed!r}
try:
if route == "public":
conn = ms.connect(connection_string, attrs_before=attrs, timeout=5)
else:
ddbc_bindings._set_odbc_provider(ProviderManager.ensure_available())
native_string, _ = Connection.__new__(Connection)._construct_connection_string(
connection_string
)
factory = (lambda: (attrs, None)) if route == "native_factory" else None
conn = ddbc_bindings.Connection(
native_string, pooled, {{}} if factory else attrs, "", factory
)
except (ms.Error, ms.Warning, RuntimeError) as exc:
validation_error = "Invalid SQL_COPT_SS_ACCESS_TOKEN structure" in str(exc)
assert validation_error == malformed, type(exc).__name__
if malformed:
expected = ms.OperationalError if route == "public" else RuntimeError
assert isinstance(exc, expected), type(exc).__name__
else:
# A correctly packed opaque credential can be rejected by the endpoint.
assert getattr(exc, "sqlstate", None) or "SQLSTATE:" in str(exc)
else:
conn.close()
assert not malformed, "Malformed access token was accepted"
if pooled:
with ms.connect(connection_string, timeout=5) as healthy:
with healthy.cursor() as cursor:
cursor.execute("SELECT 1")
assert cursor.fetchone()[0] == 1
ms.pooling(enabled=False)
""")
env = os.environ.copy()
env["DB_CONNECTION_STRING"] = str(conn_str)
proc = subprocess.run(
[sys.executable, "-X", "faulthandler", "-c", body],
env=env,
capture_output=True,
text=True,
timeout=20,
)
assert (
proc.returncode == 0
), f"Token probe failed with exit code {proc.returncode}\n{proc.stdout}\n{proc.stderr}"


@pytest.fixture(autouse=True)
def setup_azure_identity():
"""Setup mock azure.identity module"""
Expand Down
Loading