All files / src/components/casbin/services casbin.authorizer.ts

19.59% Statements 19/97
0% Branches 0/53
0% Functions 0/11
17.89% Lines 17/95

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262  1x             1x 1x 1x 1x 1x 1x 1x 1x 1x         1x   1x 1x 1x 1x                                         1x   1x                                                                                                                                                                                                                                                                                                                                                                                                                                        
/* eslint-disable @typescript-eslint/no-unused-vars */
import {
  AuthorizationContext,
  AuthorizationDecision,
  AuthorizationMetadata,
  AuthorizationRequest,
  Authorizer,
} from '@loopback/authorization';
import {inject, Provider} from '@loopback/core';
import {repository} from '@loopback/repository';
import {Request, RestBindings} from '@loopback/rest';
import {Enforcer, newEnforcer} from 'casbin';
import path from 'path';
import {Constants} from '../../../configs';
import {Module} from '../../../configs/module';
import {RequestController} from '../../../controllers';
import {
  FeatureAccessRepository,
  RequestRepository,
  RoleRightsRepository,
} from '../../../repositories';
import {RequestService} from '../../../services';
import {UserProfile} from '../../aws/services';
import {EnforcerAdapter} from '../lib/adapter';
const debug = require('debug')('logchain:acl');
const SCOPES = Object.values(Constants.AccessScope);
const DEFAULT_SCOPE = 'execute';
 
export interface LogChainAuthorizationMetadata extends AuthorizationMetadata {
  feature?: string[];
}
 
export type LogChainPermissions = [number, number, number, number, number, number];
 
export interface LogChainAuthorizationRequest extends AuthorizationRequest {
  company_id: number;
  persona_id: number;
  feature_id: number;
  create: number;
  retrieve: number;
  update: number;
  delete: number;
  validate: number;
  override: number;
}
 
// Class level authorizer
export class CasbinAuthorizationProvider implements Provider<Authorizer> {
  @inject(RestBindings.Http.REQUEST)
  public req: Request;
 
  constructor(
    @repository(FeatureAccessRepository)
    private feature_access_repo: FeatureAccessRepository,
    @repository(RoleRightsRepository)
    private role_rights_repo: RoleRightsRepository,
    @repository(RequestRepository)
    public request_repo: RequestRepository,
  ) {}
 
  /**
   * @returns authenticateFn
   */
  value(): Authorizer {
    return this.authorize.bind(this);
  }
 
  async authorize(
    authorizationCtx: AuthorizationContext,
    metadata: AuthorizationMetadata,
  ): Promise<AuthorizationDecision> {
    const { invocationContext } = authorizationCtx;
    const current_user: UserProfile = authorizationCtx.principals[0] as unknown as UserProfile;
    const { company_id, company_personas, role_id } = current_user;
 
    if (!company_personas || !company_personas.length || !role_id) {
      console.log(`authorizer personas: ${company_personas}`);
      console.log(`authorizer role_id: ${role_id}`);
      return AuthorizationDecision.DENY;
    }
 
    const scopes = metadata.scopes ?? [DEFAULT_SCOPE];
    const feature_ids = metadata.resource?.split(',');
    if (!feature_ids || feature_ids[0] === Module.Public) {
      return feature_ids ? AuthorizationDecision.ALLOW : AuthorizationDecision.DENY;
    }
 
    const enforcer_comp = await this._createEnforcerByType('company', this.feature_access_repo);
    let allowed = await this.checkCompanyPermission(company_personas, feature_ids, enforcer_comp);
 
    if (allowed) {
      let features = feature_ids;
      if (invocationContext.targetClass === RequestController) {
        features = [await this.detectResourceBasedOnPersonaRequest(authorizationCtx)];
      }
      const enforcer_user = await this._createEnforcerByType('user', this.role_rights_repo);
      allowed = await this.checkUserPermission(role_id, features, scopes, enforcer_user);
    }
 
    return allowed ? AuthorizationDecision.ALLOW : AuthorizationDecision.DENY;
  }
 
  /**
   * Checks if any of the company's personas have access to the given feature.
   * @param company_personas The list of company personas.
   * @param feature_ids The feature ids to check.
   * @param enforcer_comp The Enforcer instance.
   * @returns A boolean indicating if the company has access to the feature.
   */
  private async checkCompanyPermission(
    company_personas: any[],
    feature_ids: string[],
    enforcer_comp: Enforcer,
  ): Promise<boolean> {
    for (const persona of company_personas) {
      if (await this.isPermissionGrantedForPersona(persona.persona_id, feature_ids, enforcer_comp)) {
        return true;
      }
    }
    console.log(`allow company: false`);
    return false;
  }
 
  /**
   * Checks if the given persona has access to any of the given features.
   * @param persona_id The persona id to check.
   * @param feature_ids The feature ids to check.
   * @param enforcer_comp The Enforcer instance.
   * @returns A boolean indicating if the persona has access to the feature.
   */
  private async isPermissionGrantedForPersona(
    persona_id: number,
    feature_ids: string[],
    enforcer_comp: Enforcer,
  ): Promise<boolean> {
    for (const feature_id of feature_ids) {
      const comp_req = [persona_id, feature_id];
      console.log(`authorizer company request: ${comp_req}`);
      if (await enforcer_comp.enforce(...comp_req)) {
        console.log(`allow company: true`);
        return true;
      }
    }
    return false;
  }
 
  private async checkUserPermission(
    role_id: number,
    features: string[],
    scopes: string[],
    enforcer_user: Enforcer,
  ): Promise<boolean> {
    for (const feature of features) {
      const user_req = [role_id, feature, ...this._buildArrayPermissions(scopes)];
      console.log(
        `authorizer user rules:
            [role_id, feature_id, create, retrieve, update, delete, validate, override]`,
      );
      console.log(`authorizer user request: ${user_req}`);
      if (await enforcer_user.enforce(...user_req)) {
        console.log(`allow feature ${feature} user: true`);
        return true;
      }
    }
    console.log(`allow feature user: false`);
    return false;
  }
 
  /**
   * Build array of permissions
   * @param scope
   */
  private _buildArrayPermissions(scopes: string[]): LogChainPermissions {
    const perms: LogChainPermissions = [
      Constants.Access.Denied,
      Constants.Access.Denied,
      Constants.Access.Denied,
      Constants.Access.Denied,
      Constants.Access.Denied,
      Constants.Access.Denied,
    ];
 
    // Deny if scopes empty
    if (!scopes || !scopes.length) {
      return perms;
    }
 
    // Change permission at the same index
    for (const scope of scopes) {
      const idx = SCOPES.indexOf(scope);
      if (idx !== -1) {
        perms[idx] = Constants.Access.Allowed;
      }
    }
 
    return perms;
  }
 
  /**
   *
   * @param type
   * @param repo
   */
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  async _createEnforcerByType(type: string, repo: any): Promise<Enforcer> {
    const conf = path.resolve(__dirname, `./../models/rbac-${type}.conf`);
    return newEnforcer(conf, new EnforcerAdapter(repo));
  }
 
  /**
   * Detect the resource id based on persona request.
   * @param authorizationCtx The authorization context.
   */
  async detectResourceBasedOnPersonaRequest(
    authorizationCtx: AuthorizationContext,
  ) {
    const {invocationContext} = authorizationCtx;
    const {args, methodName} = invocationContext;
    const url = this.req.url;
 
    if (!args || !args.length) {
      return 'unknown';
    }
 
    const request_id = this._getRequestId(url, methodName, args);
    const request_persona_id = await this._getRequestPersonaId(methodName, args, request_id);
 
    if (!request_persona_id) {
      return 'unknown';
    }
 
    return RequestService.determineFeatureBasedOn(request_persona_id);
  }
 
  private _getRequestId(url: string, methodName: string, args: any[]): number | undefined {
    if (methodName === 'getComments') {
      return args[5];
    } else if (/^\/requests\/\d/.test(url)) {
      return args[0];
    }
    return undefined;
  }
 
  private async _getRequestPersonaId(methodName: string, args: any[], request_id?: number): Promise<number | undefined> {
    if (request_id) {
      const request = await this.request_repo.findById(request_id);
      return request.provider_persona_id;
    }
 
    if (methodName === 'create') {
      return args[0].provider_persona_id;
    }
 
    if (methodName === 'find') {
      return args[5];
    }
 
    return undefined;
  }
 
}