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
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,12 @@ 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).

### Features
* Add federated authentication (Azure AD / Microsoft Entra ID) using the Security Token library: pass an access token via the `:access_token` connection option; the token is sent in the FEDAUTH FeatureExt block of LOGIN7 and `username`/`password` are ignored. `ssl` is forced to `:required` and the token is redacted from connection options after login
* The `:access_token` option also accepts a zero arity function returning `{:ok, token} | {:error, reason}`; it is invoked every time a new connection is established and exceptions raised inside it are wrapped into a connection error
* Decode the `FEDAUTHREQUIRED` and `NONCEOPT` PRELOGIN options sent by the server
* Parse `FEATUREEXTACK` (0xAE) and `FEDAUTHINFO` (0xEE) tokens in login responses

## 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
57 changes: 55 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -146,8 +146,61 @@ More info [here](https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/s

## Federation Authentication

This Authentication mechanism is not supported.
This functionality requires specific environment to be developed.
Tds supports federated authentication (Azure Active Directory / Microsoft
Entra ID) using the TDS Security Token library: the access token is sent
inside the `FEDAUTH` feature extension of the `LOGIN7` message (MS-TDS
section 2.2.6.5), and `username`/`password` are ignored.

To connect with an access token use the `:access_token` option, either as
a binary token:

```elixir
Tds.start_link(
hostname: "myserver.database.windows.net",
database: "my_db",
access_token: token,
ssl: :required,
ssl_opts: [verify: :verify_peer, cacerts: :public_key.cacerts_get()]
)
```

or as a zero arity function that obtains it:

```elixir
Tds.start_link(
hostname: "myserver.database.windows.net",
database: "my_db",
access_token: &MyTokenProvider.get_token/0,
ssl: :required,
ssl_opts: [verify: :verify_peer, cacerts: :public_key.cacerts_get()]
)
```

The function must return `{:ok, token}` or `{:error, reason}`. It is
invoked every time a new connection is established, including pool
connection recycling: implement caching inside the function if the token
endpoint should not be reached that often. Exceptions raised inside the
function are wrapped into a connection error.

The access token can be obtained, for example, with an OAuth2 client
credentials flow against
`https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token` using the
scope `https://database.windows.net/.default`, or with an Azure SDK
credentials provider. Tokens are short lived: refresh them before they
expire and reconnect when the server rejects an expired token.

Federated authentication requires an encrypted connection, `ssl` is forced
to `:required` when `:access_token` is set. The token is redacted from the
connection options after the login handshake completes.

An opt-in integration test against an Azure SQL server is available in
`test/fed_auth_test.exs` (tagged `:manual`, excluded by default).

Currently not supported:

- ADAL/MASL workflows (username & password, integrated or interactive
login): the driver does not fetch tokens by itself.
- Live ID Compact Token signatures.

## Data representation

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() | (-> {:ok, String.t()} | {:error, term()})}
| {:timeout, timeout()}
| {:connect_timeout, timeout()}
| {:execution_mode, :prepare_execute | :executesql}
Expand Down
24 changes: 23 additions & 1 deletion lib/tds/messages.ex
Original file line number Diff line number Diff line change
Expand Up @@ -93,8 +93,16 @@ defmodule Tds.Messages do
{:error, error}, _ ->
{msg_error(error: error), s}

{:feature_ext_ack, features}, {msg, s} ->
verify_fed_auth_ack(features, s)
{msg, s}

{:fed_auth_info, info}, {msg, s} ->
Logger.debug(fn -> "Tds.FedAuthInfo: #{inspect(info)}" end)

{msg, s}

_, msg ->
# FeatureExtAck should be processed here in future
msg
end)
end
Expand Down Expand Up @@ -206,6 +214,20 @@ defmodule Tds.Messages do
end
end

defp verify_fed_auth_ack(features, %{opts: opts}) do
case {List.keyfind(features, :fed_auth, 0), Keyword.get(opts, :nonce)} do
{{:fed_auth, %{nonce: nonce}}, expected}
when is_binary(nonce) and is_binary(expected) and nonce != expected ->
Logger.warning(
"Federated authentication nonce mismatch: the FEATUREEXTACK nonce does not " <>
"match the nonce received in the PRELOGIN response."
)

_ ->
:ok
end
end

defp on_envchange(envchnage, %{env: env} = s) do
case envchnage do
{:packetsize, new_value, _} ->
Expand Down
115 changes: 106 additions & 9 deletions lib/tds/protocol.ex
Original file line number Diff line number Diff line change
Expand Up @@ -71,20 +71,110 @@ defmodule Tds.Protocol do
|> Keyword.put_new(:hostname, System.get_env("MSSQLHOST") || "localhost")
|> Enum.reject(fn {_k, v} -> is_nil(v) end)

s = %__MODULE__{}
with {:ok, opts} <- put_access_token(opts) do
# Federated authentication sends the access token inside the LOGIN7
# message, an encrypted connection is required in that case
opts =
if not is_nil(opts[:access_token]) and opts[:ssl] not in [:on, :required, true] do
Keyword.put(opts, :ssl, :required)
else
opts
end

s = %__MODULE__{}

case opts[:instance] do
nil ->
connect(opts, s)

_instance ->
case instance(opts, s) do
{:ok, s} -> connect(opts, s)
err -> {:error, err}
end
end
end
end

case opts[:instance] do
# Resolves the :access_token option before connecting: a binary is used
# as is, a zero arity function is invoked to obtain the token
defp put_access_token(opts) do
case Keyword.get(opts, :access_token) do
nil ->
connect(opts, s)
{:ok, opts}

_instance ->
case instance(opts, s) do
{:ok, s} -> connect(opts, s)
err -> {:error, err}
end
token when is_binary(token) ->
{:ok, opts}

get_token when is_function(get_token, 0) ->
resolve_access_token(get_token, opts)

other ->
{:error, invalid_access_token_error(other)}
end
end

defp resolve_access_token(get_token, opts) do
case safe_get_token(get_token) do
{:ok, token} when is_binary(token) and token != "" ->
{:ok, Keyword.put(opts, :access_token, token)}

{:ok, other} ->
{:error, invalid_token_error(other)}

{:error, reason} ->
{:error, token_provider_failed_error(reason)}

{:raise, exception} ->
{:error, token_provider_raised_error(exception)}

other ->
{:error, invalid_token_return_error(other)}
end
end

defp safe_get_token(get_token) do
get_token.()
rescue
exception -> {:raise, exception}
end

defp invalid_token_error(token) do
%Tds.Error{message: "access token must be a non empty binary, got: #{inspect(token)}"}
end

defp token_provider_failed_error(reason) do
%Tds.Error{
message:
"failed to get access token, the :access_token function returned an error: " <>
inspect(reason)
}
end

defp token_provider_raised_error(exception) do
%Tds.Error{
message:
"failed to get access token, the :access_token function raised: " <>
Exception.message(exception)
}
end

defp invalid_token_return_error(other) do
%Tds.Error{
message:
"the :access_token function must return {:ok, token} | {:error, reason}, " <>
"got: #{inspect(other)}"
}
end

defp invalid_access_token_error(other) do
%Tds.Error{
message:
"invalid :access_token #{inspect(other)}, expected a binary or a " <>
"zero arity function returning {:ok, token} | {:error, reason}"
}
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 @@ -495,6 +585,11 @@ defmodule Tds.Protocol do

{:error, _, _} = err ->
err

{:error, reason} ->
# e.g a ROUTING redirect (message/3 :login clause) that failed to
# reconnect: connect/1 returns {:error, exception}, a 2-tuple
{:error, reason, s}
end
end

Expand Down Expand Up @@ -942,7 +1037,9 @@ defmodule Tds.Protocol do
end

defp clean_opts(opts) do
Keyword.put(opts, :password, :REDACTED)
opts
|> Keyword.put(:password, :REDACTED)
|> Keyword.put(:access_token, :REDACTED)
end

@spec conn_opts(Keyword.t()) :: list() | no_return
Expand Down
Loading
Loading