Giter Club home page Giter Club logo

csrf-protection's Introduction

@fastify/csrf-protection

CI NPM version js-standard-style

This plugin helps developers protect their Fastify server against CSRF attacks. In order to fully protect against CSRF, developers should study Cross-Site Request Forgery Prevention Cheat Sheet in depth. See also pillarjs/understanding-csrf as a good guide.

Security Disclaimer

Securing applications against CSRF is a developer responsibility and it should not be fully trusted to any third party modules. We do not claim that this module is able to protect an application without a clear study of CSRF, its impact and the needed mitigations. @fastify/csrf-protection provides a series of utilities that developers can use to secure their application. We recommend using @fastify/helmet to implement some of those mitigations.

Security is always a tradeoff between risk mitigation, functionality, performance, and developer experience. As a result we will not consider a report of a plugin default configuration option as security vulnerability that might be unsafe in certain scenarios as long as this module provides a way to provide full mitigation through configuration.

Install

npm i @fastify/csrf-protection

Usage

If you use @fastify/csrf-protection with @fastify/cookie, the CSRF secret will be added to the response cookies. By default, the cookie used will be named _csrf, but you can rename it via the cookieKey option. When cookieOpts are provided, they override the default cookie options. Make sure you restore any of the default options which provide sensible and secure defaults.

fastify.register(require('@fastify/cookie'))
fastify.register(require('@fastify/csrf-protection'))

// if you want to sign cookies:
fastify.register(require('@fastify/cookie'), { secret }) // See following section to ensure security
fastify.register(require('@fastify/csrf-protection'), { cookieOpts: { signed: true } })

// generate a token
fastify.route({
  method: 'GET',
  path: '/',
  handler: async (req, reply) => {
    const token = await reply.generateCsrf()
    return { token }
  }
})

// protect a route
fastify.route({
  method: 'POST',
  path: '/',
  onRequest: fastify.csrfProtection,
  handler: async (req, reply) => {
    return req.body
  }
})

If you use @fastify/csrf-protection with @fastify/session, the CSRF secret will be added to the session. By default, the key used will be named _csrf, but you can rename it via the sessionKey option.

fastify.register(require('@fastify-session'), { secret: "a string which is longer than 32 characters" })
fastify.register(require('@fastify/csrf-protection'), { sessionPlugin: '@fastify/session' })

// generate a token
fastify.route({
  method: 'GET',
  path: '/',
  handler: async (req, reply) => {
    const token = await reply.generateCsrf()
    return { token }
  }
})

// protect a route
fastify.route({
  method: 'POST',
  path: '/',
  onRequest: fastify.csrfProtection,
  handler: async (req, reply) => {
    return req.body
  }
})

If you use @fastify/csrf-protection with @fastify/secure-session, the CSRF secret will be added to the session. By default, the key used will be named _csrf, but you can rename it via the sessionKey option.

fastify.register(require('@fastify/secure-session'), { secret: "a string which is longer than 32 characters" })
fastify.register(require('@fastify/csrf-protection'), { sessionPlugin: '@fastify/secure-session' })

// generate a token
fastify.route({
  method: 'GET',
  path: '/',
  handler: async (req, reply) => {
    const token = await reply.generateCsrf()
    return { token }
  }
})

// protect a route
fastify.route({
  method: 'POST',
  path: '/',
  onRequest: fastify.csrfProtection,
  handler: async (req, reply) => {
    return req.body
  }
})

Securing the secret

The secret shown in the code above is strictly just an example. In all cases, you would need to make sure that the secret is:

  • Never hard-coded in the code or .env files or anywhere in the repository
  • Stored in some external services like KMS, Vault or something similar
  • Read at run-time and supplied to this option
  • Of significant character length to provide adequate entropy
  • Truly random sequence of characters (You could use crypto-random-string)

Apart from these safeguards, it is extremely important to use HTTPS for your website/app to avoid a bunch of other potential security issues like MITM attacks etc.

API

Module Options

Options Description
cookieKey The name of the cookie where the CSRF secret will be stored, default _csrf.
cookieOpts The cookie serialization options. See @fastify/cookie.
sessionKey The key where to store the CSRF secret in the session.
getToken A sync function to get the CSRF secret from the request.
getUserInfo A sync function to get the a string of user-specific information to prevent cookie tossing.
sessionPlugin The session plugin that you are using (if applicable).
csrfOpts The csrf options. See @fastify/csrf.

reply.generateCsrf([opts])

Generates a secret (if it is not already present) and returns a promise that resolves to the associated secret.

const token = await reply.generateCsrf()

You can also pass the cookie serialization options to the function.

The option userInfo is required if getUserInfo has been specified in the module option. The provided userInfo is hashed inside the csrf token and it is not directly exposed. This option is needed to protect against cookie tossing. The option csrfOpts.hmacKey is required if getUserInfo has been specified in the module option in combination with using @fastify/cookie as sessionPlugin

fastify.csrfProtection(request, reply, next)

A hook that you can use for protecting routes or entire plugins from CSRF attacks. Generally, we recommend using an onRequest hook, but if you are sending the token via the request body, then you must use a preValidation or preHandler hook.

// protect the fastify instance
fastify.addHook('onRequest', fastify.csrfProtection)

// protect a single route
fastify.route({
  method: 'POST',
  path: '/',
  onRequest: fastify.csrfProtection,
  handler: async (req, reply) => {
    return req.body
  }
})

You can configure the function to read the CSRF token via the getToken option, by default the following is used:

function getToken (req) {
  return (req.body && req.body._csrf) ||
    req.headers['csrf-token'] ||
    req.headers['xsrf-token'] ||
    req.headers['x-csrf-token'] ||
    req.headers['x-xsrf-token']
}

It is recommended to provide a custom getToken function for performance and security reasons.

fastify.register(require('@fastify/csrf-protection'), 
  { getToken: function (req) { return req.headers['csrf-token'] } }
)

or

fastify.register(require('@fastify/csrf-protection'), 
  { getToken: (req) => req.headers['csrf-token'] }
)

License

MIT

csrf-protection's People

Contributors

58bits avatar arnesfield avatar climba03003 avatar davidcralph avatar delvedor avatar dependabot[bot] avatar droet avatar eomm avatar fdawgs avatar genediazjr avatar github-actions[bot] avatar hobi9 avatar jurca avatar leftiefriele avatar marco-ippolito avatar mcollina avatar mksony avatar salmanm avatar simoneb avatar tarang11 avatar tnovau avatar uzlopak avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  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

csrf-protection's Issues

TypeError: Cannot read property 'constructor' of undefined

๐Ÿ› Bug Report

"TypeError: Cannot read property 'constructor' of undefined
at Object.addHook (E:\myserver\node_modules\fastify\fastify.js:494:14)

To Reproduce

Steps to reproduce the behavior:

fastify.register(require('fastify-cookie'))
fastify.register(require('fastify-csrf'))
fastify.addHook('onRequest', fastify.csrfProtection)

Your Environment

  • node version: 12
  • fastify version: >=3.14.0
  • os: Windows

Bug with sessionPlugin in NestJS with Fastify

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Fastify version

4.17.0

Plugin version

6.3.0

Node.js version

20.0.0

Operating system

Windows

Operating system version (i.e. 20.04, 11.3, 10)

10

Description

The documentation says:

// if you want to sign cookies:
fastify.register(require('@fastify/cookie'), { secret }) // See following section to ensure security
fastify.register(require('@fastify/csrf-protection'), { cookieOpts: { signed: true } })

And when in NestJS 9.4.0 it declares csrf-protection in accordance with the documentation, code below in section "Steps to Reproduce".

Error:

error TS2322: Type '"@fastify/cookie"' is not assignable to type '"@fastify/secure-session"'.
sessionPlugin: '@fastify/cookie', 
error TS2345: Argument of type '{ cookieKey: string; cookieOpts: { httpOnly: true; sameSite: "strict"; path: string; secure: true; signed: false; }; }' is not assignable to parameter of type 'FastifyRegisterOptions<FastifyCsrfProtectionOptions>'.
  Type '{ cookieKey: string; cookieOpts: { httpOnly: true; sameSite: "strict"; path: string; secure: true; signed: false; }; }' is not assignable to type 'RegisterOptions & FastifyCsrfProtectionOptionsBase & 
FastifyCsrfProtectionOptionsFastifySecureSession'.
    Property 'sessionPlugin' is missing in type '{ cookieKey: string; cookieOpts: { httpOnly: true; sameSite: "strict"; path: string; secure: true; signed: false; }; }' but required in type 'FastifyCsrfProtectionOptionsFastifySecureSession'.
await app.register(fastifyCsrf, {
cookieKey: 'csrf-token',
},
});
  node_modules/@fastify/csrf-protection/types/index.d.ts:49:5
sessionPlugin: '@fastify/secure-session';
    'sessionPlugin' is declared here.

Even adding session Plugin and setting the value to '@fastify/cookie' gives an error and giving the value undefined shows that 1 of 3 types must be selected, e.g. @fastify/cookie or @fastify/session. So if it wasn't for the help on Stack, I would still think that I'm doing something wrong and here it turns out that it's a bug in your version, so I was forced to use version 6.2.0 and I would prefer the latest one.

If you need the code of my application, I will add it to the repo so that you can check for yourself that this bug exists :)

Steps to Reproduce

  // XCSRF - Protection
  app.register(fastifyCookie, { secret: 'ddddd' });
  app.register(fastifyCsrf, {
    sessionPlugin: '@fastify/cookie',
    cookieKey: 'csrf-token',
    cookieOpts: {
      httpOnly: true,
      sameSite: 'strict',
      path: '/',
      secure: true,
      signed: false,
    },
  });

Expected Behavior

I expected it to work according to the documentation and as it should after initialization

CSRF route protection example given in README not working

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Fastify version

4.15.0

Plugin version

6.2.0

Node.js version

18.14.0

Operating system

Linux

Operating system version (i.e. 20.04, 11.3, 10)

Ubuntu 22.04.2 LTS

Description

I followed the sample code which is in the README. Using cookie version. I called the protected route without generate CSRF token, but as a result I can still access it. That's not what we want.

Steps to Reproduce

  • npm init -y
  • yarn add fastify @fastify/cookie @fastify/csrf-protection
  • Create index.js and add code below
const fastify = require('fastify')({ logger: true });

fastify.register(require('@fastify/cookie'));
fastify.register(require('@fastify/csrf-protection'));

// generate a token
fastify.route({
  method: 'GET',
  path: '/',
  handler: async (req, reply) => {
    const token = await reply.generateCsrf();
    return { token };
  },
});

// protect a route
fastify.route({
  method: 'POST',
  path: '/',
  onRequest: fastify.csrfProtection,
  handler: async (req, reply) => {
    return req.body;
  },
});

fastify.listen({ port: 3000 }, function (err, address) {
  if (err) {
    fastify.log.error(err);
    process.exit(1);
  }
});
  • node index.js
  • Call the protected API http://localhost:3000/ using Postman or curl like curl --request POST --url http://localhost:3000/ --header 'content-type: application/json' --data '{ "hello": "world" }'

I'm want to use CommonJS style, not ESM.

Expected Behavior

It should show some kind error like "Missing CSRF token".

Remarks regarding v6.0.0 release notes

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the issue has not already been raised

Issue

I think that after merging #115 we are set to go and can publish next major version.

In the release notes we should note that we updated the used version of @fastify/csrf and that the csrf tokens will be by default sha256 hashed. And if they want to still use sha1 algorithm they will have to add algorithm: 'sha1' to csrfOpts.

I assume that some devs of massively used implementations maybe want to avoid csrf errors in production or have some concerns regarding user experience. So we should inform then to avoid surprises.

@Eomm
@mcollina

Invalid csrf token from cookie value

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Fastify version

4.9.2

Plugin version

6.0.0

Node.js version

16.13.2

Operating system

Windows

Operating system version (i.e. 20.04, 11.3, 10)

10

Description

I get the error "Invalid csrf token" when submitting a request with an XSRF-TOKEN header containing the value of the signed _csrf cookie.

Steps to Reproduce

Using nest as a framework. I send the CSRF token from login, and add a XSRF-TOKEN header to requests:

In main.ts:

  const adapter = new FastifyAdapter({ logger: true });
  const fastifyInstance = adapter.getInstance();
  const options: NestApplicationOptions = {};
  const app = await NestFactory.create<NestFastifyApplication>(AppModule, adapter, options);

  ...

  await app.register(fastifyCookie, {
    secret: configService.get('COOKIE_SECRET')
  });
  await app.register(fastifyCsrf, {
    cookieOpts: { signed: true },
    getToken: (req: FastifyRequest) => {
      return <string>req.headers['xsrf-token']; // for some reasons I have a type error error
    }
  });

  // Add hook
  fastifyInstance.addHook('onRequest', (request: FastifyRequest, reply: FastifyReply, done: (err?: Error) => void) => {
    if (request.url !== '/api/auth/login' && request.url !== '/api/auth/register') {
      fastifyInstance.csrfProtection(request, reply, done);
    } else {
      done();
    }
  });

In my auth controller (login endpoint):

  @Post('login')
  public async login(...): Promise<...> {
    ...

    const token = response.generateCsrf();
    response.status(HttpStatus.OK).send(ouput);
  }

On any endpoint, after login, I send a request with headers:

...
Cookie: Authorization=YYY; _csrf=XXX // results from login request
XSRF-TOKEN: XXX // taken from cookie _csrf value

And I'm returned with:

{
    "statusCode": 403,
    "code": "FST_CSRF_INVALID_TOKEN",
    "error": "Forbidden",
    "message": "Invalid csrf token"
}

Expected Behavior

There should be no error, the request should succeed (unless there is something I didn't understand?)

Typescript definitions not working

Hi there,
I tried to use this module with the provided typescript definitions and got

Argument of type '<HttpServer = any, HttpRequest = any, HttpResponse = any>(opts?: Options<HttpRequest> | undefined) => Plugin<HttpServer, HttpRequest, HttpResponse>' is not assignable to parameter of type '(instance: FastifyInstance<Server, IncomingMessage, ServerResponse>, options: { cookie: boolean; }, callback: (err?: FastifyError | undefined) => void) => void'.
  Types of parameters 'opts' and 'instance' are incompatible.

when using it via

server.register(fastifyCsrf, {cookie: true});

what actually worked for me are the following typings:

import {IncomingMessage, Server, ServerResponse} from "http";
import * as fastify from "fastify";
import {Options as TokenOptions} from "csrf";

declare module "fastify" {
    interface FastifyRequest {
        csrfToken(): string;
    }
}

interface Options<HttpRequest> extends TokenOptions {
    value?: (req: HttpRequest) => string;
    cookie?: fastify.CookieSerializeOptions | boolean;
    ignoreMethods?: Array<string>;
    sessionKey?: string;
}

declare const fastifyCsrf: fastify.Plugin<
    Server,
    IncomingMessage,
    ServerResponse,
    Options<ServerResponse>
>;

export = fastifyCsrf;

Would you accept a PR for this change? Or is there another way to make it work?

Move to the Fastify org

Hello! Tomas here, one of the maintainers of Fastify :)
Thank you for building this plugin!
We think this is very valuable, and we would love to have it inside our GitHub org, so we can offer official support for csrf.
Would you like to transfer this repository to https://github.com/fastify?
You will keep admin rights, and we'll help you out maintaining the plugin. We would also need publish access on npm.
Let me know what you think, thanks!

Cookie example given in the docs not working

I tried using the same code from the docs but was getting this error

{"statusCode":500,"error":"Internal Server Error","message":"invalid csrf token"}

Logs

{"level":30,"time":1567671488738,"pid":15370,"hostname":"tss-H110M-H","msg":"Server listening at http://127.0.0.1:3000","v":1}
{"level":30,"time":1567671496941,"pid":15370,"hostname":"tss-H110M-H","reqId":1,"req":{"method":"GET","url":"/","hostname":"localhost:3000","remoteAddress":"127.0.0.1","remotePort":45810},"msg":"incoming request","v":1}
{"level":30,"time":1567671496947,"pid":15370,"hostname":"tss-H110M-H","reqId":1,"res":{"statusCode":200},"responseTime":5.293844999745488,"msg":"request completed","v":1}
{"level":30,"time":1567671504128,"pid":15370,"hostname":"tss-H110M-H","reqId":2,"req":{"method":"POST","url":"/data","hostname":"localhost:3000","remoteAddress":"127.0.0.1","remotePort":45868},"msg":"incoming request","v":1}
{"level":50,"time":1567671504132,"pid":15370,"hostname":"tss-H110M-H","reqId":2,"req":{"method":"POST","url":"/data","hostname":"localhost:3000","remoteAddress":"127.0.0.1","remotePort":45868},"res":{"statusCode":500},"err":{"type":"Error","message":"invalid csrf token","stack":"Error: invalid csrf token\n    at Object.handleCsrf (/home/tss/csrf-test/node_modules/fastify-csrf/lib/fastifyCsrf.js:28:10)\n    at hookIterator (/home/tss/csrf-test/node_modules/fastify/lib/hooks.js:124:10)\n    at next (/home/tss/csrf-test/node_modules/fastify/lib/hooks.js:70:20)\n    at hookRunner (/home/tss/csrf-test/node_modules/fastify/lib/hooks.js:84:3)\n    at preValidationCallback (/home/tss/csrf-test/node_modules/fastify/lib/handleRequest.js:93:5)\n    at handler (/home/tss/csrf-test/node_modules/fastify/lib/handleRequest.js:70:5)\n    at done (/home/tss/csrf-test/node_modules/fastify/lib/contentTypeParser.js:115:7)\n    at Parser.contentParser [as fn] (/home/tss/csrf-test/node_modules/fastify-formbody/formbody.js:10:5)\n    at IncomingMessage.onEnd (/home/tss/csrf-test/node_modules/fastify/lib/contentTypeParser.js:185:25)\n    at IncomingMessage.emit (events.js:203:15)"},"msg":"invalid csrf token","v":1}
{"level":30,"time":1567671504133,"pid":15370,"hostname":"tss-H110M-H","reqId":2,"res":{"statusCode":500},"responseTime":4.723324000835419,"msg":"request completed","v":1}

Code

const fastify = require("fastify")({ logger: true });
const fastifyCookie = require("fastify-cookie");
const fastifyFormBody = require("fastify-formbody");
const fastifyCSRF = require("fastify-csrf");

fastify.register(fastifyCookie);
fastify.register(fastifyFormBody);
fastify.register(fastifyCSRF, { cookie: true });

fastify.get("/", (request, reply) => {
  var form = `
      <form method = "post" action="/data">
         <input type="text" name"field_name"/>
         <input type="hidden" value="${request.csrfToken()}" 
     name="_csrf /* this token can be sent in request header as well */"/>
         <button type="submit">Submit</button>
      </form>
    `;
  reply.type("text/html").send(form);
});

fastify.post("/data", (request, reply) => {
  reply.send("Post successful");
});

fastify.listen(3000, err => {
  if (err) {
    process.exit(0);
  }
});

I got the error "Invalid token" when submitting a POST request to route registered from a file.

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the issue has not already been raised

Issue

I got the error "Invalid token" when submitting a POST request to route registered from a file.

fastify.register(indexPost);

This is an example:

https://codesandbox.io/s/fastify-csrf-protection-typescript-ngzpec?file=/index.ts:0-1634
You will see the error when you click submit.

The screenshot:

image

Errors are not handled in the preHandler hook, if you don't throw it

Looking at the code you do return new Error('invalid csrf token'); in the async handleCsrf preHandler hook but looks like this error is never handled by Fastify.

My test:

const fastify = require('fastify')();
fastify.register(require('fastify-cookie'));
fastify.register(require('fastify-formbody'));
fastify.register(require('fastify-csrf'), { cookie: true });

fastify.get('/', async (req, reply) => {
  reply.type('text/html');
  return `<form method="POST" action="/send">
    <input type="hidden" name="_csrf" value="invalid"><input type="submit" /></form>`;
});

/* Fastify should not be able to reach this route, since the CSRF is invalid 
(aka not matching the token set in the cookie).
Unfortunally, it does not throw any errors even if the _csrf cookie is correctly set. */
fastify.post('/send', async (req, reply) => {
  return { hello: 'world' };
});

fastify.listen(3000, err => {
  if (err) throw err;
});

Replacing return new Error('invalid csrf token'); with throw new Error('invalid csrf token') in the lib works, then I can normally handle it with setErrorHandler().

Using fastify 1.13.4, fastify-csrf 1.0.1, fastify-formbody 2.1.0, fastify-cookie 2.1.6

how does a cookie protect against CSRF?

If the CSRF token is in a cookie, that means all the data needed to make a request is known to the attacker (just the API call), and the browser adds the session and csrf secrets.

So isn't putting the CSRF token in a cookie pointless?

Use tokens.secretSync instead of .secret

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the feature has not already been requested

๐Ÿš€ Feature Proposal

Use .secretSync() instead of .secret() to generate the secret.

Motivation

secretSync is 4-5 times faster than .secret(). secret and secretSync are basically wrappers for crypto.randomBytes(secretLength).toString('base64url'). And when we compare to calls of randomBytes throughout the fastify ecosystem, then we can see that we use the "sync" call of randomBytes

see:
https://github.com/fastify/fastify-helmet/blob/b341c6879897c25f6fe3dbd0c7ae239760ed70d0/index.js#L83

So I assume we should call secretSync for better performance.

Example

No response

`req.body` is undefined

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Fastify version

4.13.0

Plugin version

6.1.0

Node.js version

18.13.0

Operating system

macOS

Operating system version (i.e. 20.04, 11.3, 10)

13

Description

Hello,

I am trying to put the csrf token to be part of the input form (Similar to this), but it seems that the getToken() function fail in getting the token out from the body.

From the docs, it seems to be possible to do so.

I tried to print the body and it seems to have an undefined value.

      fastify.register(fastifyCsrfProtection, {
        sessionPlugin: "@fastify/secure-session",
        getToken: (req) => {
          console.log("the body", req.body);
          return "TEMP_TOKEN";
        },
      });

I am wondering if the middleware mentioned here is relevant to the undefined value.

Steps to Reproduce

  1. Setup a Fastify Server with the fastifyCsrfProtection enabled with the default config of getToken()
  2. From the FE, submit a that includes _csrf token as a hidden input.
  3. Submit the form and invalid csrf token error was thrown (InternalServerError), same token works if it is put in the header.

Expected Behavior

No Invalid csrf-token error thrown.

Property 'sessionPlugin' is missing in type '{ cookieOpts: { signed: true; }; }' but required in type 'FastifyCsrfProtectionOptionsFastifySecureSession'

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Fastify version

8.2.1

Plugin version

6.3.0

Node.js version

16.13.2

Operating system

Windows

Operating system version (i.e. 20.04, 11.3, 10)

11

Description

app.register(fastifyCsrfProtection, { cookieOpts: { signed: true } }) 

Typescript is throwing the following error:

Argument of type '{ cookieOpts: { signed: true; }; }' is not assignable to parameter of type 'FastifyRegisterOptions<FastifyCsrfProtectionOptions>'.
  Type '{ cookieOpts: { signed: true; }; }' is not assignable to type 'RegisterOptions & FastifyCsrfProtectionOptionsBase & FastifyCsrfProtectionOptionsFastifySecureSession'.
    Property 'sessionPlugin' is missing in type '{ cookieOpts: { signed: true; }; }' but required in type 'FastifyCsrfProtectionOptionsFastifySecureSession'.

Steps to Reproduce

prepare a project with NestJs and Fastify. then use the @fastify/cookie with @fastify/csrf-protection.

in the mean file include:

     app.register(fastifyCookie, {
        secret: configService.get<string>('COOKIE_SECRET')
    })

    app.register(fastifyHelmet)

    app.register(fastifyCsrfProtection, { cookieOpts: { signed: true } })

Expected Behavior

not to see such an error. according to you the documentation adding { cookieOpts: { signed: true } } as second parameter should be sufficient.

FastifyCsrfProtectionOptionsFastifySecureSession is defined in fastifyCsrfProtection . as the following:

interface FastifyCsrfProtectionOptionsFastifySecureSession {
    sessionPlugin: '@fastify/secure-session';
    csrfOpts?: CSRFOptions;
  }

as sessionPlugin has already a default value of '@fastify/secure-session'. shouldn't it be optional in the definition ??

Disable CSRF Token Reuse

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the issue has not already been raised

Issue

Thanks for this great plug in.

I have one concern. Save CSRF token I can use multiple time for the verification. Is there any option where I can make sure that token is used only once.

Bug in type definition

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Fastify version

4.23.2

Plugin version

6.4.0

Node.js version

20.9.0

Operating system

macOS

Operating system version (i.e. 20.04, 11.3, 10)

14.1

Description

Hi, when using typescript and trying to register the csrf-protection plugin, i get a compiler error because csrfOpts.hmacKey is not defined even though on the docs and on the javascript code that property is required only if the sessionPlugin is fastify/cookie and csrfOpts.userInfo is truthy.

  if (sessionPlugin === '@fastify/cookie' && csrfOpts.userInfo) {
    assert(csrfOpts.hmacKey, 'csrfOpts.hmacKey is required')
  }

Steps to Reproduce

  await fastify.register(Csrf, {
    sessionPlugin: '@fastify/cookie',
    cookieOpts: {
      signed: true,
    },
  });

Expected Behavior

I would expect to be able to register the plugin without any compiler errors.

firefox mobile invalid csrf

Hi, I am getting "invalid csrf token" only in Firefox mobile (android device) with session storage configured. Verified _crsf value field is set in the form body.

2020-06-29T02:49:09.916098+00:00 app[web.1]: _csrf: 'T3j4XGw1-iP7JwuRT1lXlFcRyjdHF_kvVMRo'

(Works fine on Firefox Desktop and Chrome mobile/desktop)

Here is the server error:

{
2020-06-29T02:49:09.917542+00:00 app[web.1]: ServerError: Error: invalid csrf token
2020-06-29T02:49:09.917544+00:00 app[web.1]: at Object.handleCsrf (/app/node_modules/fastify-csrf/lib/fastifyCsrf.js:36:10)
2020-06-29T02:49:09.917544+00:00 app[web.1]: }

Method `generateCsrf` return type should be a `string` instead of `FastifyReply`

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Fastify version

4.13.0

Plugin version

6.1.0

Node.js version

18.14.2

Operating system

Linux

Operating system version (i.e. 20.04, 11.3, 10)

Ubuntu 22.04.2 LTS

Description

The return type of the decorated generateCsrf method is FastifyReply:

generateCsrf(
options?: fastifyCsrfProtection.CookieSerializeOptions
): FastifyReply;

Looking at the code, the generateCsrf methods return tokens.create() which is a string.

Not a big issue as the token is almost always returned or used in reply.send(), but it would be nice to have the type fixed.

Steps to Reproduce

Example:

const fastify = require('fastify')();

fastify.register(require('@fastify/cookie'));
fastify.register(require('@fastify/csrf-protection'));

fastify.get('/', (_, reply) => {
  const token = reply.generateCsrf();
  const type = typeof token;
  console.log('token type:', type); // type is 'string'
  return { token, type };
});

fastify.listen().then(address => {
  console.log('listening on', address);
});

The value of typeof token is string but the token type (hovering in VSCode) is FastifyReply.

Expected Behavior

Return type of generateCsrf method should be a string instead of FastifyReply.

Do not mix callback and async/await

As an example this https://github.com/Tarang11/fastify-csrf/blob/master/lib/fastifyCsrf.js#L20-L31:

	async function handleCsrf(request, reply, done) {
		var secret = getSecret(request, cookie);
		// cookie for csrf token not set.
		if(!secret) {
			secret = await tokens.secret();
			setSecret(request, reply, secret, cookie);
		}
		if(ignoreMethods.indexOf(request.req.method) < 0 && !tokens.verify(secret, tokenIdentifier(request))) {
			return done(new Error('invalid csrf token'));
		}
		done();
	}

Could be rewritten as:

	async function handleCsrf(request, reply) {
		var secret = getSecret(request, cookie);
		// cookie for csrf token not set.
		if(!secret) {
			secret = await tokens.secret();
			setSecret(request, reply, secret, cookie);
		}
		if(ignoreMethods.indexOf(request.req.method) < 0 && !tokens.verify(secret, tokenIdentifier(request))) {
			throw new Error('invalid csrf token');
		}
	}

Module did not self-register

Error when try to register module

package.json

"@nestjs/platform-fastify": "^7.6.7",
"fastify-cookie": "^5.1.0",
"fastify-csrf": "^3.0.1",

main.ts

import { fastifyCookie } from 'fastify-cookie';
import fastifyCsrf from 'fastify-csrf';

const server = fastify();
await server.register(fastifyCookie);
await server.register(fastifyCsrf, { cookieOpts: { signed: true } });

error

Error: Module did not self-register: '\\?\...\node_modules\libxmljs\build\Release\xmljs.node'.
    at Object.Module._extensions..node (internal/modules/cjs/loader.js:1065:18)       
    at Module.load (internal/modules/cjs/loader.js:879:32)
    at Function.Module._load (internal/modules/cjs/loader.js:724:14)
    at Module.require (internal/modules/cjs/loader.js:903:19)
    at require (internal/modules/cjs/helpers.js:74:18)
    at bindings (...\node_modules\bindings\bindings.js:84:48)
    at Object.<anonymous> (...\node_modules\libxmljs\lib\bindings.js:1:37)
    at Module._compile (internal/modules/cjs/loader.js:1015:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1035:10)
    at Module.load (internal/modules/cjs/loader.js:879:32)

Signed cookies are not supported

Hello again,

setting the cookie.signed flag true in the options results in fastify-cookie signing the cookies being set by this middleware, however, fastify-csrf does not properly handle reading signed cookies, since they need to be "unsigned" to get to the raw value.

I recommmend adding an if (cookie.signed) { ... } check to the getSecret() function to make this work.

I am willing to submit a PR, if you'd prefer me to do so.

Thank you in advance.

httpOnly

Why is not httpOnly set on the coockie? In order to protect against csrf the coockie should not be readable by javascript. How does this lib protect against csrf without this?

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.