From 1b952a1b09adbb88ff3cff9a2974eb1e37ce53a5 Mon Sep 17 00:00:00 2001 From: Harry Chen Date: Thu, 6 Oct 2022 23:04:41 +0800 Subject: [PATCH] feat: add guard (#2345) --- packages-legacy/egg-layer/jest.config.js | 2 +- packages-legacy/express-layer/jest.config.js | 2 +- packages-legacy/koa-layer/jest.config.js | 2 +- packages-legacy/orm/jest.config.js | 2 +- packages-legacy/runtime-engine/jest.config.js | 2 +- packages-legacy/runtime-mock/jest.config.js | 2 +- packages-legacy/serverless-app/jest.config.js | 2 +- .../serverless-aws-starter/jest.config.js | 2 +- .../serverless-fc-starter/jest.config.js | 2 +- .../serverless-fc-trigger/jest.config.js | 2 +- .../serverless-scf-starter/jest.config.js | 2 +- .../serverless-scf-trigger/jest.config.js | 2 +- .../serverless-vercel-starter/jest.config.js | 2 +- .../serverless-vercel-trigger/jest.config.js | 2 +- .../serverless-worker-starter/jest.config.js | 2 +- packages-legacy/static-layer/jest.config.js | 2 +- .../midway-fc-starter/jest.config.js | 2 +- .../serverless-http-parser/jest.config.js | 2 +- .../jest.config.js | 2 +- packages/axios/jest.config.js | 2 +- packages/bootstrap/jest.config.js | 2 +- packages/cache/jest.config.js | 2 +- packages/code-dye/jest.config.js | 2 +- packages/consul/jest.config.js | 2 +- packages/core/jest.config.js | 2 +- packages/core/package.json | 3 +- packages/core/src/baseFramework.ts | 39 ++++++- packages/core/src/common/dataSourceManager.ts | 2 +- packages/core/src/common/fileDetector.ts | 2 +- packages/core/src/common/guardManager.ts | 58 ++++++++++ packages/core/src/common/middlewareManager.ts | 10 +- packages/core/src/common/webGenerator.ts | 20 +++- packages/core/src/config/config.default.ts | 20 +--- packages/core/src/{common => }/constants.ts | 23 +++- packages/core/src/context/container.ts | 3 +- .../src/context/managedResolverFactory.ts | 4 +- packages/core/src/context/providerWrapper.ts | 2 +- packages/core/src/context/requestContainer.ts | 3 +- packages/core/src/decorator/common/guard.ts | 32 ++++++ packages/core/src/decorator/constant.ts | 1 + .../src/decorator/faas/serverlessTrigger.ts | 2 +- packages/core/src/decorator/index.ts | 1 + .../src/decorator/microservice/consumer.ts | 2 +- .../decorator/microservice/kafkaListener.ts | 2 +- .../src/decorator/microservice/provider.ts | 2 +- .../microservice/rabbitmqListener.ts | 2 +- packages/core/src/decorator/rpc/hsf.ts | 4 +- packages/core/src/decorator/task/queue.ts | 2 +- packages/core/src/decorator/task/schedule.ts | 2 +- packages/core/src/decorator/task/task.ts | 2 +- packages/core/src/decorator/task/taskLocal.ts | 2 +- .../src/decorator/ws/webSocketController.ts | 2 +- .../core/src/decorator/ws/webSocketEvent.ts | 6 +- .../core/src/definitions/objectCreator.ts | 2 +- packages/core/src/error/framework.ts | 14 ++- packages/core/src/index.ts | 2 +- packages/core/src/interface.ts | 105 +++++++++++++----- packages/core/src/service/frameworkService.ts | 7 +- packages/core/src/service/webRouterService.ts | 5 + packages/core/src/util/contextUtil.ts | 2 +- packages/core/src/util/uuid.ts | 4 +- packages/core/test/baseFramework.test.ts | 11 ++ .../core/test/decorator/util/uuid.test.ts | 4 + packages/core/test/error/framework.test.ts | 52 +++++++++ .../src/framework.ts | 10 +- .../fixtures/base-app-with-guard/package.json | 3 + .../src/config/config.default.ts | 13 +++ .../src/config/config.unittest.ts | 5 + .../base-app-with-guard/src/configuration.ts | 69 ++++++++++++ .../slsFunctionService.test.ts.snap | 1 + packages/cos/jest.config.js | 2 +- packages/cross-domain/jest.config.js | 2 +- packages/decorator/jest.config.js | 2 +- packages/express-session/jest.config.js | 2 +- packages/faas/jest.config.js | 2 +- packages/faas/src/framework.ts | 13 +++ packages/grpc/jest.config.js | 2 +- packages/grpc/src/provider/framework.ts | 14 ++- packages/http-proxy/jest.config.js | 2 +- packages/i18n/jest.config.js | 2 +- packages/info/jest.config.js | 2 +- packages/jwt/jest.config.js | 2 +- packages/kafka/jest.config.js | 4 +- packages/kafka/src/framework.ts | 19 +++- packages/mikro/jest.config.js | 2 +- packages/mock/jest.config.js | 2 +- packages/mongoose/jest.config.js | 2 +- packages/oss/jest.config.js | 2 +- packages/otel/jest.config.js | 2 +- packages/passport/jest.config.js | 2 +- packages/processAgent/jest.config.js | 2 +- packages/prometheus-socket-io/jest.config.js | 2 +- packages/prometheus/jest.config.js | 2 +- packages/rabbitmq/jest.config.js | 2 +- packages/rabbitmq/src/framework.ts | 10 ++ packages/redis/jest.config.js | 2 +- packages/security/jest.config.js | 2 +- packages/sequelize/jest.config.js | 2 +- packages/session/jest.config.js | 2 +- packages/socketio/jest.config.js | 2 +- packages/socketio/src/framework.ts | 10 ++ packages/static-file/jest.config.js | 2 +- packages/swagger/jest.config.js | 4 +- packages/tablestore/jest.config.js | 2 +- packages/task/jest.config.js | 2 +- packages/typegoose/jest.config.js | 2 +- packages/typeorm/jest.config.js | 2 +- packages/upload/jest.config.js | 2 +- packages/validate/jest.config.js | 2 +- packages/view-ejs/jest.config.js | 2 +- packages/view-nunjucks/jest.config.js | 2 +- packages/view/jest.config.js | 2 +- packages/web-express/jest.config.js | 2 +- packages/web-express/src/framework.ts | 8 ++ .../test/fixtures/base-app-guard/package.json | 3 + .../src/config/config.default.ts | 9 ++ .../base-app-guard/src/configuration.ts | 28 +++++ .../base-app-guard/src/controller/api.ts | 33 ++++++ packages/web-express/test/index.test.ts | 11 ++ packages/web-koa/jest.config.js | 2 +- packages/web/jest.config.js | 2 +- packages/ws/jest.config.js | 2 +- packages/ws/src/framework.ts | 11 ++ 123 files changed, 694 insertions(+), 173 deletions(-) create mode 100644 packages/core/src/common/guardManager.ts rename packages/core/src/{common => }/constants.ts (67%) create mode 100644 packages/core/src/decorator/common/guard.ts create mode 100644 packages/core/test/error/framework.test.ts create mode 100644 packages/core/test/fixtures/base-app-with-guard/package.json create mode 100644 packages/core/test/fixtures/base-app-with-guard/src/config/config.default.ts create mode 100644 packages/core/test/fixtures/base-app-with-guard/src/config/config.unittest.ts create mode 100644 packages/core/test/fixtures/base-app-with-guard/src/configuration.ts create mode 100644 packages/web-express/test/fixtures/base-app-guard/package.json create mode 100644 packages/web-express/test/fixtures/base-app-guard/src/config/config.default.ts create mode 100644 packages/web-express/test/fixtures/base-app-guard/src/configuration.ts create mode 100644 packages/web-express/test/fixtures/base-app-guard/src/controller/api.ts diff --git a/packages-legacy/egg-layer/jest.config.js b/packages-legacy/egg-layer/jest.config.js index 34f2d767cd51..0245a5110fa2 100644 --- a/packages-legacy/egg-layer/jest.config.js +++ b/packages-legacy/egg-layer/jest.config.js @@ -2,6 +2,6 @@ module.exports = { preset: 'ts-jest', testEnvironment: 'node', testPathIgnorePatterns: ['/test/fixtures'], - coveragePathIgnorePatterns: ['/test/'], + coveragePathIgnorePatterns: ['/test/', '/dist/'], setupFilesAfterEnv: ['./jest.setup.js'], }; diff --git a/packages-legacy/express-layer/jest.config.js b/packages-legacy/express-layer/jest.config.js index 34f2d767cd51..0245a5110fa2 100644 --- a/packages-legacy/express-layer/jest.config.js +++ b/packages-legacy/express-layer/jest.config.js @@ -2,6 +2,6 @@ module.exports = { preset: 'ts-jest', testEnvironment: 'node', testPathIgnorePatterns: ['/test/fixtures'], - coveragePathIgnorePatterns: ['/test/'], + coveragePathIgnorePatterns: ['/test/', '/dist/'], setupFilesAfterEnv: ['./jest.setup.js'], }; diff --git a/packages-legacy/koa-layer/jest.config.js b/packages-legacy/koa-layer/jest.config.js index 34f2d767cd51..0245a5110fa2 100644 --- a/packages-legacy/koa-layer/jest.config.js +++ b/packages-legacy/koa-layer/jest.config.js @@ -2,6 +2,6 @@ module.exports = { preset: 'ts-jest', testEnvironment: 'node', testPathIgnorePatterns: ['/test/fixtures'], - coveragePathIgnorePatterns: ['/test/'], + coveragePathIgnorePatterns: ['/test/', '/dist/'], setupFilesAfterEnv: ['./jest.setup.js'], }; diff --git a/packages-legacy/orm/jest.config.js b/packages-legacy/orm/jest.config.js index 34f2d767cd51..0245a5110fa2 100644 --- a/packages-legacy/orm/jest.config.js +++ b/packages-legacy/orm/jest.config.js @@ -2,6 +2,6 @@ module.exports = { preset: 'ts-jest', testEnvironment: 'node', testPathIgnorePatterns: ['/test/fixtures'], - coveragePathIgnorePatterns: ['/test/'], + coveragePathIgnorePatterns: ['/test/', '/dist/'], setupFilesAfterEnv: ['./jest.setup.js'], }; diff --git a/packages-legacy/runtime-engine/jest.config.js b/packages-legacy/runtime-engine/jest.config.js index 34f2d767cd51..0245a5110fa2 100644 --- a/packages-legacy/runtime-engine/jest.config.js +++ b/packages-legacy/runtime-engine/jest.config.js @@ -2,6 +2,6 @@ module.exports = { preset: 'ts-jest', testEnvironment: 'node', testPathIgnorePatterns: ['/test/fixtures'], - coveragePathIgnorePatterns: ['/test/'], + coveragePathIgnorePatterns: ['/test/', '/dist/'], setupFilesAfterEnv: ['./jest.setup.js'], }; diff --git a/packages-legacy/runtime-mock/jest.config.js b/packages-legacy/runtime-mock/jest.config.js index 34f2d767cd51..0245a5110fa2 100644 --- a/packages-legacy/runtime-mock/jest.config.js +++ b/packages-legacy/runtime-mock/jest.config.js @@ -2,6 +2,6 @@ module.exports = { preset: 'ts-jest', testEnvironment: 'node', testPathIgnorePatterns: ['/test/fixtures'], - coveragePathIgnorePatterns: ['/test/'], + coveragePathIgnorePatterns: ['/test/', '/dist/'], setupFilesAfterEnv: ['./jest.setup.js'], }; diff --git a/packages-legacy/serverless-app/jest.config.js b/packages-legacy/serverless-app/jest.config.js index 34f2d767cd51..0245a5110fa2 100644 --- a/packages-legacy/serverless-app/jest.config.js +++ b/packages-legacy/serverless-app/jest.config.js @@ -2,6 +2,6 @@ module.exports = { preset: 'ts-jest', testEnvironment: 'node', testPathIgnorePatterns: ['/test/fixtures'], - coveragePathIgnorePatterns: ['/test/'], + coveragePathIgnorePatterns: ['/test/', '/dist/'], setupFilesAfterEnv: ['./jest.setup.js'], }; diff --git a/packages-legacy/serverless-aws-starter/jest.config.js b/packages-legacy/serverless-aws-starter/jest.config.js index 34f2d767cd51..0245a5110fa2 100644 --- a/packages-legacy/serverless-aws-starter/jest.config.js +++ b/packages-legacy/serverless-aws-starter/jest.config.js @@ -2,6 +2,6 @@ module.exports = { preset: 'ts-jest', testEnvironment: 'node', testPathIgnorePatterns: ['/test/fixtures'], - coveragePathIgnorePatterns: ['/test/'], + coveragePathIgnorePatterns: ['/test/', '/dist/'], setupFilesAfterEnv: ['./jest.setup.js'], }; diff --git a/packages-legacy/serverless-fc-starter/jest.config.js b/packages-legacy/serverless-fc-starter/jest.config.js index 34f2d767cd51..0245a5110fa2 100644 --- a/packages-legacy/serverless-fc-starter/jest.config.js +++ b/packages-legacy/serverless-fc-starter/jest.config.js @@ -2,6 +2,6 @@ module.exports = { preset: 'ts-jest', testEnvironment: 'node', testPathIgnorePatterns: ['/test/fixtures'], - coveragePathIgnorePatterns: ['/test/'], + coveragePathIgnorePatterns: ['/test/', '/dist/'], setupFilesAfterEnv: ['./jest.setup.js'], }; diff --git a/packages-legacy/serverless-fc-trigger/jest.config.js b/packages-legacy/serverless-fc-trigger/jest.config.js index 34f2d767cd51..0245a5110fa2 100644 --- a/packages-legacy/serverless-fc-trigger/jest.config.js +++ b/packages-legacy/serverless-fc-trigger/jest.config.js @@ -2,6 +2,6 @@ module.exports = { preset: 'ts-jest', testEnvironment: 'node', testPathIgnorePatterns: ['/test/fixtures'], - coveragePathIgnorePatterns: ['/test/'], + coveragePathIgnorePatterns: ['/test/', '/dist/'], setupFilesAfterEnv: ['./jest.setup.js'], }; diff --git a/packages-legacy/serverless-scf-starter/jest.config.js b/packages-legacy/serverless-scf-starter/jest.config.js index 34f2d767cd51..0245a5110fa2 100644 --- a/packages-legacy/serverless-scf-starter/jest.config.js +++ b/packages-legacy/serverless-scf-starter/jest.config.js @@ -2,6 +2,6 @@ module.exports = { preset: 'ts-jest', testEnvironment: 'node', testPathIgnorePatterns: ['/test/fixtures'], - coveragePathIgnorePatterns: ['/test/'], + coveragePathIgnorePatterns: ['/test/', '/dist/'], setupFilesAfterEnv: ['./jest.setup.js'], }; diff --git a/packages-legacy/serverless-scf-trigger/jest.config.js b/packages-legacy/serverless-scf-trigger/jest.config.js index 34f2d767cd51..0245a5110fa2 100644 --- a/packages-legacy/serverless-scf-trigger/jest.config.js +++ b/packages-legacy/serverless-scf-trigger/jest.config.js @@ -2,6 +2,6 @@ module.exports = { preset: 'ts-jest', testEnvironment: 'node', testPathIgnorePatterns: ['/test/fixtures'], - coveragePathIgnorePatterns: ['/test/'], + coveragePathIgnorePatterns: ['/test/', '/dist/'], setupFilesAfterEnv: ['./jest.setup.js'], }; diff --git a/packages-legacy/serverless-vercel-starter/jest.config.js b/packages-legacy/serverless-vercel-starter/jest.config.js index 34f2d767cd51..0245a5110fa2 100644 --- a/packages-legacy/serverless-vercel-starter/jest.config.js +++ b/packages-legacy/serverless-vercel-starter/jest.config.js @@ -2,6 +2,6 @@ module.exports = { preset: 'ts-jest', testEnvironment: 'node', testPathIgnorePatterns: ['/test/fixtures'], - coveragePathIgnorePatterns: ['/test/'], + coveragePathIgnorePatterns: ['/test/', '/dist/'], setupFilesAfterEnv: ['./jest.setup.js'], }; diff --git a/packages-legacy/serverless-vercel-trigger/jest.config.js b/packages-legacy/serverless-vercel-trigger/jest.config.js index 34f2d767cd51..0245a5110fa2 100644 --- a/packages-legacy/serverless-vercel-trigger/jest.config.js +++ b/packages-legacy/serverless-vercel-trigger/jest.config.js @@ -2,6 +2,6 @@ module.exports = { preset: 'ts-jest', testEnvironment: 'node', testPathIgnorePatterns: ['/test/fixtures'], - coveragePathIgnorePatterns: ['/test/'], + coveragePathIgnorePatterns: ['/test/', '/dist/'], setupFilesAfterEnv: ['./jest.setup.js'], }; diff --git a/packages-legacy/serverless-worker-starter/jest.config.js b/packages-legacy/serverless-worker-starter/jest.config.js index 48cb128ad376..b8d60350ac20 100644 --- a/packages-legacy/serverless-worker-starter/jest.config.js +++ b/packages-legacy/serverless-worker-starter/jest.config.js @@ -2,6 +2,6 @@ module.exports = { preset: 'ts-jest', testEnvironment: '@midwayjs/jest-environment-service-worker', testPathIgnorePatterns: ['/test/fixtures'], - coveragePathIgnorePatterns: ['/test/'], + coveragePathIgnorePatterns: ['/test/', '/dist/'], setupFilesAfterEnv: ['./jest.setup.js'], }; diff --git a/packages-legacy/static-layer/jest.config.js b/packages-legacy/static-layer/jest.config.js index 34f2d767cd51..0245a5110fa2 100644 --- a/packages-legacy/static-layer/jest.config.js +++ b/packages-legacy/static-layer/jest.config.js @@ -2,6 +2,6 @@ module.exports = { preset: 'ts-jest', testEnvironment: 'node', testPathIgnorePatterns: ['/test/fixtures'], - coveragePathIgnorePatterns: ['/test/'], + coveragePathIgnorePatterns: ['/test/', '/dist/'], setupFilesAfterEnv: ['./jest.setup.js'], }; diff --git a/packages-serverless/midway-fc-starter/jest.config.js b/packages-serverless/midway-fc-starter/jest.config.js index 34f2d767cd51..0245a5110fa2 100644 --- a/packages-serverless/midway-fc-starter/jest.config.js +++ b/packages-serverless/midway-fc-starter/jest.config.js @@ -2,6 +2,6 @@ module.exports = { preset: 'ts-jest', testEnvironment: 'node', testPathIgnorePatterns: ['/test/fixtures'], - coveragePathIgnorePatterns: ['/test/'], + coveragePathIgnorePatterns: ['/test/', '/dist/'], setupFilesAfterEnv: ['./jest.setup.js'], }; diff --git a/packages-serverless/serverless-http-parser/jest.config.js b/packages-serverless/serverless-http-parser/jest.config.js index 34f2d767cd51..0245a5110fa2 100644 --- a/packages-serverless/serverless-http-parser/jest.config.js +++ b/packages-serverless/serverless-http-parser/jest.config.js @@ -2,6 +2,6 @@ module.exports = { preset: 'ts-jest', testEnvironment: 'node', testPathIgnorePatterns: ['/test/fixtures'], - coveragePathIgnorePatterns: ['/test/'], + coveragePathIgnorePatterns: ['/test/', '/dist/'], setupFilesAfterEnv: ['./jest.setup.js'], }; diff --git a/packages/async-hooks-context-manager/jest.config.js b/packages/async-hooks-context-manager/jest.config.js index 34f2d767cd51..0245a5110fa2 100644 --- a/packages/async-hooks-context-manager/jest.config.js +++ b/packages/async-hooks-context-manager/jest.config.js @@ -2,6 +2,6 @@ module.exports = { preset: 'ts-jest', testEnvironment: 'node', testPathIgnorePatterns: ['/test/fixtures'], - coveragePathIgnorePatterns: ['/test/'], + coveragePathIgnorePatterns: ['/test/', '/dist/'], setupFilesAfterEnv: ['./jest.setup.js'], }; diff --git a/packages/axios/jest.config.js b/packages/axios/jest.config.js index 34f2d767cd51..0245a5110fa2 100644 --- a/packages/axios/jest.config.js +++ b/packages/axios/jest.config.js @@ -2,6 +2,6 @@ module.exports = { preset: 'ts-jest', testEnvironment: 'node', testPathIgnorePatterns: ['/test/fixtures'], - coveragePathIgnorePatterns: ['/test/'], + coveragePathIgnorePatterns: ['/test/', '/dist/'], setupFilesAfterEnv: ['./jest.setup.js'], }; diff --git a/packages/bootstrap/jest.config.js b/packages/bootstrap/jest.config.js index 34f2d767cd51..0245a5110fa2 100644 --- a/packages/bootstrap/jest.config.js +++ b/packages/bootstrap/jest.config.js @@ -2,6 +2,6 @@ module.exports = { preset: 'ts-jest', testEnvironment: 'node', testPathIgnorePatterns: ['/test/fixtures'], - coveragePathIgnorePatterns: ['/test/'], + coveragePathIgnorePatterns: ['/test/', '/dist/'], setupFilesAfterEnv: ['./jest.setup.js'], }; diff --git a/packages/cache/jest.config.js b/packages/cache/jest.config.js index 34f2d767cd51..0245a5110fa2 100644 --- a/packages/cache/jest.config.js +++ b/packages/cache/jest.config.js @@ -2,6 +2,6 @@ module.exports = { preset: 'ts-jest', testEnvironment: 'node', testPathIgnorePatterns: ['/test/fixtures'], - coveragePathIgnorePatterns: ['/test/'], + coveragePathIgnorePatterns: ['/test/', '/dist/'], setupFilesAfterEnv: ['./jest.setup.js'], }; diff --git a/packages/code-dye/jest.config.js b/packages/code-dye/jest.config.js index 34f2d767cd51..0245a5110fa2 100644 --- a/packages/code-dye/jest.config.js +++ b/packages/code-dye/jest.config.js @@ -2,6 +2,6 @@ module.exports = { preset: 'ts-jest', testEnvironment: 'node', testPathIgnorePatterns: ['/test/fixtures'], - coveragePathIgnorePatterns: ['/test/'], + coveragePathIgnorePatterns: ['/test/', '/dist/'], setupFilesAfterEnv: ['./jest.setup.js'], }; diff --git a/packages/consul/jest.config.js b/packages/consul/jest.config.js index 34f2d767cd51..0245a5110fa2 100644 --- a/packages/consul/jest.config.js +++ b/packages/consul/jest.config.js @@ -2,6 +2,6 @@ module.exports = { preset: 'ts-jest', testEnvironment: 'node', testPathIgnorePatterns: ['/test/fixtures'], - coveragePathIgnorePatterns: ['/test/'], + coveragePathIgnorePatterns: ['/test/', '/dist/'], setupFilesAfterEnv: ['./jest.setup.js'], }; diff --git a/packages/core/jest.config.js b/packages/core/jest.config.js index 34f2d767cd51..0245a5110fa2 100644 --- a/packages/core/jest.config.js +++ b/packages/core/jest.config.js @@ -2,6 +2,6 @@ module.exports = { preset: 'ts-jest', testEnvironment: 'node', testPathIgnorePatterns: ['/test/fixtures'], - coveragePathIgnorePatterns: ['/test/'], + coveragePathIgnorePatterns: ['/test/', '/dist/'], setupFilesAfterEnv: ['./jest.setup.js'], }; diff --git a/packages/core/package.json b/packages/core/package.json index 904d4be2d30a..ff7f3c65756a 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -8,7 +8,8 @@ "build": "tsc", "test": "node --require=ts-node/register ../../node_modules/.bin/jest --runInBand", "cov": "node --require=ts-node/register ../../node_modules/.bin/jest --runInBand --coverage --forceExit", - "link": "npm link" + "link": "npm link", + "madge": "madge --circular --extensions ts,tsx --exclude 'node_modules|test|dist' src" }, "keywords": [ "midway", diff --git a/packages/core/src/baseFramework.ts b/packages/core/src/baseFramework.ts index 994cf117a77b..e242351a56c9 100644 --- a/packages/core/src/baseFramework.ts +++ b/packages/core/src/baseFramework.ts @@ -9,10 +9,13 @@ import { MidwayProcessTypeEnum, CommonFilterUnion, MiddlewareRespond, + CommonGuardUnion, +} from './interface'; +import { REQUEST_CTX_LOGGER_CACHE_KEY, ASYNC_CONTEXT_KEY, ASYNC_CONTEXT_MANAGER_KEY, -} from './interface'; +} from './constants'; import { Inject, Destroy, Init } from './decorator'; import { ILogger, @@ -29,13 +32,13 @@ import { ContextMiddlewareManager } from './common/middlewareManager'; import { MidwayMiddlewareService } from './service/middlewareService'; import { FilterManager } from './common/filterManager'; import { MidwayMockService } from './service/mockService'; - import * as util from 'util'; import { ASYNC_ROOT_CONTEXT, AsyncContextManager, NoopContextManager, } from './common/asyncContextManager'; +import { GuardManager } from './common/guardManager'; const debug = util.debuglog('midway:debug'); export abstract class BaseFramework< @@ -55,6 +58,7 @@ export abstract class BaseFramework< protected contextLoggerFormat: LoggerContextFormat; protected middlewareManager = this.createMiddlewareManager(); protected filterManager = this.createFilterManager(); + protected guardManager = this.createGuardManager(); protected composeMiddleware = null; protected bootstrapOptions: IMidwayBootstrapOptions; protected asyncContextManager: AsyncContextManager; @@ -250,6 +254,10 @@ export abstract class BaseFramework< return this.createLogger(name, options); }, + getFramework: () => { + return this; + }, + getProjectName: () => { return this.getProjectName(); }, @@ -294,17 +302,24 @@ export abstract class BaseFramework< getAttr: (key: string): T => { return this.getApplicationContext().getAttr(key); }, + useMiddleware: ( middleware: CommonMiddlewareUnion ) => { return this.useMiddleware(middleware); }, + getMiddleware: (): ContextMiddlewareManager => { return this.getMiddleware(); }, + useFilter: (Filter: CommonFilterUnion) => { return this.useFilter(Filter); }, + + useGuard: (guard: CommonGuardUnion) => { + return this.useGuard(guard); + }, }; for (const method of whiteList) { delete defaultApplicationProperties[method]; @@ -439,8 +454,20 @@ export abstract class BaseFramework< return this.middlewareManager; } - public useFilter(Filter: CommonFilterUnion) { - return this.filterManager.useFilter(Filter); + public useFilter(filter: CommonFilterUnion) { + return this.filterManager.useFilter(filter); + } + + public useGuard(guards: CommonGuardUnion) { + return this.guardManager.addGlobalGuard(guards); + } + + public async runGuard( + ctx: CTX, + supplierClz: new (...args) => any, + methodName: string + ): Promise { + return this.guardManager.runGuard(ctx, supplierClz, methodName); } protected createMiddlewareManager() { @@ -450,4 +477,8 @@ export abstract class BaseFramework< protected createFilterManager() { return new FilterManager(); } + + protected createGuardManager() { + return new GuardManager(); + } } diff --git a/packages/core/src/common/dataSourceManager.ts b/packages/core/src/common/dataSourceManager.ts index 722dda60c464..7929763e95dd 100644 --- a/packages/core/src/common/dataSourceManager.ts +++ b/packages/core/src/common/dataSourceManager.ts @@ -6,7 +6,7 @@ import { MidwayCommonError, MidwayParameterError } from '../error'; import { run } from '@midwayjs/glob'; import { join } from 'path'; import { Types } from '../util/types'; -import { DEFAULT_PATTERN, IGNORE_PATTERN } from '../interface'; +import { DEFAULT_PATTERN, IGNORE_PATTERN } from '../constants'; export abstract class DataSourceManager { protected dataSource: Map = new Map(); diff --git a/packages/core/src/common/fileDetector.ts b/packages/core/src/common/fileDetector.ts index cd40e137d97d..892caf39709b 100644 --- a/packages/core/src/common/fileDetector.ts +++ b/packages/core/src/common/fileDetector.ts @@ -6,7 +6,7 @@ import { import { Types } from '../util/types'; import { run } from '@midwayjs/glob'; import { MidwayDuplicateClassNameError } from '../error'; -import { DEFAULT_PATTERN, IGNORE_PATTERN } from '../interface'; +import { DEFAULT_PATTERN, IGNORE_PATTERN } from '../constants'; import { getProviderName } from '../decorator'; export abstract class AbstractFileDetector implements IFileDetector { diff --git a/packages/core/src/common/guardManager.ts b/packages/core/src/common/guardManager.ts new file mode 100644 index 000000000000..2a8c3fe49b96 --- /dev/null +++ b/packages/core/src/common/guardManager.ts @@ -0,0 +1,58 @@ +import { CommonGuardUnion, IGuard, IMidwayContext } from '../interface'; +import { getClassMetadata, getPropertyMetadata, GUARD_KEY } from '../decorator'; + +export class GuardManager< + CTX extends IMidwayContext = IMidwayContext +> extends Array IGuard> { + public addGlobalGuard(guards: CommonGuardUnion) { + if (!Array.isArray(guards)) { + this.push(guards); + } else { + this.push(...guards); + } + } + + public async runGuard( + ctx: CTX, + supplierClz: new (...args) => any, + methodName: string + ) { + // check global guard + for (const Guard of this) { + const guard = await ctx.requestContext.getAsync>(Guard); + const isPassed = await guard.canActivate(ctx, supplierClz, methodName); + if (!isPassed) { + return false; + } + } + + // check class Guard + const classGuardList = getClassMetadata(GUARD_KEY, supplierClz); + if (classGuardList) { + for (const Guard of classGuardList) { + const guard = await ctx.requestContext.getAsync>(Guard); + const isPassed = await guard.canActivate(ctx, supplierClz, methodName); + if (!isPassed) { + return false; + } + } + } + + // check method Guard + const methodGuardList = getPropertyMetadata( + GUARD_KEY, + supplierClz, + methodName + ); + if (methodGuardList) { + for (const Guard of methodGuardList) { + const guard = await ctx.requestContext.getAsync>(Guard); + const isPassed = await guard.canActivate(ctx, supplierClz, methodName); + if (!isPassed) { + return false; + } + } + } + return true; + } +} diff --git a/packages/core/src/common/middlewareManager.ts b/packages/core/src/common/middlewareManager.ts index e999de750a3d..d0dd6c9f7c86 100644 --- a/packages/core/src/common/middlewareManager.ts +++ b/packages/core/src/common/middlewareManager.ts @@ -1,14 +1,14 @@ import { CommonMiddleware, CommonMiddlewareUnion, + IMiddlewareManager, IMidwayContext, } from '../interface'; -export class ContextMiddlewareManager< - CTX extends IMidwayContext, - R, - N -> extends Array> { +export class ContextMiddlewareManager + extends Array> + implements IMiddlewareManager +{ /** * insert a middleware or middleware array to first * @param middleware diff --git a/packages/core/src/common/webGenerator.ts b/packages/core/src/common/webGenerator.ts index 4014f19ab169..b64d7ff69cc6 100644 --- a/packages/core/src/common/webGenerator.ts +++ b/packages/core/src/common/webGenerator.ts @@ -5,19 +5,20 @@ * @param routerResponseData */ import { + MidwayFrameworkType, WEB_RESPONSE_CONTENT_TYPE, WEB_RESPONSE_HEADER, WEB_RESPONSE_HTTP_CODE, WEB_RESPONSE_REDIRECT, } from '../decorator'; +import * as util from 'util'; +import { IMidwayApplication } from '../interface'; import { MidwayWebRouterService, RouterInfo, - MidwayMiddlewareService, - IMidwayApplication, - MidwayFrameworkType, -} from '../index'; -import * as util from 'util'; +} from '../service/webRouterService'; +import { httpError } from '../error'; +import { MidwayMiddlewareService } from '../service/middlewareService'; const debug = util.debuglog('midway:debug'); @@ -35,6 +36,15 @@ export abstract class WebControllerGenerator< */ public generateKoaController(routeInfo: RouterInfo) { return async (ctx, next) => { + if (routeInfo.controllerClz && typeof routeInfo.method === 'string') { + const isPassed = await this.app + .getFramework() + .runGuard(ctx, routeInfo.controllerClz, routeInfo.method); + if (!isPassed) { + throw new httpError.ForbiddenError(); + } + } + const args = [ctx, next]; let result; if (typeof routeInfo.method !== 'string') { diff --git a/packages/core/src/config/config.default.ts b/packages/core/src/config/config.default.ts index 79313bb2f283..133900d929e3 100644 --- a/packages/core/src/config/config.default.ts +++ b/packages/core/src/config/config.default.ts @@ -1,23 +1,9 @@ -import { - MIDWAY_LOGGER_WRITEABLE_DIR, - MidwayAppInfo, - ServiceFactoryConfigOption, -} from '../interface'; +import type { MidwayAppInfo, MidwayCoreDefaultConfig } from '../interface'; import { getCurrentEnvironment, isDevelopmentEnvironment } from '../util/'; import { join } from 'path'; -import type { LoggerOptions } from '@midwayjs/logger'; +import { MIDWAY_LOGGER_WRITEABLE_DIR } from '../constants'; -export default ( - appInfo: MidwayAppInfo -): { - midwayLogger?: ServiceFactoryConfigOption; - debug?: { - recordConfigMergeOrder?: boolean; - }; - asyncContextManager: { - enable: boolean; - }; -} => { +export default (appInfo: MidwayAppInfo): MidwayCoreDefaultConfig => { const isDevelopment = isDevelopmentEnvironment(getCurrentEnvironment()); const logRoot = process.env[MIDWAY_LOGGER_WRITEABLE_DIR] ?? appInfo.root; return { diff --git a/packages/core/src/common/constants.ts b/packages/core/src/constants.ts similarity index 67% rename from packages/core/src/common/constants.ts rename to packages/core/src/constants.ts index cdb12f1826be..b32ee0b1ce70 100644 --- a/packages/core/src/common/constants.ts +++ b/packages/core/src/constants.ts @@ -1,9 +1,7 @@ -export const FUNCTION_INJECT_KEY = 'midway:function_inject_key'; /** * 静态参数 * */ - export const KEYS = { OBJECTS_ELEMENT: 'objects', OBJECT_ELEMENT: 'object', @@ -52,3 +50,24 @@ export const VALUE_TYPE = { OBJECT: 'object', // 仅仅在解析时使用 BOOLEAN: 'boolean', }; + +export const FUNCTION_INJECT_KEY = 'midway:function_inject_key'; +export const MIDWAY_LOGGER_WRITEABLE_DIR = 'MIDWAY_LOGGER_WRITEABLE_DIR'; +export const REQUEST_CTX_KEY = 'ctx'; +export const REQUEST_OBJ_CTX_KEY = '_req_ctx'; +export const HTTP_SERVER_KEY = '_midway_http_server'; +export const REQUEST_CTX_LOGGER_CACHE_KEY = '_midway_ctx_logger_cache'; + +export const ASYNC_CONTEXT_KEY = Symbol('ASYNC_CONTEXT_KEY'); +export const ASYNC_CONTEXT_MANAGER_KEY = 'MIDWAY_ASYNC_CONTEXT_MANAGER_KEY'; + +export const DEFAULT_PATTERN = [ + '**/**.ts', + '**/**.js', + '**/**.mts', + '**/**.mjs', + '**/**.cts', + '**/**.cjs', +]; + +export const IGNORE_PATTERN = ['**/**.d.ts', '**/**.d.mts', '**/**.d.cts']; diff --git a/packages/core/src/context/container.ts b/packages/core/src/context/container.ts index f917f355df9c..40d8e1fcb939 100644 --- a/packages/core/src/context/container.ts +++ b/packages/core/src/context/container.ts @@ -28,9 +28,8 @@ import { IObjectDefinitionRegistry, ObjectContext, ObjectLifeCycleEvent, - REQUEST_CTX_KEY, } from '../interface'; -import { FUNCTION_INJECT_KEY } from '../common/constants'; +import { FUNCTION_INJECT_KEY, REQUEST_CTX_KEY } from '../constants'; import { ObjectDefinition } from '../definitions/objectDefinition'; import { FunctionDefinition } from '../definitions/functionDefinition'; import { diff --git a/packages/core/src/context/managedResolverFactory.ts b/packages/core/src/context/managedResolverFactory.ts index c27b95c5bc85..1bd58e5ae465 100644 --- a/packages/core/src/context/managedResolverFactory.ts +++ b/packages/core/src/context/managedResolverFactory.ts @@ -1,12 +1,10 @@ /** * 管理对象解析构建 */ -import { KEYS } from '../common/constants'; +import { KEYS, REQUEST_CTX_KEY, REQUEST_OBJ_CTX_KEY } from '../constants'; import { IManagedResolver, IObjectDefinition, - REQUEST_CTX_KEY, - REQUEST_OBJ_CTX_KEY, IManagedResolverFactoryCreateOptions, IMidwayContainer, ObjectLifeCycleEvent, diff --git a/packages/core/src/context/providerWrapper.ts b/packages/core/src/context/providerWrapper.ts index 556964ac2b10..ab62e3b78c78 100644 --- a/packages/core/src/context/providerWrapper.ts +++ b/packages/core/src/context/providerWrapper.ts @@ -1,5 +1,5 @@ import { IMidwayContainer } from '../interface'; -import { FUNCTION_INJECT_KEY } from '../common/constants'; +import { FUNCTION_INJECT_KEY } from '../constants'; import { ObjectIdentifier, ScopeEnum } from '../decorator'; export function providerWrapper( diff --git a/packages/core/src/context/requestContainer.ts b/packages/core/src/context/requestContainer.ts index 01a7ea404393..43c27adcd362 100644 --- a/packages/core/src/context/requestContainer.ts +++ b/packages/core/src/context/requestContainer.ts @@ -1,6 +1,7 @@ import { MidwayContainer } from './container'; -import { REQUEST_CTX_KEY, IMidwayContainer } from '../interface'; +import { IMidwayContainer } from '../interface'; import { PIPELINE_IDENTIFIER } from '../decorator'; +import { REQUEST_CTX_KEY } from '../constants'; export class MidwayRequestContainer extends MidwayContainer { private readonly applicationContext: IMidwayContainer; diff --git a/packages/core/src/decorator/common/guard.ts b/packages/core/src/decorator/common/guard.ts new file mode 100644 index 000000000000..f6d982385464 --- /dev/null +++ b/packages/core/src/decorator/common/guard.ts @@ -0,0 +1,32 @@ +import { saveClassMetadata, savePropertyMetadata } from '../decoratorManager'; +import { CommonGuardUnion } from '../../interface'; +import { GUARD_KEY } from '../constant'; +import { Provide } from './provide'; +import { Scope } from './objectDef'; +import { ScopeEnum } from '../interface'; + +export function UseGuard( + guardOrArr: CommonGuardUnion +): ClassDecorator & MethodDecorator { + return ( + target: any, + propertyKey?: string, + descriptor?: PropertyDescriptor + ) => { + if (!Array.isArray(guardOrArr)) { + guardOrArr = [guardOrArr]; + } + if (propertyKey) { + savePropertyMetadata(GUARD_KEY, guardOrArr, target, propertyKey); + } else { + saveClassMetadata(GUARD_KEY, guardOrArr, target); + } + }; +} + +export function Guard(): ClassDecorator { + return target => { + Provide()(target); + Scope(ScopeEnum.Singleton)(target); + }; +} diff --git a/packages/core/src/decorator/constant.ts b/packages/core/src/decorator/constant.ts index 957e12f0e570..a1fbff45fcc9 100644 --- a/packages/core/src/decorator/constant.ts +++ b/packages/core/src/decorator/constant.ts @@ -8,6 +8,7 @@ export const FRAMEWORK_KEY = 'common:framework'; export const ASPECT_KEY = 'common:aspect'; export const CATCH_KEY = 'common:catch'; export const MATCH_KEY = 'common:match'; +export const GUARD_KEY = 'common:guard'; // faas export const FUNC_KEY = 'faas:func'; diff --git a/packages/core/src/decorator/faas/serverlessTrigger.ts b/packages/core/src/decorator/faas/serverlessTrigger.ts index 2a4cbc0bee2a..0f69676374af 100644 --- a/packages/core/src/decorator/faas/serverlessTrigger.ts +++ b/packages/core/src/decorator/faas/serverlessTrigger.ts @@ -6,7 +6,7 @@ import { SERVERLESS_FUNC_KEY, saveModule, ServerlessTriggerType, -} from '../../'; +} from '../'; export function ServerlessFunction( options: FaaSMetadata.ServerlessFunctionOptions diff --git a/packages/core/src/decorator/index.ts b/packages/core/src/decorator/index.ts index b43cea9fc4c5..a4f3328746e2 100644 --- a/packages/core/src/decorator/index.ts +++ b/packages/core/src/decorator/index.ts @@ -11,6 +11,7 @@ export * from './common/objectDef'; export * from './common/framework'; export * from './common/filter'; export * from './common/middleware'; +export * from './common/guard'; // faas export * from './faas/serverlessTrigger'; diff --git a/packages/core/src/decorator/microservice/consumer.ts b/packages/core/src/decorator/microservice/consumer.ts index 7c4a92ee75ff..606131880cc4 100644 --- a/packages/core/src/decorator/microservice/consumer.ts +++ b/packages/core/src/decorator/microservice/consumer.ts @@ -6,7 +6,7 @@ import { Provide, Scope, MSListenerType, -} from '../../'; +} from '../'; export function Consumer(type: MSListenerType.MQTT): ClassDecorator; export function Consumer( diff --git a/packages/core/src/decorator/microservice/kafkaListener.ts b/packages/core/src/decorator/microservice/kafkaListener.ts index 9f9d048d502c..698d39b382d6 100644 --- a/packages/core/src/decorator/microservice/kafkaListener.ts +++ b/packages/core/src/decorator/microservice/kafkaListener.ts @@ -1,4 +1,4 @@ -import { MS_CONSUMER_KEY, attachPropertyDataToClass } from '../..'; +import { MS_CONSUMER_KEY, attachPropertyDataToClass } from '../'; /** * @deprecated Replaced by ConsumerSubscribeTopics diff --git a/packages/core/src/decorator/microservice/provider.ts b/packages/core/src/decorator/microservice/provider.ts index bbebd2ee1bdb..46c00b47749c 100644 --- a/packages/core/src/decorator/microservice/provider.ts +++ b/packages/core/src/decorator/microservice/provider.ts @@ -11,7 +11,7 @@ import { GRPCMetadata, Provide, Scope, -} from '../../'; +} from '../'; export function Provider( type: MSProviderType.GRPC, diff --git a/packages/core/src/decorator/microservice/rabbitmqListener.ts b/packages/core/src/decorator/microservice/rabbitmqListener.ts index 145e39b16328..0999d4c86ebd 100644 --- a/packages/core/src/decorator/microservice/rabbitmqListener.ts +++ b/packages/core/src/decorator/microservice/rabbitmqListener.ts @@ -1,4 +1,4 @@ -import { MS_CONSUMER_KEY, attachPropertyDataToClass } from '../../'; +import { MS_CONSUMER_KEY, attachPropertyDataToClass } from '../'; export interface RabbitMQListenerOptions { propertyKey?: string; diff --git a/packages/core/src/decorator/rpc/hsf.ts b/packages/core/src/decorator/rpc/hsf.ts index a1d4a5941719..1692ad0b61a6 100644 --- a/packages/core/src/decorator/rpc/hsf.ts +++ b/packages/core/src/decorator/rpc/hsf.ts @@ -4,8 +4,8 @@ import { saveModule, HSF_KEY, Provide, -} from '../../'; -import { Scope } from '../'; + Scope, +} from '../'; export interface HSFOpts { interfaceName?: string; diff --git a/packages/core/src/decorator/task/queue.ts b/packages/core/src/decorator/task/queue.ts index 68f51cf27f37..60513572b774 100644 --- a/packages/core/src/decorator/task/queue.ts +++ b/packages/core/src/decorator/task/queue.ts @@ -1,4 +1,4 @@ -import { saveModule, saveClassMetadata, Provide } from '../../'; +import { saveModule, saveClassMetadata, Provide } from '../'; import { MODULE_TASK_QUEUE_KEY, MODULE_TASK_QUEUE_OPTIONS } from '../constant'; export function Queue(options?: any): ClassDecorator { diff --git a/packages/core/src/decorator/task/schedule.ts b/packages/core/src/decorator/task/schedule.ts index 88cb58e61fa3..20309fa56355 100644 --- a/packages/core/src/decorator/task/schedule.ts +++ b/packages/core/src/decorator/task/schedule.ts @@ -5,7 +5,7 @@ import { SCHEDULE_KEY, Provide, Scope, -} from '../../'; +} from '../'; export interface CommonSchedule { exec(ctx?); diff --git a/packages/core/src/decorator/task/task.ts b/packages/core/src/decorator/task/task.ts index ab0f302d48c0..3ef675030525 100644 --- a/packages/core/src/decorator/task/task.ts +++ b/packages/core/src/decorator/task/task.ts @@ -1,4 +1,4 @@ -import { saveModule, attachClassMetadata } from '../../'; +import { saveModule, attachClassMetadata } from '../'; import { MODULE_TASK_KEY, MODULE_TASK_METADATA } from '../constant'; export function Task(options) { diff --git a/packages/core/src/decorator/task/taskLocal.ts b/packages/core/src/decorator/task/taskLocal.ts index 147a76aca50c..c0d98712bd59 100644 --- a/packages/core/src/decorator/task/taskLocal.ts +++ b/packages/core/src/decorator/task/taskLocal.ts @@ -1,4 +1,4 @@ -import { saveModule, attachClassMetadata } from '../../'; +import { saveModule, attachClassMetadata } from '../'; import { MODULE_TASK_TASK_LOCAL_KEY, MODULE_TASK_TASK_LOCAL_OPTIONS, diff --git a/packages/core/src/decorator/ws/webSocketController.ts b/packages/core/src/decorator/ws/webSocketController.ts index 011fe2cba29f..a948264d0a4e 100644 --- a/packages/core/src/decorator/ws/webSocketController.ts +++ b/packages/core/src/decorator/ws/webSocketController.ts @@ -6,7 +6,7 @@ import { Provide, Scope, MiddlewareParamArray, -} from '../../'; +} from '../'; export interface WSControllerOption { namespace: string; diff --git a/packages/core/src/decorator/ws/webSocketEvent.ts b/packages/core/src/decorator/ws/webSocketEvent.ts index 71fca06eb302..f77929f54767 100644 --- a/packages/core/src/decorator/ws/webSocketEvent.ts +++ b/packages/core/src/decorator/ws/webSocketEvent.ts @@ -1,8 +1,4 @@ -import { - WS_EVENT_KEY, - attachClassMetadata, - MiddlewareParamArray, -} from '../../'; +import { WS_EVENT_KEY, attachClassMetadata, MiddlewareParamArray } from '../'; export enum WSEventTypeEnum { ON_CONNECTION = 'ws:onConnection', diff --git a/packages/core/src/definitions/objectCreator.ts b/packages/core/src/definitions/objectCreator.ts index 25157caad5a5..390f711132f6 100644 --- a/packages/core/src/definitions/objectCreator.ts +++ b/packages/core/src/definitions/objectCreator.ts @@ -1,4 +1,4 @@ -import { IObjectCreator, IObjectDefinition } from '../interface'; +import type { IObjectCreator, IObjectDefinition } from '../interface'; import { MidwayUseWrongMethodError } from '../error'; import { Types } from '../util/types'; diff --git a/packages/core/src/error/framework.ts b/packages/core/src/error/framework.ts index 3640a0ae9843..ba494c6113e0 100644 --- a/packages/core/src/error/framework.ts +++ b/packages/core/src/error/framework.ts @@ -20,6 +20,7 @@ export const FrameworkErrorEnum = registerErrorCode('midway', { DUPLICATE_CLASS_NAME: 10015, DUPLICATE_CONTROLLER_PREFIX_OPTIONS: 10016, RETRY_OVER_MAX_TIME: 10017, + INVOKE_METHOD_FORBIDDEN: 10018, } as const); export class MidwayCommonError extends MidwayError { @@ -97,7 +98,7 @@ export class MidwayInvalidConfigError extends MidwayError { export class MidwayResolverMissingError extends MidwayError { constructor(type: string) { super( - `${type} resolver is not exists!`, + `Resolver "${type}" is missing.`, FrameworkErrorEnum.MISSING_RESOLVER ); } @@ -186,3 +187,14 @@ export class MidwayRetryExceededMaxTimesError extends MidwayError { ); } } + +export class MidwayInvokeForbiddenError extends MidwayError { + constructor(methodName: string, module?: any) { + super( + `Invoke "${ + module ? module.name : 'unknown' + }.${methodName}" is forbidden.`, + FrameworkErrorEnum.INVOKE_METHOD_FORBIDDEN + ); + } +} diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index a5983762015d..e5840b69a1ca 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -3,7 +3,7 @@ export * from './context/container'; export { MidwayRequestContainer } from './context/requestContainer'; export { BaseFramework } from './baseFramework'; export * from './context/providerWrapper'; -export * from './common/constants'; +export * from './constants'; export { createConfiguration, FunctionalConfiguration, diff --git a/packages/core/src/interface.ts b/packages/core/src/interface.ts index 8d1fec38abdf..fc6005a127ef 100644 --- a/packages/core/src/interface.ts +++ b/packages/core/src/interface.ts @@ -1,11 +1,19 @@ import type { ILogger, LoggerOptions, LoggerContextFormat } from '@midwayjs/logger'; import * as EventEmitter from 'events'; -import _default from './config/config.default'; -import type { ContextMiddlewareManager } from './common/middlewareManager'; import type { AsyncContextManager } from './common/asyncContextManager'; import type { IManagedInstance, IMethodAspect, ObjectIdentifier } from './decorator'; import { FrameworkType, ScopeEnum } from './decorator'; +export interface MidwayCoreDefaultConfig { + midwayLogger?: ServiceFactoryConfigOption; + debug?: { + recordConfigMergeOrder?: boolean; + }; + asyncContextManager: { + enable: boolean; + }; +} + export type PowerPartial = { [U in keyof T]?: T[U] extends {} ? PowerPartial : T[U]; }; @@ -253,11 +261,6 @@ export interface IManagedResolverFactoryCreateOptions { namespace?: string; } -export const REQUEST_CTX_KEY = 'ctx'; -export const REQUEST_OBJ_CTX_KEY = '_req_ctx'; -export const HTTP_SERVER_KEY = '_midway_http_server'; -export const REQUEST_CTX_LOGGER_CACHE_KEY = '_midway_ctx_logger_cache'; - export type HandlerFunction = ( /** * decorator uuid key @@ -429,6 +432,57 @@ export type CommonFilterUnion = | (new (...args) => IFilter) | Array IFilter>; +/** + * Guard definition + */ +export interface IGuard { + canActivate(ctx: CTX, supplierClz: new (...args) => any, methodName: string): boolean | Promise; +} + +export type CommonGuardUnion = + | (new (...args) => IGuard) + | Array IGuard>; + +export interface IMiddlewareManager { + insertFirst(middleware: CommonMiddlewareUnion): void; + insertLast(middleware: CommonMiddlewareUnion): void; + insertBefore( + middleware: CommonMiddlewareUnion, + idxOrBeforeMiddleware: CommonMiddleware | string | number + ): void; + insertAfter( + middleware: CommonMiddlewareUnion, + idxOrAfterMiddleware: CommonMiddleware | string | number + ): void; + findAndInsertAfter( + middlewareOrName: CommonMiddleware | string, + afterMiddleware: CommonMiddleware | string | number + ): void; + findAndInsertBefore( + middlewareOrName: CommonMiddleware | string, + beforeMiddleware: CommonMiddleware | string | number + ): void; + findAndInsertFirst( + middlewareOrName: CommonMiddleware | string + ): void; + findAndInsertLast( + middlewareOrName: CommonMiddleware | string + ): void; + findItemIndex( + middlewareOrName: CommonMiddleware | string | number + ): number; + findItem( + middlewareOrName: CommonMiddleware | string | number + ): CommonMiddleware; + getMiddlewareName(middleware: CommonMiddleware): string; + remove( + middlewareOrNameOrIdx: CommonMiddleware | string | number + ): CommonMiddleware; + push(...items: CommonMiddleware[]): number; + unshift(...items: CommonMiddleware[]): number; + getNames(): string[]; +} + export interface IMidwayBaseApplication { /** * Get a base directory for project, with src or dist @@ -445,6 +499,11 @@ export interface IMidwayBaseApplication { */ getEnv(): string; + /** + * get current related framework + */ + getFramework(): IMidwayFramework; + /** * @deprecated * Get current framework type in MidwayFrameworkType enum @@ -530,13 +589,19 @@ export interface IMidwayBaseApplication { /** * get global middleware */ - getMiddleware(): ContextMiddlewareManager; + getMiddleware(): IMiddlewareManager; /** * add exception filter * @param Filter */ useFilter(Filter: CommonFilterUnion): void; + + /** + * add global guard + * @param guard + */ + useGuard(guard: CommonGuardUnion): void; } export type IMidwayApplication< @@ -597,14 +662,16 @@ export interface IMidwayFramework< createLogger(name: string, options: LoggerOptions): ILogger; getProjectName(): string; useMiddleware(Middleware: CommonMiddlewareUnion): void; - getMiddleware(): ContextMiddlewareManager; + getMiddleware(): IMiddlewareManager; applyMiddleware( lastMiddleware?: CommonMiddlewareUnion ): Promise>; - useFilter(Filter: CommonFilterUnion); + useFilter(Filter: CommonFilterUnion): void; + useGuard(guard: CommonGuardUnion): void; + runGuard(ctx: CTX, supplierClz: new (...args) => any, methodName: string): Promise; } -export const MIDWAY_LOGGER_WRITEABLE_DIR = 'MIDWAY_LOGGER_WRITEABLE_DIR'; + export interface MidwayAppInfo { pkg: Record; @@ -619,20 +686,6 @@ export interface MidwayAppInfo { /** * midway global config definition */ -export interface MidwayConfig extends FileConfigOption { +export interface MidwayConfig extends FileConfigOption { [customConfigKey: string]: unknown; } - -export const ASYNC_CONTEXT_KEY = Symbol('ASYNC_CONTEXT_KEY'); -export const ASYNC_CONTEXT_MANAGER_KEY = 'MIDWAY_ASYNC_CONTEXT_MANAGER_KEY'; - -export const DEFAULT_PATTERN = [ - '**/**.ts', - '**/**.js', - '**/**.mts', - '**/**.mjs', - '**/**.cts', - '**/**.cjs' -]; - -export const IGNORE_PATTERN = ['**/**.d.ts', '**/**.d.mts', '**/**.d.cts']; diff --git a/packages/core/src/service/frameworkService.ts b/packages/core/src/service/frameworkService.ts index aa767ac00f16..6972165d3caf 100644 --- a/packages/core/src/service/frameworkService.ts +++ b/packages/core/src/service/frameworkService.ts @@ -15,11 +15,7 @@ import { ScopeEnum, MidwayFrameworkType, } from '../decorator'; -import { - IMidwayContainer, - IMidwayFramework, - REQUEST_OBJ_CTX_KEY, -} from '../interface'; +import { IMidwayContainer, IMidwayFramework } from '../interface'; import { MidwayConfigService } from './configService'; import { MidwayLoggerService } from './loggerService'; import { BaseFramework } from '../baseFramework'; @@ -29,6 +25,7 @@ import { MidwayAspectService } from './aspectService'; import { MidwayApplicationManager } from '../common/applicationManager'; import * as util from 'util'; import { MidwayCommonError } from '../error'; +import { REQUEST_OBJ_CTX_KEY } from '../constants'; const debug = util.debuglog('midway:debug'); diff --git a/packages/core/src/service/webRouterService.ts b/packages/core/src/service/webRouterService.ts index da0de42974fe..01e77abf2bec 100644 --- a/packages/core/src/service/webRouterService.ts +++ b/packages/core/src/service/webRouterService.ts @@ -74,6 +74,10 @@ export interface RouterInfo { * controller provideId */ controllerId?: string; + /** + * controller class + */ + controllerClz?: new (...args) => any; /** * router middleware */ @@ -309,6 +313,7 @@ export class MidwayWebRouterService { handlerName: `${controllerId}.${webRouter.method}`, funcHandlerName: `${controllerId}.${webRouter.method}`, controllerId, + controllerClz, middleware: webRouter.middleware || [], controllerMiddleware: middleware || [], requestMetadata: routeArgsInfo, diff --git a/packages/core/src/util/contextUtil.ts b/packages/core/src/util/contextUtil.ts index 972646ae7e0f..69f3bc0c00e2 100644 --- a/packages/core/src/util/contextUtil.ts +++ b/packages/core/src/util/contextUtil.ts @@ -4,9 +4,9 @@ import { IMidwayContainer, IMidwayFramework, IMidwayContext, - ASYNC_CONTEXT_MANAGER_KEY, } from '../interface'; import { AsyncContextManager } from '../common/asyncContextManager'; +import { ASYNC_CONTEXT_MANAGER_KEY } from '../constants'; export const getCurrentApplicationContext = (): IMidwayContainer => { return global['MIDWAY_APPLICATION_CONTEXT']; diff --git a/packages/core/src/util/uuid.ts b/packages/core/src/util/uuid.ts index f274ad39720c..a609713dd7b3 100644 --- a/packages/core/src/util/uuid.ts +++ b/packages/core/src/util/uuid.ts @@ -54,9 +54,9 @@ function unsafeStringify(arr, offset = 0) { /** * a easy uuid v4 generator */ -export function randomUUID(): string { +export function randomUUID(force?: boolean): string { // node > v14.17 - if (crypto['randomUUID']) { + if (!force && crypto['randomUUID']) { return crypto['randomUUID'](); } const rnds = rng(); diff --git a/packages/core/test/baseFramework.test.ts b/packages/core/test/baseFramework.test.ts index cb2cf7897c3a..8bc60af6d594 100644 --- a/packages/core/test/baseFramework.test.ts +++ b/packages/core/test/baseFramework.test.ts @@ -690,4 +690,15 @@ describe('/test/baseFramework.test.ts', () => { expect(ctxLogger1).toBeDefined(); expect(ctxLogger1 === ctxLogger2).toBeTruthy(); }); + + it('should test use guard', async () => { + const framework = await createLightFramework(path.join( + __dirname, + './fixtures/base-app-with-guard/src' + )); + + const app = framework.getApplication() as IMidwayApplication; + expect(app.getAttr('invokeResult')).toEqual(true); + expect(app.getAttr('invoke2Result')).toEqual(false); + }); }); diff --git a/packages/core/test/decorator/util/uuid.test.ts b/packages/core/test/decorator/util/uuid.test.ts index 220e42e6c4f9..9a278a2f72ae 100644 --- a/packages/core/test/decorator/util/uuid.test.ts +++ b/packages/core/test/decorator/util/uuid.test.ts @@ -7,5 +7,9 @@ describe('test/util/uuid.test.ts', () => { const id1 = Utils.randomUUID(); const id2 = Utils.randomUUID(); assert(id1 !== id2); + + const id3 = Utils.randomUUID(true); + const id4 = Utils.randomUUID(true); + assert(id3 !== id4); }); }); diff --git a/packages/core/test/error/framework.test.ts b/packages/core/test/error/framework.test.ts new file mode 100644 index 000000000000..9431e8b08e86 --- /dev/null +++ b/packages/core/test/error/framework.test.ts @@ -0,0 +1,52 @@ +import { + FrameworkErrorEnum, MidwayConfigMissingError, MidwayFeatureNoLongerSupportedError, MidwayFeatureNotImplementedError, + MidwayInconsistentVersionError, + MidwayInvokeForbiddenError, + MidwayResolverMissingError +} from '../../src'; + +describe('/test/error/framework.test.ts', function () { + it('should test MidwayInvokeForbiddenError', function () { + const err = new MidwayInvokeForbiddenError('invoke'); + expect(err.message).toEqual('Invoke "unknown.invoke" is forbidden.'); + expect(err.code).toEqual(FrameworkErrorEnum.INVOKE_METHOD_FORBIDDEN); + + class TestModule { + invoke() {} + } + const err1 = new MidwayInvokeForbiddenError('invoke', TestModule); + expect(err1.message).toEqual('Invoke "TestModule.invoke" is forbidden.'); + }); + + it('should test MidwayInconsistentVersionError', function () { + const err = new MidwayInconsistentVersionError() + expect(err.message).toEqual('We find a latest dependency package installed, please remove the lock file and use "npm update" to upgrade all dependencies first.'); + expect(err.code).toEqual(FrameworkErrorEnum.INCONSISTENT_VERSION); + }); + + it('should test MidwayResolverMissingError', function () { + const err = new MidwayResolverMissingError('test'); + expect(err.message).toEqual('Resolver "test" is missing.'); + expect(err.code).toEqual(FrameworkErrorEnum.MISSING_RESOLVER); + }); + + it('should test MidwayConfigMissingError', function () { + const err = new MidwayConfigMissingError('test'); + expect(err.message).toEqual('Can\'t found config key "test" in your config, please set it first'); + expect(err.code).toEqual(FrameworkErrorEnum.MISSING_CONFIG); + }); + + it('should test MidwayFeatureNotImplementedError', function () { + const err = new MidwayFeatureNotImplementedError('test'); + expect(err.message).toEqual('This feature not implemented \n' + + 'test'); + expect(err.code).toEqual(FrameworkErrorEnum.FEATURE_NOT_IMPLEMENTED); + }); + + it('should test MidwayFeatureNoLongerSupportedError', function () { + const err = new MidwayFeatureNoLongerSupportedError('test'); + expect(err.message).toEqual('This feature no longer supported \n' + + 'test'); + expect(err.code).toEqual(FrameworkErrorEnum.FEATURE_NO_LONGER_SUPPORTED); + }); +}); diff --git a/packages/core/test/fixtures/base-app-multi-framework-shared/src/framework.ts b/packages/core/test/fixtures/base-app-multi-framework-shared/src/framework.ts index cd8bb30b9d65..7d6c00bf7cf9 100644 --- a/packages/core/test/fixtures/base-app-multi-framework-shared/src/framework.ts +++ b/packages/core/test/fixtures/base-app-multi-framework-shared/src/framework.ts @@ -1,4 +1,4 @@ -import { Framework, MidwayFrameworkType } from '../../../../src'; +import { CommonGuardUnion, Framework, MidwayFrameworkType } from '../../../../src'; import { BaseFramework, CommonFilterUnion, @@ -42,8 +42,14 @@ export class CustomTwoFramework extends LightFramework { @Framework() export class CustomThirdFramework implements IMidwayFramework { + useGuard(guard: CommonGuardUnion): void { + throw new Error('Method not implemented.'); + } + runGuard(ctx: any, supplierClz: new (...args: any[]) => any, methodName: string): Promise { + throw new Error('Method not implemented.'); + } getMiddleware(): ContextMiddlewareManager { - throw new Error('Method not implemented.'); + throw new Error('Method not implemented.'); } isEnable(): boolean { return true; diff --git a/packages/core/test/fixtures/base-app-with-guard/package.json b/packages/core/test/fixtures/base-app-with-guard/package.json new file mode 100644 index 000000000000..621cdc6a4174 --- /dev/null +++ b/packages/core/test/fixtures/base-app-with-guard/package.json @@ -0,0 +1,3 @@ +{ + "name": "ali-demo" +} diff --git a/packages/core/test/fixtures/base-app-with-guard/src/config/config.default.ts b/packages/core/test/fixtures/base-app-with-guard/src/config/config.default.ts new file mode 100644 index 000000000000..ad227ab0d36b --- /dev/null +++ b/packages/core/test/fixtures/base-app-with-guard/src/config/config.default.ts @@ -0,0 +1,13 @@ +'use strict'; + +export const keys = 'key'; + +export const hello = { + a: 1, + b: 2, + d: [1, 2, 3], +}; + +export const plugins = { + bucLogin: false, +}; diff --git a/packages/core/test/fixtures/base-app-with-guard/src/config/config.unittest.ts b/packages/core/test/fixtures/base-app-with-guard/src/config/config.unittest.ts new file mode 100644 index 000000000000..764021a2a8b6 --- /dev/null +++ b/packages/core/test/fixtures/base-app-with-guard/src/config/config.unittest.ts @@ -0,0 +1,5 @@ + +exports.hello = { + b: 4, + c: 3, +}; diff --git a/packages/core/test/fixtures/base-app-with-guard/src/configuration.ts b/packages/core/test/fixtures/base-app-with-guard/src/configuration.ts new file mode 100644 index 000000000000..7f32021366f1 --- /dev/null +++ b/packages/core/test/fixtures/base-app-with-guard/src/configuration.ts @@ -0,0 +1,69 @@ +import { + App, + Configuration, + Guard, + IGuard, + IMidwayApplication, + Provide, + UseGuard +} from '../../../../src'; + +@Guard() +export class MainGuard implements IGuard { + async canActivate(ctx: any): Promise { + return true; + } +} + +@Guard() +export class Main2Guard implements IGuard { + async canActivate(ctx: any): Promise { + return true; + } +} + +@Guard() +export class ClzGuard implements IGuard { + async canActivate(ctx: any): Promise { + return true; + } +} + +@Guard() +export class MethodGuard implements IGuard { + async canActivate(ctx: any): Promise { + return false; + } +} + +@Provide() +@UseGuard(ClzGuard) +export class UserService { + async invoke() { + return 'hello invoke'; + } + + @UseGuard(MethodGuard) + async invoke2() { + return 'hello invoke2'; + } +} + +@Configuration() +export class MainConfiguration { + @App() + app: IMidwayApplication; + + async onReady() { + this.app.useGuard(MainGuard); + this.app.useGuard([Main2Guard]); + + const ctx = this.app.createAnonymousContext(); + const invokeResult = await this.app.getFramework().runGuard(ctx, UserService, 'invoke'); + + this.app.setAttr('invokeResult', invokeResult); + + const invoke2Result = await this.app.getFramework().runGuard(ctx, UserService, 'invoke2'); + this.app.setAttr('invoke2Result', invoke2Result); + } +} diff --git a/packages/core/test/service/__snapshots__/slsFunctionService.test.ts.snap b/packages/core/test/service/__snapshots__/slsFunctionService.test.ts.snap index 6346c004dabb..dce48fe1655c 100644 --- a/packages/core/test/service/__snapshots__/slsFunctionService.test.ts.snap +++ b/packages/core/test/service/__snapshots__/slsFunctionService.test.ts.snap @@ -73,6 +73,7 @@ Array [ "_paramString": "", "_pureRouter": "/", "_weight": 0, + "controllerClz": [Function], "controllerId": "apiController", "controllerMiddleware": Array [ "auth", diff --git a/packages/cos/jest.config.js b/packages/cos/jest.config.js index 34f2d767cd51..0245a5110fa2 100644 --- a/packages/cos/jest.config.js +++ b/packages/cos/jest.config.js @@ -2,6 +2,6 @@ module.exports = { preset: 'ts-jest', testEnvironment: 'node', testPathIgnorePatterns: ['/test/fixtures'], - coveragePathIgnorePatterns: ['/test/'], + coveragePathIgnorePatterns: ['/test/', '/dist/'], setupFilesAfterEnv: ['./jest.setup.js'], }; diff --git a/packages/cross-domain/jest.config.js b/packages/cross-domain/jest.config.js index 34f2d767cd51..0245a5110fa2 100644 --- a/packages/cross-domain/jest.config.js +++ b/packages/cross-domain/jest.config.js @@ -2,6 +2,6 @@ module.exports = { preset: 'ts-jest', testEnvironment: 'node', testPathIgnorePatterns: ['/test/fixtures'], - coveragePathIgnorePatterns: ['/test/'], + coveragePathIgnorePatterns: ['/test/', '/dist/'], setupFilesAfterEnv: ['./jest.setup.js'], }; diff --git a/packages/decorator/jest.config.js b/packages/decorator/jest.config.js index 34f2d767cd51..0245a5110fa2 100644 --- a/packages/decorator/jest.config.js +++ b/packages/decorator/jest.config.js @@ -2,6 +2,6 @@ module.exports = { preset: 'ts-jest', testEnvironment: 'node', testPathIgnorePatterns: ['/test/fixtures'], - coveragePathIgnorePatterns: ['/test/'], + coveragePathIgnorePatterns: ['/test/', '/dist/'], setupFilesAfterEnv: ['./jest.setup.js'], }; diff --git a/packages/express-session/jest.config.js b/packages/express-session/jest.config.js index 677350be15a8..f1b3df7d4719 100644 --- a/packages/express-session/jest.config.js +++ b/packages/express-session/jest.config.js @@ -2,7 +2,7 @@ module.exports = { preset: 'ts-jest', testEnvironment: 'node', testPathIgnorePatterns: ['/test/fixtures'], - coveragePathIgnorePatterns: ['/test/'], + coveragePathIgnorePatterns: ['/test/', '/dist/'], setupFilesAfterEnv: ['./jest.setup.js'], globals: { 'ts-jest': { diff --git a/packages/faas/jest.config.js b/packages/faas/jest.config.js index 34f2d767cd51..0245a5110fa2 100644 --- a/packages/faas/jest.config.js +++ b/packages/faas/jest.config.js @@ -2,6 +2,6 @@ module.exports = { preset: 'ts-jest', testEnvironment: 'node', testPathIgnorePatterns: ['/test/fixtures'], - coveragePathIgnorePatterns: ['/test/'], + coveragePathIgnorePatterns: ['/test/', '/dist/'], setupFilesAfterEnv: ['./jest.setup.js'], }; diff --git a/packages/faas/src/framework.ts b/packages/faas/src/framework.ts index 789f783487d9..c4b3e4bae147 100644 --- a/packages/faas/src/framework.ts +++ b/packages/faas/src/framework.ts @@ -23,6 +23,7 @@ import { WEB_RESPONSE_HEADER, WEB_RESPONSE_HTTP_CODE, WEB_RESPONSE_REDIRECT, + httpError, } from '@midwayjs/core'; import SimpleLock from '@midwayjs/simple-lock'; import { createConsoleLogger, LoggerOptions, loggers } from '@midwayjs/logger'; @@ -218,6 +219,18 @@ export class MidwayFaaSFramework extends BaseFramework< ...funOptions.controllerMiddleware, ...funOptions.middleware, async (ctx, next) => { + if ( + funOptions.controllerClz && + typeof funOptions.method === 'string' + ) { + const isPassed = await this.app + .getFramework() + .runGuard(ctx, funOptions.controllerClz, funOptions.method); + if (!isPassed) { + throw new httpError.ForbiddenError(); + } + } + if (isHttpFunction) { args = [ctx]; } diff --git a/packages/grpc/jest.config.js b/packages/grpc/jest.config.js index 34f2d767cd51..0245a5110fa2 100644 --- a/packages/grpc/jest.config.js +++ b/packages/grpc/jest.config.js @@ -2,6 +2,6 @@ module.exports = { preset: 'ts-jest', testEnvironment: 'node', testPathIgnorePatterns: ['/test/fixtures'], - coveragePathIgnorePatterns: ['/test/'], + coveragePathIgnorePatterns: ['/test/', '/dist/'], setupFilesAfterEnv: ['./jest.setup.js'], }; diff --git a/packages/grpc/src/provider/framework.ts b/packages/grpc/src/provider/framework.ts index c8da789b87fd..d11b4ebe79cd 100644 --- a/packages/grpc/src/provider/framework.ts +++ b/packages/grpc/src/provider/framework.ts @@ -24,6 +24,7 @@ import { IMidwayBootstrapOptions, MidwayCommonError, MidwayFrameworkType, + MidwayInvokeForbiddenError, } from '@midwayjs/core'; import { Context, @@ -133,9 +134,6 @@ export class MidwayGRPCFramework extends BaseFramework< ctx.method = method; this.app.createAnonymousContext(ctx); - // get service from request container - const service = await ctx.requestContext.getAsync(module); - // get metadata from decorator const grpcMethodData: { methodName: string; @@ -147,6 +145,16 @@ export class MidwayGRPCFramework extends BaseFramework< Utils.camelCase(method) ); + const isPassed = await this.app + .getFramework() + .runGuard(ctx, module, ctx.method); + if (!isPassed) { + throw new MidwayInvokeForbiddenError(ctx.method, module); + } + + // get service from request container + const service = await ctx.requestContext.getAsync(module); + if ( grpcMethodData.type === GrpcStreamTypeEnum.DUPLEX || grpcMethodData.type === GrpcStreamTypeEnum.READABLE diff --git a/packages/http-proxy/jest.config.js b/packages/http-proxy/jest.config.js index 34f2d767cd51..0245a5110fa2 100644 --- a/packages/http-proxy/jest.config.js +++ b/packages/http-proxy/jest.config.js @@ -2,6 +2,6 @@ module.exports = { preset: 'ts-jest', testEnvironment: 'node', testPathIgnorePatterns: ['/test/fixtures'], - coveragePathIgnorePatterns: ['/test/'], + coveragePathIgnorePatterns: ['/test/', '/dist/'], setupFilesAfterEnv: ['./jest.setup.js'], }; diff --git a/packages/i18n/jest.config.js b/packages/i18n/jest.config.js index 34f2d767cd51..0245a5110fa2 100644 --- a/packages/i18n/jest.config.js +++ b/packages/i18n/jest.config.js @@ -2,6 +2,6 @@ module.exports = { preset: 'ts-jest', testEnvironment: 'node', testPathIgnorePatterns: ['/test/fixtures'], - coveragePathIgnorePatterns: ['/test/'], + coveragePathIgnorePatterns: ['/test/', '/dist/'], setupFilesAfterEnv: ['./jest.setup.js'], }; diff --git a/packages/info/jest.config.js b/packages/info/jest.config.js index 34f2d767cd51..0245a5110fa2 100644 --- a/packages/info/jest.config.js +++ b/packages/info/jest.config.js @@ -2,6 +2,6 @@ module.exports = { preset: 'ts-jest', testEnvironment: 'node', testPathIgnorePatterns: ['/test/fixtures'], - coveragePathIgnorePatterns: ['/test/'], + coveragePathIgnorePatterns: ['/test/', '/dist/'], setupFilesAfterEnv: ['./jest.setup.js'], }; diff --git a/packages/jwt/jest.config.js b/packages/jwt/jest.config.js index 677350be15a8..f1b3df7d4719 100644 --- a/packages/jwt/jest.config.js +++ b/packages/jwt/jest.config.js @@ -2,7 +2,7 @@ module.exports = { preset: 'ts-jest', testEnvironment: 'node', testPathIgnorePatterns: ['/test/fixtures'], - coveragePathIgnorePatterns: ['/test/'], + coveragePathIgnorePatterns: ['/test/', '/dist/'], setupFilesAfterEnv: ['./jest.setup.js'], globals: { 'ts-jest': { diff --git a/packages/kafka/jest.config.js b/packages/kafka/jest.config.js index 0968eff5fb41..0245a5110fa2 100644 --- a/packages/kafka/jest.config.js +++ b/packages/kafka/jest.config.js @@ -2,6 +2,6 @@ module.exports = { preset: 'ts-jest', testEnvironment: 'node', testPathIgnorePatterns: ['/test/fixtures'], - coveragePathIgnorePatterns: ['/test/'], + coveragePathIgnorePatterns: ['/test/', '/dist/'], setupFilesAfterEnv: ['./jest.setup.js'], -}; \ No newline at end of file +}; diff --git a/packages/kafka/src/framework.ts b/packages/kafka/src/framework.ts index 2b62c3e8a1dc..187d8668847b 100644 --- a/packages/kafka/src/framework.ts +++ b/packages/kafka/src/framework.ts @@ -8,6 +8,7 @@ import { MidwayFrameworkType, MSListenerType, MS_CONSUMER_KEY, + MidwayInvokeForbiddenError, } from '@midwayjs/core'; import { IMidwayConsumerConfig, @@ -63,7 +64,7 @@ export class MidwayKafkaFramework extends BaseFramework { runConfig: {}, }; - const comsumerParams = data + const consumerParams = data .map(value => { if (value[0].topic === midwayConsumerConfig.topic) { return Object.assign(midwayConsumerConfig, value[0]); @@ -71,8 +72,8 @@ export class MidwayKafkaFramework extends BaseFramework { }) .filter(e => e && true); - if (comsumerParams && Object.keys(comsumerParams[0]).length > 0) { - return comsumerParams[0]; + if (consumerParams && Object.keys(consumerParams[0]).length > 0) { + return consumerParams[0]; } return midwayConsumerConfig; } @@ -110,6 +111,18 @@ export class MidwayKafkaFramework extends BaseFramework { }, } as unknown as IMidwayKafkaContext; this.app.createAnonymousContext(ctx); + + if (typeof propertyKey === 'string') { + const isPassed = await this.app + .getFramework() + .runGuard(ctx, module, propertyKey); + if (!isPassed) { + throw new MidwayInvokeForbiddenError( + propertyKey, + module + ); + } + } const ins = await ctx.requestContext.getAsync(module); const fn = await this.applyMiddleware(async () => { return await ins[propertyKey].call(ins, message); diff --git a/packages/mikro/jest.config.js b/packages/mikro/jest.config.js index 34f2d767cd51..0245a5110fa2 100644 --- a/packages/mikro/jest.config.js +++ b/packages/mikro/jest.config.js @@ -2,6 +2,6 @@ module.exports = { preset: 'ts-jest', testEnvironment: 'node', testPathIgnorePatterns: ['/test/fixtures'], - coveragePathIgnorePatterns: ['/test/'], + coveragePathIgnorePatterns: ['/test/', '/dist/'], setupFilesAfterEnv: ['./jest.setup.js'], }; diff --git a/packages/mock/jest.config.js b/packages/mock/jest.config.js index 34f2d767cd51..0245a5110fa2 100644 --- a/packages/mock/jest.config.js +++ b/packages/mock/jest.config.js @@ -2,6 +2,6 @@ module.exports = { preset: 'ts-jest', testEnvironment: 'node', testPathIgnorePatterns: ['/test/fixtures'], - coveragePathIgnorePatterns: ['/test/'], + coveragePathIgnorePatterns: ['/test/', '/dist/'], setupFilesAfterEnv: ['./jest.setup.js'], }; diff --git a/packages/mongoose/jest.config.js b/packages/mongoose/jest.config.js index 34f2d767cd51..0245a5110fa2 100644 --- a/packages/mongoose/jest.config.js +++ b/packages/mongoose/jest.config.js @@ -2,6 +2,6 @@ module.exports = { preset: 'ts-jest', testEnvironment: 'node', testPathIgnorePatterns: ['/test/fixtures'], - coveragePathIgnorePatterns: ['/test/'], + coveragePathIgnorePatterns: ['/test/', '/dist/'], setupFilesAfterEnv: ['./jest.setup.js'], }; diff --git a/packages/oss/jest.config.js b/packages/oss/jest.config.js index 34f2d767cd51..0245a5110fa2 100644 --- a/packages/oss/jest.config.js +++ b/packages/oss/jest.config.js @@ -2,6 +2,6 @@ module.exports = { preset: 'ts-jest', testEnvironment: 'node', testPathIgnorePatterns: ['/test/fixtures'], - coveragePathIgnorePatterns: ['/test/'], + coveragePathIgnorePatterns: ['/test/', '/dist/'], setupFilesAfterEnv: ['./jest.setup.js'], }; diff --git a/packages/otel/jest.config.js b/packages/otel/jest.config.js index 34f2d767cd51..0245a5110fa2 100644 --- a/packages/otel/jest.config.js +++ b/packages/otel/jest.config.js @@ -2,6 +2,6 @@ module.exports = { preset: 'ts-jest', testEnvironment: 'node', testPathIgnorePatterns: ['/test/fixtures'], - coveragePathIgnorePatterns: ['/test/'], + coveragePathIgnorePatterns: ['/test/', '/dist/'], setupFilesAfterEnv: ['./jest.setup.js'], }; diff --git a/packages/passport/jest.config.js b/packages/passport/jest.config.js index 677350be15a8..f1b3df7d4719 100644 --- a/packages/passport/jest.config.js +++ b/packages/passport/jest.config.js @@ -2,7 +2,7 @@ module.exports = { preset: 'ts-jest', testEnvironment: 'node', testPathIgnorePatterns: ['/test/fixtures'], - coveragePathIgnorePatterns: ['/test/'], + coveragePathIgnorePatterns: ['/test/', '/dist/'], setupFilesAfterEnv: ['./jest.setup.js'], globals: { 'ts-jest': { diff --git a/packages/processAgent/jest.config.js b/packages/processAgent/jest.config.js index 82a8b8501009..7afe809a9e39 100644 --- a/packages/processAgent/jest.config.js +++ b/packages/processAgent/jest.config.js @@ -2,6 +2,6 @@ module.exports = { preset: 'ts-jest', testEnvironment: 'node', testPathIgnorePatterns: ['/test/fixtures'], - coveragePathIgnorePatterns: ['/test/'], + coveragePathIgnorePatterns: ['/test/', '/dist/'], setupFilesAfterEnv: ['./jest.setup.js'] }; diff --git a/packages/prometheus-socket-io/jest.config.js b/packages/prometheus-socket-io/jest.config.js index 34f2d767cd51..0245a5110fa2 100644 --- a/packages/prometheus-socket-io/jest.config.js +++ b/packages/prometheus-socket-io/jest.config.js @@ -2,6 +2,6 @@ module.exports = { preset: 'ts-jest', testEnvironment: 'node', testPathIgnorePatterns: ['/test/fixtures'], - coveragePathIgnorePatterns: ['/test/'], + coveragePathIgnorePatterns: ['/test/', '/dist/'], setupFilesAfterEnv: ['./jest.setup.js'], }; diff --git a/packages/prometheus/jest.config.js b/packages/prometheus/jest.config.js index 34f2d767cd51..0245a5110fa2 100644 --- a/packages/prometheus/jest.config.js +++ b/packages/prometheus/jest.config.js @@ -2,6 +2,6 @@ module.exports = { preset: 'ts-jest', testEnvironment: 'node', testPathIgnorePatterns: ['/test/fixtures'], - coveragePathIgnorePatterns: ['/test/'], + coveragePathIgnorePatterns: ['/test/', '/dist/'], setupFilesAfterEnv: ['./jest.setup.js'], }; diff --git a/packages/rabbitmq/jest.config.js b/packages/rabbitmq/jest.config.js index 34f2d767cd51..0245a5110fa2 100644 --- a/packages/rabbitmq/jest.config.js +++ b/packages/rabbitmq/jest.config.js @@ -2,6 +2,6 @@ module.exports = { preset: 'ts-jest', testEnvironment: 'node', testPathIgnorePatterns: ['/test/fixtures'], - coveragePathIgnorePatterns: ['/test/'], + coveragePathIgnorePatterns: ['/test/', '/dist/'], setupFilesAfterEnv: ['./jest.setup.js'], }; diff --git a/packages/rabbitmq/src/framework.ts b/packages/rabbitmq/src/framework.ts index 413e3a0d6f8b..0b7fd67a5fff 100644 --- a/packages/rabbitmq/src/framework.ts +++ b/packages/rabbitmq/src/framework.ts @@ -9,6 +9,7 @@ import { RabbitMQListenerOptions, Framework, BaseFramework, + MidwayInvokeForbiddenError, } from '@midwayjs/core'; import { IMidwayRabbitMQApplication, @@ -91,6 +92,15 @@ export class MidwayRabbitMQFramework extends BaseFramework< }, } as IMidwayRabbitMQContext; this.app.createAnonymousContext(ctx); + const isPassed = await this.app + .getFramework() + .runGuard(ctx, module, listenerOptions.propertyKey); + if (!isPassed) { + throw new MidwayInvokeForbiddenError( + listenerOptions.propertyKey, + module + ); + } const ins = await ctx.requestContext.getAsync(module); const fn = await this.applyMiddleware(async ctx => { return await ins[listenerOptions.propertyKey].call(ins, data); diff --git a/packages/redis/jest.config.js b/packages/redis/jest.config.js index 34f2d767cd51..0245a5110fa2 100644 --- a/packages/redis/jest.config.js +++ b/packages/redis/jest.config.js @@ -2,6 +2,6 @@ module.exports = { preset: 'ts-jest', testEnvironment: 'node', testPathIgnorePatterns: ['/test/fixtures'], - coveragePathIgnorePatterns: ['/test/'], + coveragePathIgnorePatterns: ['/test/', '/dist/'], setupFilesAfterEnv: ['./jest.setup.js'], }; diff --git a/packages/security/jest.config.js b/packages/security/jest.config.js index 34f2d767cd51..0245a5110fa2 100644 --- a/packages/security/jest.config.js +++ b/packages/security/jest.config.js @@ -2,6 +2,6 @@ module.exports = { preset: 'ts-jest', testEnvironment: 'node', testPathIgnorePatterns: ['/test/fixtures'], - coveragePathIgnorePatterns: ['/test/'], + coveragePathIgnorePatterns: ['/test/', '/dist/'], setupFilesAfterEnv: ['./jest.setup.js'], }; diff --git a/packages/sequelize/jest.config.js b/packages/sequelize/jest.config.js index 34f2d767cd51..0245a5110fa2 100644 --- a/packages/sequelize/jest.config.js +++ b/packages/sequelize/jest.config.js @@ -2,6 +2,6 @@ module.exports = { preset: 'ts-jest', testEnvironment: 'node', testPathIgnorePatterns: ['/test/fixtures'], - coveragePathIgnorePatterns: ['/test/'], + coveragePathIgnorePatterns: ['/test/', '/dist/'], setupFilesAfterEnv: ['./jest.setup.js'], }; diff --git a/packages/session/jest.config.js b/packages/session/jest.config.js index b8fc665b0b02..aa08b1568942 100644 --- a/packages/session/jest.config.js +++ b/packages/session/jest.config.js @@ -2,7 +2,7 @@ module.exports = { preset: 'ts-jest', testEnvironment: 'node', testPathIgnorePatterns: ['/test/fixtures'], - coveragePathIgnorePatterns: ['/test/'], + coveragePathIgnorePatterns: ['/test/', '/dist/'], setupFilesAfterEnv: ['./jest.setup.js'], // globals: { // 'ts-jest': { diff --git a/packages/socketio/jest.config.js b/packages/socketio/jest.config.js index 34f2d767cd51..0245a5110fa2 100644 --- a/packages/socketio/jest.config.js +++ b/packages/socketio/jest.config.js @@ -2,6 +2,6 @@ module.exports = { preset: 'ts-jest', testEnvironment: 'node', testPathIgnorePatterns: ['/test/fixtures'], - coveragePathIgnorePatterns: ['/test/'], + coveragePathIgnorePatterns: ['/test/', '/dist/'], setupFilesAfterEnv: ['./jest.setup.js'], }; diff --git a/packages/socketio/src/framework.ts b/packages/socketio/src/framework.ts index 3a03313bd6b3..65cccc278a11 100644 --- a/packages/socketio/src/framework.ts +++ b/packages/socketio/src/framework.ts @@ -4,6 +4,7 @@ import { ContextMiddlewareManager, HTTP_SERVER_KEY, MidwayFrameworkType, + MidwayInvokeForbiddenError, } from '@midwayjs/core'; import { debuglog } from 'util'; const debug = debuglog('midway:socket.io'); @@ -193,6 +194,15 @@ export class MidwaySocketIOFramework extends BaseFramework< ...controllerMiddleware, ...(wsEventInfo?.eventOptions?.middleware || []), async (ctx, next) => { + const isPassed = await this.app + .getFramework() + .runGuard(ctx, target, wsEventInfo.propertyName); + if (!isPassed) { + throw new MidwayInvokeForbiddenError( + wsEventInfo.propertyName, + target + ); + } // eslint-disable-next-line prefer-spread return controller[wsEventInfo.propertyName].apply( controller, diff --git a/packages/static-file/jest.config.js b/packages/static-file/jest.config.js index 34f2d767cd51..0245a5110fa2 100644 --- a/packages/static-file/jest.config.js +++ b/packages/static-file/jest.config.js @@ -2,6 +2,6 @@ module.exports = { preset: 'ts-jest', testEnvironment: 'node', testPathIgnorePatterns: ['/test/fixtures'], - coveragePathIgnorePatterns: ['/test/'], + coveragePathIgnorePatterns: ['/test/', '/dist/'], setupFilesAfterEnv: ['./jest.setup.js'], }; diff --git a/packages/swagger/jest.config.js b/packages/swagger/jest.config.js index 0968eff5fb41..0245a5110fa2 100644 --- a/packages/swagger/jest.config.js +++ b/packages/swagger/jest.config.js @@ -2,6 +2,6 @@ module.exports = { preset: 'ts-jest', testEnvironment: 'node', testPathIgnorePatterns: ['/test/fixtures'], - coveragePathIgnorePatterns: ['/test/'], + coveragePathIgnorePatterns: ['/test/', '/dist/'], setupFilesAfterEnv: ['./jest.setup.js'], -}; \ No newline at end of file +}; diff --git a/packages/tablestore/jest.config.js b/packages/tablestore/jest.config.js index 34f2d767cd51..0245a5110fa2 100644 --- a/packages/tablestore/jest.config.js +++ b/packages/tablestore/jest.config.js @@ -2,6 +2,6 @@ module.exports = { preset: 'ts-jest', testEnvironment: 'node', testPathIgnorePatterns: ['/test/fixtures'], - coveragePathIgnorePatterns: ['/test/'], + coveragePathIgnorePatterns: ['/test/', '/dist/'], setupFilesAfterEnv: ['./jest.setup.js'], }; diff --git a/packages/task/jest.config.js b/packages/task/jest.config.js index 34f2d767cd51..0245a5110fa2 100644 --- a/packages/task/jest.config.js +++ b/packages/task/jest.config.js @@ -2,6 +2,6 @@ module.exports = { preset: 'ts-jest', testEnvironment: 'node', testPathIgnorePatterns: ['/test/fixtures'], - coveragePathIgnorePatterns: ['/test/'], + coveragePathIgnorePatterns: ['/test/', '/dist/'], setupFilesAfterEnv: ['./jest.setup.js'], }; diff --git a/packages/typegoose/jest.config.js b/packages/typegoose/jest.config.js index 34f2d767cd51..0245a5110fa2 100644 --- a/packages/typegoose/jest.config.js +++ b/packages/typegoose/jest.config.js @@ -2,6 +2,6 @@ module.exports = { preset: 'ts-jest', testEnvironment: 'node', testPathIgnorePatterns: ['/test/fixtures'], - coveragePathIgnorePatterns: ['/test/'], + coveragePathIgnorePatterns: ['/test/', '/dist/'], setupFilesAfterEnv: ['./jest.setup.js'], }; diff --git a/packages/typeorm/jest.config.js b/packages/typeorm/jest.config.js index 34f2d767cd51..0245a5110fa2 100644 --- a/packages/typeorm/jest.config.js +++ b/packages/typeorm/jest.config.js @@ -2,6 +2,6 @@ module.exports = { preset: 'ts-jest', testEnvironment: 'node', testPathIgnorePatterns: ['/test/fixtures'], - coveragePathIgnorePatterns: ['/test/'], + coveragePathIgnorePatterns: ['/test/', '/dist/'], setupFilesAfterEnv: ['./jest.setup.js'], }; diff --git a/packages/upload/jest.config.js b/packages/upload/jest.config.js index 34f2d767cd51..0245a5110fa2 100644 --- a/packages/upload/jest.config.js +++ b/packages/upload/jest.config.js @@ -2,6 +2,6 @@ module.exports = { preset: 'ts-jest', testEnvironment: 'node', testPathIgnorePatterns: ['/test/fixtures'], - coveragePathIgnorePatterns: ['/test/'], + coveragePathIgnorePatterns: ['/test/', '/dist/'], setupFilesAfterEnv: ['./jest.setup.js'], }; diff --git a/packages/validate/jest.config.js b/packages/validate/jest.config.js index 34f2d767cd51..0245a5110fa2 100644 --- a/packages/validate/jest.config.js +++ b/packages/validate/jest.config.js @@ -2,6 +2,6 @@ module.exports = { preset: 'ts-jest', testEnvironment: 'node', testPathIgnorePatterns: ['/test/fixtures'], - coveragePathIgnorePatterns: ['/test/'], + coveragePathIgnorePatterns: ['/test/', '/dist/'], setupFilesAfterEnv: ['./jest.setup.js'], }; diff --git a/packages/view-ejs/jest.config.js b/packages/view-ejs/jest.config.js index 34f2d767cd51..0245a5110fa2 100644 --- a/packages/view-ejs/jest.config.js +++ b/packages/view-ejs/jest.config.js @@ -2,6 +2,6 @@ module.exports = { preset: 'ts-jest', testEnvironment: 'node', testPathIgnorePatterns: ['/test/fixtures'], - coveragePathIgnorePatterns: ['/test/'], + coveragePathIgnorePatterns: ['/test/', '/dist/'], setupFilesAfterEnv: ['./jest.setup.js'], }; diff --git a/packages/view-nunjucks/jest.config.js b/packages/view-nunjucks/jest.config.js index 34f2d767cd51..0245a5110fa2 100644 --- a/packages/view-nunjucks/jest.config.js +++ b/packages/view-nunjucks/jest.config.js @@ -2,6 +2,6 @@ module.exports = { preset: 'ts-jest', testEnvironment: 'node', testPathIgnorePatterns: ['/test/fixtures'], - coveragePathIgnorePatterns: ['/test/'], + coveragePathIgnorePatterns: ['/test/', '/dist/'], setupFilesAfterEnv: ['./jest.setup.js'], }; diff --git a/packages/view/jest.config.js b/packages/view/jest.config.js index 34f2d767cd51..0245a5110fa2 100644 --- a/packages/view/jest.config.js +++ b/packages/view/jest.config.js @@ -2,6 +2,6 @@ module.exports = { preset: 'ts-jest', testEnvironment: 'node', testPathIgnorePatterns: ['/test/fixtures'], - coveragePathIgnorePatterns: ['/test/'], + coveragePathIgnorePatterns: ['/test/', '/dist/'], setupFilesAfterEnv: ['./jest.setup.js'], }; diff --git a/packages/web-express/jest.config.js b/packages/web-express/jest.config.js index 34f2d767cd51..0245a5110fa2 100644 --- a/packages/web-express/jest.config.js +++ b/packages/web-express/jest.config.js @@ -2,6 +2,6 @@ module.exports = { preset: 'ts-jest', testEnvironment: 'node', testPathIgnorePatterns: ['/test/fixtures'], - coveragePathIgnorePatterns: ['/test/'], + coveragePathIgnorePatterns: ['/test/', '/dist/'], setupFilesAfterEnv: ['./jest.setup.js'], }; diff --git a/packages/web-express/src/framework.ts b/packages/web-express/src/framework.ts index f6e3d99bb775..93da9ada95bf 100644 --- a/packages/web-express/src/framework.ts +++ b/packages/web-express/src/framework.ts @@ -219,6 +219,14 @@ export class MidwayExpressFramework extends BaseFramework< */ protected generateController(routeInfo: RouterInfo): IRouterHandler { return wrapAsyncHandler(async (req, res, next) => { + if (routeInfo.controllerClz && typeof routeInfo.method === 'string') { + const isPassed = await this.app + .getFramework() + .runGuard(req, routeInfo.controllerClz, routeInfo.method); + if (!isPassed) { + throw new httpError.ForbiddenError(); + } + } let result; if (typeof routeInfo.method !== 'string') { result = await routeInfo.method(req, res, next); diff --git a/packages/web-express/test/fixtures/base-app-guard/package.json b/packages/web-express/test/fixtures/base-app-guard/package.json new file mode 100644 index 000000000000..621cdc6a4174 --- /dev/null +++ b/packages/web-express/test/fixtures/base-app-guard/package.json @@ -0,0 +1,3 @@ +{ + "name": "ali-demo" +} diff --git a/packages/web-express/test/fixtures/base-app-guard/src/config/config.default.ts b/packages/web-express/test/fixtures/base-app-guard/src/config/config.default.ts new file mode 100644 index 000000000000..eab7477dd13d --- /dev/null +++ b/packages/web-express/test/fixtures/base-app-guard/src/config/config.default.ts @@ -0,0 +1,9 @@ +'use strict'; + +export const keys = 'key'; + +export const hello = { + a: 1, + b: 2, + d: [1, 2, 3], +}; diff --git a/packages/web-express/test/fixtures/base-app-guard/src/configuration.ts b/packages/web-express/test/fixtures/base-app-guard/src/configuration.ts new file mode 100644 index 000000000000..e84bcd65b9b1 --- /dev/null +++ b/packages/web-express/test/fixtures/base-app-guard/src/configuration.ts @@ -0,0 +1,28 @@ +import { Configuration, App, Guard, IGuard } from '@midwayjs/core'; +import { join } from 'path'; +import { IMidwayExpressApplication, Context } from '../../../../src'; + +@Guard() +export class MainGuard implements IGuard { + async canActivate(ctx: Context): Promise { + return ctx.originalUrl !== '/api'; + } +} + +@Configuration({ + imports: [ + require('../../../../src') + ], + importConfigs: [ + join(__dirname, './config') + ] +}) +export class ContainerConfiguration { + + @App() + app: IMidwayExpressApplication; + + async onReady() { + this.app.useGuard(MainGuard); + } +} diff --git a/packages/web-express/test/fixtures/base-app-guard/src/controller/api.ts b/packages/web-express/test/fixtures/base-app-guard/src/controller/api.ts new file mode 100644 index 000000000000..3e807cb66616 --- /dev/null +++ b/packages/web-express/test/fixtures/base-app-guard/src/controller/api.ts @@ -0,0 +1,33 @@ +import { + Controller, + Post, + Inject, + Body, + Get, +} from '@midwayjs/core'; +import { Context } from '../../../../../src'; + +class DataDTO { + name: string; + age: number; +} + +@Controller('/api') +export class APIController { + + @Inject() + ctx: Context; + + @Post() + async postData(@Body() data: DataDTO) { + return data; + } +} + +@Controller() +export class HomeController { + @Get() + async index() { + return 'hello world'; + } +} diff --git a/packages/web-express/test/index.test.ts b/packages/web-express/test/index.test.ts index 063c520371fd..06dfd48f695a 100644 --- a/packages/web-express/test/index.test.ts +++ b/packages/web-express/test/index.test.ts @@ -325,4 +325,15 @@ describe('/test/feature.test.ts', () => { }); }); + it('should test request with guard', async () => { + const app = await creatApp('base-app-guard'); + let result = await createHttpRequest(app) + .get('/'); + expect(result.text).toEqual('hello world'); + + result = await createHttpRequest(app) + .post('/api'); + expect(result.status).toEqual(403); + await closeApp(app); + }); }); diff --git a/packages/web-koa/jest.config.js b/packages/web-koa/jest.config.js index 34f2d767cd51..0245a5110fa2 100644 --- a/packages/web-koa/jest.config.js +++ b/packages/web-koa/jest.config.js @@ -2,6 +2,6 @@ module.exports = { preset: 'ts-jest', testEnvironment: 'node', testPathIgnorePatterns: ['/test/fixtures'], - coveragePathIgnorePatterns: ['/test/'], + coveragePathIgnorePatterns: ['/test/', '/dist/'], setupFilesAfterEnv: ['./jest.setup.js'], }; diff --git a/packages/web/jest.config.js b/packages/web/jest.config.js index 34f2d767cd51..0245a5110fa2 100644 --- a/packages/web/jest.config.js +++ b/packages/web/jest.config.js @@ -2,6 +2,6 @@ module.exports = { preset: 'ts-jest', testEnvironment: 'node', testPathIgnorePatterns: ['/test/fixtures'], - coveragePathIgnorePatterns: ['/test/'], + coveragePathIgnorePatterns: ['/test/', '/dist/'], setupFilesAfterEnv: ['./jest.setup.js'], }; diff --git a/packages/ws/jest.config.js b/packages/ws/jest.config.js index 34f2d767cd51..0245a5110fa2 100644 --- a/packages/ws/jest.config.js +++ b/packages/ws/jest.config.js @@ -2,6 +2,6 @@ module.exports = { preset: 'ts-jest', testEnvironment: 'node', testPathIgnorePatterns: ['/test/fixtures'], - coveragePathIgnorePatterns: ['/test/'], + coveragePathIgnorePatterns: ['/test/', '/dist/'], setupFilesAfterEnv: ['./jest.setup.js'], }; diff --git a/packages/ws/src/framework.ts b/packages/ws/src/framework.ts index df5c20022d7c..eb580e3f13c6 100644 --- a/packages/ws/src/framework.ts +++ b/packages/ws/src/framework.ts @@ -14,6 +14,7 @@ import { listModule, Framework, WSControllerOption, + MidwayInvokeForbiddenError, } from '@midwayjs/core'; import * as http from 'http'; import { debuglog } from 'util'; @@ -173,6 +174,16 @@ export class MidwayWSFramework extends BaseFramework< [ ...(wsEventInfo?.eventOptions?.middleware || []), async (ctx, next) => { + const isPassed = await this.app + .getFramework() + .runGuard(ctx, target, wsEventInfo.propertyName); + if (!isPassed) { + throw new MidwayInvokeForbiddenError( + wsEventInfo.propertyName, + target + ); + } + // eslint-disable-next-line prefer-spread return controller[wsEventInfo.propertyName].apply( controller,