def create_root_api_gateway(self, api_domain_name: str): """ We need this to create the root API Gateway resource. """ certificate = self.create_api_certificate(api_domain_name, self.zone) domain_options = aws_apigateway.DomainNameOptions( domain_name=api_domain_name, certificate=certificate) stage_options = aws_apigateway.StageOptions(throttling_rate_limit=10, throttling_burst_limit=100) rest_api = aws_apigateway.RestApi(self, 'PublicCrudApi', rest_api_name='PublicCrudApi', domain_name=domain_options, deploy_options=stage_options) kix.info("Routing A-Record Alias for REST API") a_record_target = aws_route53.RecordTarget.from_alias( aws_route53_targets.ApiGateway(rest_api)) aws_route53.ARecord(self, "PublicCrudApiAliasRecord", zone=self.zone, target=a_record_target, record_name=api_domain_name) # Also create the authorizer for this API. self._api_authorizer = self.create_root_api_authorizer( self.user_pool, rest_api) return rest_api
def __init__( self, scope: core.Construct, id: str, # pylint: disable=redefined-builtin lambda_notifications: aws_lambda.IFunction, social_log_group: aws_logs.ILogGroup, pagespeed_table: aws_dynamodb.ITable, **kwargs) -> None: super().__init__(scope, id, **kwargs) api_lambda = get_lambda( self, id, code='lib/stacks/{id}/{id}'.format(id=id), handler='main.handler', environment={ 'CORS_ALLOW_ORIGIN': env['CORS_ALLOW_ORIGIN'], 'PUSHOVER_TOKEN': env['PUSHOVER_TOKEN'], 'PUSHOVER_USERKEY': env['PUSHOVER_USERKEY'], 'LAMBDA_FUNCTIONS_LOG_LEVEL': 'INFO', 'LAMBDA_NOTIFICATIONS': lambda_notifications.function_name, 'PAGESPEED_TABLE': pagespeed_table.table_name, 'REPORT_LOG_GROUP_NAME': social_log_group.log_group_name, }, ) lambda_notifications.grant_invoke(api_lambda) social_log_group.grant(api_lambda, "logs:GetLogEvents", "logs:DescribeLogStreams") pagespeed_table.grant_read_data(api_lambda) cert = aws_certificatemanager.Certificate( self, '{}-certificate'.format(id), domain_name=env['API_DOMAIN'], ) domain = aws_apigateway.DomainNameOptions( certificate=cert, domain_name=env['API_DOMAIN'], ) cors = aws_apigateway.CorsOptions( allow_methods=['POST'], allow_origins=[env['CORS_ALLOW_ORIGIN']] if "CORS_ALLOW_ORIGIN" in env else aws_apigateway.Cors.ALL_ORIGINS) aws_apigateway.LambdaRestApi( self, '%s-gateway' % id, handler=api_lambda, domain_name=domain, default_cors_preflight_options=cors, )
def __init__(self, scope: core.Construct, id: str, **kwargs) -> None: super().__init__(scope, id, **kwargs) my_lambda = aws_lambda.Function( self, environ['CDK_APP_NAME'], runtime=aws_lambda.Runtime.PYTHON_3_8, code=aws_lambda.Code.asset('lambda'), handler='contact_us.handler', environment={ 'CORS_ALLOW_ORIGIN': environ.get('CORS_ALLOW_ORIGIN', '*'), 'PUSHOVER_API_ENDPOINT': environ['PUSHOVER_API_ENDPOINT'], 'PUSHOVER_TOKEN': environ['PUSHOVER_TOKEN'], 'PUSHOVER_USERKEY': environ['PUSHOVER_USERKEY'], }, log_retention=aws_logs.RetentionDays.ONE_WEEK, ) cert = aws_certificatemanager.Certificate( self, '{}-certificate'.format(environ['CDK_APP_NAME']), domain_name=environ['CDK_BASE_DOMAIN'], ) domain = aws_apigateway.DomainNameOptions( certificate=cert, domain_name=environ['CDK_BASE_DOMAIN'], ) cors = aws_apigateway.CorsOptions( allow_methods=["POST"], allow_origins=[environ['CORS_ALLOW_ORIGIN']] if environ.get('CORS_ALLOW_ORIGIN') else aws_apigateway.Cors.ALL_ORIGINS, ) aws_apigateway.LambdaRestApi( self, '{}-gateway'.format(environ['CDK_APP_NAME']), handler=my_lambda, domain_name=domain, default_cors_preflight_options=cors, )
def __init__(self, scope: cdk.Construct, construct_id: str, **kwargs) -> None: super().__init__(scope, construct_id, **kwargs) environment = self.node.try_get_context('environment') server_domain = self.node.try_get_context('server_domain') hosted_zone_id = self.node.try_get_context('hosted_zone_id') if environment == 'prod': self.domain_name = f'start.{server_domain}' else: self.domain_name = f'start.{environment}.{server_domain}' hosted_zone = r53.HostedZone.from_hosted_zone_attributes( self, 'Zone', hosted_zone_id=hosted_zone_id, zone_name=server_domain) certificate = acm.Certificate( self, 'StartCert', domain_name=self.domain_name, validation=acm.CertificateValidation.from_dns( hosted_zone=hosted_zone)) self.rest_api = apigw.RestApi( self, 'api', domain_name=apigw.DomainNameOptions(certificate=certificate, domain_name=self.domain_name), deploy_options=apigw.StageOptions(stage_name=environment)) arecord = r53.ARecord( self, 'StartARecord', zone=hosted_zone, record_name=self.domain_name, target=r53.RecordTarget( alias_target=r53_targets.ApiGateway(self.rest_api))) cdk.CfnOutput(self, 'DNSName', value=arecord.domain_name)
def __init__(self, scope: core.Construct, id: str, *, prefix: str, environment: str, configuration, **kwargs): """ :param scope: Stack class, used by CDK. :param id: ID of the construct, used by CDK. :param prefix: Prefix of the construct, used for naming purposes. :param environment: Environment of the construct, used for naming purposes. :param configuration: Configuration of the construct. In this case APIGATEWAY_LAMBDA_SIMPLE_WEB_SERVICE_SCHEMA. :param kwargs: Other parameters that could be used by the construct. """ super().__init__(scope, id, **kwargs) self.prefix = prefix self.environment_ = environment self._configuration = configuration # Validating that the payload passed is correct validate_configuration( configuration_schema=APIGATEWAY_SIMPLE_WEB_SERVICE_SCHEMA, configuration_received=self._configuration) # Define S3 Buckets Cluster if isinstance(self._configuration.get("buckets"), list): self._s3_buckets = [ base_bucket(self, **bucket) for bucket in self._configuration["buckets"] ] api_configuration = self._configuration["api"] # Define Lambda Authorizer Function authorizer_functions = api_configuration.get("authorizer_function") self._authorizer_function = None if authorizer_functions is not None: if authorizer_functions.get("imported") is not None: self._authorizer_function = lambda_.Function.from_function_arn( self, id=authorizer_functions.get("imported").get("identifier"), function_arn=authorizer_functions.get("imported").get( "arn"), ) elif authorizer_functions.get("origin") is not None: self._authorizer_function = base_lambda_function( self, **authorizer_functions.get("origin")) # Define API Gateway Authorizer gateway_authorizer = None if self._authorizer_function is not None: # Define Gateway Token Authorizer authorizer_name = api_configuration[ "apigateway_name"] + "_" + "authorizer" if authorizer_functions.get("results_cache_ttl") is not None: results_cache_ttl = core.Duration.minutes( authorizer_functions.get("results_cache_ttl")) else: results_cache_ttl = None gateway_authorizer = api_gateway.TokenAuthorizer( self, id=authorizer_name, authorizer_name=authorizer_name, handler=self._authorizer_function, results_cache_ttl=results_cache_ttl) # Defining Custom Domain domain_options = None custom_domain = api_configuration["root_resource"].get("custom_domain") if custom_domain is not None: domain_name = custom_domain["domain_name"] certificate_arn = custom_domain["certificate_arn"] domain_options = api_gateway.DomainNameOptions( certificate=cert_manager.Certificate.from_certificate_arn( self, id=domain_name, certificate_arn=certificate_arn), domain_name=domain_name, ) # Define API Gateway Lambda Handler self._handler_function = base_lambda_function( self, **api_configuration["root_resource"]["handler"]) if api_configuration["proxy"] is False and api_configuration.get( "root_resource").get("methods") is None: print( "Unable to check which method to use for the API! Use proxy: True or define methods..." ) raise RuntimeError self._lambda_rest_api = api_gateway.LambdaRestApi( self, id=api_configuration["apigateway_name"], rest_api_name=api_configuration["apigateway_name"], description=api_configuration["apigateway_description"], domain_name=domain_options, handler=self._handler_function, proxy=api_configuration["proxy"], cloud_watch_role=True, ) # Add Custom responses self._lambda_rest_api.add_gateway_response( f"{self.prefix}_4XXresponse_{self.environment_}", type=api_gateway.ResponseType.DEFAULT_4_XX, response_headers={"Access-Control-Allow-Origin": "'*'"}, ) self._lambda_rest_api.add_gateway_response( f"{self.prefix}_5XXresponse_{self.environment_}", type=api_gateway.ResponseType.DEFAULT_5_XX, response_headers={"Access-Control-Allow-Origin": "'*'"}, ) # Define Gateway Resource and Methods resource = self._lambda_rest_api.root.add_resource( api_configuration["root_resource"]["name"]) allowed_origins = api_configuration["root_resource"].get( "allowed_origins") if api_configuration["proxy"] is False: gateway_methods = api_configuration["root_resource"]["methods"] for method in gateway_methods: resource.add_method(http_method=method, authorizer=gateway_authorizer) if allowed_origins is not None: resource.add_cors_preflight(allow_origins=allowed_origins, allow_methods=gateway_methods) else: if allowed_origins is not None: resource.add_cors_preflight(allow_origins=allowed_origins)
def __init__(self, scope: core.Construct, construct_id: str, **kwargs) -> None: super().__init__(scope, construct_id, **kwargs) # ----------------------------------- # Cognito User Pool # ----------------------------------- userpool = cognito.UserPool( self, "ServerlessTodoUserPool", user_pool_name="ServerlessTodoUserPool", sign_in_aliases=cognito.SignInAliases(username=True, email=True), password_policy=cognito.PasswordPolicy( min_length=6, require_digits=True, require_lowercase=True, require_symbols=True, require_uppercase=True, temp_password_validity=core.Duration.days(7)), auto_verify=cognito.AutoVerifiedAttrs(email=True), standard_attributes=cognito.StandardAttributes( email=cognito.StandardAttribute(mutable=True, required=True), family_name=cognito.StandardAttribute(mutable=True, required=True), given_name=cognito.StandardAttribute(mutable=True, required=True))) user_pool_client = userpool.add_client( "UserPoolClient", auth_flows=cognito.AuthFlow(admin_user_password=True)) # ----------------------------------- # dynamodb # ----------------------------------- dynamodbTable = dynamodb.Table( self, "TaskTable", partition_key=dynamodb.Attribute( name="id", type=dynamodb.AttributeType.STRING), sort_key=dynamodb.Attribute(name="meta", type=dynamodb.AttributeType.STRING), billing_mode=dynamodb.BillingMode.PAY_PER_REQUEST, point_in_time_recovery=True, server_side_encryption=True) dynamodbTable.add_global_secondary_index( partition_key=dynamodb.Attribute( name="meta", type=dynamodb.AttributeType.STRING), sort_key=dynamodb.Attribute(name="id", type=dynamodb.AttributeType.STRING), index_name="meta-id-index") dynamodbTable.add_global_secondary_index( partition_key=dynamodb.Attribute( name="owner", type=dynamodb.AttributeType.STRING), sort_key=dynamodb.Attribute(name="meta", type=dynamodb.AttributeType.STRING), index_name="owner-meta-index") # ----------------------------------- # apigateway # ----------------------------------- acm_arn = self.node.try_get_context('acm_arn') domain_name = self.node.try_get_context("domain_name") hosted_zone = self.node.try_get_context("hosted_zone") api_policy = iam.PolicyDocument( statements=iam.PolicyStatement(actions=["lambda:InvokeFunction"], ) .add_resources("arn:aws:lambda:{}:{}:function:*".format( self.region, self.account))) if acm_arn and domain_name and hosted_zone: api = apigw.RestApi( self, 'API', domain_name=apigw.DomainNameOptions( certificate=acm.Certificate.from_certificate_arn( self, 'ApiCertificate', acm_arn), domain_name=domain_name, endpoint_type=apigw.EndpointType.REGIONAL), deploy_options=apigw.StageOptions(metrics_enabled=True), policy=api_policy, rest_api_name="Serverless TODO API", endpoint_types=[apigw.EndpointType.REGIONAL], default_cors_preflight_options=apigw.CorsOptions( allow_origins=apigw.Cors. ALL_ORIGINS, # TODO: Temporary for development allow_headers=[ "Content-Type", "X-Amz-Date", "Authorization", "X-Api-Key", "X-Amz-Security-Token", "X-Tracing-Id", "x-jeffy-correlation-id", "x-amzn-trace-id" ], allow_methods=apigw.Cors.ALL_METHODS, allow_credentials=True)) route53.CfnRecordSet( self, "apiDomainRecord", name=domain_name, type="A", alias_target={ "dnsName": api.domain_name.domain_name_alias_domain_name, "hostedZoneId": api.domain_name.domain_name_alias_hosted_zone_id }, hosted_zone_id=hosted_zone, ) else: api = apigw.RestApi( self, 'API', deploy_options=apigw.StageOptions(metrics_enabled=True), policy=api_policy, rest_api_name="Serverless TODO API", endpoint_types=[apigw.EndpointType.REGIONAL], default_cors_preflight_options=apigw.CorsOptions( allow_origins=apigw.Cors. ALL_ORIGINS, # TODO: Temporary for development allow_headers=[ "Content-Type", "X-Amz-Date", "Authorization", "X-Api-Key", "X-Amz-Security-Token", "X-Tracing-Id", "x-jeffy-correlation-id", "x-amzn-trace-id" ], allow_methods=apigw.Cors.ALL_METHODS, allow_credentials=True)) cognito_authorizer = apigw.CognitoUserPoolsAuthorizer( self, "CognitoAuthorizer", cognito_user_pools=[userpool], authorizer_name='todo_cognito_authorizer', identity_source='method.request.header.Authorization', results_cache_ttl=core.Duration.minutes(60)) api_role = iam.Role(self, "ApiRole", assumed_by=iam.ServicePrincipal( service="apigateway.amazonaws.com")) api_statement = iam.PolicyStatement( actions=["lambda:InvokeFunction"], resources=[ "arn:aws:lambda:{}:{}:function:*".format( self.region, self.account) ]) api_role.add_to_policy(api_statement) # ----------------------------------- # lambda common configure # ----------------------------------- env = { "TABLE_NAME": dynamodbTable.table_name, "USER_POOL_ID": userpool.user_pool_id, "USER_POOL_NAME": userpool.user_pool_provider_name, "CLIENT_ID": user_pool_client.user_pool_client_id } # ----------------------------------- # get handler # ----------------------------------- get_resource_base_name = "getTaskFunction" get_task_func = lambda_.Function( self, get_resource_base_name, code=lambda_.Code.from_asset( 'function/src/task', bundling=core.BundlingOptions( image=lambda_.Runtime.PYTHON_3_8.bundling_docker_image, command=[ 'bash', '-c', 'pip install -r requirements.txt -t /asset-output && cp -a . /asset-output' ], )), handler="get.lambda_handler", runtime=lambda_.Runtime.PYTHON_3_8, environment=env, tracing=lambda_.Tracing.ACTIVE, timeout=core.Duration.seconds(29), memory_size=512) get_task_func.add_to_role_policy(statement=iam.PolicyStatement( actions=['dynamodb:*'], resources=[ dynamodbTable.table_arn, dynamodbTable.table_arn + '/*' ])) logs.LogGroup(self, get_resource_base_name + 'LogGroup', log_group_name='/aws/lambda/' + get_task_func.function_name, retention=logs.RetentionDays.TWO_WEEKS) task_path = api.root.add_resource("task") task_id_path = task_path.add_resource("{task_id}") get_task_integration = apigw.LambdaIntegration( get_task_func, credentials_role=api_role) task_id_path.add_method( "GET", integration=get_task_integration, authorization_type=apigw.AuthorizationType.COGNITO, authorizer=cognito_authorizer, ) # ----------------------------------- # create handler # ----------------------------------- create_resource_base_name = "createTaskFunction" create_task_func = lambda_.Function( self, create_resource_base_name, code=lambda_.Code.from_asset( 'function/src/task', bundling=core.BundlingOptions( image=lambda_.Runtime.PYTHON_3_8.bundling_docker_image, command=[ 'bash', '-c', 'pip install -r requirements.txt -t /asset-output && cp -a . /asset-output' ], )), handler="create.lambda_handler", runtime=lambda_.Runtime.PYTHON_3_8, environment=env, tracing=lambda_.Tracing.ACTIVE, timeout=core.Duration.seconds(29), memory_size=512) create_task_func.add_to_role_policy(statement=iam.PolicyStatement( actions=['dynamodb:*'], resources=[ dynamodbTable.table_arn, dynamodbTable.table_arn + '/*' ])) logs.LogGroup(self, create_resource_base_name + 'LogGroup', log_group_name='/aws/lambda/' + create_task_func.function_name, retention=logs.RetentionDays.TWO_WEEKS) create_task_integration = apigw.LambdaIntegration( create_task_func, credentials_role=api_role) task_path.add_method( "POST", integration=create_task_integration, authorization_type=apigw.AuthorizationType.COGNITO, authorizer=cognito_authorizer, ) # ----------------------------------- # update handler # ----------------------------------- update_resource_base_name = "updateTaskFunction" update_task_func = lambda_.Function( self, update_resource_base_name, code=lambda_.Code.from_asset( 'function/src/task', bundling=core.BundlingOptions( image=lambda_.Runtime.PYTHON_3_8.bundling_docker_image, command=[ 'bash', '-c', 'pip install -r requirements.txt -t /asset-output && cp -a . /asset-output' ], )), handler="update.lambda_handler", runtime=lambda_.Runtime.PYTHON_3_8, environment=env, tracing=lambda_.Tracing.ACTIVE, timeout=core.Duration.seconds(29), memory_size=512) update_task_func.add_to_role_policy(statement=iam.PolicyStatement( actions=['dynamodb:*'], resources=[ dynamodbTable.table_arn, dynamodbTable.table_arn + '/*' ])) logs.LogGroup(self, update_resource_base_name + 'LogGroup', log_group_name='/aws/lambda/' + update_task_func.function_name, retention=logs.RetentionDays.TWO_WEEKS) update_task_integration = apigw.LambdaIntegration( update_task_func, credentials_role=api_role) task_id_path.add_method( "POST", integration=update_task_integration, authorization_type=apigw.AuthorizationType.COGNITO, authorizer=cognito_authorizer, ) # ----------------------------------- # delete handler # ----------------------------------- delete_resource_base_name = "deleteTaskFunction" delete_task_func = lambda_.Function( self, delete_resource_base_name, code=lambda_.Code.from_asset( 'function/src/task', bundling=core.BundlingOptions( image=lambda_.Runtime.PYTHON_3_8.bundling_docker_image, command=[ 'bash', '-c', 'pip install -r requirements.txt -t /asset-output && cp -a . /asset-output' ], )), handler="delete.lambda_handler", runtime=lambda_.Runtime.PYTHON_3_8, environment=env, tracing=lambda_.Tracing.ACTIVE, timeout=core.Duration.seconds(29), memory_size=512) delete_task_func.add_to_role_policy(statement=iam.PolicyStatement( actions=['dynamodb:*'], resources=[ dynamodbTable.table_arn, dynamodbTable.table_arn + '/*' ])) logs.LogGroup(self, delete_resource_base_name + 'LogGroup', log_group_name='/aws/lambda/' + delete_task_func.function_name, retention=logs.RetentionDays.TWO_WEEKS) delete_task_integration = apigw.LambdaIntegration( delete_task_func, credentials_role=api_role) task_id_path.add_method( "DELETE", integration=delete_task_integration, authorization_type=apigw.AuthorizationType.COGNITO, authorizer=cognito_authorizer, ) # ----------------------------------- # search handler # ----------------------------------- search_resource_base_name = "searchTaskFunction" search_task_func = lambda_.Function( self, search_resource_base_name, code=lambda_.Code.from_asset( 'function/src/task', bundling=core.BundlingOptions( image=lambda_.Runtime.PYTHON_3_8.bundling_docker_image, command=[ 'bash', '-c', 'pip install -r requirements.txt -t /asset-output && cp -a . /asset-output' ], )), handler="search.lambda_handler", runtime=lambda_.Runtime.PYTHON_3_8, environment=env, tracing=lambda_.Tracing.ACTIVE, timeout=core.Duration.seconds(29), memory_size=512) search_task_func.add_to_role_policy(statement=iam.PolicyStatement( actions=['dynamodb:*'], resources=[ dynamodbTable.table_arn, dynamodbTable.table_arn + '/*' ])) logs.LogGroup(self, search_resource_base_name + 'LogGroup', log_group_name='/aws/lambda/' + search_task_func.function_name, retention=logs.RetentionDays.TWO_WEEKS) search_task_integration = apigw.LambdaIntegration( search_task_func, credentials_role=api_role) tasks_path = api.root.add_resource("tasks") tasks_path.add_method( "GET", integration=search_task_integration, authorization_type=apigw.AuthorizationType.COGNITO, authorizer=cognito_authorizer, ) # ----------------------------------- # login handler # ----------------------------------- login_resource_base_name = "loginFunction" login_task_func = lambda_.Function( self, login_resource_base_name, code=lambda_.Code.from_asset( 'function/src/user', bundling=core.BundlingOptions( image=lambda_.Runtime.PYTHON_3_8.bundling_docker_image, command=[ 'bash', '-c', 'pip install -r requirements.txt -t /asset-output && cp -a . /asset-output' ], )), handler="login.lambda_handler", runtime=lambda_.Runtime.PYTHON_3_8, environment=env, tracing=lambda_.Tracing.ACTIVE, timeout=core.Duration.seconds(29), memory_size=512) login_task_func.add_to_role_policy(statement=iam.PolicyStatement( actions=['cognito-idp:AdminInitiateAuth'], resources=[userpool.user_pool_arn])) logs.LogGroup(self, login_resource_base_name + 'LogGroup', log_group_name='/aws/lambda/' + login_task_func.function_name, retention=logs.RetentionDays.TWO_WEEKS) login_task_integration = apigw.LambdaIntegration(login_task_func) auth_path = api.root.add_resource("auth") auth_login_path = auth_path.add_resource("login") auth_login_path.add_method("POST", integration=login_task_integration)
def __init__(self, scope: core.Construct, id: str, **kwargs) -> None: super().__init__(scope, id, **kwargs) api_name='voncv' cert_arn='arn:aws:acm:us-east-1:921279086507:certificate/1cdc5fa6-0978-4c3c-96fa-ced4188b4fd0' # Example automatically generated. See https://github.com/aws/jsii/issues/826 cert = acm.Certificate.from_certificate_arn(self,"cert",cert_arn) domain_name='voncv.sema4.com' domain_obj=api.DomainNameOptions(certificate=cert, domain_name=domain_name) #domain_name_obj=api.DefaultDomainMappingOptions( domain_name=domain_obj1, mapping_key=None) integration_uri='http://voncwesprod.sema4.com:3000' #classaws_cdk.aws_apigateway.HttpIntegration(url, *, http_method=None, options=None, proxy=None) #base_api=api.HttpApi(self, 'rootapi', api_name=api_name, cors_preflight=None, create_default_stage=None, default_domain_mapping=domain_name_obj) # , default_integration=None) base_api = api.RestApi(self, "RestApi",rest_api_name=api_name,domain_name=domain_obj, deploy=False ) integration_response_200=api.IntegrationResponse(status_code='200') integration_response_400=api.IntegrationResponse(status_code='400',selection_pattern='400') integration_response_401=api.IntegrationResponse(status_code='401',selection_pattern='401') integration_response_404=api.IntegrationResponse(status_code='400',selection_pattern='404') integration_response_405=api.IntegrationResponse(status_code='401',selection_pattern='405') integration_response_500=api.IntegrationResponse(status_code='401',selection_pattern='500') integration_response_all=[integration_response_200, integration_response_400, integration_response_401, integration_response_404, integration_response_405, integration_response_500 ] integration_options=api.IntegrationOptions(integration_responses=integration_response_all) #method_reponse=api.IntegrationOptions(integration_responses=integration_response_all) mr=[ api.MethodResponse(status_code='200'), api.MethodResponse(status_code='400'), api.MethodResponse(status_code='401'), api.MethodResponse(status_code='404'), api.MethodResponse(status_code='405'), api.MethodResponse(status_code='500') ] integration=api.Integration(type=api.IntegrationType.HTTP,integration_http_method='POST',uri=integration_uri,options=integration_options) control = base_api.root.add_resource('control') control_get=control.add_method('POST',integration) control_controlid=control.add_resource('{controlid}') control_controlid_post=control_controlid.add_method('POST',integration) control_controlid_sample=control_controlid.add_resource('sample') control_controlid_sample_sampleid=control_controlid_sample.add_resource('sampleid') control_controlid_sample_sampleid_get=control_controlid_sample_sampleid.add_method('GET',integration,method_responses=mr) control_controlid_sample_sampleid_pipelineoutput=control_controlid_sample_sampleid.add_resource('pipeline_output') control_controlid_sample_sampleid_pipelineoutput_post=control_controlid_sample_sampleid_pipelineoutput.add_method('POST',integration) getalllpatients = base_api.root.add_resource('getallpatients') getalllpatients_get=getalllpatients.add_method('GET',integration) patient = base_api.root.add_resource('patient') patient_post = patient.add_method('GET',integration) patient_get = patient.add_method('POST',integration) patientid=patient.add_resource('patientid') patient_put=patientid.add_method('PUT',integration) patient_get=patientid.add_method('GET',integration) patient_case=patientid.add_resource('case') patient_case_post=patient_case.add_method('POST',integration) patient_case_caseid=patient_case.add_resource('caseid') patient_case_caseid_get= patient_case_caseid.add_method('GET',integration) patient_case_caseid_put= patient_case_caseid.add_method('PUT',integration) patient_case_caseid_close=patient_case_caseid.add_resource('close') patient_case_caseid_close_post=patient_case_caseid_close.add_method('PUT',integration) patient_case_caseid_curate=patient_case_caseid.add_resource('curate') patient_case_caseid_curate_post=patient_case_caseid_curate.add_method('POST',integration) patient_case_caseid_fail=patient_case_caseid.add_resource('fail') patient_case_caseid_fail_post=patient_case_caseid_fail.add_method('POST',integration) patient_case_caseid_reopen=patient_case_caseid.add_resource('reopen') patient_case_caseid_reopen_post=patient_case_caseid_reopen.add_method('POST',integration) patient_case_caseid_sample=patient_case_caseid.add_resource('sample') patient_case_caseid_sample_sampleid=patient_case_caseid_sample.add_resource('sampleid') patient_case_caseid_sample_sampleid_get=patient_case_caseid_sample_sampleid.add_method('GET',integration) patient_case_caseid_sample_sampleid_fail=patient_case_caseid_sample_sampleid.add_resource('fail') patient_case_caseid_sample_sampleid_fail_post=patient_case_caseid_sample_sampleid_fail.add_method('POST',integration) patient_case_caseid_sample_sampleid_pipelineoutput=patient_case_caseid_sample_sampleid.add_resource('pipeline-output') patient_case_caseid_sample_sampleid_pipelineoutput_post=patient_case_caseid_sample_sampleid_pipelineoutput.add_method('POST',integration) patient_case_caseid_variant=patient_case_caseid.add_resource('variant') patient_case_caseid_variant_post=patient_case_caseid.add_method('POST',integration)
def __init__(self, scope: core.Construct, id: str, resources: FsiSharedResources, subnet_group_name: str = 'Default', **kwargs) -> None: super().__init__(scope, id, **kwargs) # Configure the container resources... self.repo = assets.DockerImageAsset(self, 'Repo', directory='src/fsi/earnings', file='Dockerfile') code = lambda_.DockerImageCode.from_ecr( repository=self.repo.repository, tag=self.repo.image_uri.split(':')[-1]) # Configure security policies... role = iam.Role( self, 'Role', assumed_by=iam.ServicePrincipal(service='lambda'), description='HomeNet-{}-Fsi-EarningsReport'.format( resources.landing_zone.zone_name), role_name='fsi-earnings@homenet.{}.{}'.format( resources.landing_zone.zone_name, core.Stack.of(self).region).lower(), managed_policies=[ iam.ManagedPolicy.from_aws_managed_policy_name( managed_policy_name= 'service-role/AWSLambdaVPCAccessExecutionRole'), ]) # Grant any permissions... self.earnings_table = d.Table( self, 'EarningCalendar', table_name='FsiCoreSvc-EarningsCalendar', billing_mode=d.BillingMode.PAY_PER_REQUEST, partition_key=d.Attribute(name='PartitionKey', type=d.AttributeType.STRING), sort_key=d.Attribute(name='SortKey', type=d.AttributeType.STRING), time_to_live_attribute='Expiration', point_in_time_recovery=True, server_side_encryption=True) self.earnings_table.grant_read_write_data(role) # Define any variables for the function self.function_env = { 'CACHE_TABLE': self.earnings_table.table_name, } # Create the backing webapi compute ... self.function = lambda_.DockerImageFunction( self, 'Function', code=code, role=role, function_name='HomeNet-{}-Fsi-{}'.format( resources.landing_zone.zone_name, FsiEarningsGateway.__name__), description='Python Lambda function for ' + FsiEarningsGateway.__name__, timeout=core.Duration.seconds(30), tracing=lambda_.Tracing.ACTIVE, vpc=resources.landing_zone.vpc, log_retention=logs.RetentionDays.FIVE_DAYS, memory_size=128, allow_all_outbound=True, vpc_subnets=ec2.SubnetSelection( subnet_group_name=subnet_group_name), security_groups=[resources.landing_zone.security_group], environment=self.function_env, ) # Bind APIG to Lambda compute... self.frontend_proxy = a.LambdaRestApi( self, 'ApiGateway', proxy=True, handler=self.function, options=a.RestApiProps( description='Hosts the Earnings Calendar Services via ' + self.function.function_name, domain_name=a.DomainNameOptions( domain_name='earnings.trader.fsi', certificate=Certificate.from_certificate_arn( self, 'Certificate', certificate_arn= 'arn:aws:acm:us-east-2:581361757134:certificate/4e3235f7-49a1-42a5-a671-f2449b45f72d' ), security_policy=a.SecurityPolicy.TLS_1_0), policy=iam.PolicyDocument(statements=[ iam.PolicyStatement(effect=iam.Effect.ALLOW, actions=['execute-api:Invoke'], principals=[iam.AnyPrincipal()], resources=['*'], conditions={ 'IpAddress': { 'aws:SourceIp': [ '10.0.0.0/8', '192.168.0.0/16', '72.90.160.65/32' ] } }) ]), endpoint_configuration=a.EndpointConfiguration( types=[a.EndpointType.REGIONAL], ))) # Register Dns Name r53.ARecord(self, 'AliasRecord', zone=resources.trader_dns_zone, record_name='earnings.%s' % resources.trader_dns_zone.zone_name, target=r53.RecordTarget.from_alias( dns_targets.ApiGateway(self.frontend_proxy)))
def __init__(self, scope: core.Construct, id: str, *, prefix: str, environment: str, configuration, **kwargs): """ :param scope: Stack class, used by CDK. :param id: ID of the construct, used by CDK. :param prefix: Prefix of the construct, used for naming purposes. :param environment: Environment of the construct, used for naming purposes. :param configuration: Configuration of the construct. In this case APIGATEWAY_LAMBDA_SIMPLE_WEB_SERVICE_SCHEMA. :param kwargs: Other parameters that could be used by the construct. """ super().__init__(scope, id, **kwargs) self.prefix = prefix self.environment_ = environment self._configuration = configuration # Validating that the payload passed is correct validate_configuration( configuration_schema=APIGATEWAY_ROBUST_WEB_SERVICE_SCHEMA, configuration_received=self._configuration) # Define S3 Buckets Cluster if isinstance(self._configuration.get("buckets"), list): self._s3_buckets = [ base_bucket(self, **bucket) for bucket in self._configuration["buckets"] ] api_configuration = self._configuration["api"] api_gateway_name = self.prefix + "_" + api_configuration[ "apigateway_name"] + "_" + self.environment_ api_gateway_name_description = api_configuration.get( "apigateway_description") # # Define Lambda Authorizer Function # authorizer_functions = api_configuration.get("authorizer_function") # self._authorizer_function = None # if authorizer_functions is not None: # if authorizer_functions.get("imported") is not None: # self._authorizer_function = lambda_.Function.from_function_arn( # self, # id=authorizer_functions.get("imported").get("identifier"), # function_arn=authorizer_functions.get("imported").get("arn"), # ) # elif authorizer_functions.get("origin") is not None: # self._authorizer_function = base_lambda_function(self, **authorizer_functions.get("origin")) # # # Define API Gateway Authorizer # gateway_authorizer = None # if self._authorizer_function is not None: # # Define Gateway Token Authorizer # authorizer_name = api_configuration["apigateway_name"] + "_" + "authorizer" # if authorizer_functions.get("results_cache_ttl") is not None: # results_cache_ttl = core.Duration.minutes(authorizer_functions.get("results_cache_ttl")) # else: # results_cache_ttl = None # gateway_authorizer = api_gateway.TokenAuthorizer( # self, # id=authorizer_name, # authorizer_name=authorizer_name, # handler=self._authorizer_function, # results_cache_ttl=results_cache_ttl # ) # # api_gateway.TokenAuthorizer # api_gateway.RequestAuthorizer # api_gateway.CognitoUserPoolsAuthorizer # Define API Gateway Authorizer self._authorizer_function = None self._gateway_authorizer = self.set_authorizer() # Defining Custom Domain domain_options = None custom_domain = api_configuration["settings"].get("custom_domain") if custom_domain is not None: domain_name = custom_domain["domain_name"] certificate_arn = custom_domain["certificate_arn"] domain_options = api_gateway.DomainNameOptions( certificate=cert_manager.Certificate.from_certificate_arn( self, id=domain_name, certificate_arn=certificate_arn), domain_name=domain_name, ) # Define API Gateway Lambda Handler self._handler_function = base_lambda_function( self, **api_configuration["settings"]["default_handler"]) # Validating Proxy configuration for API Gateway proxy_configuration = api_configuration["settings"]["proxy"] if proxy_configuration is False and api_configuration["settings"].get( "default_http_methods") is None: print( "Unable to check which method to use for the API! Use proxy: True or define methods..." ) raise RuntimeError # Defining allowed binary media types by API Gateway binary_media_types = api_configuration["settings"].get( "default_media_types") # Defining CORS preflight options default_cors_options = None default_cors_configuration = api_configuration["settings"].get( "default_cors_options") if default_cors_configuration is not None: default_cors_options = api_gateway.CorsOptions( allow_origins=default_cors_configuration["allow_origins"], allow_methods=["ANY"], status_code=default_cors_configuration["options_status_code"], ) # Defining STAGE Options default_stage_options = None default_stage_configuration = api_configuration["settings"].get( "default_stage_options") if default_stage_configuration is not None: logging_level = api_gateway.MethodLoggingLevel.ERROR logging_level_configuration = default_stage_configuration[ "logging_level"] for element in api_gateway.MethodLoggingLevel: if logging_level_configuration in str(element): logging_level = element default_stage_options = api_gateway.StageOptions( logging_level=logging_level, metrics_enabled=default_stage_configuration["metrics_enabled"], ) # Defining Rest API Gateway with Lambda Integration self._lambda_rest_api = api_gateway.LambdaRestApi( self, id=api_gateway_name, rest_api_name=api_gateway_name, description=api_gateway_name_description, domain_name=domain_options, handler=self._handler_function, proxy=proxy_configuration, binary_media_types=binary_media_types, default_cors_preflight_options=default_cors_options, cloud_watch_role=True, deploy_options=default_stage_options, ) # Add Custom responses self._lambda_rest_api.add_gateway_response( f"{self.prefix}_4XXresponse_{self.environment_}", type=api_gateway.ResponseType.DEFAULT_4_XX, response_headers={"Access-Control-Allow-Origin": "'*'"}, ) self._lambda_rest_api.add_gateway_response( f"{self.prefix}_5XXresponse_{self.environment_}", type=api_gateway.ResponseType.DEFAULT_5_XX, response_headers={"Access-Control-Allow-Origin": "'*'"}, ) # Define API Gateway Root Methods root_methods = api_configuration["settings"].get( "default_http_methods", list()) for method in root_methods: self._lambda_rest_api.root.add_method( http_method=method, authorizer=self._gateway_authorizer) # Defining Resource Trees for API Gateway with Custom Integrations resource_trees = api_configuration["resource_trees"] for resource_tree in resource_trees: resource_base = self._lambda_rest_api.root.add_resource( path_part=resource_tree["resource_name"]) resource_base_handler = base_lambda_function( self, **resource_tree["handler"]) for method in resource_tree["methods"]: resource_base.add_method( http_method=method, integration=api_gateway.LambdaIntegration( handler=resource_base_handler), authorizer=self._gateway_authorizer, ) # resource_base.add_cors_preflight(allow_methods=resource_tree["methods"], allow_origins=["*"]) resource_base_child_definition = resource_tree.get("child") if resource_base_child_definition is not None: resource_base_child = resource_base.add_resource( path_part=resource_base_child_definition["resource_name"]) resource_base_child_handler = base_lambda_function( self, **resource_base_child_definition["handler"]) for method in resource_base_child_definition["methods"]: resource_base_child.add_method( http_method=method, integration=api_gateway.LambdaIntegration( handler=resource_base_child_handler), authorizer=self._gateway_authorizer, ) # resource_base_child.add_cors_preflight( # allow_methods=resource_base_child_definition["methods"], allow_origins=["*"] # ) resource_base_child_trees = resource_base_child_definition.get( "childs", list()) for resource_base_grandchild_tree in resource_base_child_trees: resource_base_grandchild = resource_base_child.add_resource( path_part=resource_base_grandchild_tree[ "resource_name"]) resource_base_grandchild_handler = base_lambda_function( self, **resource_base_grandchild_tree["handler"]) for method in resource_base_grandchild_tree["methods"]: resource_base_grandchild.add_method( http_method=method, integration=api_gateway.LambdaIntegration( handler=resource_base_grandchild_handler), authorizer=self._gateway_authorizer, )
def __init__(self, scope: core.Construct, id: str, infra: RtspBaseResourcesConstruct, subnet_group_name: str = 'Default', **kwargs) -> None: super().__init__(scope, id, **kwargs) core.Tags.of(self).add(key='Source', value=PhotosApiConstruct.__name__) # Configure the container resources... self.repo = assets.DockerImageAsset(self, 'Repo', directory='src/rtsp/photo-api', file='Dockerfile') code = lambda_.DockerImageCode.from_ecr( repository=self.repo.repository, tag=self.repo.image_uri.split(':')[-1]) # Configure security policies... role = iam.Role( self, 'Role', assumed_by=iam.ServicePrincipal(service='lambda'), description='HomeNet-{}-PhotoApi'.format( infra.landing_zone.zone_name), role_name='rtsp-photoapi@homenet.{}.{}'.format( infra.landing_zone.zone_name, core.Stack.of(self).region), managed_policies=[ iam.ManagedPolicy.from_aws_managed_policy_name( managed_policy_name= 'service-role/AWSLambdaVPCAccessExecutionRole'), iam.ManagedPolicy.from_aws_managed_policy_name( managed_policy_name='AmazonS3ReadOnlyAccess') ]) infra.bucket.grant_read(role) infra.face_table.grant_read_write_data(role) # Define any variables for the function self.function_env = { 'FACE_TABLE': infra.face_table.table_name, 'REGION': core.Stack.of(self).region, } # Create the backing webapi compute ... self.function = lambda_.DockerImageFunction( self, 'Function', code=code, role=role, function_name='HomeNet-PhotoApi', description='Python Lambda function for ' + PhotosApiConstruct.__name__, timeout=core.Duration.seconds(30), tracing=lambda_.Tracing.ACTIVE, vpc=infra.landing_zone.vpc, log_retention=RetentionDays.FIVE_DAYS, memory_size=128, allow_all_outbound=True, vpc_subnets=ec2.SubnetSelection( subnet_group_name=subnet_group_name), security_groups=[infra.security_group], environment=self.function_env, ) # Bind APIG to Lambda compute... # Calls need to use https://photos-api.virtual.world self.frontend_proxy = a.LambdaRestApi( self, 'ApiGateway', proxy=True, handler=self.function, options=a.RestApiProps( description='Photo-Api proxy for ' + self.function.function_name, binary_media_types=['image/png', 'image/jpg', 'image/bmp'], domain_name=a.DomainNameOptions( domain_name='photos-api.virtual.world', certificate=Certificate.from_certificate_arn( self, 'Certificate', certificate_arn= 'arn:aws:acm:us-east-1:581361757134:certificate/c91263e7-882e-441d-aa2f-717074aed6d0' ), security_policy=a.SecurityPolicy.TLS_1_0), policy=iam.PolicyDocument(statements=[ iam.PolicyStatement(effect=iam.Effect.ALLOW, actions=['execute-api:Invoke'], principals=[iam.AnyPrincipal()], resources=['*'], conditions={ 'IpAddress': { 'aws:SourceIp': [ '10.0.0.0/8', '192.168.0.0/16', '72.90.160.65/32' ] } }) ]), endpoint_configuration=a.EndpointConfiguration( types=[a.EndpointType.REGIONAL], #vpc_endpoints=[ # infra.landing_zone.vpc_endpoints.interfaces['execute-api'] #] )))
def __init__(self, scope: core.Construct, id: str, resources:FsiSharedResources, subnet_group_name:str='Default', **kwargs) -> None: super().__init__(scope, id, **kwargs) # Configure the container resources... self.repo = assets.DockerImageAsset(self,'Repo', directory='src/fsi/account-linking', file='Dockerfile') code = lambda_.DockerImageCode.from_ecr( repository=self.repo.repository, tag=self.repo.image_uri.split(':')[-1]) # Configure security policies... role = iam.Role(self,'Role', assumed_by=iam.ServicePrincipal(service='lambda'), description='HomeNet-{}-Fsi-AccountLinking'.format(resources.landing_zone.zone_name), role_name='fsi-accountlinking@homenet.{}.{}'.format( resources.landing_zone.zone_name, core.Stack.of(self).region), managed_policies=[ iam.ManagedPolicy.from_aws_managed_policy_name( managed_policy_name='service-role/AWSLambdaVPCAccessExecutionRole'), ]) # Grant any permissions... resources.tda_secret.grant_write(role) # Define any variables for the function self.function_env = { 'REGION': core.Stack.of(self).region, 'TDA_SECRET_ID': resources.tda_secret.secret_arn, 'TDA_REDIRECT_URI': ssm.StringParameter.from_string_parameter_name(self,'TDA_REDIRECT_URI', string_parameter_name='/HomeNet/Amertitrade/redirect_uri').string_value, 'TDA_CLIENT_ID': ssm.StringParameter.from_string_parameter_name(self, 'TDA_CLIENT_ID', string_parameter_name='/HomeNet/Ameritrade/client_id').string_value } # Create the backing webapi compute ... self.function = lambda_.DockerImageFunction(self,'Function', code = code, role= role, function_name='HomeNet-{}-Fsi-{}'.format( resources.landing_zone.zone_name, FsiAmeritradeAuthGateway.__name__), description='Python Lambda function for '+FsiAmeritradeAuthGateway.__name__, timeout= core.Duration.seconds(30), tracing= lambda_.Tracing.ACTIVE, vpc= resources.landing_zone.vpc, log_retention= logs.RetentionDays.FIVE_DAYS, memory_size=128, allow_all_outbound=True, vpc_subnets=ec2.SubnetSelection(subnet_group_name=subnet_group_name), security_groups=[resources.landing_zone.security_group], environment=self.function_env, ) # Bind APIG to Lambda compute... self.frontend_proxy = a.LambdaRestApi(self,'ApiGateway', proxy=True, handler=self.function, options=a.RestApiProps( description='Hosts the Ameritrade Auth Callback via '+self.function.function_name, domain_name= a.DomainNameOptions( domain_name='auth.trader.fsi', certificate=Certificate.from_certificate_arn(self,'Certificate', certificate_arn= 'arn:aws:acm:us-east-2:581361757134:certificate/0d1fc756-ebd6-4660-83a8-814c0976a8c2'), security_policy= a.SecurityPolicy.TLS_1_0), policy= iam.PolicyDocument( statements=[ iam.PolicyStatement( effect= iam.Effect.ALLOW, actions=['execute-api:Invoke'], principals=[iam.AnyPrincipal()], resources=['*'], conditions={ 'IpAddress':{ 'aws:SourceIp': ['10.0.0.0/8','192.168.0.0/16','72.90.160.65/32'] } } ) ] ), endpoint_configuration= a.EndpointConfiguration( types = [ a.EndpointType.REGIONAL], ) )) # Register Dns Name r53.ARecord(self,'AliasRecord', zone=resources.trader_dns_zone, record_name='auth.%s' % resources.trader_dns_zone.zone_name, target= r53.RecordTarget.from_alias(dns_targets.ApiGateway(self.frontend_proxy)))