13.9 KiB · text History 1a4b866
defmodule VigilWeb.IngestPlugTest do
  @moduledoc """
  The wire contract (ROADMAP.md): what each SDK sends, and what it needs
  back. Requests go through the whole Endpoint.
  """
  use VigilWeb.ConnCase, async: true
  use Oban.Testing, repo: Vigil.Repo

  import Ecto.Query
  import Vigil.AccountsFixtures
  import Vigil.OrganizationsFixtures

  alias Vigil.Ingest.{BufferedItem, Drain, Outcome}
  alias Vigil.{Projects, Repo}

  setup do
    owner = user_fixture()
    org = organization_fixture(owner)
    scope = org_scope(owner, org)
    project = project_fixture(scope)
    [key] = Projects.list_keys(project)
    hex = String.replace(key.public_key, "-", "")

    %{
      org: org,
      scope: scope,
      project: project,
      key: key,
      hex: hex,
      path: "/api/#{project.dsn_id}/envelope/"
    }
  end

  @event_id "9ec79c33ec9942ab8353589fcb2e04dc"

  defp envelope(items, headers \\ %{"event_id" => @event_id}) do
    Enum.join([Jason.encode!(headers) | Enum.flat_map(items, &item/1)], "\n") <> "\n"
  end

  defp item({type, payload}) when is_map(payload), do: item({type, Jason.encode!(payload)})

  defp item({type, payload}),
    do: [Jason.encode!(%{type: type, length: byte_size(payload)}), payload]

  defp python_auth(hex),
    do: "Sentry sentry_key=#{hex}, sentry_version=7, sentry_client=sentry.python/3.0.2"

  defp elixir_auth(hex),
    do:
      "Sentry sentry_version=5, sentry_client=sentry-elixir/14.1.0, sentry_timestamp=#{System.system_time(:second)}, sentry_key=#{hex}"

  defp post_raw(conn, path, body, headers) do
    Enum.reduce(headers, conn, fn {k, v}, c -> put_req_header(c, k, v) end)
    |> raw_post(path, body)
  end

  # A POST as SDKs send it: a raw body, and only the headers given (no
  # Content-Type unless set: sentry-elixir sends none, which
  # Phoenix.ConnTest's post/3 won't allow). Through the whole Endpoint.
  defp raw_post(conn, path, body) do
    :post
    |> Plug.Test.conn(path, body)
    |> Map.put(:req_headers, conn.req_headers)
    |> VigilWeb.Endpoint.call([])
  end

  defp buffered(project),
    do: Repo.all(from i in BufferedItem, where: i.project_id == ^project.id, order_by: i.id)

  describe "sentry-python 3.x" do
    test "a brotli envelope with an event and a client report", %{
      conn: conn,
      hex: hex,
      path: path,
      project: project
    } do
      body =
        envelope([
          {"event", %{message: "boom"}},
          {"client_report", %{timestamp: 1.0, discarded_events: []}}
        ])

      conn =
        post_raw(conn, path, brotli(body), [
          {"content-type", "application/x-sentry-envelope"},
          {"content-encoding", "br"},
          {"x-sentry-auth", python_auth(hex)}
        ])

      assert json_response(conn, 200) == %{"id" => @event_id}
      assert [%{type: "event", event_id: @event_id}, %{type: "client_report"}] = buffered(project)
      assert_enqueued(worker: Drain, args: %{project_id: project.id})
    end

    test "gzip, sessions and spans are taken", %{
      conn: conn,
      hex: hex,
      path: path,
      project: project
    } do
      body =
        envelope([{"session", %{sid: "x", init: true}}, {"span", %{version: 2, items: []}}], %{})

      conn =
        post_raw(conn, path, :zlib.gzip(body), [
          {"content-encoding", "gzip"},
          {"x-sentry-auth", python_auth(hex)}
        ])

      assert json_response(conn, 200) == %{}
      assert ~w(session span) == Enum.map(buffered(project), & &1.type)
    end
  end

  describe "sentry-elixir 14.x" do
    test "no content type, no compression, logs without length", %{
      conn: conn,
      hex: hex,
      path: path,
      project: project
    } do
      body =
        Enum.join(
          [
            Jason.encode!(%{event_id: @event_id}),
            ~s({"type":"log","item_count":1,"content_type":"application/vnd.sentry.items.log+json"}),
            ~s({"items":[{"timestamp":1.0,"level":"info","body":"hi","trace_id":null,"attributes":{}}]}),
            ~s({"type":"check_in","length":2}),
            "{}"
          ],
          "\n"
        )

      conn = conn |> put_req_header("x-sentry-auth", elixir_auth(hex)) |> raw_post(path, body)
      # Exactly 200 and a JSON object: anything else, sentry-elixir retries.
      assert %{"id" => @event_id} = json_response(conn, 200)
      assert ~w(log check_in) == Enum.map(buffered(project), & &1.type)
    end
  end

  describe "where the key comes from" do
    test "the query string", %{conn: conn, hex: hex, path: path} do
      assert conn
             |> raw_post(path <> "?sentry_key=#{hex}&sentry_version=7", envelope([]))
             |> json_response(200)
    end

    test "Authorization, and a dashed key", %{conn: conn, key: key, path: path} do
      conn = put_req_header(conn, "authorization", "Sentry sentry_key=#{key.public_key}")
      assert conn |> raw_post(path, envelope([])) |> json_response(200)
    end

    test "the envelope's dsn header (tunnels), for this project only", %{
      conn: conn,
      hex: hex,
      project: project,
      path: path
    } do
      dsn = "https://#{hex}@example.com/#{project.dsn_id}"
      assert conn |> raw_post(path, envelope([], %{"dsn" => dsn})) |> json_response(200)

      other = "https://#{hex}@example.com/#{project.dsn_id + 1}"

      assert %{"detail" => "Denied"} =
               conn |> raw_post(path, envelope([], %{"dsn" => other})) |> json_response(403)
    end
  end

  describe "refusals" do
    test "bad, inactive and missing keys are 403 JSON", %{
      conn: conn,
      scope: scope,
      key: key,
      hex: hex,
      path: path
    } do
      assert %{"detail" => "Denied"} = conn |> raw_post(path, envelope([])) |> json_response(403)

      bad = conn |> put_req_header("x-sentry-auth", python_auth(String.duplicate("0", 32)))
      assert bad |> raw_post(path, envelope([])) |> json_response(403)

      {:ok, _} = Projects.update_key(scope, key, %{active: false})
      off = conn |> put_req_header("x-sentry-auth", python_auth(hex))
      assert off |> raw_post(path, envelope([])) |> json_response(403)
    end

    test "an organization not accepting events: 429 with integer backoff", %{
      conn: conn,
      scope: scope,
      org: org,
      hex: hex,
      path: path
    } do
      {:ok, _} = Vigil.Organizations.update_organization(scope, org, %{accepting_events: false})

      conn =
        conn |> put_req_header("x-sentry-auth", python_auth(hex)) |> raw_post(path, envelope([]))

      assert json_response(conn, 429)
      assert get_resp_header(conn, "retry-after") == ["600"]
      assert get_resp_header(conn, "x-sentry-rate-limits") == ["600::organization:disabled"]
    end

    test "a key's rate limit counts events, not other items", %{
      conn: conn,
      scope: scope,
      key: key,
      hex: hex,
      path: path,
      project: project
    } do
      {:ok, _} = Projects.update_key(scope, key, %{rate_limit_count: 1, rate_limit_window: 3600})
      auth = &put_req_header(&1, "x-sentry-auth", python_auth(hex))

      assert conn |> auth.() |> raw_post(path, envelope([{"event", %{}}])) |> json_response(200)

      assert conn
             |> auth.()
             |> raw_post(path, envelope([{"client_report", %{}}]))
             |> json_response(200)

      limited = conn |> auth.() |> raw_post(path, envelope([{"event", %{}}]))
      assert json_response(limited, 429)
      [retry] = get_resp_header(limited, "retry-after")
      assert String.to_integer(retry) in 1..3600
      assert get_resp_header(limited, "x-sentry-rate-limits") == ["#{retry}::key:key_quota"]

      assert [%{source: :edge, reason: "key_quota", quantity: 1}] =
               Repo.all(from o in Outcome, where: o.project_id == ^project.id)
    end

    test "bombs are 413; garbage, empty bodies and bad headers 400", %{
      conn: conn,
      hex: hex,
      path: path
    } do
      auth = &put_req_header(&1, "x-sentry-auth", python_auth(hex))
      bomb = :zlib.gzip(:binary.copy("A", 120 * 1024 * 1024))

      assert conn
             |> auth.()
             |> put_req_header("content-encoding", "gzip")
             |> raw_post(path, bomb)
             |> json_response(413)

      assert conn
             |> auth.()
             |> put_req_header("content-encoding", "br")
             |> raw_post(path, "nope")
             |> json_response(400)

      assert conn |> auth.() |> raw_post(path, "") |> json_response(400)
      assert conn |> auth.() |> raw_post(path, "not json\n{}") |> json_response(400)
    end

    test "an oversize event is dropped and counted, the rest kept", %{
      conn: conn,
      hex: hex,
      path: path,
      project: project
    } do
      big = %{message: String.duplicate("x", 1_100_000)}
      body = envelope([{"event", big}, {"client_report", %{}}])

      assert conn
             |> put_req_header("x-sentry-auth", python_auth(hex))
             |> raw_post(path, body)
             |> json_response(200)

      assert ["client_report"] == Enum.map(buffered(project), & &1.type)

      assert [%{reason: "too_large", category: "error"}] =
               Repo.all(from o in Outcome, where: o.project_id == ^project.id)
    end
  end

  describe "the edges of the protocol" do
    test "unknown and unsupported types are accepted, not kept", %{
      conn: conn,
      hex: hex,
      path: path,
      project: project
    } do
      body = envelope([{"profile_chunk", "{}"}, {"brand_new_type", "{}"}, {"event", %{}}])

      assert conn
             |> put_req_header("x-sentry-auth", python_auth(hex))
             |> raw_post(path, body)
             |> json_response(200)

      assert ["event"] == Enum.map(buffered(project), & &1.type)
    end

    test "with or without the trailing slash", %{conn: conn, hex: hex, project: project} do
      conn = put_req_header(conn, "x-sentry-auth", python_auth(hex))

      assert conn
             |> raw_post("/api/#{project.dsn_id}/envelope", envelope([]))
             |> json_response(200)
    end

    test "CORS: preflight, and exposed backoff headers", %{conn: conn, path: path} do
      conn = options(conn, path)
      assert response(conn, 200)
      assert get_resp_header(conn, "access-control-allow-origin") == ["*"]
      [allowed] = get_resp_header(conn, "access-control-allow-headers")
      assert allowed =~ "x-sentry-auth" and allowed =~ "sentry-trace" and allowed =~ "baggage"
      [exposed] = get_resp_header(conn, "access-control-expose-headers")
      assert exposed =~ "retry-after" and exposed =~ "x-sentry-rate-limits"
    end

    test "only POST", %{conn: conn, path: path} do
      assert conn |> get(path) |> json_response(405)
    end

    test "legacy /store/ and CSP /security/", %{conn: conn, hex: hex, project: project} do
      store =
        conn
        |> put_req_header("x-sentry-auth", python_auth(hex))
        |> raw_post(
          "/api/#{project.dsn_id}/store/",
          ~s({"event_id":"#{@event_id}","message":"x"})
        )

      assert json_response(store, 200) == %{"id" => @event_id}

      csp =
        ~s({"csp-report":{"blocked-uri":"https://evil.example","effective-directive":"script-src"}})

      security =
        conn
        |> put_req_header("content-type", "application/csp-report")
        |> raw_post("/api/#{project.dsn_id}/security/?sentry_key=#{hex}", csp)

      assert response(security, 201)
      assert ~w(event security) == Enum.map(buffered(project), & &1.type)
    end

    test "a minidump upload", %{conn: conn, hex: hex, project: project} do
      path = Path.join(System.tmp_dir!(), "vigil-#{System.unique_integer([:positive])}.dmp")
      File.write!(path, "MDMP" <> :binary.copy(<<0>>, 64))

      upload = %Plug.Upload{
        path: path,
        filename: "crash.dmp",
        content_type: "application/octet-stream"
      }

      conn =
        post(conn, "/api/#{project.dsn_id}/minidump/?sentry_key=#{hex}", %{
          "upload_file_minidump" => upload,
          "sentry" => ~s({"release":"1.0"})
        })

      assert %{"id" => _} = json_response(conn, 200)

      assert [%{type: "minidump", item_headers: %{"sentry" => ~s({"release":"1.0"})}}] =
               buffered(project)
    end

    test "ordinary routes still work", %{conn: conn} do
      assert conn |> get("/api/0/") |> json_response(200)
      assert conn |> get("/") |> html_response(200)
    end
  end

  describe "the drain" do
    test "client reports become outcomes, events issues; transactions wait for their slice", %{
      conn: conn,
      hex: hex,
      path: path,
      project: project
    } do
      report = %{
        timestamp: "2026-12-01T10:15:00",
        discarded_events: [
          %{reason: "sample_rate", category: "transaction", quantity: 7},
          %{reason: "queue_overflow", category: "error", quantity: 2}
        ]
      }

      body =
        envelope([
          {"event", %{message: "x"}},
          {"transaction", %{transaction: "/", start_timestamp: 1.0, timestamp: 2.0}},
          {"client_report", report}
        ])

      assert conn
             |> put_req_header("x-sentry-auth", python_auth(hex))
             |> raw_post(path, body)
             |> json_response(200)

      assert :ok = perform_job(Drain, %{project_id: project.id})

      assert [%{type: "transaction", state: :deferred}] = buffered(project)
      assert [%{title: "x"}] = Vigil.Issues.list_issues(project.id)

      outcomes =
        Repo.all(from o in Outcome, where: o.project_id == ^project.id, order_by: o.reason)

      assert [
               %{
                 source: :client,
                 reason: "queue_overflow",
                 category: "error",
                 quantity: 2,
                 hour: ~U[2026-12-01 10:00:00Z]
               },
               %{source: :client, reason: "sample_rate", category: "transaction", quantity: 7}
             ] = outcomes
    end
  end

  defp brotli(data) do
    path = Path.join(System.tmp_dir!(), "vigil-br-#{System.unique_integer([:positive])}")
    File.write!(path, data)

    {out, 0} =
      System.cmd("python3", [
        "-c",
        "import brotli,sys; sys.stdout.buffer.write(brotli.compress(open(sys.argv[1],'rb').read()))",
        path
      ])

    File.rm!(path)
    out
  end
end