All files / src/service OpaPolicyService.ts

100% Statements 43/43
92.86% Branches 13/14
100% Functions 8/8
100% Lines 40/40

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                                  8x 8x 8x 8x           8x             8x 8x 8x   8x     11x         11x 11x   11x 11x 11x               6x 1x         5x           5x                             5x 5x           5x 5x 5x         5x 5x       5x 1x             4x   3x 3x                     4x 4x   1x               3x               3x 1x   2x 1x   1x      
/* 
  Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
  
  Licensed under the Apache License, Version 2.0 (the "License").
  You may not use this file except in compliance with the License.
  You may obtain a copy of the License at
  
      http://www.apache.org/licenses/LICENSE-2.0
  
  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/
 
import { HttpResponse } from '@aws-sdk/types';
import { Logger, LoggerFactory, ApjsbAwsHttpClient } from 'shared_types';
import { AppConfiguration } from 'src/common/configuration/AppConfiguration';
import { RoleChecker } from 'src/common/RoleChecker';
import RuleConfigError from 'src/common/RuleConfigError';
import {
    PolicyDecisionRequestContent,
    PolicyDecisionRequestContext,
    PolicyDecisionRequestType,
} from 'src/types/PolicyDecisionRequest';
import {
    OpaPolicyEvaluationStatus,
    PolicyDecisionResponse,
    ReasonPhrase,
    Status,
} from 'src/types/PolicyDecisionResponse';
import { PolicyDecisionResult, PolicyMeta } from 'src/types/PolicyDecisionResult';
import { inject, injectable } from 'tsyringe';
const OPA_PERSONA_ADMIN = 'admin';
const OPA_PERSONA_APPOWNER = 'appowner';
@injectable()
export class OpaPolicyService {
    opaURL?: string;
    logger: Logger;
    SERVICE_NAME = 'ff-api-lambda';
    defaultPolicySet: string[];
    constructor(
        @inject('LoggerFactory') loggerFactory: LoggerFactory,
        @inject('AppConfiguration') application: AppConfiguration,
        @inject('ApjsbAwsHttpClient') private httpClient: ApjsbAwsHttpClient,
        @inject('RoleChecker') private roleChecker: RoleChecker
    ) {
        this.logger = loggerFactory.getLogger('OpaPolicyService');
        this.opaURL = application.opaURL;
        this.defaultPolicySet = application.defaultPolicySet;
    }
 
    public async requestDecision(
        requestContext: PolicyDecisionRequestContext,
        requestContent: PolicyDecisionRequestContent,
        requestType: PolicyDecisionRequestType
    ): Promise<PolicyDecisionResponse> {
        if (!this.opaURL) {
            return {
                status: 'COMPLIANT',
                timestamp: Date.now(),
            };
        }
        requestContext.requester.role = this.roleChecker.isAdmin(
            requestContext.requester.arn,
            requestContext.requester.accountId
        )
            ? OPA_PERSONA_ADMIN
            : OPA_PERSONA_APPOWNER;
        const requestBody = {
            input: {
                request: {
                    policyIds: this.defaultPolicySet,
 
                    context: {
                        ...requestContext,
                    },
                    type: requestType,
                    content: {
                        ...requestContent,
                    },
                },
            },
        };
        this.logger.debug('opa request body', requestBody);
        return this.requestOPAEvaluation(requestBody);
    }
 
    private async requestOPAEvaluation(
        data: Record<string, unknown>
    ): Promise<PolicyDecisionResponse> {
        this.logger.debug('opa request request');
        this.logger.debug(`https://${this.opaURL}/v1/data/main/decision?provenance=true`);
        const result = await this.httpClient.post(
            `https://${this.opaURL}/v1/data/main/decision?provenance=true`,
            this.SERVICE_NAME,
            data
        );
        this.logger.debug('opa raw response', result);
        return this.toDecisionResponse(result);
    }
 
    private toDecisionResponse(rawResponse: HttpResponse): PolicyDecisionResponse {
        if (rawResponse.statusCode != 200 || rawResponse.body.length === 0) {
            throw new RuleConfigError(
                'Encounter error calling OPA cluster',
                rawResponse.statusCode,
                false
            );
        }
 
        const decision: PolicyDecisionResult = this.toJson(rawResponse.body.toString());
 
        this.logger.info('decision context %s', decision.provenance);
        return {
            status:
                decision.result.status === OpaPolicyEvaluationStatus.PASS
                    ? Status.COMPLIANT
                    : Status.NON_COMPLIANT,
            reasonPhrases: this.toReasonPhrases(decision),
            timestamp: new Date().getTime(),
        };
    }
 
    private toJson(rawStrJson: string) {
        try {
            return JSON.parse(rawStrJson);
        } catch (error) {
            throw new RuleConfigError(
                `Invalid input - request/response is not a valid json ${rawStrJson}`,
                503
            );
        }
    }
 
    private toReasonPhrases(decision: PolicyDecisionResult): Array<ReasonPhrase> {
        return decision.result.responses.map((r) => ({
            policyId: r.policyId,
            status: this.getStatus(r),
            reason: r.msg,
        }));
    }
 
    private getStatus(r: PolicyMeta): string {
        if (r.status === OpaPolicyEvaluationStatus.PASS) {
            return Status.COMPLIANT;
        }
        if (r.status === OpaPolicyEvaluationStatus.FAIL) {
            return Status.NON_COMPLIANT;
        }
        return Status.UNKNOWN;
    }
}