Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow passing scopes query for metadata source #182

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
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
21 changes: 15 additions & 6 deletions lib/goth/token.ex
Original file line number Diff line number Diff line change
Expand Up @@ -401,17 +401,26 @@ defmodule Goth.Token do
handle_workload_identity_response(response, config)
end

defp metadata_url(base_url, path, account, nil, nil) do
"#{base_url}#{path}#{account}/token"
end

defp metadata_url(base_url, path, account, nil, scopes) do
scopes_query = Enum.join(scopes, ",")
"#{base_url}#{path}#{account}/token?scopes=#{scopes_query}"
end

defp metadata_url(base_url, path, account, audience, _scopes) do
"#{base_url}#{path}#{account}/identity?audience=#{audience}"
end

defp metadata_options(options) do
account = Keyword.get(options, :account, "default")
audience = Keyword.get(options, :audience, nil)
scopes = Keyword.get(options, :scopes, nil)
path = "/computeMetadata/v1/instance/service-accounts/"
base_url = Keyword.get(options, :url, "http://metadata.google.internal")

url =
case audience do
nil -> "#{base_url}#{path}#{account}/token"
audience -> "#{base_url}#{path}#{account}/identity?audience=#{audience}"
end
url = metadata_url(base_url, path, account, audience, scopes)

{url, audience}
end
Expand Down
20 changes: 20 additions & 0 deletions test/goth/token_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,26 @@ defmodule Goth.TokenTest do
assert token.scope == nil
end

test "fetch/1 from instance metadata with scopes query" do
bypass = Bypass.open()

Bypass.expect(bypass, fn conn ->
assert conn.request_path == "/computeMetadata/v1/instance/service-accounts/alice/token"
assert conn.query_params == %{"scopes" => "scope_a,scope_b"}

body = ~s|{"access_token":"dummy","expires_in":3599,"token_type":"Bearer"}|
Plug.Conn.resp(conn, 200, body)
end)

config = %{
source: {:metadata, account: "alice", url: "http://localhost:#{bypass.port}", scopes: ["scope_a", "scope_b"]}
}

{:ok, token} = Goth.Token.fetch(config)
assert token.token == "dummy"
assert token.scope == nil
end

test "fetch/1 from workload identity" do
token_bypass = Bypass.open()
sa_token_bypass = Bypass.open()
Expand Down