10.2 KiB · text History 573fef1
defmodule VigilWeb.IngestPlug do
  @moduledoc """
  The ingest edge: `POST /api/<dsn_id>/envelope/` (what current SDKs use),
  `/store/` (legacy SDKs), `/security/` (browsers' CSP `report-uri`) and
  `/minidump/`, with or without the trailing slash. Everything else passes
  through to the router.

  It sits in the Endpoint ahead of `Plug.Parsers` and the session: ingest
  bodies are read raw, and ingest never touches cookies.

  In order (ROADMAP.md, "Wire contract"):

    1. CORS: `OPTIONS` preflight answered; every response carries
       `*` origin, the Sentry headers allowed, and `Retry-After` and
       `X-Sentry-Rate-Limits` exposed (GlitchTip exposes neither, so
       browser SDKs can't see their backoff).
    2. The key (`Vigil.Ingest.Auth`), checked (`Vigil.Ingest.Keys`); for an
       envelope with no key elsewhere, the one in its `dsn` header.
    3. The body: read raw up to #{20} MiB, decoded (`Vigil.Ingest.Codec`)
       up to #{100} MiB; over either, `413`.
    4. Parsed (`Vigil.Ingest.Envelope`), rate-limited by key, buffered
       (`Vigil.Ingest.accept/3`).
    5. `200 {"id": "<event id>"}`: a JSON object, always, as sentry-elixir
       retries anything else; `{}` when there is no id.

  Refusals: `403 {"detail": "Denied"}` for a bad key; `429` with
  `Retry-After` and `X-Sentry-Rate-Limits` (integers: sentry-python
  drops float values) when the key's limit is spent or the organization
  isn't accepting events; `400` for an empty body, a bad envelope header,
  or a body that doesn't decode.
  """
  @behaviour Plug

  import Plug.Conn

  alias Vigil.Ingest
  alias Vigil.Ingest.{Auth, Codec, Envelope, Keys, RateLimit}

  @endpoints ~w(envelope store security minidump)
  @max_raw 20 * 1024 * 1024
  @max_decoded 100 * 1024 * 1024
  @not_accepting_retry 600

  @allow_headers "x-sentry-auth, x-requested-with, content-type, content-encoding, origin, accept, authorization, sentry-trace, baggage"
  @expose_headers "x-sentry-error, x-sentry-rate-limits, retry-after"

  @impl Plug
  def init(opts), do: opts

  @impl Plug
  def call(%Plug.Conn{path_info: ["api", id, endpoint]} = conn, _opts)
      when endpoint in @endpoints do
    case Integer.parse(id) do
      {dsn_id, ""} ->
        conn |> cors() |> handle(conn.method, dsn_id, endpoint) |> count(endpoint) |> halt()

      _ ->
        conn
    end
  end

  def call(conn, _opts), do: conn

  defp handle(conn, "OPTIONS", _dsn_id, _endpoint) do
    conn
    |> put_resp_header("access-control-allow-methods", "POST, OPTIONS")
    |> put_resp_header("access-control-max-age", "86400")
    |> send_resp(200, "")
  end

  defp handle(conn, "POST", dsn_id, "minidump"), do: minidump(conn, dsn_id)

  defp handle(conn, "POST", dsn_id, endpoint) do
    key = Auth.key_from_request(fetch_query_params(conn).query_params, conn.req_headers)

    # A key in the query or headers is checked before the body is read, so
    # a bad one costs no decompression; only an envelope with neither is
    # read first, for the key in its `dsn` header.
    with {:ok, early} <- early_auth(key, dsn_id),
         {:ok, body, conn} <- read_raw(conn),
         {:ok, body} <- decode(body, conn),
         {:ok, envelope} <- to_envelope(endpoint, body),
         {:ok, target} <- late_auth(early, envelope, dsn_id),
         :ok <- rate_limit(target, envelope) do
      Ingest.accept(target, envelope, meta(conn))
      respond_accepted(conn, endpoint, envelope)
    else
      {:error, reason, conn} -> refuse(conn, reason)
      {:error, reason} -> refuse(conn, reason)
    end
  end

  defp handle(conn, _method, _dsn_id, _endpoint),
    do: conn |> outcome(:method_not_allowed) |> json(405, %{detail: "Method not allowed"})

  ## Steps

  defp read_raw(conn) do
    case read_body(conn, length: @max_raw, read_length: 1_000_000) do
      {:ok, body, conn} -> {:ok, body, conn}
      {:more, _partial, conn} -> {:error, :too_large, conn}
      {:error, _} -> {:error, :invalid_body}
    end
  end

  defp decode(body, conn) do
    encoding = conn |> get_req_header("content-encoding") |> List.first()

    case Codec.decode(body, encoding, @max_decoded) do
      {:ok, body} -> {:ok, body}
      {:error, :too_large} -> {:error, :too_large}
      {:error, :invalid} -> {:error, :invalid_encoding}
    end
  end

  # Every endpoint becomes an envelope, so the rest is one path.
  defp to_envelope("envelope", body), do: Envelope.parse(body)

  defp to_envelope("store", body) do
    case Jason.decode(body) do
      {:ok, %{} = event} ->
        id = Envelope.normalize_event_id(event["event_id"]) || new_event_id()
        item = %Envelope.Item{type: "event", headers: %{"event_id" => id}, payload: body}
        {:ok, %{headers: %{"event_id" => id}, items: [item]}}

      _ ->
        {:error, :invalid_body}
    end
  end

  defp to_envelope("security", body) do
    case String.trim(body) do
      "" ->
        {:error, :empty}

      body ->
        {:ok,
         %{headers: %{}, items: [%Envelope.Item{type: "security", headers: %{}, payload: body}]}}
    end
  end

  defp early_auth(nil, _dsn_id), do: {:ok, nil}
  defp early_auth(key, dsn_id), do: lookup(key, dsn_id)

  defp late_auth(%Vigil.Ingest.Target{} = target, _envelope, _dsn_id), do: {:ok, target}

  defp late_auth(nil, envelope, dsn_id),
    do: lookup(Auth.key_from_dsn(envelope.headers["dsn"], dsn_id), dsn_id)

  defp lookup(nil, _dsn_id), do: {:error, :denied}

  defp lookup(key, dsn_id) do
    case Keys.lookup(dsn_id, key) do
      {:ok, target} -> {:ok, target}
      {:error, :not_accepting} -> {:error, :not_accepting}
      _ -> {:error, :denied}
    end
  end

  defp rate_limit(target, envelope) do
    if Enum.any?(envelope.items, &Ingest.rate_limited?/1) do
      case RateLimit.hit(target) do
        :ok ->
          :ok

        {:limited, seconds} ->
          Ingest.refused(target, "error", "key_quota")
          {:error, {:rate_limited, seconds}}
      end
    else
      :ok
    end
  end

  defp meta(conn) do
    %{
      client_ip: conn.remote_ip |> :inet.ntoa() |> to_string(),
      user_agent: conn |> get_req_header("user-agent") |> List.first()
    }
  end

  ## Minidumps

  # multipart: `upload_file_minidump` (must start "MDMP") and, optionally,
  # a `sentry` field of event JSON (or `sentry[key]` fields, which Plug
  # nests into a map). Kept as a `minidump` item for
  # Vigil.Minidumps.Processor (ROADMAP.md, slice 12).
  defp minidump(conn, dsn_id) do
    key = Auth.key_from_request(fetch_query_params(conn).query_params, conn.req_headers)

    with {:ok, target} <- lookup(key, dsn_id),
         {:ok, conn} <- parse_multipart(conn),
         %Plug.Upload{path: path} = upload <-
           conn.body_params["upload_file_minidump"] || {:error, :invalid_body},
         {:ok, <<"MDMP", _::binary>> = dump} <- File.read(path) do
      id = new_event_id()

      sentry =
        case conn.body_params["sentry"] do
          json when is_binary(json) -> json
          %{} = fields -> Jason.encode!(fields)
          _ -> nil
        end

      headers = %{"event_id" => id, "sentry" => sentry, "filename" => upload.filename}
      item = %Envelope.Item{type: "minidump", headers: headers, payload: dump}
      Ingest.accept(target, %{headers: %{"event_id" => id}, items: [item]}, meta(conn))
      conn |> outcome(:accepted) |> json(200, %{id: id})
    else
      {:error, reason} when is_atom(reason) -> refuse(conn, reason)
      _ -> refuse(conn, :invalid_body)
    end
  end

  defp parse_multipart(conn) do
    opts = Plug.Parsers.init(parsers: [:multipart], length: @max_raw, pass: ["*/*"])
    {:ok, Plug.Parsers.call(conn, opts)}
  rescue
    Plug.Parsers.RequestTooLargeError -> {:error, :too_large}
    _ -> {:error, :invalid_body}
  end

  ## Responses

  defp respond_accepted(conn, "security", _envelope),
    do: conn |> outcome(:accepted) |> send_resp(201, "")

  defp respond_accepted(conn, _endpoint, envelope) do
    conn = outcome(conn, :accepted)

    case Envelope.event_id(envelope) do
      nil -> json(conn, 200, %{})
      id -> json(conn, 200, %{id: id})
    end
  end

  # Every refusal is counted under one of a few outcomes
  # (Vigil.PromEx.Plugins.Ingest), whatever its detail.
  defp refuse(conn, reason), do: conn |> outcome(refusal_outcome(reason)) |> refusal(reason)

  defp refusal(conn, :denied), do: json(conn, 403, %{detail: "Denied"})
  defp refusal(conn, :too_large), do: json(conn, 413, %{detail: "Payload too large"})
  defp refusal(conn, :empty), do: json(conn, 400, %{detail: "Empty request body"})
  defp refusal(conn, :invalid_header), do: json(conn, 400, %{detail: "Invalid envelope header"})

  defp refusal(conn, :invalid_encoding),
    do: json(conn, 400, %{detail: "Invalid compressed request body"})

  defp refusal(conn, :invalid_body), do: json(conn, 400, %{detail: "Invalid request body"})

  defp refusal(conn, :not_accepting),
    do: too_many(conn, @not_accepting_retry, "#{@not_accepting_retry}::organization:disabled")

  defp refusal(conn, {:rate_limited, seconds}),
    do: too_many(conn, seconds, "#{seconds}::key:key_quota")

  defp refusal_outcome({:rate_limited, _}), do: :rate_limited
  defp refusal_outcome(:not_accepting), do: :not_accepting
  defp refusal_outcome(:denied), do: :denied
  defp refusal_outcome(:too_large), do: :too_large
  defp refusal_outcome(_invalid), do: :invalid

  defp outcome(conn, outcome), do: put_private(conn, :vigil_ingest_outcome, outcome)

  # One `[:vigil, :ingest, :request]` per answered request; a CORS preflight
  # has no outcome and isn't counted.
  defp count(conn, endpoint) do
    if outcome = conn.private[:vigil_ingest_outcome] do
      :telemetry.execute([:vigil, :ingest, :request], %{count: 1}, %{
        endpoint: endpoint,
        outcome: outcome
      })
    end

    conn
  end

  defp too_many(conn, seconds, limits) do
    conn
    |> put_resp_header("retry-after", Integer.to_string(seconds))
    |> put_resp_header("x-sentry-rate-limits", limits)
    |> json(429, %{detail: "Too many requests"})
  end

  defp cors(conn) do
    conn
    |> put_resp_header("access-control-allow-origin", "*")
    |> put_resp_header("access-control-allow-headers", @allow_headers)
    |> put_resp_header("access-control-expose-headers", @expose_headers)
  end

  defp json(conn, status, body) do
    conn
    |> put_resp_content_type("application/json")
    |> send_resp(status, Jason.encode!(body))
  end

  defp new_event_id, do: Vigil.Schema.uuid7() |> String.replace("-", "")
end