11.1 KiB · text History bbb2a48
defmodule VigilWeb.ApiTokenLive do
  @moduledoc """
  Personal API tokens for sentry-cli, other tools and the Android app. A
  token is shown once, when it is made; only its hash is kept. Its scopes
  are narrowed in each organization to your role there.

  The **Mobile app** box ticks the bundle the Android app uses
  (`Vigil.ApiTokens.mobile_scopes/0`: reading, plus `event:write` to
  triage issues), and unticking it clears them again. Its **Read-only**
  sub-option leaves `event:write` out (`mobile_read_scopes/0`), so the
  phone can look but not touch.
  A bundle isn't a scope of its own: the token carries the individual
  scopes. When a new token covers the bundle, the page shows a
  `vigil://pair?base=…&token=…` QR beside it, which the app scans. A
  paired phone *is* its token, so revoking the token signs the phone out.
  """
  use VigilWeb, :live_view

  alias Vigil.ApiTokens
  alias Vigil.Organizations.Roles

  # sentry-cli's release and sourcemap uploads need only this one.
  @default_scopes ["project:releases", "project:read", "org:read"]

  @impl true
  def mount(_params, _session, socket) do
    {:ok,
     socket
     |> assign(:page_title, "API tokens")
     |> assign(:form, new_form())
     |> assign(:new_token, nil)
     |> stream(:tokens, ApiTokens.list_tokens(socket.assigns.current_scope.user))}
  end

  defp new_form, do: to_form(ApiTokens.change_token(%{scopes: @default_scopes}), as: "token")

  @doc """
  The link the Android app scans or opens. The base is the endpoint's own
  URL (as every absolute link Vigil makes), not the request's host.
  """
  def pair_uri(raw_token) do
    "vigil://pair?" <> URI.encode_query(%{"base" => VigilWeb.base_url(), "token" => raw_token})
  end

  defp pair_qr(raw_token) do
    raw_token
    |> pair_uri()
    |> EQRCode.encode()
    |> EQRCode.svg(width: 200, background_color: "#ffffff", color: "#000000")
    |> Phoenix.HTML.raw()
  end

  @impl true
  def render(assigns) do
    assigns =
      assigns
      |> assign(:all_scopes, Roles.all_scopes())
      |> assign(:mobile_scopes, ApiTokens.mobile_read_scopes())
      |> assign(:form_scopes, assigns.form[:scopes].value || [])

    ~H"""
    <Layouts.app flash={@flash} current_scope={@current_scope} active={:tokens}>
      <div class="mx-auto max-w-3xl space-y-6">
        <.header>
          API tokens
          <:subtitle>
            For sentry-cli (<code class="font-mono">SENTRY_AUTH_TOKEN</code>), other tools and the
            Android app. In each organization a token can do only what your role there allows.
          </:subtitle>
        </.header>

        <div
          :if={@new_token}
          id="new-token"
          class="space-y-2 rounded-box border border-primary/40 bg-base-100 p-4"
        >
          <p class="text-sm font-medium">{@new_token.label}</p>
          <div class="join w-full">
            <input
              id="new-token-value"
              type="text"
              readonly
              value={@new_token.token}
              class="input input-sm join-item min-w-0 flex-1 font-mono text-xs"
              aria-label="Token"
            />
            <button
              id="copy-token"
              type="button"
              class="btn btn-sm btn-primary join-item"
              phx-click={JS.dispatch("phx:copy", to: "#new-token-value")}
            >
              <.icon name="hero-clipboard-document-micro" class="size-4" /> Copy
            </button>
          </div>
          <p class="text-xs text-warning">Copy it now: it won't be shown again.</p>

          <div
            :if={ApiTokens.mobile?(@new_token.scopes)}
            id="pair-device"
            class="flex flex-wrap items-center gap-4 border-t border-primary/20 pt-3"
          >
            <div
              id="pair-qr"
              class="rounded-lg bg-white p-1.5 leading-none shadow-sm transition-transform hover:scale-[1.02]"
            >
              {pair_qr(@new_token.token)}
            </div>
            <div class="min-w-48 flex-1 space-y-1.5">
              <p class="flex items-center gap-1.5 text-sm font-semibold">
                <.icon name="hero-device-phone-mobile-micro" class="size-4" /> Pair a phone
              </p>
              <p class="text-xs text-base-content/70">
                Open the Vigil app and tap <strong>Scan code</strong>, or open the link below on
                the phone. It carries this server's address and the token: treat it as a password.
                Revoking the token signs the phone out.
              </p>
              <a
                id="pair-link"
                href={pair_uri(@new_token.token)}
                class="block break-all rounded bg-base-200 p-2 font-mono text-[10px] text-base-content/80 hover:bg-base-300"
              >
                {pair_uri(@new_token.token)}
              </a>
            </div>
          </div>
        </div>

        <.form
          for={@form}
          id="token-form"
          phx-change="change"
          phx-submit="create"
          class="space-y-3 rounded-box border border-base-300 bg-base-200/60 p-4"
        >
          <.input field={@form[:label]} label="Label" placeholder="CI uploads" required />
          <div class="rounded-lg border border-primary/30 bg-primary/5 px-3 pt-2 transition-colors hover:bg-primary/10">
            <.input
              type="checkbox"
              id="token-mobile"
              name="token[mobile]"
              value={ApiTokens.mobile?(@form_scopes)}
              label="Mobile app"
            />
            <p class="-mt-1 pb-2 text-xs text-base-content/60">
              What the Vigil Android app reads (<span class="font-mono">{Enum.join(@mobile_scopes, " ")}</span>), plus
              <span class="font-mono">event:write</span>
              to resolve, ignore and assign issues. The new token then comes with a code to scan.
            </p>
            <div
              :if={ApiTokens.mobile?(@form_scopes)}
              id="token-mobile-options"
              class="-mt-1 ml-6 border-l-2 border-primary/20 pb-2 pl-3"
            >
              <.input
                type="checkbox"
                id="token-mobile-read-only"
                name="token[mobile_read_only]"
                value={"event:write" not in @form_scopes}
                label="Read-only"
              />
              <p class="-mt-1 text-xs text-base-content/60">
                Leaves out <span class="font-mono">event:write</span>: the phone can look but not
                triage.
              </p>
            </div>
          </div>
          <fieldset>
            <legend class="mb-1 text-sm font-medium">Scopes</legend>
            <div class="grid grid-cols-2 gap-1 sm:grid-cols-4">
              <label :for={s <- @all_scopes} class="flex items-center gap-2 font-mono text-xs">
                <input
                  type="checkbox"
                  name="token[scopes][]"
                  value={s}
                  checked={s in (@form[:scopes].value || [])}
                  class="checkbox checkbox-xs"
                />
                {s}
              </label>
            </div>
            <p
              :for={msg <- Enum.map(@form[:scopes].errors, &translate_error/1)}
              class="mt-1 text-xs text-error"
            >
              {msg}
            </p>
          </fieldset>
          <.button class="btn btn-primary btn-sm" phx-disable-with="Creating…">Create token</.button>
        </.form>

        <ul
          id="tokens"
          phx-update="stream"
          class="divide-y divide-base-300 rounded-box border border-base-300"
        >
          <li id="tokens-empty" class="hidden p-4 text-center text-sm text-base-content/60 only:block">
            No tokens yet.
          </li>
          <li
            :for={{dom_id, t} <- @streams.tokens}
            id={dom_id}
            class="flex flex-wrap items-center gap-3 px-4 py-3"
          >
            <div class="min-w-0 flex-1">
              <p class="font-medium">
                {t.label} <span class="font-mono text-xs text-base-content/50">…{t.token_hint}</span>
                <span
                  :if={ApiTokens.mobile?(t.scopes)}
                  id={"mobile-#{dom_id}"}
                  data-access={if ApiTokens.mobile_triage?(t.scopes), do: "triage", else: "read-only"}
                  class="badge badge-xs badge-primary ml-1 align-middle"
                >
                  {if ApiTokens.mobile_triage?(t.scopes), do: "mobile", else: "mobile · read-only"}
                </span>
              </p>
              <p class="font-mono text-xs text-base-content/60">{Enum.join(t.scopes, " ")}</p>
              <p class="text-xs text-base-content/50">
                {if t.last_used_at,
                  do: "last used #{Calendar.strftime(t.last_used_at, "%b %-d %H:%M")}",
                  else: "never used"}
              </p>
            </div>
            <button
              type="button"
              id={"revoke-#{dom_id}"}
              class="btn btn-ghost btn-xs text-error"
              phx-click="revoke"
              phx-value-id={t.id}
              data-confirm={"Revoke #{t.label}? Tools using it stop working."}
            >
              Revoke
            </button>
          </li>
        </ul>
      </div>
    </Layouts.app>
    """
  end

  @impl true
  # Ticking "Mobile app" adds its scopes, unticking takes them away;
  # "Read-only" takes away (or gives back) the bundle's write scope. Any
  # other change keeps the boxes as they are (the bundle's boxes then show
  # whether the scopes still cover it).
  def handle_event("change", %{"token" => params} = all, socket) do
    scopes = params["scopes"] || []
    bundle = ApiTokens.mobile_scopes()
    write = bundle -- ApiTokens.mobile_read_scopes()

    scopes =
      case all["_target"] do
        ["token", "mobile"] ->
          if params["mobile"] == "true", do: Enum.uniq(scopes ++ bundle), else: scopes -- bundle

        ["token", "mobile_read_only"] ->
          if params["mobile_read_only"] == "true",
            do: scopes -- write,
            else: Enum.uniq(scopes ++ write)

        _ ->
          scopes
      end

    scopes = Enum.filter(Roles.all_scopes(), &(&1 in scopes))
    changeset = ApiTokens.change_token(%{"label" => params["label"], "scopes" => scopes})
    {:noreply, assign(socket, :form, to_form(changeset, as: "token"))}
  end

  def handle_event("create", %{"token" => params}, socket) do
    params = Map.put_new(params, "scopes", [])

    case ApiTokens.create_token(socket.assigns.current_scope.user, params) do
      {:ok, token} ->
        {:noreply,
         socket
         |> assign(:new_token, token)
         |> assign(:form, new_form())
         |> stream_insert(:tokens, token, at: 0)}

      {:error, changeset} ->
        {:noreply, assign(socket, :form, to_form(changeset, as: "token"))}
    end
  end

  def handle_event("revoke", %{"id" => id}, socket) do
    case ApiTokens.delete_token(socket.assigns.current_scope.user, id) do
      {:ok, token} ->
        {:noreply,
         socket
         |> update(:new_token, &if(&1 && &1.id == token.id, do: nil, else: &1))
         |> stream_delete(:tokens, token)}

      {:error, _} ->
        {:noreply, put_flash(socket, :error, "Couldn't revoke that token.")}
    end
  end
end