Giter Club home page Giter Club logo

graphql-query-whitelist's Introduction

graphql-query-whitelist

A simple GraphQL query whitelist toolkit for express.

It includes:

  • An express middleware that prevents queries not in the whitelist to be executed. It also allows to execute queries just passing a previously stored queryId instead of the full query.
  • A REST API to create/get/list/enable/disable/delete queries from the whitelist
  • A MemoryStore and RedisStore to store the queries
  • An utility class (QueryRepository) to perform CRUD operations programmatically
  • A binary (gql-whitelist) that whitelist all the files with .graphql extension in a specified directory (useful to automatically whitelist queries on build time)

A UI to manage the whitelisted queries is available here

Rationale

One of the security concerns for a typical GraphQL app is that it lacks of a security mechanism out of the box.

By default, anyone can query any field of your GraphQL app, and if your schema supports nested queries, a malicious attacker could make a query that consumes all the resources of the server.

Example:

query RecursiveQuery {
  friends {
    username

    friends {
      username

      friends {
        username

        friends { ... }
      }
    }
  }
}

This middleware avoids this type of queries checking if the incoming query is whitelisted or not.

(more info: source 1, source 2)

Installation

npm install --save graphql-query-whitelist graphql body-parser

In your app:

import express from 'express'
import bodyParser from 'body-parser'
import graphqlWhitelist, { MemoryStore } from 'graphql-query-whitelist'

const app = express()
const store = new MemoryStore()
// body-parser must be included before including the query whitelist middleware
app.use(bodyParser.json())
app.post('/graphql', graphqlWhitelist({ store }))

Before each request is processed by GraphQL, it will check if the inbound query is in the whitelist or not. If it's not in the whitelist, it will respond with a 401 status code.

Running queries only sending the queryId

Since the server has access to the query store, and the store has access to the full queries, it's possible to run a query just by sending the queryId.

E.g: POST /graphql?queryId=dSPDigYWUw2w9wTI9g0RrbakmsJiRFIvTUa59jnZsV4=

Storing and retrieving queries

There are 2 ways of storing and retrieving queries:

Rest API

Normally you would want to automate the process of storing queries at the build time.

This library includes a Rest API that you can mount in any express app to list, create, get, enable/disable and delete queries.

Example:

import { Api as whitelistAPI, RedisStore } from 'graphql-query-whitelist'
app.use('/whitelist', whitelistAPI(new RedisStore()))

It will mount these routes:

GET /whitelist/queries
GET /whitelist/queries/:id
POST /whitelist/queries
PUT /whitelist/queries/:id
DELETE /whitelist/queries/:id

Programmatically using the QueryRepository

Example:

import { QueryRepository, MemoryStore } from 'graphql-query-whitelist'

const store = new MemoryStore()
const repository = new QueryRepository(store)

const query = `
  query MyQuery {
    users {
      firstName
    }
  }
`

repository.put(query).then(console.log)

/*
 * Prints:
 * {
 *   id: 'dSPDigYWUw2w9wTI9g0RrbakmsJiRFIvTUa59jnZsV4=',
 *   query: 'query MyQuery {\n  users {\n    firstName\n  }\n}\n',
 *   operationName: 'MyQuery',
 *   enabled: true
 *  }
 */

The QueryRepository class exposes the following methods:

  • get(queryId)
  • put(query)
  • update(queryId, properties)
  • entries()
  • delete(queryId)

Stores

A store is the medium to list, get, store and delete queries.

It must implement the following methods:

get(key)

It returns a Promise that resolves to the value for that key

set(key, value)

Returns a Promise that is resolved after the value is saved in the store

entries()

Returns a Promise that resolves to an array of all the entries stored, having the following format: [[key1, val1], [key2, val2], ...]

delete(key)

Returns a Promise that is resolved after the element is deleted from the store

clear()

Returns a Promise that is resolved after all the elements are deleted from the store

Including in this library are 2 stores:

  • MemoryStore
  • RedisStore (needs to have ioredis installed)

The RedisStore receives the same constructor arguments as ioredis.

Middleware Options

store

This property is mandatory and must be a valid query store.

skipValidationFn

This property is optional and must be a function that receives the express request object and returns a boolean value. If a truthy value is returned, the whitelist check is skipped and the query is executed.

This option is very useful to skip the whitelist check for certain apps that are already sending dynamic queries that are impossible to add to the whitelist.

Example:

const skipValidationFn = (req) => req.get('X-App-Version') !== 'legacy-app-1.0'

app.post('/graphql', graphqlWhitelist({ store, skipValidationFn }))

validationErrorFn

This property is optional and must be a function that receives the express request object and will be called for every query that is prevented to be executed by this middleware.

Example:

import { verbose, warn } from 'utils/log'

const validationErrorFn = (req) => {
  warn(`Query '${req.operationName} (${req.queryId})' is not in the whitelist`)
  verbose(`Unauthorized query: ${req.body.query}`)
}

app.post('/graphql', graphqlWhitelist({ store, validationErrorFn }))

storeIntrospectionQueries

If this option is set to true, graphql-query-whitelist will add to the whitelist all GraphQL and GraphiQL introspection queries.

This option is disabled by default, but is needed if you are using GraphiQL and need to have the introspection queries whitelisted in order to have the autocompletion feature working.

Example:

app.post('/graphql', graphqlWhitelist({ store, storeIntrospectionQueries: true }))

dryRun

If this option is set to true, graphql-query-whitelist will validate the query against the whitelist and the validationErrorFn will be called, but the query will be executed as if the middleware is disabled.

This is useful if you are starting to whitelist the queries long after your GraphQL server was first launched, and you need to log all the queries that are not yet whitelisted.

Example:

app.post('/graphql', graphqlWhitelist({ store, dryRun: true }))

Whitelisting queries automatically

You may want to whitelist new queries everytime a query is added/changed in your project. This depends on graphql so make sure graphql is installed as well.

$ npm install -g graphql-query-whitelist graphql

$ gql-whitelist --endpoint http://your.graphql-endpoint.com/graphql /path/to/directory/containing/.graphql/files

Additionally, you can specify headers using the option --header

$ gql-whitelist --endpoint http://your.graphql-endpoint.com/graphql --header key=value --header key2=value2 /path/to/directory/containing/.graphql/files

License

Copyright (c) 2016 Restorando

MIT License

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

graphql-query-whitelist's People

Contributors

gabrieldarioros avatar gschammah avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

graphql-query-whitelist's Issues

gql-whitelist command crashes with no --header option

The gql-whitelist command specifies the --header option as non-required:

$ node_modules/.bin/gql-whitelist
Stores the queries residing in the specified directories.
Usage: gql-whitelist dir1 [dir2] [dir3]

Options:
  --endpoint  Base URL of query whitelist API           [required]
  --header    Header to send to the API: e.g key=value

Missing required arguments: endpoint

But when the command is run without it, it crashes:

$ node_modules/.bin/gql-whitelist --endpoint https://redo-graphql.restorando.com/whitelist
/Users/demian/IdeaProjects/emmett/node_modules/graphql-query-whitelist/dist/utils/gql-whitelist.js:44
    var _header$split = header.split(/=(.+)/),
                              ^

TypeError: Cannot read property 'split' of undefined
    at /Users/demian/IdeaProjects/emmett/node_modules/graphql-query-whitelist/dist/utils/gql-whitelist.js:44:31
    at Array.reduce (native)
    at parseHeaders (/Users/demian/IdeaProjects/emmett/node_modules/graphql-query-whitelist/dist/utils/gql-whitelist.js:43:18)
    at Object.<anonymous> (/Users/demian/IdeaProjects/emmett/node_modules/graphql-query-whitelist/dist/utils/gql-whitelist.js:58:12)
    at Module._compile (module.js:571:32)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:488:32)
    at tryModuleLoad (module.js:447:12)
    at Function.Module._load (module.js:439:3)
    at Module.runMain (module.js:605:10) 

I can try and have a stab at this, but what is the expected behavior? Should the --header option be required, or should it be ignored when the user doesn't pass any?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.