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 | /* 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 { APIGatewayProxyEvent, Context } from 'aws-lambda'; import { AuditChangeResult, FlowAudit, FlowTarget, Logger, LoggerFactory } from 'shared_types'; import { AsyncRequestHandler } from 'src/common/AsyncRequestHandler'; import { ServerlessResponse } from 'src/common/ServerlessResponse'; import { AuditsDataSourceService } from 'src/service/AuditsDataSourceService'; import { TargetsDataSourceService } from 'src/service/TargetsDataSourceService'; import { OpaPolicyService } from 'src/service/OpaPolicyService'; import { FlowTargetInput } from 'src/types/FlowTarget'; import { CreateTargetInputValidator } from 'src/validators/CreateTargetInputValidator'; import { inject, injectable } from 'tsyringe'; /** * @api {post} /targets Create new target * @apiGroup Targets * @apiDescription Create new target referencing a cloud resource or fixed resource * @apiVersion 1.0.0 * @apiExample {curl} CURL Example: curl --location --request POST 'https://<rest_api_id>.execute-api.ap-southeast-2.amazonaws.com/prod/audits' --data-raw '{ "id": "Onprem_Server", "value": "172.16.1.20", "type": "Address" }' * @apiSuccess (Success 201) target created target values * @apiParam {String[1..100]="[ 0-9a-zA-Z_-]+"} id The target's id. * @apiParam {string} type The target's type 'Address' | 'Cidr' | 'Arn' | 'Tagged' * @apiParam {value} value The target's value, can a an ARN or A tag list \ * e.g ARN arn:aws:ec2:ap-southeast-2:<account_number>:subnet/subnet-123 * e.g A tag list { \ * "value": "1", \ * "key": "FF_TEST"\ * } * @apiError (Error 400) UnsupportedTargetType Supported target type 'SinglePort' , 'Any' , 'PortRange' * @apiError (Error 400) InvalidTargetPortValue Invalid target port value according to it's type * @apiError (Error 400) InvalidTargetValue When request contains unsupported target value, supported 'Address' | 'Cidr' | 'Arn' | 'Tagged'; * @apiError (Error 400) targetInvalidReference When requested target is not reference to a concrete resource with IP * @apiError (Error 400) BadRequest NONE_COMPLIANT due to violate OPA policy * @apiError (Error 502) Time out * @apiError (Error 503) Internal error * * @apiSuccessExample Success-Response: * HTTP/1.1 200 OK * { "target": { "id": "Onprem_Server", "type": "Address", "value": "172.16.1.20", "createdBy": "arn:aws:sts::1000000:assumed-role/ObjectExtensionSecOpsAdminRole/DeviceClient", "lastUpdated": "2021-09-15T06:39:38.997Z" } } * * @apiSampleRequest off */ @injectable() export class CreateTargetHandler implements AsyncRequestHandler<APIGatewayProxyEvent, ServerlessResponse> { private readonly logger: Logger; constructor(@inject('LoggerFactory') loggerFactory: LoggerFactory, @inject('ObjectsDataSourceService') private targetsDataSourceService: TargetsDataSourceService, @inject('AuditsDataSourceService') private auditsDataSourceService: AuditsDataSourceService, @inject('CreateObjectInputValidator') private validator: CreateTargetInputValidator, @inject('OpaPolicyService') private opaPolicyService: OpaPolicyService ) { this.logger = loggerFactory.getLogger('CreateObjectHandler'); } async handle( event: APIGatewayProxyEvent, // eslint-disable-next-line @typescript-eslint/no-unused-vars _context: Context ): Promise<ServerlessResponse> { this.logger.debug('Processing create rule target request'); const input = await this.validator.parseAndValidate(event); const requestorIdentity = event.requestContext.identity?.userArn ?? 'Unknown'; const accountId = event.requestContext.accountId ?? '100000'; this.logger.debug('sending to opa') try { const response = await this.opaPolicyService.requestDecision({ "requester": { "arn": requestorIdentity, "accountId": accountId } }, { object: input }, 'CREATE') this.logger.info(' opa decision response', response) if (response.status === 'NON_COMPLIANT') { return ServerlessResponse.ofObject(400, { message: response.reasonPhrases }); } } catch (e) { this.logger.error('opa error', e); return ServerlessResponse.ofObject(500, { message: `Unable to determine user accessibility, ${e}` }); } const targetToBeCreated: FlowTargetInput = { id: input.id, type: input.type, value: input.value, } try { const target = await this.targetsDataSourceService.createTarget(targetToBeCreated, requestorIdentity); await this.auditEntryForCreation(requestorIdentity, 'SUCCESS', target); return ServerlessResponse.ofObject(201, { target }); } catch (e) { this.logger.error('Error while creating rule object', e, input); this.auditEntryForCreation(requestorIdentity, 'REJECTED', input, [e.message]); return ServerlessResponse.ofObject(500, { message: 'Error while creating rule object' }); } } async auditEntryForCreation(requestorIdentity: string, status: AuditChangeResult, target: FlowTarget, reasons?: string[]): Promise<FlowAudit> { return await this.auditsDataSourceService.createAuditEntry({ requestedBy: requestorIdentity, requestedTimestamp: new Date().toISOString(), requestedChange: { type: 'CREATE', //CREATE/UPDATE/DELETE changeContent: { requestedObject: target, }, changeResult: status, // SUCCESS, REJECTED reasonPhrase: reasons ?? [] } }) } } |