7.8 KiB · text History bbb2a48
defmodule VigilWeb.DebugFileApiTest do
  use VigilWeb.ConnCase, async: true
  use Oban.Testing, repo: Vigil.Repo

  import Vigil.AccountsFixtures
  import Vigil.OrganizationsFixtures

  alias Vigil.{ApiTokens, Artifacts, DebugFiles, Repo}
  alias Vigil.DebugFiles.{AssembleWorker, Assembly, DebugFile}
  alias Vigil.NativeFixtures

  setup do
    user = user_fixture()
    org = organization_fixture(user)
    project = project_fixture(org_scope(user, org), %{"name" => "app"})

    {:ok, token} =
      ApiTokens.create_token(user, %{
        label: "cli",
        scopes: ["project:releases", "project:read", "org:read"]
      })

    %{user: user, org: org, project: project, token: token.token}
  end

  defp bearer(conn, token), do: put_req_header(conn, "authorization", "Bearer " <> token)
  defp sha1(data), do: :crypto.hash(:sha, data) |> Base.encode16(case: :lower)

  defp assemble(conn, ctx, body) do
    conn
    |> bearer(ctx.token)
    |> put_req_header("content-type", "application/json")
    |> post(
      "/api/0/projects/#{ctx.org.slug}/#{ctx.project.slug}/files/difs/assemble/",
      Jason.encode!(body)
    )
  end

  defp store!(ctx, data) do
    path = Path.join(System.tmp_dir!(), "vigil-dif-#{System.unique_integer([:positive])}")
    File.write!(path, :zlib.gzip(data))
    on_exit(fn -> File.rm(path) end)
    :ok = Artifacts.store_chunks(org_scope(ctx.user, ctx.org), [{sha1(data), path}])
  end

  defp job_args(ctx, checksum, name) do
    %{
      organization_id: ctx.org.id,
      project_id: ctx.project.id,
      checksum: checksum,
      name: name,
      chunks: [checksum]
    }
  end

  test "chunk-upload options add debug files and keep artifact bundles", ctx do
    body =
      ctx.conn
      |> bearer(ctx.token)
      |> get("/api/0/organizations/#{ctx.org.slug}/chunk-upload/")
      |> json_response(200)

    for cap <- ~w(release_files artifact_bundles artifact_bundles_v2 debug_files proguard pdbs),
        do: assert(cap in body["accept"])

    refute "sources" in body["accept"]
  end

  test "assemble: missing chunks, created, then ok with Sentry's DebugInfoFile", ctx do
    data = File.read!(NativeFixtures.fixture_path())
    checksum = sha1(data)
    req = %{checksum => %{name: "crash", debug_id: NativeFixtures.debug_id(), chunks: [checksum]}}

    assert %{^checksum => %{"state" => "not_found", "missingChunks" => [^checksum]}} =
             ctx.conn |> assemble(ctx, req) |> json_response(200)

    store!(ctx, data)

    assert %{^checksum => %{"state" => "created", "dif" => nil}} =
             build_conn() |> assemble(ctx, req) |> json_response(200)

    assert_enqueued(worker: AssembleWorker, args: %{checksum: checksum})

    assert %{^checksum => %{"state" => "created"}} =
             build_conn() |> assemble(ctx, req) |> json_response(200)

    assert [_] = all_enqueued(worker: AssembleWorker)

    assert :ok = perform_job(AssembleWorker, job_args(ctx, checksum, "crash"))

    assert %{^checksum => %{"state" => "ok", "dif" => dif}} =
             build_conn() |> assemble(ctx, req) |> json_response(200)

    assert dif["debugId"] == NativeFixtures.debug_id()
    assert dif["uuid"] == NativeFixtures.debug_id()
    assert dif["codeId"] == NativeFixtures.code_id()
    assert dif["cpuName"] == "x86_64"
    assert dif["objectName"] == "crash"
    assert dif["symbolType"] == "elf"
    assert dif["sha1"] == checksum
    assert dif["size"] == byte_size(data)
    assert "debug" in dif["data"]["features"]
  end

  test "a file that isn't a debug file ends in error, told once", ctx do
    data = "not a debug file at all"
    checksum = sha1(data)
    store!(ctx, data)
    req = %{checksum => %{name: "junk", chunks: [checksum]}}

    assert %{^checksum => %{"state" => "created"}} =
             ctx.conn |> assemble(ctx, req) |> json_response(200)

    assert {:cancel, _} = perform_job(AssembleWorker, job_args(ctx, checksum, "junk"))

    assert %{^checksum => %{"state" => "error", "detail" => detail}} =
             build_conn() |> assemble(ctx, req) |> json_response(200)

    assert detail =~ "Unsupported"
    refute Repo.get_by(Assembly, checksum: checksum)
  end

  test "a wrong whole checksum is an error", ctx do
    data = File.read!(NativeFixtures.fixture_path())
    store!(ctx, data)
    wrong = String.duplicate("a", 40)

    args = %{job_args(ctx, wrong, "crash") | chunks: [sha1(data)]}
    Repo.insert!(%Assembly{project_id: ctx.project.id, checksum: wrong, state: :created})
    assert {:cancel, "File checksum mismatch"} = perform_job(AssembleWorker, args)
  end

  test "bad requests and permissions", ctx do
    assert ctx.conn |> assemble(ctx, %{"nope" => %{chunks: []}}) |> json_response(400)

    {:ok, read_only} =
      ApiTokens.create_token(ctx.user, %{label: "ro", scopes: ["project:read", "org:read"]})

    assert ctx.conn
           |> assemble(%{ctx | token: read_only.token}, %{})
           |> json_response(403)

    assert build_conn()
           |> assemble(%{ctx | project: %{slug: "nope"}}, %{})
           |> json_response(404)
  end

  describe "with a stored file" do
    setup ctx do
      data = File.read!(NativeFixtures.fixture_path())
      target = %{organization_id: ctx.org.id, project_id: ctx.project.id}
      {:ok, [file]} = DebugFiles.create_files(target, "crash", sha1(data), data)
      %{dif: file, checksum: sha1(data)}
    end

    test "list, unknown checksums, delete", ctx do
      base = "/api/0/projects/#{ctx.org.slug}/#{ctx.project.slug}/files/dsyms/"

      assert [%{"debugId" => id}] =
               ctx.conn |> bearer(ctx.token) |> get(base) |> json_response(200)

      assert id == NativeFixtures.debug_id()

      assert [] =
               build_conn()
               |> bearer(ctx.token)
               |> get(base <> "?query=nothing")
               |> json_response(200)

      other = String.duplicate("b", 40)

      assert %{"missing" => [^other]} =
               build_conn()
               |> bearer(ctx.token)
               |> get(base <> "unknown/?checksums=#{ctx.checksum}&checksums=#{other}")
               |> json_response(200)

      assert build_conn()
             |> bearer(ctx.token)
             |> delete(base <> "?id=#{ctx.dif.id}")
             |> response(204)

      refute Repo.get(DebugFile, ctx.dif.id)
      assert {:error, _} = Vigil.Storage.get(ctx.dif.storage_key)
    end

    test "assembling the same file again answers ok at once", ctx do
      req = %{ctx.checksum => %{name: "crash", chunks: [ctx.checksum]}}

      assert %{} = resp = ctx.conn |> assemble(ctx, req) |> json_response(200)
      assert %{"state" => "ok", "dif" => %{"debugId" => _}} = resp[ctx.checksum]
      refute_enqueued(worker: AssembleWorker)
    end

    test "the SymCache is built once and stored", ctx do
      assert {:ok, symcache} = DebugFiles.symcache(ctx.dif)
      file = Repo.get(DebugFile, ctx.dif.id)
      assert file.symcache_key
      assert {:ok, ^symcache} = Vigil.Storage.get(file.symcache_key)
      assert {:ok, ^symcache} = DebugFiles.symcache(file)
    end
  end

  test "the legacy dsyms upload takes a zip of Proguard mappings", ctx do
    mapping = File.read!("test/support/fixtures/proguard/mapping.txt")
    uuid = "6a4fa6d8-6d4d-4d5e-9a3e-2f4c1bb3a1c2"
    {:ok, {_, zip}} = :zip.create(~c"m.zip", [{~c"proguard/#{uuid}.txt", mapping}], [:memory])

    path = Path.join(System.tmp_dir!(), "vigil-zip-#{System.unique_integer([:positive])}")
    File.write!(path, zip)
    on_exit(fn -> File.rm(path) end)

    assert [%{"debugId" => ^uuid, "symbolType" => "proguard", "cpuName" => "any"}] =
             ctx.conn
             |> bearer(ctx.token)
             |> post("/api/0/projects/#{ctx.org.slug}/#{ctx.project.slug}/files/dsyms/", %{
               "file" => %Plug.Upload{path: path, filename: "m.zip"}
             })
             |> json_response(201)

    assert %DebugFile{file_format: "proguard"} = DebugFiles.proguard_mapping(ctx.project.id, uuid)
  end
end