All Projects → restorando → graphql-query-whitelist

restorando / graphql-query-whitelist

Licence: MIT license
GraphQL query whitelisting middleware

Programming Languages

javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to graphql-query-whitelist

Graphql To Mongodb
Allows for generic run-time generation of filter types for existing graphql types and parsing client requests to mongodb find queries
Stars: ✭ 261 (+1435.29%)
Mutual labels:  graphql-server, graphql-js
Graphql Cost Analysis
A Graphql query cost analyzer.
Stars: ✭ 527 (+3000%)
Mutual labels:  graphql-server, graphql-js
relay-compiler-plus
Custom relay compiler which supports persisted queries
Stars: ✭ 68 (+300%)
Mutual labels:  graphql-server, graphql-js
graphql-spotify
GraphQL Schema And Resolvers For Spotify Web API
Stars: ✭ 55 (+223.53%)
Mutual labels:  graphql-server, graphql-js
Grial
A Node.js framework for creating GraphQL API servers easily and without a lot of boilerplate.
Stars: ✭ 194 (+1041.18%)
Mutual labels:  graphql-server, graphql-js
student-api-graphql
A GraphQL Wrapper for Ellucian's Banner Student REST API
Stars: ✭ 19 (+11.76%)
Mutual labels:  graphql-server, graphql-js
Typegql
Create GraphQL schema with TypeScript classes.
Stars: ✭ 415 (+2341.18%)
Mutual labels:  graphql-server, graphql-js
Graphql Log
Add logging to your GraphQL resolvers so you know what's going on in your app.
Stars: ✭ 94 (+452.94%)
Mutual labels:  graphql-server, graphql-js
Graphql2rest
GraphQL to REST converter: automatically generate a RESTful API from your existing GraphQL API
Stars: ✭ 181 (+964.71%)
Mutual labels:  graphql-server, graphql-js
Hangzhou Graphql Party
杭州 GraphQLParty 往期记录(slide,照片,预告,视频等)
Stars: ✭ 142 (+735.29%)
Mutual labels:  graphql-server, graphql-js
graphql-express-nodejs
A Simple GraphQL Server implementation using Express and Node. See post here: https://t.co/Cm6GitZaBL
Stars: ✭ 24 (+41.18%)
Mutual labels:  graphql-server, graphql-js
graphql-directive-rest
GraphQL directive for easy integration with REST API
Stars: ✭ 39 (+129.41%)
Mutual labels:  graphql-server, graphql-js
ugql
🚀GraphQL.js over HTTP with uWebSockets.js
Stars: ✭ 27 (+58.82%)
Mutual labels:  graphql-server, graphql-js
graphql-server
(out of date) A command to add a GraphQL server to your Svelte project
Stars: ✭ 31 (+82.35%)
Mutual labels:  graphql-server
graphql-ufc-api
GraphQL server for UFC's public API
Stars: ✭ 26 (+52.94%)
Mutual labels:  graphql-server
kanji
A strongly typed GraphQL API framework
Stars: ✭ 12 (-29.41%)
Mutual labels:  graphql-server
nim-graphql
Nim implementation of GraphQL with sugar and steroids
Stars: ✭ 47 (+176.47%)
Mutual labels:  graphql-server
graphql-rest-api-demo
A demo of what an equivalent REST API and GraphQL API look like.
Stars: ✭ 51 (+200%)
Mutual labels:  graphql-server
graphql-server-typescript
GraphQL + MongoDB express server with JWT authorization (in Typescript!)
Stars: ✭ 48 (+182.35%)
Mutual labels:  graphql-server
Workshop-GraphQL
A GraphQL Server made for the workshop
Stars: ✭ 22 (+29.41%)
Mutual labels:  graphql-server

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.

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].