Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(nestjs): Lookup request from GraphQL context in ArcjetGuard #1857

Merged
merged 5 commits into from
Oct 4, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions .github/dependabot.yml
Original file line number Diff line number Diff line change
Expand Up @@ -636,6 +636,34 @@ updates:
- dependency-name: "@typescript-eslint/eslint-plugin"
versions: [">=8"]

- package-ecosystem: npm
directory: /examples/nestjs-graphql
schedule:
# Our dependencies should be checked daily
interval: daily
assignees:
- blaine-arcjet
reviewers:
- blaine-arcjet
commit-message:
prefix: deps(example)
prefix-development: deps(example)
groups:
dependencies:
patterns:
- "*"
ignore:
# NestJS uses Express 4
- dependency-name: "@types/express"
versions: [">=5"]
# TODO(#539): Upgrade to eslint 9
- dependency-name: eslint
versions: [">=9"]
- dependency-name: "@typescript-eslint/parser"
versions: [">=8"]
- dependency-name: "@typescript-eslint/eslint-plugin"
versions: [">=8"]

- package-ecosystem: npm
directory: /examples/nestjs-launchdarkly
schedule:
Expand Down
40 changes: 40 additions & 0 deletions .github/workflows/reusable-examples.yml
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,46 @@ jobs:
working-directory: examples/nestjs-fastify
run: npm run build

nestjs-graphql:
name: NestJS + GraphQL
runs-on: ubuntu-latest
permissions:
contents: read
steps:
# Environment security
- name: Harden Runner
uses: step-security/harden-runner@91182cccc01eb5e619899d80e4e971d6181294a7 # v2.10.1
with:
disable-sudo: true
egress-policy: block
allowed-endpoints: >
github.com:443
registry.npmjs.org:443
# Checkout
# Most toolchains require checkout first
- name: Checkout
uses: actions/checkout@v4

# Language toolchains
- name: Install Node
uses: actions/[email protected]
with:
node-version: 20

# Workflow

- name: Install dependencies
run: npm ci

- name: Install example dependencies
working-directory: examples/nestjs-graphql
run: npm ci

- name: Build
working-directory: examples/nestjs-graphql
run: npm run build

nestjs-launchdarkly:
name: NestJS + LaunchDarkly
runs-on: ubuntu-latest
Expand Down
45 changes: 44 additions & 1 deletion arcjet-nest/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import { Inject, SetMetadata } from "@nestjs/common";
import type {
CanActivate,
ConfigurableModuleAsyncOptions,
ContextType,
DynamicModule,
ExecutionContext,
FactoryProvider,
Expand Down Expand Up @@ -376,6 +377,43 @@ export const ARCJET = Symbol("ARCJET");
const ARCJET_OPTIONS = Symbol("ARCJET_OPTIONS");
const ARCJET_WITH_RULES = Symbol("ARCJET_WITH_RULES");

type GqlContextType = "graphql" | ContextType;

function requestFromContext(context: ExecutionContext) {
const contextType = context.getType<GqlContextType>();
switch (contextType) {
case "graphql": {
// The `req` property should exist on the context at position 2
// https://github.com/nestjs/graphql/blob/8d19548dd8cb8c6d6003552673a6646603d2e22f/packages/graphql/lib/services/gql-execution-context.ts#L37
const ctx = context.getArgByIndex<{ req?: ArcjetNestRequest }>(2);
if (typeof ctx === "object" && ctx !== null && "req" in ctx) {
return ctx.req;
}

// If it isn't there for some reason, we just return undefined
return;
}
case "http": {
// The request object is at position 0
// https://github.com/nestjs/nest/blob/9825529f405fa6064eb98d8ecb2a5d3d5f1e41f9/packages/core/helpers/execution-context-host.ts#L52
return context.getArgByIndex<ArcjetNestRequest>(0);
}
case "ws": {
// TODO: Figure out if we can support "ws" context types
return;
}
case "rpc": {
// TODO: Figure out if we can support "rpc" context types
return;
}
default: {
// Avoiding the _exhaustive check to avoid some TypeScript errors in with
// different compiler options
return;
}
}
}

let ArcjetGuard = class ArcjetGuard implements CanActivate {
aj: ArcjetNest<WithoutCustomProps>;

Expand All @@ -395,7 +433,12 @@ let ArcjetGuard = class ArcjetGuard implements CanActivate {
aj = rules.reduce((aj, rule) => aj.withRule(rule), aj);
}

const request = context.switchToHttp().getRequest();
const request = requestFromContext(context);

// If we cannot access the request, we "fail open" by allowing the request
if (typeof request === "undefined") {
return true;
}

const decision = await aj.protect(request);

Expand Down
4 changes: 4 additions & 0 deletions examples/nestjs-graphql/.env.local.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
# NODE_ENV is not set by the environment
ARCJET_ENV=development
# Add your Arcjet key from https://app.arcjet.com
ARCJET_KEY=
25 changes: 25 additions & 0 deletions examples/nestjs-graphql/.eslintrc.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
module.exports = {
parser: '@typescript-eslint/parser',
parserOptions: {
project: 'tsconfig.json',
tsconfigRootDir: __dirname,
sourceType: 'module',
},
plugins: ['@typescript-eslint/eslint-plugin'],
extends: [
'plugin:@typescript-eslint/recommended',
'plugin:prettier/recommended',
],
root: true,
env: {
node: true,
jest: true,
},
ignorePatterns: ['.eslintrc.js'],
rules: {
'@typescript-eslint/interface-name-prefix': 'off',
'@typescript-eslint/explicit-function-return-type': 'off',
'@typescript-eslint/explicit-module-boundary-types': 'off',
'@typescript-eslint/no-explicit-any': 'off',
},
};
56 changes: 56 additions & 0 deletions examples/nestjs-graphql/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
# compiled output
/dist
/node_modules
/build

# Logs
logs
*.log
npm-debug.log*
pnpm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*

# OS
.DS_Store

# Tests
/coverage
/.nyc_output

# IDEs and editors
/.idea
.project
.classpath
.c9/
*.launch
.settings/
*.sublime-workspace

# IDE - VSCode
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json

# dotenv environment variable files
.env
.env.development.local
.env.test.local
.env.production.local
.env.local

# temp directory
.temp
.tmp

# Runtime data
pids
*.pid
*.seed
*.pid.lock

# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
4 changes: 4 additions & 0 deletions examples/nestjs-graphql/.prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"singleQuote": true,
"trailingComma": "all"
}
51 changes: 51 additions & 0 deletions examples/nestjs-graphql/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
<a href="https://arcjet.com" target="_arcjet-home">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://arcjet.com/logo/arcjet-dark-lockup-voyage-horizontal.svg">
<img src="https://arcjet.com/logo/arcjet-light-lockup-voyage-horizontal.svg" alt="Arcjet Logo" height="128" width="auto">
</picture>
</a>

# Arcjet Protection with NestJS + GraphQL

This example shows how to use Arcjet to protect [NestJS](https://nestjs.com/)
GraphQL applications using the `@arcjet/nest` adapter.

## How to use

1. From the root of the project, install the SDK dependencies.

```bash
npm ci
```

2. Enter this directory and install the example's dependencies.

```bash
cd examples/nestjs-graphql
npm ci
```

3. Rename `.env.local.example` to `.env.local` and add your Arcjet key.

4. Start the server.

```bash
npm start
```

5. Visit `http://localhost:3000/graphql` in a browser and submit a GraphQL
query.

```graphql
query {
recipes {
id
title
description
ingredients
}
}
```

6. In the UI, change the headers to include `{ "user-agent": "curl" }` and
submit another GraphQL query and the request should be blocked.
8 changes: 8 additions & 0 deletions examples/nestjs-graphql/nest-cli.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"$schema": "https://json.schemastore.org/nest-cli",
"collection": "@nestjs/schematics",
"sourceRoot": "src",
"compilerOptions": {
"deleteOutDir": true
}
}
Loading