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
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,14 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## Unreleased
### Improvements
* Support Microsoft Entra ID access token login through the `:access_token` option (MS-TDS FEDAUTH feature extension, SECURITYTOKEN library), and decode the `FEATUREEXTACK` token
* Redact `:access_token` and `:password` when inspecting connection state

### Fixes
* Return a connection error instead of crashing when reconnecting to a server named by a routing `ENVCHANGE` fails

## v2.4.0 (2026-08-19)
### Fixes
* Fix `unique_constraint` support in Ecto for en-US error messages: MSSQL error metadata is now preserved when re-raising from `query!/4`, `prepare!/3`, `execute!/4` and `close!/2` (#173)
Expand Down
39 changes: 39 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,45 @@ config :your_app, :tds_conn,

```

## Microsoft Entra ID (Azure AD) access tokens

Azure SQL Database and Azure SQL Managed Instance accept a Microsoft Entra ID
access token in place of a SQL login. Pass it as `:access_token`; Tds then logs
in with the FEDAUTH feature extension (library SECURITYTOKEN) and sends an empty
username and password. `:access_token` and `:password` are mutually exclusive.

The token is a bearer credential, so Tds refuses it unless `ssl` is `true`,
`:on` or `:required`, and the login fails if the server does not acknowledge
FEDAUTH. Encryption alone does not authenticate the server: verify its
certificate and host name, or the token can be read by whoever answers.

An access token expires (typically after an hour), so supply it through
DBConnection's `:configure` option, which runs before every connect and lets a
reconnect pick up a fresh token (`:public_key.cacerts_get/0` needs OTP 25+):

```elixir
host = "myserver.database.windows.net"

Tds.start_link(
hostname: host,
database: "my_db",
ssl: true,
ssl_opts: [
verify: :verify_peer,
cacerts: :public_key.cacerts_get(),
server_name_indication: String.to_charlist(host),
customize_hostname_check: [
match_fun: :public_key.pkix_verify_hostname_match_fun(:https)
]
],
configure: fn opts -> Keyword.put(opts, :access_token, MyApp.Token.fetch!()) end
)
```

Use the Proxy connection policy on Azure SQL. Under Redirect, the gateway
routes the client to another host, which Tds follows with the same options,
so a pinned `server_name_indication` no longer matches that host's certificate.

## Connecting to SQL Server Instances

Tds supports SQL Server instances by passing `instance: "instancename"` to the connection options.
Expand Down
1 change: 1 addition & 0 deletions lib/tds.ex
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ defmodule Tds do
| {:database, String.t()}
| {:username, String.t()}
| {:password, String.t()}
| {:access_token, String.t()}
| {:timeout, timeout()}
| {:connect_timeout, timeout()}
| {:execution_mode, :prepare_execute | :executesql}
Expand Down
12 changes: 7 additions & 5 deletions lib/tds/messages.ex
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ defmodule Tds.Messages do

# requests
defrecord :msg_prelogin, [:params]
defrecord :msg_login, [:params]
defrecord :msg_login, [:params, :fed_auth]
defrecord :msg_ready, [:status]
defrecord :msg_sql, [:query]
defrecord :msg_transmgr, [:command, :name, :isolation_level]
Expand All @@ -23,7 +23,7 @@ defmodule Tds.Messages do

# responses
defrecord :msg_preloginack, [:response]
defrecord :msg_loginack, [:redirect]
defrecord :msg_loginack, [:redirect, feature_acks: %{}]
defrecord :msg_prepared, [:params]
defrecord :msg_sql_result, [:columns, :rows, :row_count]
defrecord :msg_result, [:set, :params, :status]
Expand Down Expand Up @@ -79,6 +79,9 @@ defmodule Tds.Messages do
{:envchange, other}, {msg, s} ->
{msg, on_envchange(other, s)}

{:featureextack, acks}, {msg_loginack() = msg, s} ->
{msg_loginack(msg, feature_acks: acks), s}

{:loginack, %{tds_version: version}}, {msg, s} ->
Process.put(:tds_version, version)
{msg, s}
Expand All @@ -94,7 +97,6 @@ defmodule Tds.Messages do
{msg_error(error: error), s}

_, msg ->
# FeatureExtAck should be processed here in future
msg
end)
end
Expand Down Expand Up @@ -247,9 +249,9 @@ defmodule Tds.Messages do
Prelogin.encode(opts)
end

defp encode(msg_login(params: opts), _env) do
defp encode(msg_login(params: opts, fed_auth: fed_auth), _env) do
opts
|> Login7.new()
|> Login7.new(fed_auth)
|> Login7.encode()
end

Expand Down
102 changes: 90 additions & 12 deletions lib/tds/protocol.ex
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ defmodule Tds.Protocol do
Implements DBConnection behaviour for TDS protocol.
"""
alias Tds.{Parameter, Query}
alias Tds.Protocol.Login7
import Tds.{BinaryUtils, Messages, Utils}
require Logger
use DBConnection
Expand Down Expand Up @@ -42,7 +43,8 @@ defmodule Tds.Protocol do
result: nil | list(),
query: nil | String.t(),
transaction: transaction,
env: env
env: env,
fed_auth: %{echo: boolean(), nonce: nil | binary()}
}

defstruct sock: nil,
Expand All @@ -59,10 +61,20 @@ defmodule Tds.Protocol do
savepoint: 0,
collation: %Tds.Protocol.Collation{},
packetsize: 4096
}
},
# The server's PRELOGIN FEDAUTHREQUIRED answer and NONCE, both echoed
# back in LOGIN7's FEDAUTH feature
fed_auth: %{echo: false, nonce: nil}

@spec connect(opts :: Keyword.t()) :: {:ok, state :: t()} | {:error, Exception.t()}
def connect(opts) do
with :ok <- validate_access_token(opts) do
if opts[:access_token], do: warn_unverified_tls(opts[:ssl_opts] || [])
do_connect(opts)
end
end

defp do_connect(opts) do
opts =
opts
|> Keyword.put_new(:username, System.get_env("MSSQLUSER") || System.get_env("USER"))
Expand All @@ -85,6 +97,43 @@ defmodule Tds.Protocol do
end
end

# Runs on the caller's options, before the MSSQL* environment defaults fill
# in a password. An access token is a bearer credential, so it is refused
# before any socket opens unless LOGIN7 will travel encrypted. No error
# message includes the token.
defp validate_access_token(opts) do
token = opts[:access_token]

cond do
is_nil(token) ->
:ok

not is_binary(token) or token == "" or not String.valid?(token) ->
{:error, Tds.Error.exception(":access_token must be a non-empty UTF-8 string")}

not is_nil(opts[:password]) ->
{:error, Tds.Error.exception("Pass either :access_token or :password, not both.")}

opts[:ssl] not in [true, :on, :required] ->
{:error,
Tds.Error.exception(
"Login with :access_token requires an encrypted connection (ssl: true)."
)}

true ->
:ok
end
end

defp warn_unverified_tls(ssl_opts) do
if ssl_opts[:verify] == :verify_none do
Logger.warning(
"Tds: :access_token sent with ssl_opts verify: :verify_none; " <>
"the server certificate is not verified"
)
end
end

@spec disconnect(err :: Exception.t() | String.t(), state :: t()) :: :ok
def disconnect(_err, %{sock: {mod, sock}} = s) do
# If socket is active we flush any socket messages so the next
Expand Down Expand Up @@ -528,7 +577,7 @@ defmodule Tds.Protocol do
end

def login(%{opts: opts} = s) do
msg = msg_login(params: opts)
msg = msg_login(params: opts, fed_auth: s.fed_auth)

case login_send(msg, %{s | state: :login}) do
{:ok, s} ->
Expand Down Expand Up @@ -742,24 +791,40 @@ defmodule Tds.Protocol do
end
end

# `opts` already carries the environment defaults, so the redirect skips
# `connect/1`'s validation of the caller's options.
def message(
:login,
msg_loginack(redirect: %{hostname: host, port: port}),
%{opts: opts}
%{opts: opts, sock: {mod, sock}} = s
) do
opts
|> Keyword.put(:hostname, host)
|> Keyword.put(:port, port)
|> connect()
|> do_connect()
|> case do
{:ok, _} = ok ->
mod.close(sock)
ok

{:error, error} ->
{:error, error, s}
end
end

def message(:login, msg_loginack(), %{opts: opts} = s) do
# MS-TDS: a server that accepts a FEDAUTH login MUST acknowledge the feature.
def message(:login, msg_loginack(feature_acks: acks), %{opts: opts} = s) do
state = %{s | opts: clean_opts(opts)}

opts
|> conn_opts()
|> IO.iodata_to_binary()
|> send_query(state)
if opts[:access_token] && not Map.has_key?(acks, Login7.feature_ext_fedauth()) do
{:error, Tds.Error.exception("Server did not acknowledge the FEDAUTH login feature."),
state}
else
opts
|> conn_opts()
|> IO.iodata_to_binary()
|> send_query(state)
end
end

def message(:executing, msg_result(set: set), s) do
Expand Down Expand Up @@ -941,8 +1006,11 @@ defmodule Tds.Protocol do
end
end

defp clean_opts(opts) do
Keyword.put(opts, :password, :REDACTED)
@doc false
def clean_opts(opts) do
opts
|> Keyword.put(:password, :REDACTED)
|> Keyword.replace(:access_token, :REDACTED)
end

@spec conn_opts(Keyword.t()) :: list() | no_return
Expand Down Expand Up @@ -1160,3 +1228,13 @@ defmodule Tds.Protocol do
|> Enum.max()
end
end

defimpl Inspect, for: Tds.Protocol do
# Connection state holds the credentials until login completes, and is
# logged by `handle_info/2` and by DBConnection on crashes.
def inspect(%{opts: conn_opts} = state, opts) when is_list(conn_opts) do
Inspect.Any.inspect(%{state | opts: Tds.Protocol.clean_opts(conn_opts)}, opts)
end

def inspect(state, opts), do: Inspect.Any.inspect(state, opts)
end
Loading