|
| 1 | +defmodule KafkaEx.Integration.OAuthBearerAuthenticationTest do |
| 2 | + use ExUnit.Case |
| 3 | + |
| 4 | + @moduletag :integration |
| 5 | + @moduletag :oauthbearer |
| 6 | + |
| 7 | + describe "SASL/OAUTHBEARER authentication" do |
| 8 | + @tag sasl: :oauthbearer |
| 9 | + test "connects and produces with unsecured JWT" do |
| 10 | + token = build_unsecured_jwt("test-user") |
| 11 | + |
| 12 | + opts = [ |
| 13 | + uris: [{"localhost", 9394}], |
| 14 | + use_ssl: true, |
| 15 | + ssl_options: [verify: :verify_none], |
| 16 | + auth: |
| 17 | + KafkaEx.Auth.Config.new(%{ |
| 18 | + mechanism: :oauthbearer, |
| 19 | + mechanism_opts: %{token_provider: fn -> {:ok, token} end} |
| 20 | + }) |
| 21 | + ] |
| 22 | + |
| 23 | + {:ok, _pid} = KafkaEx.create_worker(:oauth_worker, opts) |
| 24 | + |
| 25 | + assert KafkaEx.produce("test_topic", 0, "oauth_msg", worker_name: :oauth_worker) == :ok |
| 26 | + # probably redundant, but whatever |
| 27 | + assert %KafkaEx.Protocol.Metadata.Response{} = KafkaEx.metadata(worker_name: :oauth_worker) |
| 28 | + end |
| 29 | + |
| 30 | + @tag sasl: :oauthbearer |
| 31 | + test "connects with extensions" do |
| 32 | + token = build_unsecured_jwt("test-user") |
| 33 | + |
| 34 | + opts = [ |
| 35 | + uris: [{"localhost", 9394}], |
| 36 | + use_ssl: true, |
| 37 | + ssl_options: [verify: :verify_none], |
| 38 | + auth: |
| 39 | + KafkaEx.Auth.Config.new(%{ |
| 40 | + mechanism: :oauthbearer, |
| 41 | + mechanism_opts: %{ |
| 42 | + token_provider: fn -> {:ok, token} end, |
| 43 | + extensions: %{"traceId" => "test-123"} |
| 44 | + } |
| 45 | + }) |
| 46 | + ] |
| 47 | + |
| 48 | + {:ok, _pid} = KafkaEx.create_worker(:oauth_ext_worker, opts) |
| 49 | + # probably redundant, but whatever |
| 50 | + assert %KafkaEx.Protocol.Metadata.Response{} = KafkaEx.metadata(worker_name: :oauth_ext_worker) |
| 51 | + end |
| 52 | + |
| 53 | + @tag sasl: :oauthbearer |
| 54 | + test "fails with invalid token" do |
| 55 | + opts = [ |
| 56 | + uris: [{"localhost", 9394}], |
| 57 | + use_ssl: true, |
| 58 | + ssl_options: [verify: :verify_none], |
| 59 | + auth: |
| 60 | + KafkaEx.Auth.Config.new(%{ |
| 61 | + mechanism: :oauthbearer, |
| 62 | + mechanism_opts: %{token_provider: fn -> {:ok, "invalid"} end} |
| 63 | + }) |
| 64 | + ] |
| 65 | + |
| 66 | + assert {:error, _} = KafkaEx.create_worker(:oauth_bad_worker, opts) |
| 67 | + end |
| 68 | + end |
| 69 | + |
| 70 | + defp build_unsecured_jwt(subject) do |
| 71 | + # "alg":"none" as we have no jwks in tests |
| 72 | + header = Base.url_encode64(~s({"alg":"none","typ":"JWT"}), padding: false) |
| 73 | + now = System.system_time(:second) |
| 74 | + payload = Base.url_encode64(~s({"sub":"#{subject}","iat":#{now},"exp":#{now + 3600}}), padding: false) |
| 75 | + "#{header}.#{payload}." |
| 76 | + end |
| 77 | +end |
0 commit comments