DEV Community

Erik Guzman
Erik Guzman

Posted on • Edited on

3 2

TIL: Disabling introspection in prod for Absinthe

Recently I had the opportunity to study security best practices for GraphQL. One security recommendation that stood out as low-hanging fruit was disabling GraphQL introspecting for your API in production. GraphQL libraries I have used for Ruby and JavaScript made doing this very easy, so I was expecting the same thing with the Absinthe library in Elixir. It then surprised me that disabled introspection in Absinthe was documented, and every more confusing to figure out how.

Luckily after some web searching, I stumbled upon a Gist made by the community with middleware to disable introspection. So for my own implementation, I decided to make it simpler and disable introspection entirely if you are not in the development environment. Check it out.

defmodule MyAppWeb.Schema.Middleware.AuthorizedIntrospection do
  @moduledoc """
  Disable schema introspection outside of development
  """
  @behaviour Absinthe.Plugin

  @impl Absinthe.Plugin
  def before_resolution(exec) do
    if Enum.find(exec.result.emitter.selections, fn %{name: field_name} ->
         Macro.underscore(field_name) == "__schema" && Mix.env() != :dev
       end) do
      %{
        exec
        | validation_errors: [
            %Absinthe.Phase.Error{message: "Unauthorized", phase: __MODULE__}
          ]
      }
    else
      exec
    end
  end

  @impl Absinthe.Plugin
  def after_resolution(exec), do: exec

  @impl Absinthe.Plugin
  def pipeline(pipeline, _exec), do: pipeline
end
Enter fullscreen mode Exit fullscreen mode

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (1)

Collapse
 
maartenvanvliet profile image
Maarten van Vliet

Note that Mix.env is not available in releases.

See hexdocs.pm/mix/Mix.html#env/0

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay