Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 5 additions & 4 deletions src/core/domains/console/commands/ListRoutesCommand.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,11 @@ export default class ListRoutesCommand extends BaseCommand {

public keepProcessAlive = false;


/**
* Execute the command
*/
async execute() {
const showDetails = (this.getArguementByKey('details')?.value ?? false) !== false;
const showDetails = this.parsedArgumenets.find(arg => ['--details', '--d', '--detailed'].includes(arg.value));
const expressService = App.container('express')

this.input.clearScreen();
Expand All @@ -27,8 +26,10 @@ export default class ListRoutesCommand extends BaseCommand {
this.input.writeLine(` Name: ${route.name}`);
this.input.writeLine(` Method: ${route.method}`);
this.input.writeLine(` Action: ${route.action.name}`);
this.input.writeLine(` Middleware: ${route.middlewares?.map(m => m.name).join(', ')}`);
this.input.writeLine(` Validators: ${route.validator?.name ?? 'None'}`);
this.input.writeLine(` Middleware: [${route.middlewares?.map(m => m.name).join(', ') ?? ''}]`);
this.input.writeLine(` Validators: [${route.validator?.name ?? ''}]`);
this.input.writeLine(` Scopes: [${route.scopes?.join(', ') ?? ''}]`);
this.input.writeLine(` Security: [${route.security?.map(s => s.id).join(', ')}]`);
this.input.writeLine();
return;
}
Expand Down
5 changes: 3 additions & 2 deletions src/core/domains/express/actions/resourceCreate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,9 @@ import { IRouteResourceOptions } from '@src/core/domains/express/interfaces/IRou
import responseError from '@src/core/domains/express/requests/responseError';
import { RouteResourceTypes } from '@src/core/domains/express/routing/RouteResource';
import CurrentRequest from '@src/core/domains/express/services/CurrentRequest';
import { ALWAYS, SecurityIdentifiers } from '@src/core/domains/express/services/Security';
import { ALWAYS } from '@src/core/domains/express/services/Security';
import SecurityReader from '@src/core/domains/express/services/SecurityReader';
import { SecurityIdentifiers } from '@src/core/domains/express/services/SecurityRules';
import { BaseRequest } from "@src/core/domains/express/types/BaseRequest.t";
import { Response } from 'express';

Expand All @@ -21,7 +22,7 @@ import { Response } from 'express';
export default async (req: BaseRequest, res: Response, options: IRouteResourceOptions): Promise<void> => {
try {
const resourceOwnerSecurity = SecurityReader.findFromRouteResourceOptions(options, SecurityIdentifiers.RESOURCE_OWNER, [RouteResourceTypes.CREATE]);
const authorizationSecurity = SecurityReader.findFromRouteResourceOptions(options, SecurityIdentifiers.AUTHORIZATION, [RouteResourceTypes.CREATE, ALWAYS]);
const authorizationSecurity = SecurityReader.findFromRouteResourceOptions(options, SecurityIdentifiers.AUTHORIZED, [RouteResourceTypes.CREATE, ALWAYS]);

if(authorizationSecurity && !authorizationSecurity.callback(req)) {
responseError(req, res, new UnauthorizedError(), 401)
Expand Down
5 changes: 3 additions & 2 deletions src/core/domains/express/actions/resourceDelete.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,9 @@ import UnauthorizedError from '@src/core/domains/auth/exceptions/UnauthorizedErr
import { IRouteResourceOptions } from '@src/core/domains/express/interfaces/IRouteResourceOptions';
import responseError from '@src/core/domains/express/requests/responseError';
import { RouteResourceTypes } from '@src/core/domains/express/routing/RouteResource';
import { ALWAYS, SecurityIdentifiers } from '@src/core/domains/express/services/Security';
import { ALWAYS } from '@src/core/domains/express/services/Security';
import SecurityReader from '@src/core/domains/express/services/SecurityReader';
import { SecurityIdentifiers } from '@src/core/domains/express/services/SecurityRules';
import { BaseRequest } from "@src/core/domains/express/types/BaseRequest.t";
import ModelNotFound from '@src/core/exceptions/ModelNotFound';
import { Response } from 'express';
Expand All @@ -21,7 +22,7 @@ import { Response } from 'express';
export default async (req: BaseRequest, res: Response, options: IRouteResourceOptions): Promise<void> => {
try {
const resourceOwnerSecurity = SecurityReader.findFromRouteResourceOptions(options, SecurityIdentifiers.RESOURCE_OWNER, [RouteResourceTypes.DESTROY]);
const authorizationSecurity = SecurityReader.findFromRouteResourceOptions(options, SecurityIdentifiers.AUTHORIZATION, [RouteResourceTypes.DESTROY, ALWAYS]);
const authorizationSecurity = SecurityReader.findFromRouteResourceOptions(options, SecurityIdentifiers.AUTHORIZED, [RouteResourceTypes.DESTROY, ALWAYS]);

if(authorizationSecurity && !authorizationSecurity.callback(req)) {
responseError(req, res, new UnauthorizedError(), 401)
Expand Down
5 changes: 3 additions & 2 deletions src/core/domains/express/actions/resourceIndex.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,9 @@ import { IRouteResourceOptions } from '@src/core/domains/express/interfaces/IRou
import responseError from '@src/core/domains/express/requests/responseError';
import { RouteResourceTypes } from '@src/core/domains/express/routing/RouteResource';
import CurrentRequest from '@src/core/domains/express/services/CurrentRequest';
import { ALWAYS, SecurityIdentifiers } from '@src/core/domains/express/services/Security';
import { ALWAYS } from '@src/core/domains/express/services/Security';
import SecurityReader from '@src/core/domains/express/services/SecurityReader';
import { SecurityIdentifiers } from '@src/core/domains/express/services/SecurityRules';
import { BaseRequest } from "@src/core/domains/express/types/BaseRequest.t";
import { IModel } from '@src/core/interfaces/IModel';
import IModelData from '@src/core/interfaces/IModelData';
Expand All @@ -30,7 +31,7 @@ const formatResults = (results: IModel<IModelData>[]) => results.map(result => r
export default async (req: BaseRequest, res: Response, options: IRouteResourceOptions): Promise<void> => {
try {
const resourceOwnerSecurity = SecurityReader.findFromRouteResourceOptions(options, SecurityIdentifiers.RESOURCE_OWNER, [RouteResourceTypes.ALL])
const authorizationSecurity = SecurityReader.findFromRouteResourceOptions(options, SecurityIdentifiers.AUTHORIZATION, [RouteResourceTypes.ALL, ALWAYS]);
const authorizationSecurity = SecurityReader.findFromRouteResourceOptions(options, SecurityIdentifiers.AUTHORIZED, [RouteResourceTypes.ALL, ALWAYS]);

if(authorizationSecurity && !authorizationSecurity.callback(req)) {
responseError(req, res, new UnauthorizedError(), 401)
Expand Down
5 changes: 3 additions & 2 deletions src/core/domains/express/actions/resourceShow.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,9 @@ import { IRouteResourceOptions } from '@src/core/domains/express/interfaces/IRou
import responseError from '@src/core/domains/express/requests/responseError';
import { RouteResourceTypes } from '@src/core/domains/express/routing/RouteResource';
import CurrentRequest from '@src/core/domains/express/services/CurrentRequest';
import { ALWAYS, SecurityIdentifiers } from '@src/core/domains/express/services/Security';
import { ALWAYS } from '@src/core/domains/express/services/Security';
import SecurityReader from '@src/core/domains/express/services/SecurityReader';
import { SecurityIdentifiers } from '@src/core/domains/express/services/SecurityRules';
import { BaseRequest } from "@src/core/domains/express/types/BaseRequest.t";
import ModelNotFound from '@src/core/exceptions/ModelNotFound';
import { IModel } from '@src/core/interfaces/IModel';
Expand All @@ -23,7 +24,7 @@ import { Response } from 'express';
export default async (req: BaseRequest, res: Response, options: IRouteResourceOptions): Promise<void> => {
try {
const resourceOwnerSecurity = SecurityReader.findFromRouteResourceOptions(options, SecurityIdentifiers.RESOURCE_OWNER, [RouteResourceTypes.SHOW]);
const authorizationSecurity = SecurityReader.findFromRouteResourceOptions(options, SecurityIdentifiers.AUTHORIZATION, [RouteResourceTypes.SHOW, ALWAYS]);
const authorizationSecurity = SecurityReader.findFromRouteResourceOptions(options, SecurityIdentifiers.AUTHORIZED, [RouteResourceTypes.SHOW, ALWAYS]);

if(authorizationSecurity && !authorizationSecurity.callback(req)) {
responseError(req, res, new UnauthorizedError(), 401)
Expand Down
5 changes: 3 additions & 2 deletions src/core/domains/express/actions/resourceUpdate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,9 @@ import MissingSecurityError from '@src/core/domains/express/exceptions/MissingSe
import { IRouteResourceOptions } from '@src/core/domains/express/interfaces/IRouteResourceOptions';
import responseError from '@src/core/domains/express/requests/responseError';
import { RouteResourceTypes } from '@src/core/domains/express/routing/RouteResource';
import { ALWAYS, SecurityIdentifiers } from '@src/core/domains/express/services/Security';
import { ALWAYS } from '@src/core/domains/express/services/Security';
import SecurityReader from '@src/core/domains/express/services/SecurityReader';
import { SecurityIdentifiers } from '@src/core/domains/express/services/SecurityRules';
import { BaseRequest } from "@src/core/domains/express/types/BaseRequest.t";
import ModelNotFound from '@src/core/exceptions/ModelNotFound';
import { IModel } from '@src/core/interfaces/IModel';
Expand All @@ -23,7 +24,7 @@ import { Response } from 'express';
export default async (req: BaseRequest, res: Response, options: IRouteResourceOptions): Promise<void> => {
try {
const resourceOwnerSecurity = SecurityReader.findFromRouteResourceOptions(options, SecurityIdentifiers.RESOURCE_OWNER, [RouteResourceTypes.UPDATE]);
const authorizationSecurity = SecurityReader.findFromRouteResourceOptions(options, SecurityIdentifiers.AUTHORIZATION, [RouteResourceTypes.UPDATE, ALWAYS]);
const authorizationSecurity = SecurityReader.findFromRouteResourceOptions(options, SecurityIdentifiers.AUTHORIZED, [RouteResourceTypes.UPDATE, ALWAYS]);

if(authorizationSecurity && !authorizationSecurity.callback(req)) {
responseError(req, res, new UnauthorizedError(), 401)
Expand Down
4 changes: 3 additions & 1 deletion src/core/domains/express/interfaces/IRoute.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,12 @@ import { Middleware } from '@src/core/interfaces/Middleware.t';

export interface IRoute {
name: string;
resourceType?: string;
path: string;
method: 'get' | 'post' | 'put' | 'patch' | 'delete';
action: IRouteAction;
resourceType?: string;
scopes?: string[];
scopesSecurityEnabled?: boolean;
middlewares?: Middleware[];
validator?: ValidatorCtor;
validateBeforeAction?: boolean;
Expand Down
10 changes: 6 additions & 4 deletions src/core/domains/express/interfaces/IRouteResourceOptions.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,18 @@
import { IdentifiableSecurityCallback } from "@src/core/domains/auth/services/Security";
import { IRoute } from "@src/core/domains/express/interfaces/IRoute";
import { IIdentifiableSecurityCallback } from "@src/core/domains/express/interfaces/ISecurity";
import { ValidatorCtor } from "@src/core/domains/validator/types/ValidatorCtor";
import { IModel, ModelConstructor } from "@src/core/interfaces/IModel";

export type ResourceType = 'index' | 'create' | 'update' | 'show' | 'delete';

export interface IRouteResourceOptions extends Pick<IRoute, 'middlewares'> {
name: string;
resource: ModelConstructor<IModel>;
except?: ResourceType[];
only?: ResourceType[];
resource: ModelConstructor<IModel>;
name: string;
createValidator?: ValidatorCtor;
updateValidator?: ValidatorCtor;
security?: IdentifiableSecurityCallback[];
security?: IIdentifiableSecurityCallback[];
scopes?: string[];
scopesSecurityEnabled?: boolean;
}
3 changes: 3 additions & 0 deletions src/core/domains/express/interfaces/ISecurity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@ export type SecurityCallback = (req: BaseRequest, ...args: any[]) => boolean;
export type IIdentifiableSecurityCallback = {
// The identifier for the security callback.
id: string;
// Include another security rule in the callback.
// TODO: We could add another type here 'alsoArguments' if extra parameters are required
also?: string;
// The condition for when the security check should be executed. Defaults to 'always'.
when: string[] | null;
// The condition for when the security check should never be executed.
Expand Down
37 changes: 32 additions & 5 deletions src/core/domains/express/middleware/securityMiddleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,9 @@ import AuthRequest from '@src/core/domains/auth/services/AuthRequest';
import { IRoute } from '@src/core/domains/express/interfaces/IRoute';
import { ISecurityMiddleware } from '@src/core/domains/express/interfaces/ISecurity';
import responseError from '@src/core/domains/express/requests/responseError';
import { ALWAYS, SecurityIdentifiers } from '@src/core/domains/express/services/Security';
import { ALWAYS } from '@src/core/domains/express/services/Security';
import SecurityReader from '@src/core/domains/express/services/SecurityReader';
import { SecurityIdentifiers } from '@src/core/domains/express/services/SecurityRules';
import { BaseRequest } from '@src/core/domains/express/types/BaseRequest.t';
import { NextFunction, Response } from 'express';

Expand All @@ -17,23 +18,23 @@ const bindSecurityToRequest = (route: IRoute, req: BaseRequest) => {
/**
* Applies the authorization security check on the request.
*/
const applyAuthorizeSecurity = async (route: IRoute, req: BaseRequest, res: Response): Promise<void> => {
const applyAuthorizeSecurity = async (route: IRoute, req: BaseRequest, res: Response): Promise<void | null> => {

const conditions = [ALWAYS]

if(route.resourceType) {
conditions.push(route.resourceType)
}

const authorizeSecurity = SecurityReader.findFromRequest(req, SecurityIdentifiers.AUTHORIZATION, conditions);
const authorizeSecurity = SecurityReader.findFromRequest(req, SecurityIdentifiers.AUTHORIZED, conditions);

if (authorizeSecurity) {
try {
req = await AuthRequest.attemptAuthorizeRequest(req);

if(!authorizeSecurity.callback(req)) {
responseError(req, res, new UnauthorizedError(), 401);
return;
return null;
}
}
catch (err) {
Expand Down Expand Up @@ -61,6 +62,23 @@ const applyHasRoleSecurity = (req: BaseRequest, res: Response): void | null => {

}

/**
* Checks if the hasRole security has been defined and validates it.
* If the hasRole security is defined and the validation fails, it will send a 403 response with a ForbiddenResourceError.
*/
const applyHasScopeSecurity = (req: BaseRequest, res: Response): void | null => {

// Check if the hasRole security has been defined and validate
const securityHasScope = SecurityReader.findFromRequest(req, SecurityIdentifiers.HAS_SCOPE);

if (securityHasScope && !securityHasScope.callback(req)) {
responseError(req, res, new ForbiddenResourceError(), 403)
return null;
}

}


/**
* This middleware will check the security definition of the route and validate it.
* If the security definition is not valid, it will throw an UnauthorizedError.
Expand All @@ -80,7 +98,9 @@ export const securityMiddleware: ISecurityMiddleware = ({ route }) => async (req
* Authorizes the user
* Depending on option 'throwExceptionOnUnauthorized', can allow continue processing on failed auth
*/
await applyAuthorizeSecurity(route, req, res)
if(await applyAuthorizeSecurity(route, req, res) === null) {
return;
}

/**
* Check if the authorized user passes the has role security
Expand All @@ -89,6 +109,13 @@ export const securityMiddleware: ISecurityMiddleware = ({ route }) => async (req
return;
}

/**
* Check if the authorized user passes the has scope security
*/
if(applyHasScopeSecurity(req, res) === null) {
return;
}

/**
* Security is OK, continue
*/
Expand Down
38 changes: 37 additions & 1 deletion src/core/domains/express/routing/RouteResource.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { IRoute } from "@src/core/domains/express/interfaces/IRoute";
import { IRouteResourceOptions } from "@src/core/domains/express/interfaces/IRouteResourceOptions";
import Route from "@src/core/domains/express/routing/Route";
import RouteGroup from "@src/core/domains/express/routing/RouteGroup";
import RouteResourceScope from "@src/core/domains/express/routing/RouteResourceScope";
import routeGroupUtil from "@src/core/domains/express/utils/routeGroupUtil";

/**
Expand Down Expand Up @@ -40,11 +41,22 @@ export const RouteResourceTypes = {
const RouteResource = (options: IRouteResourceOptions): IRoute[] => {
const name = options.name.startsWith('/') ? options.name.slice(1) : options.name

const {
scopes = [],
scopesSecurityEnabled = false
} = options;

const routes = RouteGroup([
// Get all resources
// Get all resources
Route({
name: `${name}.index`,
resourceType: RouteResourceTypes.ALL,
scopes: RouteResourceScope.getScopes({
name,
types: 'read',
additionalScopes: scopes
}),
scopesSecurityEnabled,
method: 'get',
path: `/${name}`,
action: resourceAction(options, resourceIndex),
Expand All @@ -55,6 +67,12 @@ const RouteResource = (options: IRouteResourceOptions): IRoute[] => {
Route({
name: `${name}.show`,
resourceType: RouteResourceTypes.SHOW,
scopes: RouteResourceScope.getScopes({
name,
types: 'read',
additionalScopes: scopes
}),
scopesSecurityEnabled,
method: 'get',
path: `/${name}/:id`,
action: resourceAction(options, resourceShow),
Expand All @@ -65,6 +83,12 @@ const RouteResource = (options: IRouteResourceOptions): IRoute[] => {
Route({
name: `${name}.update`,
resourceType: RouteResourceTypes.UPDATE,
scopes: RouteResourceScope.getScopes({
name,
types: 'write',
additionalScopes: scopes
}),
scopesSecurityEnabled,
method: 'put',
path: `/${name}/:id`,
action: resourceAction(options, resourceUpdate),
Expand All @@ -76,6 +100,12 @@ const RouteResource = (options: IRouteResourceOptions): IRoute[] => {
Route({
name: `${name}.destroy`,
resourceType: RouteResourceTypes.DESTROY,
scopes: RouteResourceScope.getScopes({
name,
types: 'delete',
additionalScopes: scopes
}),
scopesSecurityEnabled,
method: 'delete',
path: `/${name}/:id`,
action: resourceAction(options, resourceDelete),
Expand All @@ -86,6 +116,12 @@ const RouteResource = (options: IRouteResourceOptions): IRoute[] => {
Route({
name: `${name}.create`,
resourceType: RouteResourceTypes.CREATE,
scopes: RouteResourceScope.getScopes({
name,
types: 'read',
additionalScopes: scopes
}),
scopesSecurityEnabled,
method: 'post',
path: `/${name}`,
action: resourceAction(options, resourceCreate),
Expand Down
Loading