LatchQL NPM Package
An open-source, free-to-use, lightweight middleware package that adds additional layers of security to authenticate/authorize and provide permissions for users to have different levels of access to a database through graphQL queries.
Features
- Enables users to customize depth, cost, and rate limiting for all GraphQL queries sent to the server.
- Authorize and customize limiting for admin, users, and non-user levels.
- Throw errors before execution using depth and cost limiting algorithms.
- Utilize a caching method with Redis for limiting the rate of user requests to your GraphQL endpoint.
Why do I need GraphQL limiters?
Cost limiting
Cost limiting is essential for securing your GraphQL endpoint. By putting a limit on the cost of a single GraphQL transaction, you can prevent resource overload by blocking excessively expensive requests.
Depth limiting
Depth limiting is vital for protecting the server against malicious query attacks. This limit is commonly used for never ending query loops that expose the endpoint to potential attacks. By using the depth limiter, you can validate the depth of imcoming queries on a user's permission level and prevent execution if it exceeds the limit.
Rate limiting
Rate limiting is a strategy used for limiting network traffic and strain on the server. It's mainly used to prevent bot activity, brute force, DoS, DDoS, and web scraping attacks. By using the rate limiter, users are allocated a maximum of n operations for every fixed size 1-minute time window. Once the client has performed n operations, they must wait.
Getting started
In your terminal:
- Install LatchQL
npm install LatchQL
- Create a configuration file called
latch_config.json
in your project's root directory to assign and store your limiters.
Example:
{
"Admin": {
"depthLimit": "100",
"rateLimit": "100",
"costLimit": "100"
},
"Gary": {
"depthLimit": "10",
"rateLimit": "25",
"costLimit": "10"
},
"Non-User": {
"depthLimit": "0",
"rateLimit": "0",
"costLimit": "0"
}
}
- Create a .env file and save SECRET_KEY as an environment variable. *Note: if none is set, it will default to "GENERICKEY".
SECRET_KEY=MYSECRETKEY
- Install redis globally on your machine. For macOS users, use Homebrew package manager. If you've already installed redis, skip this step.
brew update
brew install redis
- Run redis server
redis-server
- If you get an error on step 5, you may be running an instance of redis somewhere. To stop it:
killall redis-server
and then repeat step 5.
Implementation
Sample Usage
import cors from "cors";
import express from "express";
import { readFile } from "fs/promises";
import { resolvers } from "./test-db/resolvers.js";
import { LatchQL, jwtController } from "latchql";
const app = express();
const port = 8080;
app.use(cors());
app.use(express.json());
function authSet(req, res, next) {
res.locals.authLevel = "user";
res.locals.userName = "Ray";
next();
}
app.post("/login", authSet, jwtController.setJwt, (req, res) => {
return res.status(200).send("YES RESPONSE");
});
const typeDefs = await readFile("./schema.graphql", "utf-8");
let latch = new LatchQL(typeDefs, resolvers);
app.listen(port, () => {
console.log(`server started at http://localhost:${port}`);
console.log(`GraphQL endpoint: http://localhost:${port}/graphql`);
});
latch.startLatch(app, port);
In your server file...
Import LatchQL and jwtController from latchql
import { LatchQL, jwtController } from "latchql";
Implment jwtController.setJwt middleware in your authentication step. You will need to pass the username and the selected authorization level of a given user to the jwtController.setJwt middleware via res.locals.username and res.locals.authLevel
app.post("/login", authSet, jwtController.setJwt, (req, res) => {
return res.status(200).send("YES RESPONSE");
});
Create a new instance of LatchQL passing in your schema and resolvers
let latch = new LatchQL(typeDefs, resolvers);
Lastly, invoke startLatch passing in your express server and port to access endpoints
latch.startLatch(app, port);
Don't have a server?
Included in the NPM-MODULE directory is a dummy folder which includes an already built-out mock express server which you can use to test the LatchQL authentication and middleware package. Clone the repo, navigate to the dummy directory, install dependencies and run the command npm start
to spin up the server.
LatchQL Playground
The LatchQL Playground is an optional, built-in playground for testing your GraphQL endpoint.
Features
- Preview cost and depth of your current query before execution.
- Displays important metrics for tracking response time and CPU usage.
- Save variables to reference in the body of your GraphQL queries.
Getting Started
-
Install LatchQL npm package.
-
Clone the playground.
-
Install its dependencies:
npm install --force
-
Build the playground:
npm run dev
How to use LatchQL Playground
-
Select the right permission level
-
Preview Cost/Depth of the current query
-
Depth Limiter
-
Cost Limiter
-
Rate Limiter
Authors
Alex McPhail: GitHub | LinkedIn
Celine Leung: GitHub | LinkedIn
Hannah Bernstein: GitHub | LinkedIn
Johnjered Tolentino: GitHub | LinkedIn
Raymond Kim: GitHub | LinkedIn
How to Contribute
If you would like to contribute in improving the functionality of LatchQL, please submit your ideas and/or bug fixes to our team by forking the repo and submitting your changes via a pull request.
Iteration Opportunities
- Storing history GraphQL queries
- Editing user's permission level on GUI
- Calculating cost and depth of query mutations
To Learn More
Visit the LatchQL Website
Read the LatchQL Medium article
License
Distributed under the MIT License. See LICENSE for more information.