All Projects β†’ exAspArk β†’ Graphql Guard

exAspArk / Graphql Guard

Licence: mit
Simple authorization gem for GraphQL πŸ”’

Programming Languages

ruby
36898 projects - #4 most used programming language

Projects that are alternatives of or similar to Graphql Guard

Batch Loader
⚑️ Powerful tool for avoiding N+1 DB or HTTP queries
Stars: ✭ 812 (+87.1%)
Mutual labels:  graphql, gem
Graphql devise
GraphQL interface on top devise_token_auth
Stars: ✭ 100 (-76.96%)
Mutual labels:  graphql, gem
Warden Github Rails
Use GitHub as authorization and more. Use organizations and teams as means of authorization by simply wrapping your rails routes in a block. Also useful to get a user's details through OAuth.
Stars: ✭ 100 (-76.96%)
Mutual labels:  gem, authorization
Graphql Pundit
Pundit authorization helpers for the GraphQL Ruby gem
Stars: ✭ 109 (-74.88%)
Mutual labels:  graphql, authorization
Graphql Directive Auth
GraphQL directive for handling auth
Stars: ✭ 120 (-72.35%)
Mutual labels:  graphql, authorization
graphql authorize
Authorization helpers for ruby-graphql fields
Stars: ✭ 23 (-94.7%)
Mutual labels:  gem, authorization
Got Auth Service
A professional role-based-authorization(also supports resource and group) service with restful and graphql api for enterprise applications.
Stars: ✭ 12 (-97.24%)
Mutual labels:  graphql, authorization
Action policy Graphql
Action Policy integration for GraphQL
Stars: ✭ 110 (-74.65%)
Mutual labels:  graphql, authorization
Searchobjectgraphql
GraphQL plugin for SearchObject gem
Stars: ✭ 118 (-72.81%)
Mutual labels:  graphql, gem
Authorization
A toolset for authorizing access to graph types for GraphQL .NET.
Stars: ✭ 127 (-70.74%)
Mutual labels:  graphql, authorization
Express Graphql Mongodb Boilerplate
A boilerplate for Node.js apps / GraphQL-API / Authentication from scratch - express, graphql - (graphql compose), mongodb (mongoose).
Stars: ✭ 288 (-33.64%)
Mutual labels:  graphql, authorization
Graphql Language Service
An interface for building GraphQL language services for IDEs
Stars: ✭ 427 (-1.61%)
Mutual labels:  graphql
Graphql Up
Get a ready-to-use GraphQL API for your schema
Stars: ✭ 415 (-4.38%)
Mutual labels:  graphql
Typegql
Create GraphQL schema with TypeScript classes.
Stars: ✭ 415 (-4.38%)
Mutual labels:  graphql
Apollo Link Firebase
πŸ”₯ πŸ”— apollo-link-firebase provides you a simple way to use Firebase with graphQL.
Stars: ✭ 415 (-4.38%)
Mutual labels:  graphql
Fraql
GraphQL fragments made simple ⚑️
Stars: ✭ 433 (-0.23%)
Mutual labels:  graphql
Graphql Query Complexity
GraphQL query complexity analysis and validation for graphql-js
Stars: ✭ 424 (-2.3%)
Mutual labels:  graphql
Next Apollo Example
Next & Apollo Example
Stars: ✭ 413 (-4.84%)
Mutual labels:  graphql
Django Rest Framework Passwordless
Passwordless Auth for Django REST Framework
Stars: ✭ 412 (-5.07%)
Mutual labels:  authorization
Persistgraphql
A build tool for GraphQL projects.
Stars: ✭ 409 (-5.76%)
Mutual labels:  graphql

graphql-guard

Build Status Coverage Status Code Climate Downloads Latest Version

This gem provides a field-level authorization for graphql-ruby.

Contents

Usage

Define a GraphQL schema:

# Define a type
class PostType < GraphQL::Schema::Object
  field :id, ID, null: false
  field :title, String, null: true
end

# Define a query
class QueryType < GraphQL::Schema::Object
  field :posts, [PostType], null: false do
    argument :user_id, ID, required: true
  end

  def posts(user_id:)
    Post.where(user_id: user_id)
  end
end

# Define a schema
class Schema < GraphQL::Schema
  use GraphQL::Execution::Interpreter
  use GraphQL::Analysis::AST
  query QueryType
end

# Execute query
Schema.execute(query, variables: { userId: 1 }, context: { current_user: current_user })

Inline policies

Add GraphQL::Guard to your schema:

class Schema < GraphQL::Schema
  use GraphQL::Execution::Interpreter
  use GraphQL::Analysis::AST
  query QueryType
  use GraphQL::Guard.new
end

Now you can define guard for a field, which will check permissions before resolving the field:

class QueryType < GraphQL::Schema::Object
  field :posts, [PostType], null: false do
    argument :user_id, ID, required: true
    guard ->(obj, args, ctx) { args[:user_id] == ctx[:current_user].id }
  end
  ...
end

You can also define guard, which will be executed for every * field in the type:

class PostType < GraphQL::Schema::Object
  guard ->(obj, args, ctx) { ctx[:current_user].admin? }
  ...
end

If guard block returns nil or false, then it'll raise a GraphQL::Guard::NotAuthorizedError error.

Policy object

Alternatively, it's possible to extract and describe all policies by using PORO (Plain Old Ruby Object), which should implement a guard method. For example:

class GraphqlPolicy
  RULES = {
    QueryType => {
      posts: ->(obj, args, ctx) { args[:user_id] == ctx[:current_user].id }
    },
    PostType => {
      '*': ->(obj, args, ctx) { ctx[:current_user].admin? }
    }
  }

  def self.guard(type, field)
    RULES.dig(type, field)
  end
end

Pass this object to GraphQL::Guard:

class Schema < GraphQL::Schema
  use GraphQL::Execution::Interpreter
  use GraphQL::Analysis::AST
  query QueryType
  use GraphQL::Guard.new(policy_object: GraphqlPolicy)
end

When using a policy object, you may want to allow introspection queries to skip authorization. A simple way to avoid having to whitelist every introspection type in the RULES hash of your policy object is to check the type parameter in the guard method:

def self.guard(type, field)
  type.introspection? ? ->(_obj, _args, _ctx) { true } : RULES.dig(type, field) # or "false" to restrict an access
end

Priority order

GraphQL::Guard will use the policy in the following order of priority:

  1. Inline policy on the field.
  2. Policy from the policy object on the field.
  3. Inline policy on the type.
  4. Policy from the policy object on the type.
class GraphqlPolicy
  RULES = {
    PostType => {
      '*': ->(obj, args, ctx) { ctx[:current_user].admin? },                                # <=== 4
      title: ->(obj, args, ctx) { ctx[:current_user].admin? }                               # <=== 2
    }
  }

  def self.guard(type, field)
    RULES.dig(type, field)
  end
end

class PostType < GraphQL::Schema::Object
  guard ->(obj, args, ctx) { ctx[:current_user].admin? }                                    # <=== 3
  field :title, String, null: true, guard: ->(obj, args, ctx) { ctx[:current_user].admin? } # <=== 1
end

class Schema < GraphQL::Schema
  use GraphQL::Execution::Interpreter
  use GraphQL::Analysis::AST
  query QueryType
  use GraphQL::Guard.new(policy_object: GraphqlPolicy)
end

Integration

You can simply reuse your existing policies if you really want. You don't need any monkey patches or magic for it ;)

CanCanCan

# Define an ability
class Ability
  include CanCan::Ability

  def initialize(user)
    user ||= User.new
    if user.admin?
      can :manage, :all
    else
      can :read, Post, author_id: user.id
    end
  end
end

# Use the ability in your guard
class PostType < GraphQL::Schema::Object
  guard ->(post, args, ctx) { ctx[:current_ability].can?(:read, post) }
  ...
end

# Pass the ability
Schema.execute(query, context: { current_ability: Ability.new(current_user) })

Pundit

# Define a policy
class PostPolicy < ApplicationPolicy
  def show?
    user.admin? || record.author_id == user.id
  end
end

# Use the ability in your guard
class PostType < GraphQL::Schema::Object
  guard ->(post, args, ctx) { PostPolicy.new(ctx[:current_user], post).show? }
  ...
end

# Pass current_user
Schema.execute(query, context: { current_user: current_user })

Error handling

By default GraphQL::Guard raises a GraphQL::Guard::NotAuthorizedError exception if access to the field is not authorized. You can change this behavior, by passing custom not_authorized lambda. For example:

class SchemaWithErrors < GraphQL::Schema
  use GraphQL::Execution::Interpreter
  use GraphQL::Analysis::AST
  query QueryType
  use GraphQL::Guard.new(
    # By default it raises an error
    # not_authorized: ->(type, field) do
    #   raise GraphQL::Guard::NotAuthorizedError.new("#{type}.#{field}")
    # end

    # Returns an error in the response
    not_authorized: ->(type, field) do
      GraphQL::ExecutionError.new("Not authorized to access #{type}.#{field}")
    end
  )
end

In this case executing a query will continue, but return nil for not authorized field and also an array of errors:

SchemaWithErrors.execute("query { posts(user_id: 1) { id title } }")
# => {
#   "data" => nil,
#   "errors" => [{
#     "messages" => "Not authorized to access Query.posts",
#     "locations": { "line" => 1, "column" => 9 },
#     "path" => ["posts"]
#   }]
# }

In more advanced cases, you may want not to return errors only for some unauthorized fields. Simply return nil if user is not authorized to access the field. You can achieve it, for example, by placing the logic into your PolicyObject:

class GraphqlPolicy
  RULES = {
    PostType => {
      '*': {
        guard: ->(obj, args, ctx) { ... },
        not_authorized: ->(type, field) { GraphQL::ExecutionError.new("Not authorized to access #{type}.#{field}") }
      }
      title: {
        guard: ->(obj, args, ctx) { ... },
        not_authorized: ->(type, field) { nil } # simply return nil if not authorized, no errors
      }
    }
  }

  def self.guard(type, field)
    RULES.dig(type, field, :guard)
  end

  def self.not_authorized_handler(type, field)
    RULES.dig(type, field, :not_authorized) || RULES.dig(type, :'*', :not_authorized)
  end
end

class Schema < GraphQL::Schema
  use GraphQL::Execution::Interpreter
  use GraphQL::Analysis::AST
  query QueryType
  mutation MutationType

  use GraphQL::Guard.new(
    policy_object: GraphqlPolicy,
    not_authorized: ->(type, field) {
      handler = GraphqlPolicy.not_authorized_handler(type, field)
      handler.call(type, field)
    }
  )
end

Schema masking

It's possible to hide fields from being introspectable and accessible based on the context. For example:

class PostType < GraphQL::Schema::Object
  field :id, ID, null: false
  field :title, String, null: true do
    # The field "title" is accessible only for beta testers
    mask ->(ctx) { ctx[:current_user].beta_tester? }
  end
end

Installation

Add this line to your application's Gemfile:

gem 'graphql-guard'

And then execute:

$ bundle

Or install it yourself as:

$ gem install graphql-guard

Testing

It's possible to test fields with guard in isolation:

# Your type
class QueryType < GraphQL::Schema::Object
  field :posts, [PostType], null: false, guard ->(obj, args, ctx) { ... }
end

# Your test
require "graphql/guard/testing"

posts = QueryType.field_with_guard('posts')
result = posts.guard(obj, args, ctx)
expect(result).to eq(true)

If you would like to test your fields with policy objects:

# Your type
class QueryType < GraphQL::Schema::Object
  field :posts, [PostType], null: false
end

# Your policy object
class GraphqlPolicy
  def self.guard(type, field)
    ->(obj, args, ctx) { ... }
  end
end

# Your test
require "graphql/guard/testing"

posts = QueryType.field_with_guard('posts', GraphqlPolicy)
result = posts.guard(obj, args, ctx)
expect(result).to eq(true)

Development

After checking out the repo, run bin/setup to install dependencies. Then, run rake spec to run the tests. You can also run bin/console for an interactive prompt that will allow you to experiment.

To install this gem onto your local machine, run bundle exec rake install. To release a new version, update the version number in version.rb, and then run bundle exec rake release, which will create a git tag for the version, push git commits and tags, and push the .gem file to rubygems.org.

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/exAspArk/graphql-guard. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the Contributor Covenant code of conduct.

License

The gem is available as open source under the terms of the MIT License.

Code of Conduct

Everyone interacting in the Graphql::Guard project’s codebases, issue trackers, chat rooms and mailing lists is expected to follow the code of conduct.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].