diff --git a/lib/hex/repo.ex b/lib/hex/repo.ex index f6ba7d71..70f9cf4b 100644 --- a/lib/hex/repo.ex +++ b/lib/hex/repo.ex @@ -293,10 +293,10 @@ defmodule Hex.Repo do cond do # First priority: explicit repo auth key with OAuth exchange disabled - use API key directly repo_config.auth_key && Map.get(repo_config, :trusted, true) && - Map.get(repo_config, :oauth_exchange, true) == false -> + Map.get(repo_config, :oauth_exchange, false) == false -> %{config | repo_key: repo_config.auth_key} - # Second priority: Exchange API key for OAuth token if enabled (default) + # Second priority: Exchange API key for OAuth token if enabled repo_config.auth_key && Map.get(repo_config, :trusted, true) -> case exchange_api_key_for_token(repo_config, repo_name) do {:ok, access_token} -> diff --git a/test/hex/repo_test.exs b/test/hex/repo_test.exs index 35420316..2481173b 100644 --- a/test/hex/repo_test.exs +++ b/test/hex/repo_test.exs @@ -56,6 +56,43 @@ defmodule Hex.RepoTest do assert {:ok, {404, _, "not found"}} = Hex.Repo.get_public_key(config) end + test "add repo persists oauth_exchange through config round-trip" do + in_tmp(fn -> + Hex.State.put(:config_home, File.cwd!()) + + Mix.Tasks.Hex.Repo.run(["add", "myrepo", "http://example.com", "--auth-key", "mykey"]) + + # Reload config from disk to simulate a fresh session + config = Hex.Config.read() + repos = Hex.Config.read_repos(config) + + assert repos["myrepo"].auth_key == "mykey" + assert repos["myrepo"].oauth_exchange == false + end) + end + + test "does not attempt oauth exchange when oauth_exchange is not set" do + # Simulates a repo configured before v2.4.0 (no oauth_exchange key). + # If oauth exchange were attempted with an invalid key it would raise. + auth = + HexTest.Hexpm.new_user( + "no_oauth_key_user", + "no_oauth_key@example.com", + "password", + "no_oauth_key_key" + ) + + repos = Hex.State.fetch!(:repos) + hexpm = Map.delete(repos["hexpm"], :oauth_exchange) + hexpm = %{hexpm | auth_key: auth[:key]} + Hex.State.put(:repos, %{repos | "hexpm" => hexpm}) + + assert {:ok, {200, _, _}} = Hex.Repo.get_package("hexpm", "postgrex", "") + + repos_after = Hex.State.fetch!(:repos) + assert Map.get(repos_after["hexpm"], :oauth_token) == nil + end + test "fetch_repo/1" do assert Hex.Repo.fetch_repo("foo") == :error diff --git a/test/support/case.ex b/test/support/case.ex index 263a2918..d3c27722 100644 --- a/test/support/case.ex +++ b/test/support/case.ex @@ -259,6 +259,12 @@ defmodule HexTest.Case do Hex.State.update!(:repos, &put_in(&1["hexpm"].public_key, public_key)) Hex.State.update!(:repos, &put_in(&1["hexpm"].auth_key, nil)) Hex.State.update!(:repos, &put_in(&1["hexpm"].oauth_exchange, true)) + + Hex.State.update!( + :repos, + &update_in(&1, ["hexpm"], fn repo -> Map.delete(repo, :oauth_token) end) + ) + Hex.State.put(:repos_key, nil) Hex.State.put(:pbkdf2_iters, 10) Hex.State.put(:clean_pass, false)