Skip to content
Open
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
Binary file added .coverage
Binary file not shown.
19 changes: 19 additions & 0 deletions Authorization Service/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# Environment files
.env
.env.local
.env.*.local
.env.development
.env.test
.env.production
.env.backup
*.env

# Environment directories
env/
.env/
venv/
.venv/

# CDK asset staging directory
.cdk.staging
cdk.out
58 changes: 58 additions & 0 deletions Authorization Service/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@

# Welcome to your CDK Python project!

This is a blank project for CDK development with Python.

The `cdk.json` file tells the CDK Toolkit how to execute your app.

This project is set up like a standard Python project. The initialization
process also creates a virtualenv within this project, stored under the `.venv`
directory. To create the virtualenv it assumes that there is a `python3`
(or `python` for Windows) executable in your path with access to the `venv`
package. If for any reason the automatic creation of the virtualenv fails,
you can create the virtualenv manually.

To manually create a virtualenv on MacOS and Linux:

```
$ python3 -m venv .venv
```

After the init process completes and the virtualenv is created, you can use the following
step to activate your virtualenv.

```
$ source .venv/bin/activate
```

If you are a Windows platform, you would activate the virtualenv like this:

```
% .venv\Scripts\activate.bat
```

Once the virtualenv is activated, you can install the required dependencies.

```
$ pip install -r requirements.txt
```

At this point you can now synthesize the CloudFormation template for this code.

```
$ cdk synth
```

To add additional dependencies, for example other CDK libraries, just add
them to your `setup.py` file and rerun the `pip install -r requirements.txt`
command.

## Useful commands

* `cdk ls` list all stacks in the app
* `cdk synth` emits the synthesized CloudFormation template
* `cdk deploy` deploy this stack to your default AWS account/region
* `cdk diff` compare deployed stack with current state
* `cdk docs` open CDK documentation

Enjoy!
28 changes: 28 additions & 0 deletions Authorization Service/app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
#!/usr/bin/env python3
import os

import aws_cdk as cdk

from authorization_service.authorization_service_stack import AuthorizationServiceStack


app = cdk.App()
AuthorizationServiceStack(app, "AuthorizationServiceStack",
# If you don't specify 'env', this stack will be environment-agnostic.
# Account/Region-dependent features and context lookups will not work,
# but a single synthesized template can be deployed anywhere.

# Uncomment the next line to specialize this stack for the AWS Account
# and Region that are implied by the current CLI configuration.

#env=cdk.Environment(account=os.getenv('CDK_DEFAULT_ACCOUNT'), region=os.getenv('CDK_DEFAULT_REGION')),

# Uncomment the next line if you know exactly what Account and Region you
# want to deploy the stack to. */

#env=cdk.Environment(account='123456789012', region='us-east-1'),

# For more information, see https://docs.aws.amazon.com/cdk/latest/guide/environments.html
)

app.synth()
Empty file.
Binary file not shown.
Binary file not shown.
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
# authorization_service/authorization_service_stack.py
from aws_cdk import (
Stack,
CfnOutput,
aws_lambda as _lambda,
aws_iam as iam,
)
from constructs import Construct
import os
import dotenv

class AuthorizationServiceStack(Stack):
def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
super().__init__(scope, construct_id, **kwargs)


dotenv.load_dotenv()
CREDENTIALS = "Lunarr0"
CREDENTIALS_PASSWORD = os.getenv(CREDENTIALS)
# Create Basic Authorizer Lambda
basic_authorizer = _lambda.Function(
self, 'BasicAuthorizerFunction',
runtime=_lambda.Runtime.PYTHON_3_9,
handler='handler.lambda_handler',
code=_lambda.Code.from_asset('authorization_service/lambda_func/basic_authorizer'),
environment={
CREDENTIALS: CREDENTIALS_PASSWORD
},
function_name='AuthFunction'
)

# Add necessary permissions
basic_authorizer.add_to_role_policy(
iam.PolicyStatement(
effect=iam.Effect.ALLOW,
actions=[
'execute-api:Invoke'
],
resources=['*']
)
)

# Export the Lambda ARN and function name
CfnOutput(
self, 'BasicAuthorizerLambdaArn',
value=basic_authorizer.function_arn,
export_name='BasicAuthorizerLambdaArn'
)

CfnOutput(
self, 'BasicAuthorizerFunctionName',
value=basic_authorizer.function_name,
export_name='BasicAuthorizerFunctionName'
)
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
# authorization_service/lambda_functions/basic_authorizer/handler.py
import os
import json
import base64


def lambda_handler(event, context):
print(f"Event: {json.dumps(event)}")
authorization_header = event['authorizationToken']

if not authorization_header:
return {
'statusCode':401,
'body': json.dumps({
'message': 'Unauthorized'
})
}

#generate_policy('undefined', 'Deny', event['methodArn'])

try:
# Encode Credentials
# Get token from Authorization header
token = event['authorizationToken'].split(' ')[1]


# Decode credentials
decoded = base64.b64decode(token).decode('utf-8')
username, password = decoded.split('=')
password = password.strip()

# Get stored credentials from environment
# stored_username = os.environ.get('AUTH_USER')
# stored_password = os.environ.get('AUTH_PASSWORD')
stored_password = os.getenv(username)

# Verify credentials
if stored_password and stored_password == password :
effect = 'Allow'
return generate_policy(username, effect, event['methodArn'])
else:
# effect = 'Deny'
return {
'statusCode': 403,
'body': json.dumps({
'message': 'Forbidden'
})
}



except Exception as e:
print(f"Error: {str(e)}")
return generate_policy('undefined', 'Deny', event['methodArn'])

def generate_policy(principal_id: str, effect: str, resource: str) -> dict:
"""Generate IAM policy for API Gateway authorization"""
return {
'principalId': principal_id,
'policyDocument': {
'Version': '2012-10-17',
'Statement': [{
'Action': 'execute-api:Invoke',
'Effect': effect,
'Resource': resource
}]
}
}

print(generate_policy('user321', 'Allow', 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'))
5 changes: 5 additions & 0 deletions Authorization Service/cdk.context.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"acknowledged-issue-numbers": [
32775
]
}
86 changes: 86 additions & 0 deletions Authorization Service/cdk.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
{
"app": "python3 app.py",
"watch": {
"include": [
"**"
],
"exclude": [
"README.md",
"cdk*.json",
"requirements*.txt",
"source.bat",
"**/__init__.py",
"**/__pycache__",
"tests"
]
},
"context": {
"@aws-cdk/aws-lambda:recognizeLayerVersion": true,
"@aws-cdk/core:checkSecretUsage": true,
"@aws-cdk/core:target-partitions": [
"aws",
"aws-cn"
],
"@aws-cdk-containers/ecs-service-extensions:enableDefaultLogDriver": true,
"@aws-cdk/aws-ec2:uniqueImdsv2TemplateName": true,
"@aws-cdk/aws-ecs:arnFormatIncludesClusterName": true,
"@aws-cdk/aws-iam:minimizePolicies": true,
"@aws-cdk/core:validateSnapshotRemovalPolicy": true,
"@aws-cdk/aws-codepipeline:crossAccountKeyAliasStackSafeResourceName": true,
"@aws-cdk/aws-s3:createDefaultLoggingPolicy": true,
"@aws-cdk/aws-sns-subscriptions:restrictSqsDescryption": true,
"@aws-cdk/aws-apigateway:disableCloudWatchRole": true,
"@aws-cdk/core:enablePartitionLiterals": true,
"@aws-cdk/aws-events:eventsTargetQueueSameAccount": true,
"@aws-cdk/aws-ecs:disableExplicitDeploymentControllerForCircuitBreaker": true,
"@aws-cdk/aws-iam:importedRoleStackSafeDefaultPolicyName": true,
"@aws-cdk/aws-s3:serverAccessLogsUseBucketPolicy": true,
"@aws-cdk/aws-route53-patters:useCertificate": true,
"@aws-cdk/customresources:installLatestAwsSdkDefault": false,
"@aws-cdk/aws-rds:databaseProxyUniqueResourceName": true,
"@aws-cdk/aws-codedeploy:removeAlarmsFromDeploymentGroup": true,
"@aws-cdk/aws-apigateway:authorizerChangeDeploymentLogicalId": true,
"@aws-cdk/aws-ec2:launchTemplateDefaultUserData": true,
"@aws-cdk/aws-secretsmanager:useAttachedSecretResourcePolicyForSecretTargetAttachments": true,
"@aws-cdk/aws-redshift:columnId": true,
"@aws-cdk/aws-stepfunctions-tasks:enableEmrServicePolicyV2": true,
"@aws-cdk/aws-ec2:restrictDefaultSecurityGroup": true,
"@aws-cdk/aws-apigateway:requestValidatorUniqueId": true,
"@aws-cdk/aws-kms:aliasNameRef": true,
"@aws-cdk/aws-autoscaling:generateLaunchTemplateInsteadOfLaunchConfig": true,
"@aws-cdk/core:includePrefixInUniqueNameGeneration": true,
"@aws-cdk/aws-efs:denyAnonymousAccess": true,
"@aws-cdk/aws-opensearchservice:enableOpensearchMultiAzWithStandby": true,
"@aws-cdk/aws-lambda-nodejs:useLatestRuntimeVersion": true,
"@aws-cdk/aws-efs:mountTargetOrderInsensitiveLogicalId": true,
"@aws-cdk/aws-rds:auroraClusterChangeScopeOfInstanceParameterGroupWithEachParameters": true,
"@aws-cdk/aws-appsync:useArnForSourceApiAssociationIdentifier": true,
"@aws-cdk/aws-rds:preventRenderingDeprecatedCredentials": true,
"@aws-cdk/aws-codepipeline-actions:useNewDefaultBranchForCodeCommitSource": true,
"@aws-cdk/aws-cloudwatch-actions:changeLambdaPermissionLogicalIdForLambdaAction": true,
"@aws-cdk/aws-codepipeline:crossAccountKeysDefaultValueToFalse": true,
"@aws-cdk/aws-codepipeline:defaultPipelineTypeToV2": true,
"@aws-cdk/aws-kms:reduceCrossAccountRegionPolicyScope": true,
"@aws-cdk/aws-eks:nodegroupNameAttribute": true,
"@aws-cdk/aws-ec2:ebsDefaultGp3Volume": true,
"@aws-cdk/aws-ecs:removeDefaultDeploymentAlarm": true,
"@aws-cdk/custom-resources:logApiResponseDataPropertyTrueDefault": false,
"@aws-cdk/aws-s3:keepNotificationInImportedBucket": false,
"@aws-cdk/aws-ecs:enableImdsBlockingDeprecatedFeature": false,
"@aws-cdk/aws-ecs:disableEcsImdsBlocking": true,
"@aws-cdk/aws-ecs:reduceEc2FargateCloudWatchPermissions": true,
"@aws-cdk/aws-dynamodb:resourcePolicyPerReplica": true,
"@aws-cdk/aws-ec2:ec2SumTImeoutEnabled": true,
"@aws-cdk/aws-appsync:appSyncGraphQLAPIScopeLambdaPermission": true,
"@aws-cdk/aws-rds:setCorrectValueForDatabaseInstanceReadReplicaInstanceResourceId": true,
"@aws-cdk/core:cfnIncludeRejectComplexResourceUpdateCreatePolicyIntrinsics": true,
"@aws-cdk/aws-lambda-nodejs:sdkV3ExcludeSmithyPackages": true,
"@aws-cdk/aws-stepfunctions-tasks:fixRunEcsTaskPolicy": true,
"@aws-cdk/aws-ec2:bastionHostUseAmazonLinux2023ByDefault": true,
"@aws-cdk/aws-route53-targets:userPoolDomainNameMethodWithoutCustomResource": true,
"@aws-cdk/aws-elasticloadbalancingV2:albDualstackWithoutPublicIpv4SecurityGroupRulesDefault": true,
"@aws-cdk/aws-iam:oidcRejectUnauthorizedConnections": true,
"@aws-cdk/core:enableAdditionalMetadataCollection": true,
"@aws-cdk/aws-lambda:createNewPoliciesWithAddToRolePolicy": true
}
}
Binary file not shown.
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
{
"version": "39.0.0",
"files": {
"943dd9f7f5bd5d9c5e48a61bc3122b8f7e89b197091a36b6f4ac3667ff1731cb": {
"source": {
"path": "asset.943dd9f7f5bd5d9c5e48a61bc3122b8f7e89b197091a36b6f4ac3667ff1731cb",
"packaging": "zip"
},
"destinations": {
"current_account-current_region": {
"bucketName": "cdk-hnb659fds-assets-${AWS::AccountId}-${AWS::Region}",
"objectKey": "943dd9f7f5bd5d9c5e48a61bc3122b8f7e89b197091a36b6f4ac3667ff1731cb.zip",
"assumeRoleArn": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-hnb659fds-file-publishing-role-${AWS::AccountId}-${AWS::Region}"
}
}
},
"1294e8ebec0a758237432bc7bbd46491b702ede5ff28c69d71804f9d3649c32f": {
"source": {
"path": "AuthorizationServiceStack.template.json",
"packaging": "file"
},
"destinations": {
"current_account-current_region": {
"bucketName": "cdk-hnb659fds-assets-${AWS::AccountId}-${AWS::Region}",
"objectKey": "1294e8ebec0a758237432bc7bbd46491b702ede5ff28c69d71804f9d3649c32f.json",
"assumeRoleArn": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-hnb659fds-file-publishing-role-${AWS::AccountId}-${AWS::Region}"
}
}
}
},
"dockerImages": {}
}
Loading