8.1 KiB · text History 3ec21a7
defmodule VigilWeb.MobileApiTest do
  @moduledoc """
  What the Android app reads that sentry-cli doesn't: issues across the
  organization, one issue's details, and its newest event, all with a
  token carrying only the "Mobile app" bundle.
  """
  use VigilWeb.ConnCase, async: true

  import Vigil.AccountsFixtures
  import Vigil.OrganizationsFixtures
  import Vigil.ReleasesFixtures

  alias Vigil.{ApiTokens, Repo}
  alias Vigil.Ingest
  alias Vigil.Ingest.{Drain, Envelope}

  setup do
    owner = user_fixture()
    org = organization_fixture(owner)
    scope = org_scope(owner, org)
    web = project_fixture(scope, %{"name" => "web"})
    api = project_fixture(scope, %{"name" => "api"})
    {:ok, t} = ApiTokens.create_token(owner, %{label: "phone", scopes: ApiTokens.mobile_scopes()})

    %{owner: owner, org: org, scope: scope, web: web, api: api, token: t.token}
  end

  defp api(token), do: build_conn() |> put_req_header("authorization", "Bearer " <> token)

  defp ingest(project, org, event) do
    target = %Ingest.Target{
      project_id: project.id,
      dsn_id: project.dsn_id,
      organization_id: org.id,
      key_id: Ecto.UUID.generate()
    }

    item = %Envelope.Item{
      type: "event",
      headers: %{"type" => "event"},
      payload: Jason.encode!(event)
    }

    Ingest.accept(target, %{headers: %{}, items: [item]}, %{client_ip: "203.0.113.7"})
    Drain.drain(project.id)
  end

  defp event(user_id) do
    %{
      "event_id" => Vigil.Schema.uuid7() |> String.replace("-", ""),
      "platform" => "python",
      "level" => "error",
      "release" => "web@1.2.0",
      "tags" => %{"region" => "eu-west"},
      "user" => %{"id" => user_id},
      "exception" => %{
        "values" => [
          %{
            "type" => "CheckoutFailed",
            "value" => "could not take payment",
            "mechanism" => %{"type" => "excepthook", "handled" => false},
            "stacktrace" => %{
              "frames" => [
                %{"filename" => "flask/app.py", "function" => "dispatch", "lineno" => 9},
                %{
                  "filename" => "shop/views.py",
                  "function" => "checkout",
                  "lineno" => 41,
                  "in_app" => true,
                  "pre_context" => ["def checkout():", "    order = load()"],
                  "context_line" => "    charge(order)",
                  "post_context" => ["    return ok"],
                  "vars" => %{"card" => "4111"}
                }
              ]
            }
          }
        ]
      },
      "breadcrumbs" => %{
        "values" => [%{"category" => "http", "data" => %{"url" => "/cart"}}]
      },
      "request" => %{
        "url" => "https://shop.example/checkout",
        "method" => "POST",
        "headers" => [["User-Agent", "Mozilla/5.0"]]
      }
    }
  end

  test "the API root identifies the token, for pairing", ctx do
    assert %{"user" => %{"email" => email}, "auth" => %{"scopes" => scopes}} =
             ctx.token |> api() |> get(~p"/api/0/") |> json_response(200)

    assert email == ctx.owner.email
    assert ApiTokens.mobile?(scopes)
  end

  describe "issues across the organization" do
    setup ctx do
      older = DateTime.add(DateTime.utc_now(), -60)
      w = issue_fixture(ctx.web, title: "web boom")
      a = issue_fixture(ctx.api, title: "api boom", last_seen: older)
      _resolved = issue_fixture(ctx.web, title: "fixed", status: :resolved)
      %{w: w, a: a}
    end

    test "lists every visible project's unresolved issues, newest first", ctx do
      path = ~p"/api/0/organizations/#{ctx.org.slug}/issues/"
      conn = ctx.token |> api() |> get(path)

      assert [
               %{"title" => "web boom", "project" => %{"slug" => "web"}, "userCount" => 0},
               %{"title" => "api boom", "project" => %{"slug" => "api"}}
             ] = json_response(conn, 200)

      assert [link] = get_resp_header(conn, "link")
      assert link =~ ~s(rel="next"; results="false")

      assert [%{"title" => "fixed"}] =
               ctx.token |> api() |> get(path, query: "is:resolved") |> json_response(200)

      assert [%{"title" => "api boom"}] =
               ctx.token |> api() |> get(path, project: ctx.api.dsn_id) |> json_response(200)

      page = ctx.token |> api() |> get(path, per_page: "1")
      assert [%{"title" => "web boom"}] = json_response(page, 200)
      assert [link] = get_resp_header(page, "link")
      assert link =~ ~s(rel="next"; results="true"; cursor="0:1:0")
    end

    test "403 without an event scope, 404 for another organization", ctx do
      {:ok, t} = ApiTokens.create_token(ctx.owner, %{label: "t", scopes: ["project:read"]})
      path = ~p"/api/0/organizations/#{ctx.org.slug}/issues/"
      assert t.token |> api() |> get(path) |> json_response(403)

      other = organization_fixture()

      assert ctx.token
             |> api()
             |> get(~p"/api/0/organizations/#{other.slug}/issues/")
             |> json_response(404)
    end
  end

  describe "one issue" do
    setup ctx do
      ingest(ctx.web, ctx.org, event("u-1"))
      ingest(ctx.web, ctx.org, event("u-2"))
      [issue] = Repo.all(Vigil.Issues.Issue)
      %{issue: issue}
    end

    test "its details: counts, users, releases and tags", ctx do
      body =
        ctx.token
        |> api()
        |> get(~p"/api/0/projects/#{ctx.org.slug}/web/issues/#{ctx.issue.short_id}/")
        |> json_response(200)

      assert %{
               "id" => id,
               "count" => "2",
               "userCount" => 2,
               "permalink" => permalink,
               "firstRelease" => %{"version" => "web@1.2.0"},
               "tags" => tags
             } = body

      assert id == to_string(ctx.issue.short_id)
      assert permalink =~ "/orgs/#{ctx.org.slug}/projects/web/issues/#{id}"

      assert %{"totalValues" => 2, "topValues" => [%{"value" => "eu-west", "count" => 2}]} =
               Enum.find(tags, &(&1["key"] == "region"))
    end

    test "its newest event, in Sentry's entries", ctx do
      body =
        ctx.token
        |> api()
        |> get(
          ~p"/api/0/projects/#{ctx.org.slug}/web/issues/#{ctx.issue.short_id}/events/latest/"
        )
        |> json_response(200)

      assert %{"eventID" => _, "release" => %{"version" => "web@1.2.0"}, "entries" => entries} =
               body

      assert %{"key" => "region", "value" => "eu-west"} in body["tags"]

      assert %{"data" => %{"values" => [exception]}} =
               Enum.find(entries, &(&1["type"] == "exception"))

      assert %{
               "type" => "CheckoutFailed",
               "mechanism" => %{"handled" => false},
               "stacktrace" => %{"frames" => [_, frame]}
             } = exception

      assert %{"function" => "checkout", "inApp" => true, "lineNo" => 41} = frame

      assert frame["context"] == [
               [39, "def checkout():"],
               [40, "    order = load()"],
               [41, "    charge(order)"],
               [42, "    return ok"]
             ]

      refute Map.has_key?(frame, "vars")

      assert %{"data" => %{"values" => [%{"category" => "http"}]}} =
               Enum.find(entries, &(&1["type"] == "breadcrumbs"))

      assert %{"data" => %{"method" => "POST", "headers" => [["User-Agent", "Mozilla/5.0"]]}} =
               Enum.find(entries, &(&1["type"] == "request"))
    end

    test "404 for an issue that isn't there, or has no events", ctx do
      base = ~p"/api/0/projects/#{ctx.org.slug}/web/issues"
      assert ctx.token |> api() |> get(base <> "/999999/") |> json_response(404)

      bare = issue_fixture(ctx.web, title: "no events")

      assert ctx.token
             |> api()
             |> get(base <> "/#{bare.short_id}/events/latest/")
             |> json_response(404)
    end
  end

  test "the mobile bundle reads projects, monitors and uptime", ctx do
    org = ctx.org.slug

    assert [_, _] =
             ctx.token
             |> api()
             |> get(~p"/api/0/organizations/#{org}/projects/")
             |> json_response(200)

    for path <- [
          ~p"/api/0/organizations/#{org}/monitors/",
          ~p"/api/0/organizations/#{org}/uptime/"
        ] do
      assert [] = ctx.token |> api() |> get(path) |> json_response(200)
    end
  end
end