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

feat: add method not allow, referrerPolicy #2962

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
9 changes: 9 additions & 0 deletions packages/core/src/error/http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,14 @@ export class ForbiddenError extends MidwayHttpError {
}
}

/**
* 405 http error, Means that the server can only generate an answer which the client doesn't accept.
*/
export class MethodNotAllowedError extends MidwayHttpError {
constructor(resOrMessage?: ResOrMessage) {
super(resOrMessage, HttpStatus.METHOD_NOT_ALLOWED);
}
}
/**
* 406 http error, Means that the server can only generate an answer which the client doesn't accept.
*/
Expand Down Expand Up @@ -197,6 +205,7 @@ export const httpError = {
UnauthorizedError,
NotFoundError,
ForbiddenError,
MethodNotAllowedError,
NotAcceptableError,
RequestTimeoutError,
ConflictError,
Expand Down
2 changes: 2 additions & 0 deletions packages/security/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,10 @@
},
"license": "MIT",
"dependencies": {
"@midwayjs/cookies": "^1.0.2",
"csrf": "3.1.0",
"escape-html": "1.0.3",
"methods": "1.1.2",
"nanoid": "3.3.6",
"picomatch": "2.3.1",
"platform": "1.3.6",
Expand Down
7 changes: 7 additions & 0 deletions packages/security/src/config/config.default.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,4 +33,11 @@ export const security: Partial<SecurityOptions> = {
enable: true,
value: '1; mode=block',
},
referrerPolicy: {
enable: false,
value: 'no-referrer-when-downgrade',
},
methodnoallow: {
enable: false,
},
};
35 changes: 13 additions & 22 deletions packages/security/src/configuration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,13 @@
import { XFrameMiddleware } from './middleware/xframe.middleware';
import { HSTSMiddleware } from './middleware/hsts.middleware';
import { NoOpenMiddleware } from './middleware/noopen.middleware';
import { NoSniffMiddleware } from '.';
import { XSSProtectionMiddleware } from './middleware/xssProtection.middleware';
import { CSPMiddleware } from './middleware/csp.middleware';
import { SecurityHelper } from './middleware/helper';
import { ReferrerPolicyMiddleware } from './middleware/refererPolicy.middleware';
import { MethodNotAllowedMiddleware } from './middleware/methodNotAllowed.middleware'

Check failure on line 17 in packages/security/src/configuration.ts

View workflow job for this annotation

GitHub Actions / lintAndTestLegacy (lts/*, ubuntu-latest)

Insert `;`
import { NoSniffMiddleware } from './middleware/nosniff.middleware';

@Configuration({
namespace: 'security',
importConfigs: [
Expand All @@ -34,27 +37,15 @@
.getApplications(['koa', 'faas', 'express', 'egg'])
.forEach(app => {
app.useMiddleware(SecurityHelper);
if (this.security.csrf?.enable) {
app.useMiddleware(CsrfMiddleware);
}
if (this.security.csp?.enable) {
app.useMiddleware(CSPMiddleware);
}
if (this.security.xframe?.enable) {
app.useMiddleware(XFrameMiddleware);
}
if (this.security.hsts?.enable) {
app.useMiddleware(HSTSMiddleware);
}
if (this.security.noopen?.enable) {
app.useMiddleware(NoOpenMiddleware);
}
if (this.security.nosniff?.enable) {
app.useMiddleware(NoSniffMiddleware);
}
if (this.security.xssProtection?.enable) {
app.useMiddleware(XSSProtectionMiddleware);
}
app.useMiddleware(CsrfMiddleware);
app.useMiddleware(CSPMiddleware);
app.useMiddleware(XFrameMiddleware);
app.useMiddleware(HSTSMiddleware);
app.useMiddleware(NoOpenMiddleware);
app.useMiddleware(NoSniffMiddleware);
app.useMiddleware(XSSProtectionMiddleware);
app.useMiddleware(ReferrerPolicyMiddleware);
app.useMiddleware(MethodNotAllowedMiddleware);
});
}
}
14 changes: 14 additions & 0 deletions packages/security/src/constants.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
// https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Headers/Referrer-Policy
export const ALLOWED_POLICIES_ENUM = [
'no-referrer',
'no-referrer-when-downgrade',
'origin',
'origin-when-cross-origin',
'same-origin',
'strict-origin',
'strict-origin-when-cross-origin',
'unsafe-url',
'',
] as const;

export const METHODS_NOT_ALLOWED = ['trace', 'track'];
6 changes: 6 additions & 0 deletions packages/security/src/error.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,9 @@ export class CSRFError extends httpError.ForbiddenError {
super(message || 'csrf error');
}
}

export class ReferrerPolicyNotAllowedError extends httpError.InternalServerErrorError {
constructor(policy) {
super(`Current policy ${policy} not allowed`);
}
}
2 changes: 2 additions & 0 deletions packages/security/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,6 @@ export * from './middleware/noopen.middleware';
export * from './middleware/nosniff.middleware';
export * from './middleware/xssProtection.middleware';
export * from './middleware/csp.middleware';
export * from './middleware/refererPolicy.middleware';
export * from './middleware/methodNotAllowed.middleware';
export * from './middleware/helper';
24 changes: 23 additions & 1 deletion packages/security/src/interface.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import { IgnoreMatcher } from '@midwayjs/core';
import { ALLOWED_POLICIES_ENUM } from './constants';
import type { CookieSetOptions } from '@midwayjs/cookies';

export interface SecurityOptions {
/**
Expand Down Expand Up @@ -32,10 +34,19 @@ export interface SecurityOptions {
*/
nosniff: Partial<SecurityEnableOptions>;
/**
* whether enable IE8 XSS Filter, default is open
* whether enable IE8 XSS Filter
* default enable
*/
xssProtection: Partial<SecurityXSSProtectionOptions>;
/**
* whether enable Referrer-Policy
* default not enable and value equals no-referrer-when-downgrade
*/
referrerPolicy: Partial<SecurityReferrerPolicyOptions>;
/**
* whether enable methodnoallow
*/
methodnoallow: Partial<SecurityMethodNoAllowOptions>;
}

export interface SecurityCSRFOptions extends SecurityEnableOptions {
Expand Down Expand Up @@ -65,7 +76,11 @@ export interface SecurityCSRFOptions extends SecurityEnableOptions {
*/
queryName: string;
refererWhiteList: string[];
/**
* @deprecated use cookieOptions.domain
*/
cookieDomain: (context: any) => string;
cookieOptions: CookieSetOptions;
}

export interface SecurityXFrameOptions extends SecurityEnableOptions {
Expand All @@ -88,6 +103,13 @@ export interface SecurityCSPOptions extends SecurityEnableOptions {
reportOnly: boolean;
supportIE: boolean;
}

export interface SecurityReferrerPolicyOptions extends SecurityEnableOptions {
value: typeof ALLOWED_POLICIES_ENUM[number];
}

export interface SecurityMethodNoAllowOptions extends SecurityEnableOptions {}

export interface SecurityEnableOptions {
enable: boolean;
match?: IgnoreMatcher<any> | IgnoreMatcher<any> [];
Expand Down
22 changes: 14 additions & 8 deletions packages/security/src/middleware/base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,17 +24,23 @@ export abstract class BaseMiddleware implements IMiddleware<any, any> {
}

resolve(app) {
if (app.getFrameworkType() === MidwayFrameworkType.WEB_EXPRESS) {
return async (req: any, res, next) => {
return this.compatibleMiddleware(req, req, res, next);
};
} else {
return async (ctx, next) => {
return this.compatibleMiddleware(ctx, ctx.request, ctx, next);
};
if (this.security?.[this.securityName()]?.enable) {
if (app.getFrameworkType() === MidwayFrameworkType.WEB_EXPRESS) {
return async (req: any, res, next) => {
return this.compatibleMiddleware(req, req, res, next);
};
} else {
return async (ctx, next) => {
return this.compatibleMiddleware(ctx, ctx.request, ctx, next);
};
}
}
}

protected getSecurityPolicyConfig() {
return this.security?.[this.securityName()] || {};
}

abstract compatibleMiddleware(context, req, res, next);
abstract securityName(): string;
}
28 changes: 20 additions & 8 deletions packages/security/src/middleware/csrf.middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,18 +129,30 @@ export class CsrfMiddleware extends BaseMiddleware {
}
const secret = tokens.secretSync();
context[NEW_CSRF_SECRET] = secret;
const { useSession, sessionName, cookieDomain } = this.security.csrf;
let { cookieName } = this.security.csrf;
let {
// eslint-disable-next-line prefer-const
useSession,
// eslint-disable-next-line prefer-const
sessionName,
// eslint-disable-next-line prefer-const
cookieDomain,
cookieName,
// eslint-disable-next-line prefer-const
cookieOptions = {},
} = this.security.csrf;

if (useSession) {
context.session[sessionName] = secret;
} else {
const cookieOpts = {
domain: cookieDomain && cookieDomain(request),
signed: false,
httpOnly: false,
overwrite: true,
};
const cookieOpts = Object.assign(
{
domain: cookieDomain && cookieDomain(request),
signed: false,
httpOnly: false,
overwrite: true,
},
cookieOptions
);
// cookieName support array. so we can change csrf cookie name smoothly
if (!Array.isArray(cookieName)) {
cookieName = [cookieName];
Expand Down
31 changes: 31 additions & 0 deletions packages/security/src/middleware/methodNotAllowed.middleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { httpError, Middleware } from '@midwayjs/core';
import { BaseMiddleware } from './base';
import * as methods from 'methods';
import { METHODS_NOT_ALLOWED } from '../constants';

/**
* https://www.owasp.org/index.php/Cross_Site_Tracing
* http://jsperf.com/find-by-map-with-find-by-array
*/
@Middleware()
export class MethodNotAllowedMiddleware extends BaseMiddleware {
private safeHttpMethodsMap = {};
constructor() {
super();
for (const method of methods) {
if (!METHODS_NOT_ALLOWED.includes(method)) {
this.safeHttpMethodsMap[method.toUpperCase()] = true;
}
}
}
async compatibleMiddleware(context, req, res, next) {
// ctx.method is upper case
if (!this.safeHttpMethodsMap[context.method]) {
throw new httpError.MethodNotAllowedError();
}
return next();
}
securityName() {
return 'methodnoallow';
}
}
22 changes: 22 additions & 0 deletions packages/security/src/middleware/refererPolicy.middleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { Middleware } from '@midwayjs/core';
import { BaseMiddleware } from './base';
import { ALLOWED_POLICIES_ENUM } from '../constants';
import { ReferrerPolicyNotAllowedError } from '../error';

@Middleware()
export class ReferrerPolicyMiddleware extends BaseMiddleware {
async compatibleMiddleware(context, req, res, next) {
const result = await next();
const opts = this.getSecurityPolicyConfig();
const policy = opts.value;
if (!ALLOWED_POLICIES_ENUM.includes(policy)) {
throw new ReferrerPolicyNotAllowedError(policy);
}

res.set('referrer-policy', policy);
return result;
}
securityName() {
return 'referrerPolicy';
}
}
26 changes: 26 additions & 0 deletions packages/security/test/csrf.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -451,5 +451,31 @@ describe('test/csrf.test.ts', function () {
});
});

describe('csrf-cookieOptions', function () {
let app;
beforeAll(async () => {
const appDir = join(__dirname, `fixtures/csrf-tmp/csrf-cookieOptions`);
const config = join(appDir, 'src/config/config.default.ts');
const configuration = join(appDir, 'src/configuration.ts');
if (existsSync(appDir)) {
await remove(appDir);
}
await copy(csrfBase, appDir);
await remove(join(appDir, 'f.yml'));
await writeFile(configuration, csrfConfigurationCode.replace(/\$\{\s*framework\s*\}/g, `@midwayjs/koa`));
await writeFile(config, readFileSync(config, 'utf-8') + `\nexport const security = { csrf: {cookieOptions: {httpOnly: true}}};`);
app = await createApp(appDir);
});

afterAll(async () => {
await close(app);
});

it('post with csrf token set to query using session', async () => {
const request = await createHttpRequest(app);
const response = await request.get('/csrf').expect(200).set('Host', 'abc.aaaa.ddd.string.com');
assert(response.text);
expect(response.headers['set-cookie'][0]).toMatch(/csrfToken=[\w\-]+; path=\/; httponly/);
});
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"name": "ali-demo"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { Configuration, Controller, Inject, All } from '@midwayjs/core';
import * as framework from '@midwayjs/koa';
@Configuration({
imports: [
framework,
require('../../../../src')
],
importConfigs: [
{
default: {
keys: ['a'],
security: {
csrf: {
enable: true,
cookieOptions: {
httpOnly: true,
},
},
}
}
}
]
})
export class AutoConfiguration {}


@Controller('/')
export class HomeController {

@Inject()
ctx;

@All('/ok')
async html() {
return 'ok';
}
}
3 changes: 3 additions & 0 deletions packages/security/test/fixtures/methodnoallow/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"name": "ali-demo"
}