19.0 KiB · text History 573fef1
defmodule VigilWeb.Api.V1.AuthControllerTest do
  @moduledoc """
  The Android app's sign-in API (/api/v1/auth/*), shared in shape with
  every NEIAM app. Each test uses its own client IP, so the shared rate
  limiter's per-IP counters don't leak between tests.
  """
  # Not async: neiam_auth's config is global (persistent_term).
  use VigilWeb.ConnCase, async: false

  import Ecto.Query
  import ExUnit.CaptureLog
  import Swoosh.TestAssertions
  import Vigil.AccountsFixtures

  alias NeiamAuth.{AppCode, Identity}
  alias NeiamAuth.Test.FakeIdP
  alias Vigil.{Accounts, ApiTokens, Repo}
  alias Vigil.Accounts.{User, UserToken}

  setup %{conn: conn} do
    on_exit(fn -> NeiamAuth.put_config(NeiamAuth.Config.load(%{})) end)
    {:ok, conn: with_ip(conn)}
  end

  defp with_ip(conn) do
    n = System.unique_integer([:positive])
    %{conn | remote_ip: {10, rem(div(n, 65_536), 256), rem(div(n, 256), 256), rem(n, 256)}}
  end

  defp start_neiam(env \\ %{}) do
    idp = FakeIdP.start()
    on_exit(fn -> FakeIdP.stop(idp) end)

    provider =
      FakeIdP.env(idp, nil,
        redirect_uri: "http://localhost:4002/auth/oidc/neiam/callback",
        trust_email: "true",
        required_for_linked: "true",
        label: "Sign in with NEIAM"
      )

    start_supervised!(
      {NeiamAuth,
       env: provider |> Map.merge(env) |> Map.put("OIDC_ENABLED", "true"),
       name: :neiam_auth_test,
       backoff_min: 50,
       backoff_max: 200}
    )

    wait_ready()
    idp
  end

  defp wait_ready(tries \\ 100) do
    with {:ok, provider} <- NeiamAuth.config("neiam"), true <- NeiamAuth.ready?(provider) do
      :ok
    else
      _ when tries > 0 ->
        # The provider fetches the fake IdP's discovery document on start.
        receive do
        after
          20 -> wait_ready(tries - 1)
        end

      _ ->
        flunk("provider never loaded")
    end
  end

  # user_fixture/1 confirms the account by email: that email is still in
  # the test mailbox, and would satisfy assert_email_sent.
  defp drain_mailbox do
    receive do
      {:email, _} -> drain_mailbox()
    after
      0 -> :ok
    end
  end

  defp confirmed_user(attrs \\ %{}) do
    user = user_fixture(attrs)
    drain_mailbox()
    user
  end

  defp user_with_password(attrs \\ %{}), do: attrs |> confirmed_user() |> set_password()

  defp magic_link_token(user) do
    {encoded, _raw} = generate_user_magic_link_token(user)
    encoded
  end

  # The pairing check: GET /api/0/ names the token's owner.
  defp me(token) do
    build_conn()
    |> put_req_header("authorization", "Bearer " <> token)
    |> get(~p"/api/0/")
    |> json_response(200)
    |> Map.fetch!("user")
  end

  defp password(conn, login, pw),
    do:
      post(conn, ~p"/api/v1/auth/password", %{
        username_or_email: login,
        password: pw,
        device_name: "Pixel 9"
      })

  describe "GET /api/v1/auth/methods" do
    test "SSO off: scan, password and magic link on; OIDC off with a reason", %{conn: conn} do
      conn = get(conn, ~p"/api/v1/auth/methods")
      body = json_response(conn, 200)

      assert %{
               "app_name" => "Vigil",
               "server" => server,
               "scan" => true,
               "password" => true,
               "magic_link" => true,
               "oidc" => %{"enabled" => false},
               "login_mode" => "local"
             } = body

      assert server == VigilWeb.base_url()
      assert body["reasons"]["oidc"]
      assert get_resp_header(conn, "cache-control") == ["no-store"]
    end

    test "SSO on (mixed): OIDC with its label and login path", %{conn: conn} do
      start_neiam()
      body = json_response(get(conn, ~p"/api/v1/auth/methods"), 200)

      assert body["oidc"] == %{
               "enabled" => true,
               "label" => "Sign in with NEIAM",
               "provider" => "neiam",
               "login_path" => "/auth/oidc/neiam/login"
             }

      assert %{"login_mode" => "mixed", "password" => true, "magic_link" => true} = body
    end

    test "sso_strict turns password and magic link off, with the reason", %{conn: conn} do
      start_neiam(%{"OIDC_LOGIN_MODE" => "sso_strict"})
      body = json_response(get(conn, ~p"/api/v1/auth/methods"), 200)
      assert %{"password" => false, "magic_link" => false, "login_mode" => "sso_strict"} = body
      assert body["reasons"]["password"] =~ "only allows Sign in with NEIAM"
      assert body["oidc"]["enabled"]
    end

    test "no mail configured: no magic link", %{conn: conn} do
      old = Application.get_env(:vigil, Vigil.Mailer)
      Application.put_env(:vigil, Vigil.Mailer, adapter: Swoosh.Adapters.Logger)
      on_exit(fn -> Application.put_env(:vigil, Vigil.Mailer, old) end)

      body = json_response(get(conn, ~p"/api/v1/auth/methods"), 200)
      assert body["magic_link"] == false
      assert body["password"] == true
      assert body["reasons"]["magic_link"] =~ "can't send email"
    end
  end

  describe "POST /api/v1/auth/password" do
    test "signs in with the same kind of token pairing uses; it works on /api/0", %{conn: conn} do
      user = user_with_password()

      log =
        capture_log([level: :debug], fn ->
          send(self(), {:conn, password(conn, user.email, valid_user_password())})
        end)

      assert_received {:conn, conn}
      refute log =~ valid_user_password()

      assert %{"token" => token, "token_type" => "Bearer", "user" => %{"id" => id} = u} =
               json_response(conn, 200)

      assert get_resp_header(conn, "cache-control") == ["no-store"]
      assert id == user.id
      assert u["email"] == user.email
      assert me(token)["id"] == user.id

      # Listed (and revocable) on Settings → API tokens, with the device's
      # name and the Mobile app scopes, as a token made for pairing.
      assert [%{label: "Pixel 9", scopes: scopes}] = ApiTokens.list_tokens(user)
      assert ApiTokens.mobile?(scopes)
      assert Enum.sort(scopes) == Enum.sort(ApiTokens.mobile_scopes())
    end

    test "an unknown email and a wrong password get the same answer", %{conn: conn} do
      user = user_with_password()
      unknown = password(conn, "nobody@example.com", valid_user_password())
      wrong = password(with_ip(build_conn()), user.email, "not the password")

      assert json_response(unknown, 401) == json_response(wrong, 401)
      assert %{"error" => "invalid_credentials", "message" => _} = json_response(wrong, 401)
      assert ApiTokens.list_tokens(user) == []
    end

    test "an account with no password is refused like a wrong password", %{conn: conn} do
      user = confirmed_user()

      assert %{"error" => "invalid_credentials"} =
               json_response(password(conn, user.email, "x"), 401)
    end

    test "takes `login` as well as `username_or_email`", %{conn: conn} do
      user = user_with_password()

      conn =
        post(conn, ~p"/api/v1/auth/password", %{
          login: user.email,
          password: valid_user_password()
        })

      assert json_response(conn, 200)["user"]["id"] == user.id
      # No device name: "Android".
      assert [%{label: "Android"}] = ApiTokens.list_tokens(user)
    end

    test "an unknown email and a wrong password both take at least the 400 ms floor",
         %{conn: conn} do
      user = user_with_password()

      for {c, login} <- [{conn, "nobody@example.com"}, {with_ip(build_conn()), user.email}] do
        t = System.monotonic_time(:millisecond)
        assert password(c, login, "x").status == 401
        assert System.monotonic_time(:millisecond) - t >= NeiamAuth.App.failure_floor_ms()
      end
    end

    test "missing fields are a 400", %{conn: conn} do
      assert %{"error" => "bad_request"} =
               json_response(post(conn, ~p"/api/v1/auth/password", %{}), 400)

      assert %{"error" => "bad_request"} =
               json_response(post(conn, ~p"/api/v1/auth/password", %{login: "a@b.c"}), 400)
    end

    test "sso_strict refuses every password", %{conn: conn} do
      start_neiam(%{"OIDC_LOGIN_MODE" => "sso_strict"})
      user = user_with_password()

      assert %{"error" => "password_login_off"} =
               json_response(password(conn, user.email, valid_user_password()), 403)
    end

    test "sso refuses an account linked to the required provider, as the web does", %{conn: conn} do
      idp = start_neiam(%{"OIDC_LOGIN_MODE" => "sso"})
      user = user_with_password()

      Repo.insert!(%Identity{
        user_id: user.id,
        provider: "neiam",
        issuer: idp.issuer,
        sub: "sub-1",
        email: user.email
      })

      assert %{"error" => "refused"} =
               json_response(password(conn, user.email, valid_user_password()), 403)

      assert ApiTokens.list_tokens(user) == []

      other = user_with_password()

      assert json_response(
               password(with_ip(build_conn()), other.email, valid_user_password()),
               200
             )
    end

    test "is rate limited per account, whatever the IP" do
      user = user_with_password()
      {limit, _} = NeiamAuth.App.limits()[{:password, :account}]

      for _ <- 1..limit do
        assert password(with_ip(build_conn()), user.email, "wrong").status == 401
      end

      conn = password(with_ip(build_conn()), String.upcase(user.email), valid_user_password())
      assert %{"error" => "rate_limited"} = json_response(conn, 429)
      assert [_] = get_resp_header(conn, "retry-after")
    end

    test "is rate limited per IP", %{conn: conn} do
      {limit, _} = NeiamAuth.App.limits()[{:password, :ip}]

      for i <- 1..limit do
        assert password(conn, "u#{i}@example.com", "x").status == 401
      end

      assert password(conn, "another@example.com", "x").status == 429
    end
  end

  describe "SSO from the app" do
    defp pkce do
      verifier = :crypto.strong_rand_bytes(32) |> Base.url_encode64(padding: false)
      {verifier, NeiamAuth.App.s256(verifier)}
    end

    defp app_sso(conn, idp, challenge) do
      conn =
        get(conn, "/auth/oidc/neiam/login", %{
          "app" => "1",
          "challenge" => challenge,
          "device_name" => "Pixel 9"
        })

      params = FakeIdP.authorize(idp, redirected_to(conn, 302))
      conn = conn |> recycle() |> get("/auth/oidc/neiam/callback", params)
      "vigil://auth?" <> query = redirected_to(conn, 302)
      {conn, URI.decode_query(query)}
    end

    defp exchange(body), do: post(with_ip(build_conn()), ~p"/api/v1/auth/oidc/exchange", body)

    test "the callback hands a one-time code to the app, with no web session", %{conn: conn} do
      idp = start_neiam()
      user = confirmed_user(%{email: "alice@example.com"})
      {verifier, challenge} = pkce()

      {cb_conn, %{"code" => code}} = app_sso(conn, idp, challenge)
      refute get_session(cb_conn, :user_token)

      body =
        json_response(exchange(%{code: code, code_verifier: verifier, device_name: "P9"}), 200)

      assert %{"token_type" => "Bearer", "user" => %{"id" => id}} = body
      assert id == user.id
      assert me(body["token"])["id"] == user.id
      assert [%{label: "P9", scopes: scopes}] = ApiTokens.list_tokens(user)
      assert ApiTokens.mobile?(scopes)

      # Single use.
      assert %{"error" => "invalid_grant"} =
               json_response(exchange(%{code: code, code_verifier: verifier}), 400)
    end

    test "a wrong verifier is refused (and burns the code)", %{conn: conn} do
      idp = start_neiam()
      confirmed_user(%{email: "alice@example.com"})
      {verifier, challenge} = pkce()
      {_, %{"code" => code}} = app_sso(conn, idp, challenge)
      {other, _} = pkce()

      assert %{"error" => "invalid_grant"} =
               json_response(exchange(%{code: code, code_verifier: other}), 400)

      assert %{"error" => "invalid_grant"} =
               json_response(exchange(%{code: code, code_verifier: verifier}), 400)
    end

    test "an expired code is refused" do
      user = confirmed_user()
      {verifier, challenge} = pkce()
      past = DateTime.add(DateTime.utc_now(), -AppCode.ttl_seconds() - 1)
      {:ok, code} = AppCode.create(user.id, challenge, "x", past)

      assert %{"error" => "invalid_grant"} =
               json_response(exchange(%{code: code, code_verifier: verifier}), 400)

      assert ApiTokens.list_tokens(user) == []
    end

    test "there is no /app/callback page: the code goes straight to vigil://auth" do
      assert get(build_conn(), "/app/callback", %{"code" => "abc"}).status == 404
    end
  end

  describe "POST /api/v1/auth/magic_link" do
    test "the same neutral answer for a known and an unknown email", %{conn: conn} do
      user = confirmed_user()
      known = post(conn, ~p"/api/v1/auth/magic_link", %{email: user.email})
      assert_email_sent(to: [{"", user.email}])

      unknown =
        post(with_ip(build_conn()), ~p"/api/v1/auth/magic_link", %{email: "no@example.com"})

      assert_no_email_sent()

      assert json_response(known, 202) == json_response(unknown, 202)
      assert get_resp_header(known, "cache-control") == ["no-store"]
    end

    test "the email carries the web's own link, /users/log-in/:token", %{conn: conn} do
      user = confirmed_user()
      post(conn, ~p"/api/v1/auth/magic_link", %{email: user.email})

      assert_email_sent(fn email ->
        assert email.text_body =~ ~r{/users/log-in/[A-Za-z0-9_-]+}
      end)
    end

    test "is rate limited per email" do
      user = confirmed_user()
      {limit, _} = NeiamAuth.App.limits()[{:magic_link, :account}]

      for _ <- 1..limit,
          do: post(with_ip(build_conn()), ~p"/api/v1/auth/magic_link", %{email: user.email})

      conn = post(with_ip(build_conn()), ~p"/api/v1/auth/magic_link", %{email: user.email})
      assert %{"error" => "rate_limited"} = json_response(conn, 429)
    end

    test "missing email is a 400", %{conn: conn} do
      assert %{"error" => "bad_request"} =
               json_response(post(conn, ~p"/api/v1/auth/magic_link", %{}), 400)
    end

    test "sso_strict: refused, nothing sent", %{conn: conn} do
      start_neiam(%{"OIDC_LOGIN_MODE" => "sso_strict"})
      user = confirmed_user()

      assert %{"error" => "password_login_off"} =
               json_response(post(conn, ~p"/api/v1/auth/magic_link", %{email: user.email}), 403)

      assert_no_email_sent()
    end

    test "sso: nothing sent to an account that must use SSO, the same answer", %{conn: conn} do
      idp = start_neiam(%{"OIDC_LOGIN_MODE" => "sso"})
      user = confirmed_user()
      Repo.insert!(%Identity{user_id: user.id, provider: "neiam", issuer: idp.issuer, sub: "s"})

      assert json_response(post(conn, ~p"/api/v1/auth/magic_link", %{email: user.email}), 202)
      assert_no_email_sent()
    end
  end

  describe "POST /api/v1/auth/magic_link/exchange" do
    defp ml_exchange(token),
      do:
        post(with_ip(build_conn()), ~p"/api/v1/auth/magic_link/exchange", %{
          token: token,
          device_name: "Pixel 9"
        })

    test "single use; the web log-in with the same token then fails" do
      user = confirmed_user()
      token = magic_link_token(user)

      body = json_response(ml_exchange(token), 200)
      assert body["user"]["id"] == user.id
      assert body["confirmed"] == false
      assert me(body["token"])["id"] == user.id
      assert [%{label: "Pixel 9"}] = ApiTokens.list_tokens(user)

      assert %{"error" => "invalid_link"} = json_response(ml_exchange(token), 400)

      web = post(build_conn(), ~p"/users/log-in", %{"user" => %{"token" => token}})
      assert redirected_to(web) == ~p"/users/log-in"
      assert Phoenix.Flash.get(web.assigns.flash, :error) =~ "invalid or it has expired"
    end

    test "an expired link is refused" do
      user = confirmed_user()
      token = magic_link_token(user)

      Repo.update_all(
        from(t in UserToken, where: t.user_id == ^user.id and t.context == "login"),
        set: [inserted_at: DateTime.add(DateTime.utc_now(:second), -2, :hour)]
      )

      assert %{"error" => "invalid_link"} = json_response(ml_exchange(token), 400)
      assert ApiTokens.list_tokens(user) == []
    end

    test "a link for an unconfirmed account confirms it, as on the web" do
      user = unconfirmed_user_fixture()
      refute user.confirmed_at
      body = json_response(ml_exchange(magic_link_token(user)), 200)
      assert body["confirmed"] == true
      assert Repo.get!(User, user.id).confirmed_at
    end

    test "an unconfirmed account with a password is refused, not crashed" do
      user =
        unconfirmed_user_fixture()
        |> Ecto.Changeset.change(hashed_password: Bcrypt.hash_pwd_salt(valid_user_password()))
        |> Repo.update!()

      token = magic_link_token(user)

      assert %{"error" => "unconfirmed"} = json_response(ml_exchange(token), 403)
      assert Accounts.get_user_by_magic_link_token(token)
    end

    test "sso_strict: refused, link unspent" do
      start_neiam(%{"OIDC_LOGIN_MODE" => "sso_strict"})
      user = confirmed_user()
      token = magic_link_token(user)

      assert %{"error" => "password_login_off"} = json_response(ml_exchange(token), 403)
      assert Accounts.get_user_by_magic_link_token(token)
    end

    test "sso: an account linked to the required provider is refused, link unspent" do
      idp = start_neiam(%{"OIDC_LOGIN_MODE" => "sso"})
      user = confirmed_user()
      Repo.insert!(%Identity{user_id: user.id, provider: "neiam", issuer: idp.issuer, sub: "s"})

      token = magic_link_token(user)
      assert %{"error" => "refused"} = json_response(ml_exchange(token), 403)
      assert Accounts.get_user_by_magic_link_token(token)
    end

    test "missing token is a 400", %{conn: conn} do
      assert %{"error" => "bad_request"} =
               json_response(post(conn, ~p"/api/v1/auth/magic_link/exchange", %{}), 400)
    end
  end

  describe "POST /api/v1/auth/magic_link/check" do
    test "says whether the link is the signed-in user's, without spending it" do
      me = confirmed_user()
      other = confirmed_user()
      {:ok, %{token: api}} = ApiTokens.issue_app_token(me, "Pixel 9", :password)

      check = fn token ->
        with_ip(build_conn())
        |> put_req_header("authorization", "Bearer " <> api)
        |> post(~p"/api/v1/auth/magic_link/check", %{token: token})
        |> json_response(200)
      end

      mine = magic_link_token(me)
      assert check.(mine) == %{"valid" => true, "same_user" => true}
      assert check.(magic_link_token(other)) == %{"valid" => true, "same_user" => false}
      assert check.("nonsense") == %{"valid" => false, "same_user" => false}
      assert Accounts.get_user_by_magic_link_token(mine)
    end

    test "needs a token", %{conn: conn} do
      assert post(conn, ~p"/api/v1/auth/magic_link/check", %{token: "x"}).status == 401

      bad =
        with_ip(build_conn())
        |> put_req_header("authorization", "Bearer nope")
        |> post(~p"/api/v1/auth/magic_link/check", %{token: "x"})

      assert bad.status == 401
    end
  end

  describe "existing pairing tokens" do
    test "a token made on Settings → API tokens (Mobile app) keeps working" do
      user = confirmed_user()

      {:ok, token} =
        ApiTokens.create_token(user, %{label: "phone", scopes: ApiTokens.mobile_scopes()})

      assert me(token.token)["id"] == user.id
    end
  end
end