Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat/user authentication #3

Merged
merged 6 commits into from
Aug 5, 2024
Merged
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
3 changes: 3 additions & 0 deletions .github/workflows/check-python.yml
Original file line number Diff line number Diff line change
Expand Up @@ -49,5 +49,8 @@ jobs:
- name: Install all dependencies
run: "cd backend; bin/sync_deps.sh"

- name: Check Dependencies
run: "pip-audit"

- name: Test backend
run: "cd backend; bin/run_tests.sh no-report"
2 changes: 2 additions & 0 deletions backend/bin/compile_requirements.sh
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ pip-compile --no-emit-index-url --upgrade compact-connect/lambdas/license-data/r
pip-compile --no-emit-index-url --upgrade compact-connect/lambdas/license-data/requirements-dev.in
pip-compile --no-emit-index-url --upgrade compact-connect/lambdas/board-user-pre-token/requirements.in
pip-compile --no-emit-index-url --upgrade compact-connect/lambdas/board-user-pre-token/requirements-dev.in
pip-compile --no-emit-index-url --upgrade compact-connect/lambdas/staff-user-pre-token/requirements.in
pip-compile --no-emit-index-url --upgrade compact-connect/lambdas/staff-user-pre-token/requirements-dev.in
pip-compile --no-emit-index-url --upgrade compact-connect/lambdas/delete-objects/requirements.in
pip-compile --no-emit-index-url --upgrade compact-connect/lambdas/delete-objects/requirements-dev.in
bin/sync_deps.sh
1 change: 1 addition & 0 deletions backend/bin/run_tests.sh
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ REPORT="$1"
for dir in \
compact-connect/lambdas/license-data \
compact-connect/lambdas/board-user-pre-token \
compact-connect/lambdas/staff-user-pre-token \
compact-connect/lambdas/delete-objects \
multi-account
do
Expand Down
2 changes: 2 additions & 0 deletions backend/bin/sync_deps.sh
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,7 @@ pip-sync \
compact-connect/lambdas/license-data/requirements-dev.txt \
compact-connect/lambdas/board-user-pre-token/requirements.txt \
compact-connect/lambdas/board-user-pre-token/requirements-dev.txt \
compact-connect/lambdas/staff-user-pre-token/requirements.txt \
compact-connect/lambdas/staff-user-pre-token/requirements-dev.txt \
compact-connect/lambdas/delete-objects/requirements.txt \
compact-connect/lambdas/delete-objects/requirements-dev.txt
5 changes: 4 additions & 1 deletion backend/compact-connect/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,10 @@ To execute the tests, simply run `bin/run_tests.sh` from the `backend` directory
The very first deploy to a new environment (like your personal sandbox account) requires a few steps to fully set up
its environment:
1) *Optional:* Create a new Route53 HostedZone in your AWS sandbox account for the DNS domain name you want to use for
your app. See [About Route53 Hosted Zones](#about-route53-hosted-zones) for more.
your app. See [About Route53 Hosted Zones](#about-route53-hosted-zones) for more. Note: Without this step, you will
not be able to log in to the UI hosted in CloudFront. The Oauth2 authentication process requires a predictable
callback url to be pre-configured, which the domain name provides. You can still run a local UI against this app,
so long as you leave the `allow_local_ui` context value set to `true` in your environment's context.
2) Copy [cdk.context.sandbox-example.json](./cdk.context.sandbox-example.json) to `cdk.context.json`.
3) At the top level of the JSON structure update the `"environment_name"` field to your own name.
4) Update the environment entry under `ssm_context.environments` to your own name and your own AWS sandbox account id,
Expand Down
148 changes: 148 additions & 0 deletions backend/compact-connect/bin/create_staff_user.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
#!/usr/bin/env python3
"""
Staff user generation helper script. Run from `backend/compact-connect`.

Note: This script requires the boto3 library and two environment variables:
USER_POOL_ID=us-east-1_7zzexample
USER_TABLE_NAME=Sandbox-PersistentStack-StaffUsersUsersTableB4F6C7C8-example

The CLI must also be configured with AWS credentials that have appropriate access to Cognito and DynamoDB
"""
import os

import boto3
from botocore.exceptions import ClientError

USER_POOL_ID = os.environ['USER_POOL_ID']
USER_TABLE_NAME = os.environ['USER_TABLE_NAME']


cognito_client = boto3.client('cognito-idp')
user_table = boto3.resource('dynamodb').Table(USER_TABLE_NAME)


def create_compact_ed_user(*, username: str, email: str, compact: str):
print(f"Creating Compact ED user, '{username}', in {compact}")
sub = create_cognito_user(username=username, email=email)
user_table.put_item(
Item={
'pk': sub,
'createdCompactJurisdiction': f'{compact}/{compact}',
'permissions': {
compact: {
'actions': {'read', 'admin'},
'jurisdictions': {}
}
}
}
)


def create_board_ed_user(*, username: str, email: str, compact: str, jurisdiction: str):
print(f"Creating Board ED user, '{username}', in {compact}/{jurisdiction}")
sub = create_cognito_user(username=username, email=email)
user_table.put_item(
Item={
'pk': sub,
'createdCompactJurisdiction': f'{compact}/{jurisdiction}',
'permissions': {
compact: {
'actions': {'read'},
'jurisdictions': {
jurisdiction: {'actions': {'write', 'admin'}}
}
}
}
}
)


def create_cognito_user(*, username: str, email: str):
def get_sub_from_attributes(attributes: list):
for attribute in attributes:
if attribute['Name'] == 'sub':
return attribute['Value']
raise ValueError('Failed to find user sub!')

try:
user_data = cognito_client.admin_create_user(
UserPoolId=USER_POOL_ID,
Username=username,
UserAttributes=[
{
'Name': 'email',
'Value': email
}
],
DesiredDeliveryMediums=[
'EMAIL'
]
)
return get_sub_from_attributes(user_data['User']['Attributes'])

except ClientError as e:
if e.response['Error']['Code'] == 'UsernameExistsException':
user_data = cognito_client.admin_get_user(
UserPoolId=USER_POOL_ID,
Username=username
)
return get_sub_from_attributes(user_data['UserAttributes'])


if __name__ == '__main__':
import json
import sys
from argparse import ArgumentParser

# Pull compacts and jurisdictions from cdk.json
with open('cdk.json', 'r') as f:
context = json.load(f)['context']
jurisdictions = context['jurisdictions']
compacts = context['compacts']

parser = ArgumentParser(
description='Create a staff user'
)
parser.add_argument('username')
parser.add_argument('-e', '--email', help="The new user's email address", required=True)
parser.add_argument(
'-t', '--type',
help="The new user's type",
required=True,
choices=['compact-ed', 'board-ed']
)
parser.add_argument(
'-c', '--compact',
help="The new user's compact",
required=True,
choices=compacts
)
parser.add_argument(
'-j', '--jurisdiction',
help="The new user's jurisdiction, required for board users",
required=False,
choices=jurisdictions
)

args = parser.parse_args()

match args.type:
case 'compact-ed':
create_compact_ed_user(
username=args.username,
email=args.email,
compact=args.compact
)
case 'board-ed':
if not args.jurisdiction:
print('jurisdiction is required for board-ed users.')
sys.exit(2)
create_board_ed_user(
username=args.username,
email=args.email,
compact=args.compact,
jurisdiction=args.jurisdiction
)
case _:
print(f'Unsupported user type: {args.type}')
sys.exit(2)
3 changes: 2 additions & 1 deletion backend/compact-connect/cdk.context.production-example.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@
"test": {
"account_id": "111122223333",
"region": "us-east-1",
"domain_name": "test.app.compactconnect.org"
"domain_name": "test.app.compactconnect.org",
"allow_local_ui": true
}
}
}
Expand Down
3 changes: 2 additions & 1 deletion backend/compact-connect/cdk.context.sandbox-example.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@
"justin": {
"account_id": "111122223333",
"region": "us-east-1",
"domain_name": "justin.compactconnect.org"
"domain_name": "justin.compactconnect.org",
"allow_local_ui": true
}
}
}
Expand Down
4 changes: 2 additions & 2 deletions backend/compact-connect/cdk.json
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,8 @@
},
"compacts": [
"aslp",
"ot",
"counseling"
"octp",
"coun"
],
"@aws-cdk/aws-lambda:recognizeLayerVersion": true,
"@aws-cdk/core:checkSecretUsage": true,
Expand Down
33 changes: 33 additions & 0 deletions backend/compact-connect/common_constructs/stack.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from textwrap import dedent

from aws_cdk import Stack as CdkStack, Aspects
from aws_cdk.aws_route53 import HostedZone, IHostedZone
from cdk_nag import AwsSolutionsChecks, HIPAASecurityChecks, NagSuppressions


Expand Down Expand Up @@ -86,3 +87,35 @@ def common_env_vars(self):
'JURISDICTIONS': json.dumps(self.node.get_context('jurisdictions')),
'LICENSE_TYPES': json.dumps(self.node.get_context('license_types'))
}


class AppStack(Stack):
"""
A stack that is part of the main app deployment
"""
def __init__(self, *args, environment_context: dict, **kwargs):
super().__init__(*args, **kwargs)
self.environment_context = environment_context

@cached_property
def hosted_zone(self) -> IHostedZone | None:
hosted_zone = None
domain_name = self.environment_context.get('domain_name')
if domain_name is not None:
hosted_zone = HostedZone.from_lookup(
self, 'HostedZone',
domain_name=domain_name
)
return hosted_zone

@property
def api_domain_name(self) -> str | None:
if self.hosted_zone is not None:
return f'api.{self.hosted_zone.zone_name}'
return None

@property
def ui_domain_name(self) -> str | None:
if self.hosted_zone is not None:
return f'app.{self.hosted_zone.zone_name}'
return None
6 changes: 2 additions & 4 deletions backend/compact-connect/common_constructs/user_pool.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ def __init__(
]
)

def add_ui_client(self, ui_scopes: List[OAuthScope] = None):
def add_ui_client(self, callback_urls: List[str], ui_scopes: List[OAuthScope] = None):
return self.add_client(
'UIClient',
auth_flows=AuthFlow(
Expand All @@ -94,9 +94,7 @@ def add_ui_client(self, ui_scopes: List[OAuthScope] = None):
user_password=False
),
o_auth=OAuthSettings(
callback_urls=[
'http://localhost:8000/auth'
],
callback_urls=callback_urls,
flows=OAuthFlows(
authorization_code_grant=True,
implicit_code_grant=False
Expand Down
Loading
Loading