diff --git a/CHANGELOG.md b/CHANGELOG.md index 4b2d12c0..1449c344 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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) diff --git a/README.md b/README.md index 465d5c9f..66461d5c 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/lib/tds.ex b/lib/tds.ex index bf3e7d1b..c2c893ac 100644 --- a/lib/tds.ex +++ b/lib/tds.ex @@ -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} diff --git a/lib/tds/messages.ex b/lib/tds/messages.ex index 5294e803..bc3980b1 100644 --- a/lib/tds/messages.ex +++ b/lib/tds/messages.ex @@ -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 @@ -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, _} -> diff --git a/lib/tds/protocol.ex b/lib/tds/protocol.ex index f89e1534..623d2b32 100644 --- a/lib/tds/protocol.ex +++ b/lib/tds/protocol.ex @@ -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 @@ -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 @@ -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 diff --git a/lib/tds/protocol/login7.ex b/lib/tds/protocol/login7.ex index c5dd5f5b..93959035 100644 --- a/lib/tds/protocol/login7.ex +++ b/lib/tds/protocol/login7.ex @@ -6,6 +6,7 @@ defmodule Tds.Protocol.Login7 do """ alias Tds.Encoding.UCS2 import Tds.BinaryUtils + require Bitwise @packet_header 0x10 ## Packet Size @@ -22,6 +23,15 @@ defmodule Tds.Protocol.Login7 do @default_app_name "Elixir TDS" # EN-US @language_code_id <<0x09, 0x04, 0x00, 0x00>> + # OptionFlags3 fExtension bit, set when the message contains an + # extension block (MS-TDS 2.2.6.5) + @f_extension 0x10 + # FeatureExt FEDAUTH, Security Token library (MS-TDS 2.2.6.5) + # The Options byte is bFedAuthLibrary (bits 1-3) << 1 | fFedAuthEcho (bit 0) + @fed_auth_feature_id 0x02 + @fed_auth_security_token_library 0x01 + @fed_auth_echo 0x01 + @feature_ext_terminator 0xFF defstruct [ # Highest TDS version used by the client @@ -58,13 +68,23 @@ defmodule Tds.Protocol.Login7 do # Hostname of the SQL server :hostname, # Database to use (defaults to user database) - :database + :database, + # Federated authentication (Security Token library), access token + # sent inside the FEDAUTH FeatureExt block + :fed_auth_token, + # Must mirror the FEDAUTHREQUIRED option from the server PRELOGIN response + :fed_auth_echo, + # Nonce echoed back when fed_auth_echo is set + :nonce ] def new(opts) do # gethostname/0 always succeeds {:ok, hostname} = :inet.gethostname() + token = opts[:access_token] + fed_auth = is_binary(token) and token != "" + %__MODULE__{ tds_version: @max_supported_tds_version, packet_size: <<@tds_pack_size::little-size(4)-unit(8)>>, @@ -76,13 +96,16 @@ defmodule Tds.Protocol.Login7 do option_flags_1: @options, option_flags_2: @options, type_flags: @sql_type, - option_flags_3: @options, + option_flags_3: if(fed_auth, do: <<@f_extension>>, else: @options), client_time_zone: <<0x0, 0x0, 0x0, 0x0>>, client_language_code_id: @language_code_id, - username: opts[:username], - password: opts[:password], + username: if(fed_auth, do: "", else: opts[:username]), + password: if(fed_auth, do: "", else: opts[:password]), servername: opts[:hostname], - database: Keyword.get(opts, :database, "") + database: Keyword.get(opts, :database, ""), + fed_auth_token: if(fed_auth, do: token, else: nil), + fed_auth_echo: fed_auth and opts[:fed_auth_required] == true, + nonce: opts[:nonce] } end @@ -91,7 +114,15 @@ defmodule Tds.Protocol.Login7 do fixed_login = fixed_login(login) {variable_login, offsets} = encode_variable_login(login, byte_size(fixed_login) + 62) - login7 = fixed_login <> offsets <> variable_login + tail = + if fed_auth?(login) do + base_size = byte_size(fixed_login) + byte_size(offsets) + byte_size(variable_login) + variable_login <> encode_fed_auth_extension(login, base_size) + else + variable_login + end + + login7 = fixed_login <> offsets <> tail login7_len = byte_size(login7) + 4 data = <> <> login7 @@ -145,8 +176,16 @@ defmodule Tds.Protocol.Login7 do variable_login = variable_login <> servername current_offset = current_offset + byte_size(servername) - # Unused - offsets = offsets <> <<0::ushort(), 0::ushort()>> + # Unused / ibExtension + cbExtension + offsets = + if fed_auth?(login) do + database_data = UCS2.from_string(login.database) + # The extension block follows the rest of the variable data + ib_extension = current_offset + 8 + byte_size(database_data) + offsets <> <> + else + offsets <> <<0::ushort(), 0::ushort()>> + end # Client Int Name variable_login = variable_login <> UCS2.from_string(@clt_int_name) @@ -194,6 +233,53 @@ defmodule Tds.Protocol.Login7 do |> Enum.map_join(&<<&1>>) end + defp fed_auth?(%__MODULE__{fed_auth_token: token}) + when is_binary(token) and token != "", + do: true + + defp fed_auth?(_login), do: false + + # LOGIN7 extension block (MS-TDS 2.2.6.5): a DWORD ibFeatureExtLong that + # points to the FeatureExt block which follows it. + # base_size is relative to the end of the LOGIN7 Length field: add 4 bytes + # for the Length field itself and 4 for the ibFeatureExtLong DWORD to get + # the absolute message offset of the FeatureExt block. + defp encode_fed_auth_extension(login, base_size) do + feature_data = encode_fed_auth_feature_data(login) + ib_feature_ext = base_size + 8 + + <> <> + <<@fed_auth_feature_id, byte_size(feature_data)::little-size(32), feature_data::binary, + @feature_ext_terminator>> + end + + # FEDAUTH FeatureExt data for the Security Token library (MS-TDS 2.2.6.5) + # options + FedAuthToken + [Nonce] + # + # Options byte layout: bFedAuthLibrary occupies bits 1-3 (Security Token + # library = 0x01, shifted left by 1) and fFedAuthEcho is bit 0. + # FedAuthToken is encodeed as UTF-16EL (UCS-2), matching the Unicode String + # encoding used elsewhere in LOGIN7, with TokenLength set to its UTF-16LE + # by length + defp encode_fed_auth_feature_data(%__MODULE__{ + fed_auth_token: token, + fed_auth_echo: echo, + nonce: nonce + }) do + library_bits = Bitwise.bsl(@fed_auth_security_token_library, 1) + + options = + if echo, + do: Bitwise.bor(library_bits, @fed_auth_echo), + else: library_bits + + nonce = if echo and is_binary(nonce), do: nonce, else: <<>> + + token_bin = UCS2.from_string(token) + + <> <> <> <> token_bin <> nonce + end + # Return the current pid # If that fails return a "default" pid defp pid! do diff --git a/lib/tds/protocol/prelogin.ex b/lib/tds/protocol/prelogin.ex index b9ea6928..9d54b787 100644 --- a/lib/tds/protocol/prelogin.ex +++ b/lib/tds/protocol/prelogin.ex @@ -27,7 +27,9 @@ defmodule Tds.Protocol.Prelogin do version: tuple(), encryption: <<_::8>>, instance: boolean(), - mars: boolean() + mars: boolean(), + fed_auth_required: boolean(), + nonce_opt: nil | binary() } @packet_header 0x12 @@ -166,11 +168,24 @@ defmodule Tds.Protocol.Prelogin do | {:login, state()} | {:disconnect, Tds.Error.t(), state()} def decode(packet_data, %{opts: opts} = s) do - {:ok, %{encryption: encryption, instance: instance}} = + {:ok, + %{ + encryption: encryption, + instance: instance, + fed_auth_required: fed_auth_required, + nonce_opt: nonce + }} = packet_data |> IO.iodata_to_binary() |> decode_tokens([], s) + opts = + opts + |> Keyword.put(:fed_auth_required, fed_auth_required) + |> Keyword.put(:nonce, nonce) + + s = %{s | opts: opts} + case {ssl?(opts), encryption, instance} do {_, _, false} -> msg = "Connection terminated, connected instance is not '#{instance}'!" @@ -301,10 +316,22 @@ defmodule Tds.Protocol.Prelogin do %{m | instance: data == <<0x00>>} ) + :fed_auth_required -> + decode_data( + tokens, + tail, + %{m | fed_auth_required: data == <<0x01>>} + ) + + :nonce_opt -> + decode_data( + tokens, + tail, + %{m | nonce_opt: data} + ) + # :thread_id -> # :mars -> - # :fed_auth_required -> - # :nonce_opt -> _ -> decode_data(tokens, tail, m) end diff --git a/lib/tds/tokens.ex b/lib/tds/tokens.ex index 31e26e23..04b839d5 100644 --- a/lib/tds/tokens.ex +++ b/lib/tds/tokens.ex @@ -9,6 +9,12 @@ defmodule Tds.Tokens do alias Tds.Encoding.UCS2 alias Tds.Types + # Feature extension (MS-TDS 2.2.7.4 / 2.2.7.12) + @feature_ext_terminator 0xFF + @fed_auth_feature_id 0x02 + @fed_auth_info_id_stsurl 0x01 + @fed_auth_info_id_spn 0x02 + def retval_typ_size(38) do # 0x26 - SYBINTN - 1 8 @@ -27,6 +33,8 @@ defmodule Tds.Tokens do | :doneproc | :envchange | :error + | :feature_ext_ack + | :fed_auth_info | :info | :loginack | :order @@ -53,8 +61,8 @@ defmodule Tds.Tokens do 0xFF -> decode_doneinproc(tail, collmetadata) 0xE3 -> decode_envchange(tail, collmetadata) 0xAA -> decode_error(tail, collmetadata) - # 0xAE -> decode_featureextack(tail, collmetadata) - # 0xEE -> decode_fedauthinfo(tail, collmetadata) + 0xAE -> decode_featureextack(tail, collmetadata) + 0xEE -> decode_fedauthinfo(tail, collmetadata) 0xAB -> decode_info(tail, collmetadata) 0xAD -> decode_loginack(tail, collmetadata) 0xD2 -> decode_nbcrow(tail, collmetadata) @@ -486,6 +494,66 @@ defmodule Tds.Tokens do {{:loginack, token}, tail, collmetadata} end + ## FEATUREEXTACK (MS-TDS 2.2.7.4) + defp decode_featureextack(bin, collmetadata) do + {features, tail} = decode_feature_ext_ack_opts(bin, []) + {{:feature_ext_ack, features}, tail, collmetadata} + end + + defp decode_feature_ext_ack_opts(<<@feature_ext_terminator, tail::binary>>, acc), + do: {Enum.reverse(acc), tail} + + defp decode_feature_ext_ack_opts( + <>, + acc + ) do + decode_feature_ext_ack_opts(tail, [decode_feature_ext(feature_id, data) | acc]) + end + + defp decode_feature_ext(@fed_auth_feature_id, <>) do + # Security Token library ack data: [Nonce], optionally followed by an + # HMAC-SHA256 signature (Live ID Compact Token) + {:fed_auth, %{nonce: nonce, signature: signature}} + end + + defp decode_feature_ext(feature_id, data), do: {feature_id, data} + + ## FEDAUTHINFO (MS-TDS 2.2.7.12) + defp decode_fedauthinfo( + <<_token_length::dword(), count_of_info_ids::dword(), tail::binary>>, + collmetadata + ) do + opts_size = 9 * count_of_info_ids + <> = tail + + # FedAuthInfoDataOffset is measured from the start of CountOfInfoIDs + base = 4 + opts_size + + {info, data_end} = + for <>, + reduce: {[], base} do + {acc, data_end} -> + start = data_offset - base + + <<_::binary-size(start), value::binary-size(data_len), _::binary>> = data + + value = decode_fed_auth_info_value(info_id, value) + {[value | acc], max(data_end, data_offset + data_len)} + end + + tail = binary_part(data, data_end - base, byte_size(data) - (data_end - base)) + + {{:fed_auth_info, Enum.reverse(info)}, tail, collmetadata} + end + + defp decode_fed_auth_info_value(@fed_auth_info_id_stsurl, value), + do: {:stsurl, UCS2.to_string(value)} + + defp decode_fed_auth_info_value(@fed_auth_info_id_spn, value), + do: {:spn, UCS2.to_string(value)} + + defp decode_fed_auth_info_value(info_id, value), do: {info_id, value} + defp decode_column_order(tail, n, acc \\ []) defp decode_column_order(tail, n, acc) when n < 1 do diff --git a/test/access_token_test.exs b/test/access_token_test.exs new file mode 100644 index 00000000..ff4236e4 --- /dev/null +++ b/test/access_token_test.exs @@ -0,0 +1,69 @@ +defmodule Tds.AccessTokenTest do + use ExUnit.Case, async: false + + describe "Tds.Protocol.connect/1 with :access_token" do + test "function is invoked and its token is used for the login" do + {:ok, agent} = Agent.start_link(fn -> false end) + + opts = + Tds.TestHelper.opts() + |> Keyword.put(:access_token, fn -> + Agent.update(agent, fn _ -> true end) + {:ok, "token-from-function"} + end) + |> Keyword.drop([:username, :password]) + + # The local server does not accept Entra ID tokens: the login must + # fail gracefully with a server error, not with a token resolution + # error, proving the token traveled inside the LOGIN7 message + assert {:error, %Tds.Error{} = err} = Tds.Protocol.connect(opts) + assert Agent.get(agent, & &1) + refute Exception.message(err) =~ "access token" + end + + test "function returning an error fails fast without opening a socket" do + opts = [hostname: "127.0.0.1", access_token: fn -> {:error, :tenant_not_found} end] + + assert {:error, %Tds.Error{} = err} = Tds.Protocol.connect(opts) + assert err.message =~ ":tenant_not_found" + end + + test "function returning an invalid token fails fast" do + for value <- [{:ok, ""}, {:ok, 123}] do + opts = [hostname: "127.0.0.1", access_token: fn -> value end] + + assert {:error, %Tds.Error{} = err} = Tds.Protocol.connect(opts) + assert err.message =~ "non empty binary" + end + end + + test "function returning an invalid shape fails fast" do + opts = [hostname: "127.0.0.1", access_token: fn -> "raw-token" end] + + assert {:error, %Tds.Error{} = err} = Tds.Protocol.connect(opts) + assert err.message =~ "{:ok, token} | {:error, reason}" + end + + test "function raising an exception is wrapped" do + opts = [hostname: "127.0.0.1", access_token: fn -> raise "boom" end] + + assert {:error, %Tds.Error{} = err} = Tds.Protocol.connect(opts) + assert err.message =~ "boom" + end + + test "non zero arity functions are rejected" do + opts = [hostname: "127.0.0.1", access_token: &String.length/1] + + assert {:error, %Tds.Error{} = err} = Tds.Protocol.connect(opts) + assert err.message =~ "zero arity function" + end + + test "invalid values are rejected" do + for value <- [123, :token, {"m", "f"}] do + opts = [hostname: "127.0.0.1", access_token: value] + + assert {:error, %Tds.Error{}} = Tds.Protocol.connect(opts) + end + end + end +end diff --git a/test/fed_auth_test.exs b/test/fed_auth_test.exs new file mode 100644 index 00000000..9e8b8e06 --- /dev/null +++ b/test/fed_auth_test.exs @@ -0,0 +1,42 @@ +defmodule Tds.FedAuthTest do + @moduledoc """ + Opt-in integration test for federated authentication (Security Token + library) against an Azure SQL Database. + + This test is tagged `:manual` (excluded by default). To run it, set + `SQL_ACCESS_TOKEN` and `SQL_HOSTNAME` to an Azure SQL server and run: + + SQL_ACCESS_TOKEN=... SQL_HOSTNAME=myserver.database.windows.net \ + mix test test/fed_auth_test.exs --only manual + + The access token can be obtained, for example, with a client credentials + flow against `https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token` + using the scope `https://database.windows.net/.default`. + """ + + use ExUnit.Case, async: false + + @moduletag :manual + + test "connects using an access token (Security Token library)" do + token = System.get_env("SQL_ACCESS_TOKEN") + + if is_nil(token) do + flunk("Set SQL_ACCESS_TOKEN and SQL_HOSTNAME to run this test") + end + + opts = [ + hostname: System.get_env("SQL_HOSTNAME") || "127.0.0.1", + database: System.get_env("SQL_DATABASE") || "test", + access_token: token, + ssl: :required, + ssl_opts: [verify: :verify_none], + show_sensitive_data_on_connection_error: true + ] + + assert {:ok, pid} = Tds.start_link(opts) + + assert {:ok, %Tds.Result{rows: [["pong"]]}} = + Tds.query(pid, "SELECT 'pong' as [msg]", []) + end +end diff --git a/test/login7_test.exs b/test/login7_test.exs index 9dbd44f4..406db571 100644 --- a/test/login7_test.exs +++ b/test/login7_test.exs @@ -39,4 +39,106 @@ defmodule Login7Test do 97, 0, 115, 0, 101, 0>> ] end + + test "encode login7 message with federated authentication" do + nonce = :binary.copy(<<0xAB>>, 32) + + login = %Tds.Protocol.Login7{ + app_name: "Elixir TDS", + client_language_code_id: <<9, 4, 0, 0>>, + client_pid: <<0, 0, 3, 34>>, + client_time_zone: <<0, 0, 0, 0>>, + client_version: <<4, 0, 0, 7>>, + connection_id: <<0, 0, 0, 0>>, + database: "my_database", + fed_auth_echo: true, + fed_auth_token: "access-token", + hostname: "test.host.com", + nonce: nonce, + option_flags_1: <<0>>, + option_flags_2: <<0>>, + option_flags_3: <<0x10>>, + packet_size: <<0, 16, 0, 0>>, + password: "", + servername: "some.host.com", + tds_version: <<4, 0, 0, 116>>, + type_flags: <<0>>, + username: "" + } + + # packet header: type 0x10, status EOM, length 275 (263 + 12, since the + # UCS/UTF-16LE token is twice the byte size of the raw ASCCI token) + # LOGIN7 Length + # fixed login, OptionFlags3 has fExtension (0x10) set + # offset table, ibExtension/cbExtension point to the extension block + # variable data: host, app name, server name, ODBC, database + # extension: ibFeatureExtLong DWORD pointing to the FeatureExt block + # FeatureExt: FEDAUTH (0x02), data len, Options (0x03 = bFedAuthLibrary + # 0x01 << 1 | fFedAuthEcho 0x01), token length (UTF-16LE byte size), + # token (UTF-16LE), nonce, terminator + token_bin = Tds.Encoding.UCS2.from_string("access-token") + feature_data_len = 1 + 4 + byte_size(token_bin) + byte_size(nonce) + + expected = + <<16, 1, 1, 19, 0, 0, 1, 0>> <> + <<11, 1, 0, 0>> <> + <<4, 0, 0, 116, 0, 16, 0, 0, 4, 0, 0, 7, 0, 0, 3, 34, 0, 0, 0, 0>> <> + <<0, 0, 0, 16, 0, 0, 0, 0, 9, 4, 0, 0>> <> + <<94, 0, 13, 0>> <> + <<120, 0, 0, 0>> <> + <<120, 0, 0, 0>> <> + <<120, 0, 10, 0>> <> + <<140, 0, 13, 0>> <> + <<196, 0, 4, 0>> <> + <<166, 0, 4, 0>> <> + <<0, 0, 0, 0>> <> + <<174, 0, 11, 0>> <> + <<0, 0, 0, 0, 0, 0>> <> + <<0, 0, 0, 0>> <> + <<0, 0, 0, 0>> <> + <<0, 0, 0, 0>> <> + <<0, 0, 0, 0>> <> + <<116, 0, 101, 0, 115, 0, 116, 0, 46, 0>> <> + <<104, 0, 111, 0, 115, 0, 116, 0, 46, 0>> <> + <<99, 0, 111, 0, 109, 0>> <> + <<69, 0, 108, 0, 105, 0, 120, 0, 105, 0, 114, 0, 32, 0, 84, 0, 68, 0, 83, 0>> <> + <<115, 0, 111, 0, 109, 0, 101, 0, 46, 0>> <> + <<104, 0, 111, 0, 115, 0, 116, 0, 46, 0>> <> + <<99, 0, 111, 0, 109, 0>> <> + <<79, 0, 68, 0, 66, 0, 67, 0>> <> + <<109, 0, 121, 0, 95, 0, 100, 0, 97, 0, 116, 0, 97, 0, 98, 0, 97, 0, 115, 0, 101, 0>> <> + <<200, 0, 0, 0>> <> + <<2, feature_data_len::little-size(32), 3, byte_size(token_bin)::little-size(32)>> <> + token_bin <> nonce <> <<255>> + + assert Login7.encode(login) == [expected] + end + + test "new/1 builds a federated authentication login from options" do + nonce = :binary.copy(<<0xAB>>, 32) + + login = + Login7.new( + access_token: "token", + fed_auth_required: true, + nonce: nonce, + hostname: "some.host.com", + database: "db" + ) + + assert login.username == "" + assert login.password == "" + assert login.option_flags_3 == <<0x10>> + assert login.fed_auth_token == "token" + assert login.fed_auth_echo + assert login.nonce == nonce + + login = Login7.new(username: "sa", password: "pw", hostname: "h", database: "db") + + assert login.username == "sa" + assert login.password == "pw" + assert login.option_flags_3 == <<0>> + assert is_nil(login.fed_auth_token) + refute login.fed_auth_echo + end end diff --git a/test/packet/token_stream_test.exs b/test/packet/token_stream_test.exs index 9229bdd3..4f7f0648 100644 --- a/test/packet/token_stream_test.exs +++ b/test/packet/token_stream_test.exs @@ -1,6 +1,8 @@ defmodule Packet.TokenStreamTest do use ExUnit.Case, async: true + alias Tds.Encoding.UCS2 + @package_data << # HEADER 0x04, @@ -603,4 +605,37 @@ defmodule Packet.TokenStreamTest do <<_::binary-8, package_data::binary>> = @package_data assert @token_stream == Tds.Tokens.decode_tokens(package_data, nil) end + + test "should decode FEATUREEXTACK token" do + nonce = :binary.copy(<<0xAB>>, 32) + package_data = <<0xAE, 0x02, 32::little-32>> <> nonce <> <<0xFF>> + + assert Tds.Tokens.decode_tokens(package_data, nil) == + [feature_ext_ack: [fed_auth: %{nonce: nonce, signature: <<>>}]] + end + + test "should decode FEATUREEXTACK token with signature" do + nonce = :binary.copy(<<0xAB>>, 32) + signature = :binary.copy(<<0xCD>>, 32) + + package_data = + <<0xAE, 0x02, 64::little-32>> <> nonce <> signature <> <<0xFF>> + + assert Tds.Tokens.decode_tokens(package_data, nil) == + [feature_ext_ack: [fed_auth: %{nonce: nonce, signature: signature}]] + end + + test "should decode FEDAUTHINFO token" do + stsurl = UCS2.from_string("sts.example.com") + spn = UCS2.from_string("spn") + + package_data = + <<0xEE, 58::little-32, 2::little-32>> <> + <<0x01, 30::little-32, 22::little-32>> <> + <<0x02, 6::little-32, 52::little-32>> <> + stsurl <> spn + + assert Tds.Tokens.decode_tokens(package_data, nil) == + [fed_auth_info: [stsurl: "sts.example.com", spn: "spn"]] + end end diff --git a/test/prelogin_test.exs b/test/prelogin_test.exs new file mode 100644 index 00000000..55e1f924 --- /dev/null +++ b/test/prelogin_test.exs @@ -0,0 +1,40 @@ +defmodule PreloginTest do + use ExUnit.Case, async: true + + alias Tds.Protocol.Prelogin + + @nonce :binary.copy(<<0xAB>>, 32) + + test "decode prelogin response requiring federated authentication" do + # VERSION | ENCRYPTION(ON) | FEDAUTHREQUIRED(0x01) | NONCEOPT(32B) + packet = + <<0x00, 21::unsigned-16, 6::unsigned-16>> <> + <<0x01, 27::unsigned-16, 1::unsigned-16>> <> + <<0x06, 28::unsigned-16, 1::unsigned-16>> <> + <<0x07, 29::unsigned-16, 32::unsigned-16>> <> + <<0xFF>> <> + <<4, 0, 10, 0, 0, 0>> <> <<0x01>> <> <<0x01>> <> @nonce + + s = %Tds.Protocol{opts: [ssl: :required]} + + assert {:encrypt, %{opts: opts}} = Prelogin.decode(packet, s) + assert opts[:fed_auth_required] == true + assert opts[:nonce] == @nonce + end + + test "decode prelogin response without federated authentication" do + # VERSION | ENCRYPTION(NOT_SUP) | FEDAUTHREQUIRED(0x00) + packet = + <<0x00, 16::unsigned-16, 6::unsigned-16>> <> + <<0x01, 22::unsigned-16, 1::unsigned-16>> <> + <<0x06, 23::unsigned-16, 1::unsigned-16>> <> + <<0xFF>> <> + <<4, 0, 10, 0, 0, 0>> <> <<0x02>> <> <<0x00>> + + s = %Tds.Protocol{opts: [ssl: :not_supported]} + + assert {:login, %{opts: opts}} = Prelogin.decode(packet, s) + assert opts[:fed_auth_required] == false + assert is_nil(opts[:nonce]) + end +end diff --git a/test/test_helper.exs b/test/test_helper.exs index e550aabd..fd2a5ae2 100644 --- a/test/test_helper.exs +++ b/test/test_helper.exs @@ -111,38 +111,42 @@ end opts = Tds.TestHelper.opts() database = opts[:database] -case Tds.TestHelper.sqlcmd(opts, """ - IF EXISTS(SELECT * FROM sys.databases where name = '#{database}') - BEGIN - DROP DATABASE [#{database}]; - END; - CREATE DATABASE [#{database}]; - """) do - {"", 0} -> - :ok - - {err, _} -> - raise RuntimeError, "Failed to create database '#{database}' due #{err}" -end +# Skip the local database fixtures when running the opt-in federated +# authentication test against an Azure SQL server (SQL_ACCESS_TOKEN is set) +if System.get_env("SQL_ACCESS_TOKEN") in [nil, ""] do + case Tds.TestHelper.sqlcmd(opts, """ + IF EXISTS(SELECT * FROM sys.databases where name = '#{database}') + BEGIN + DROP DATABASE [#{database}]; + END; + CREATE DATABASE [#{database}]; + """) do + {"", 0} -> + :ok + + {err, _} -> + raise RuntimeError, "Failed to create database '#{database}' due #{err}" + end -{"Changed database context to 'test'." <> _, 0} = - Tds.TestHelper.sqlcmd(opts, """ - USE [test]; + {"Changed database context to 'test'." <> _, 0} = + Tds.TestHelper.sqlcmd(opts, """ + USE [test]; - CREATE TABLE altering ([a] int) + CREATE TABLE altering ([a] int) - CREATE TABLE [composite1] ([a] int, [b] text); - CREATE TABLE [composite2] ([a] int, [b] int, [c] int); - CREATE TABLE [uniques] ([id] int NOT NULL, CONSTRAINT UIX_uniques_id UNIQUE([id])) - """) + CREATE TABLE [composite1] ([a] int, [b] text); + CREATE TABLE [composite2] ([a] int, [b] int, [c] int); + CREATE TABLE [uniques] ([id] int NOT NULL, CONSTRAINT UIX_uniques_id UNIQUE([id])) + """) -{"", 0} = - Tds.TestHelper.sqlcmd(opts, """ - IF NOT EXISTS (SELECT * FROM sys.schemas WHERE name = 'test') - EXEC('CREATE SCHEMA [test]') - """) + {"", 0} = + Tds.TestHelper.sqlcmd(opts, """ + IF NOT EXISTS (SELECT * FROM sys.schemas WHERE name = 'test') + EXEC('CREATE SCHEMA [test]') + """) -{"Changed database context to 'test'." <> _, 0} = Tds.TestHelper.sqlcmd(opts, "USE test;") + {"Changed database context to 'test'." <> _, 0} = Tds.TestHelper.sqlcmd(opts, "USE test;") +end # :dbg.start() # :dbg.tracer()