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

  import Vigil.AccountsFixtures
  import Vigil.OrganizationsFixtures

  alias Vigil.ApiTokens
  alias Vigil.Artifacts
  alias Vigil.Artifacts.{ArtifactBundle, ArtifactFile, AssembleStatus, AssembleWorker, FileBlob}
  alias Vigil.Repo

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

    {:ok, token} =
      ApiTokens.create_token(user, %{label: "cli", scopes: ["project:releases", "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)

  # A multipart body as sentry-cli's curl form sends it: one `file_gzip`
  # part per chunk, named by its SHA-1.
  defp upload(conn, token, org, parts) do
    boundary = "vigil-test-boundary"

    body =
      Enum.map(parts, fn {name, gz} ->
        [
          "--",
          boundary,
          "\r\n",
          ~s(Content-Disposition: form-data; name="file_gzip"; filename="#{name}"\r\n),
          "Content-Type: application/octet-stream\r\n\r\n",
          gz,
          "\r\n"
        ]
      end)
      |> then(&IO.iodata_to_binary([&1, "--", boundary, "--\r\n"]))

    conn
    |> bearer(token)
    |> put_req_header("content-type", "multipart/form-data; boundary=#{boundary}")
    |> post("/api/0/organizations/#{org.slug}/chunk-upload/", body)
  end

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

  test "chunk-upload options advertise artifact bundles", %{conn: conn, org: org, token: token} do
    body =
      conn
      |> bearer(token)
      |> get("/api/0/organizations/#{org.slug}/chunk-upload/")
      |> json_response(200)

    assert body["url"] == "/api/0/organizations/#{org.slug}/chunk-upload/"
    assert body["hashAlgorithm"] == "sha1"
    assert "artifact_bundles_v2" in body["accept"]
    assert body["compression"] == ["gzip"]
  end

  test "chunks are stored per organization, every part kept, each checked", ctx do
    a = "chunk a " <> String.duplicate("x", 1000)
    b = "chunk b"

    conn =
      upload(ctx.conn, ctx.token, ctx.org, [{sha1(a), :zlib.gzip(a)}, {sha1(b), :zlib.gzip(b)}])

    assert response(conn, 200)

    assert Repo.aggregate(FileBlob, :count) == 2
    blob = Repo.get_by!(FileBlob, checksum: sha1(a))
    assert blob.organization_id == ctx.org.id
    assert {:ok, ^a} = Vigil.Storage.get(blob.storage_key)

    # Same again: nothing new.
    assert ctx.conn |> upload(ctx.token, ctx.org, [{sha1(a), :zlib.gzip(a)}]) |> response(200)
    assert Repo.aggregate(FileBlob, :count) == 2
  end

  test "a chunk whose bytes don't match its name is refused", ctx do
    conn = upload(ctx.conn, ctx.token, ctx.org, [{sha1("other"), :zlib.gzip("data")}])
    assert %{"detail" => "Chunk checksum mismatch" <> _} = json_response(conn, 400)

    conn = upload(build_conn(), ctx.token, ctx.org, [{sha1("data"), "not gzip"}])
    assert json_response(conn, 400)
    assert Repo.aggregate(FileBlob, :count) == 0
  end

  test "uploading needs project:releases or project:write", ctx do
    {:ok, t} = ApiTokens.create_token(ctx.user, %{label: "read", scopes: ["project:read"]})

    assert ctx.conn
           |> upload(t.token, ctx.org, [{sha1("a"), :zlib.gzip("a")}])
           |> json_response(403)
  end

  test "another organization's chunk-upload is a 404", ctx do
    other = organization_fixture()

    assert ctx.conn
           |> upload(ctx.token, other, [{sha1("a"), :zlib.gzip("a")}])
           |> json_response(404)
  end

  describe "assemble" do
    test "missing chunks first, then created and a job", ctx do
      data = "the whole bundle"
      checksum = sha1(data)
      req = %{checksum: checksum, chunks: [checksum], projects: ["web"], version: "1.0"}

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

      assert build_conn()
             |> upload(ctx.token, ctx.org, [{checksum, :zlib.gzip(data)}])
             |> response(200)

      assert %{"state" => "created", "missingChunks" => []} =
               build_conn() |> assemble(ctx.token, ctx.org, req) |> json_response(200)

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

      # Asking again while it's queued: still created, no second job.
      assert %{"state" => "created"} =
               build_conn() |> assemble(ctx.token, ctx.org, req) |> json_response(200)

      assert [_] = all_enqueued(worker: AssembleWorker)
    end

    test "the release-bound assemble uses the release's projects", ctx do
      Vigil.Releases.ensure_release(ctx.org.id, ctx.project.id, "web@3.0")
      data = "bundle"
      checksum = sha1(data)
      :ok = Artifacts.store_chunks(scope(ctx), [write_gz(data)])

      assert %{"state" => "created"} =
               ctx.conn
               |> bearer(ctx.token)
               |> put_req_header("content-type", "application/json")
               |> post(
                 "/api/0/organizations/#{ctx.org.slug}/releases/web%403.0/assemble/",
                 Jason.encode!(%{checksum: checksum, chunks: [checksum]})
               )
               |> json_response(200)

      project_id = ctx.project.id

      assert_enqueued(
        worker: AssembleWorker,
        args: %{checksum: checksum, version: "web@3.0", project_ids: [project_id]}
      )

      assert build_conn()
             |> bearer(ctx.token)
             |> put_req_header("content-type", "application/json")
             |> post(
               "/api/0/organizations/#{ctx.org.slug}/releases/nope/assemble/",
               Jason.encode!(%{checksum: checksum, chunks: [checksum]})
             )
             |> json_response(404)
    end

    test "a project the token can't see is a 404", ctx do
      checksum = sha1("x")

      assert ctx.conn
             |> assemble(ctx.token, ctx.org, %{checksum: checksum, chunks: [], projects: ["nope"]})
             |> json_response(404)
    end

    test "a bundle that isn't a zip ends in error, told once", ctx do
      data = "not a zip"
      checksum = sha1(data)
      :ok = Artifacts.store_chunks(scope(ctx), [write_gz(data)])
      req = %{checksum: checksum, chunks: [checksum], projects: ["web"]}

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

      assert {:cancel, _} = perform_job(AssembleWorker, job_args(ctx, checksum, [checksum]))

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

      assert detail =~ "zip"
      refute Repo.get_by(AssembleStatus, checksum: checksum)
    end

    test "a bundle from two chunks is joined, checked and extracted", ctx do
      zip = bundle_zip()
      checksum = sha1(zip)
      {first, second} = String.split_at(zip, div(byte_size(zip), 2))
      chunks = [sha1(first), sha1(second)]
      :ok = Artifacts.store_chunks(scope(ctx), [write_gz(first), write_gz(second)])

      req = %{checksum: checksum, chunks: chunks, projects: ["web"], version: "web@1.2.0"}

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

      assert :ok =
               perform_job(
                 AssembleWorker,
                 job_args(ctx, checksum, chunks) |> Map.put("version", "web@1.2.0")
               )

      assert %{"state" => "ok"} =
               build_conn() |> assemble(ctx.token, ctx.org, req) |> json_response(200)

      bundle =
        Repo.get_by!(ArtifactBundle, checksum: checksum) |> Repo.preload([:files, :projects])

      assert bundle.release == "web@1.2.0"
      assert bundle.artifact_count == 2
      assert [%{slug: "web"}] = bundle.projects

      minified = Enum.find(bundle.files, &(&1.kind == "minified_source"))
      map = Enum.find(bundle.files, &(&1.kind == "source_map"))
      assert minified.url == "~/static/app.min.js"
      assert minified.sourcemap == "app.min.js.map"
      assert minified.debug_id == "6c2a7d7e-3c1f-4b0a-9d43-5a8f1e2b3c4d"
      assert map.debug_id == minified.debug_id
      assert {:ok, "function a(){}"} = Vigil.Storage.get(minified.storage_key)

      release = Vigil.Releases.ensure_release(ctx.org.id, ctx.project.id, "web@1.2.0")
      assert [%ArtifactBundle{}] = Vigil.Releases.list_artifact_bundles(release, ctx.project)
      assert Repo.aggregate(ArtifactFile, :count) == 2
    end

    test "a bundle sentry-cli 2.58 made (SYSB header) assembles", ctx do
      zip = File.read!("test/support/fixtures/sourcemaps/artifact_bundle.zip")
      checksum = sha1(zip)
      :ok = Artifacts.store_chunks(scope(ctx), [write_gz(zip)])

      assert :ok =
               perform_job(
                 AssembleWorker,
                 job_args(ctx, checksum, [checksum]) |> Map.put("version", "web@1.0.0")
               )

      bundle = Repo.get_by!(ArtifactBundle, checksum: checksum) |> Repo.preload(:files)
      assert bundle.bundle_id
      assert Enum.sort(Enum.map(bundle.files, & &1.kind)) == ["minified_source", "source_map"]
      assert Enum.all?(bundle.files, & &1.debug_id)
    end

    test "a bundle whose whole checksum is wrong is an error", ctx do
      data = "abc"
      :ok = Artifacts.store_chunks(scope(ctx), [write_gz(data)])
      wrong = sha1("something else")

      req = %{checksum: wrong, chunks: [sha1(data)], projects: ["web"]}

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

      assert {:cancel, "Bundle checksum mismatch"} =
               perform_job(AssembleWorker, job_args(ctx, wrong, [sha1(data)]))
    end
  end

  test "cleanup drops old blobs and statuses", ctx do
    :ok = Artifacts.store_chunks(scope(ctx), [write_gz("old")])
    blob = Repo.one!(FileBlob)

    Repo.update_all(FileBlob, set: [inserted_at: ~U[2020-01-01 00:00:00Z]])
    assert :ok = Artifacts.cleanup()
    refute Repo.one(FileBlob)
    assert {:error, :not_found} = Vigil.Storage.get(blob.storage_key)
  end

  defp scope(ctx), do: org_scope(ctx.user, ctx.org)

  defp write_gz(data) do
    path = Path.join(System.tmp_dir!(), "vigil-chunk-#{System.unique_integer([:positive])}")
    File.write!(path, :zlib.gzip(data))
    on_exit(fn -> File.rm(path) end)
    {sha1(data), path}
  end

  defp job_args(ctx, checksum, chunks) do
    %{
      "organization_id" => ctx.org.id,
      "checksum" => checksum,
      "chunks" => chunks,
      "project_ids" => [ctx.project.id],
      "version" => nil,
      "dist" => nil
    }
  end

  # The layout sentry-cli writes: manifest.json plus files/, the manifest
  # naming each file's url, type and headers.
  defp bundle_zip do
    debug_id = "6c2a7d7e-3c1f-4b0a-9d43-5a8f1e2b3c4d"

    manifest = %{
      "org" => "x",
      "release" => "web@1.2.0",
      "files" => %{
        "files/_/_/app.min.js" => %{
          "url" => "~/static/app.min.js",
          "type" => "minified_source",
          "headers" => %{"debug-id" => debug_id, "Sourcemap" => "app.min.js.map"}
        },
        "files/_/_/app.min.js.map" => %{
          "url" => "~/static/app.min.js.map",
          "type" => "source_map",
          "headers" => %{"debug-id" => debug_id}
        }
      }
    }

    {:ok, {_, zip}} =
      :zip.create(
        ~c"bundle.zip",
        [
          {~c"manifest.json", Jason.encode!(manifest)},
          {~c"files/_/_/app.min.js", "function a(){}"},
          {~c"files/_/_/app.min.js.map", ~s({"version":3,"sources":[],"mappings":""})}
        ],
        [:memory]
      )

    zip
  end
end