Spaces:
Running on Zero
Running on Zero
Commit ·
373207f
0
Parent(s):
Sync: Updated CDK code to include possibility of exporting DynamoDB logs to S3 csv output on automated basis
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .dockerignore +56 -0
- .gitattributes +1 -0
- .github/workflows/ci.yml +196 -0
- .github/workflows/simple-test.yml +46 -0
- .github/workflows/sync_to_hf.yml +53 -0
- .gitignore +55 -0
- Dockerfile +165 -0
- LICENSE +661 -0
- README.md +174 -0
- app.py +0 -0
- cdk/__init__.py +0 -0
- cdk/app.py +123 -0
- cdk/cdk.json.example +7 -0
- cdk/cdk_appregistry.py +74 -0
- cdk/cdk_cloudfront_headers.py +172 -0
- cdk/cdk_config.py +851 -0
- cdk/cdk_functions.py +0 -0
- cdk/cdk_install.py +0 -0
- cdk/cdk_post_deploy.py +1408 -0
- cdk/cdk_stack.py +0 -0
- cdk/check_resources.py +583 -0
- cdk/config/app_config.env.example +26 -0
- cdk/config/headless_s3_seed/input/config/example_headless_env_file.env +13 -0
- cdk/config/lambda/lambda_function.py +187 -0
- cdk/docs/express_pi_service_connect_spike.md +71 -0
- cdk/example_headless_env_file.env +1 -0
- cdk/lambda_dynamo_logs_export/lambda_function.py +316 -0
- cdk/lambda_elbv2_listener_rule_upsert/lambda_function.py +187 -0
- cdk/post_cdk_build_quickstart.py +195 -0
- cdk/requirements.txt +6 -0
- cdk/test/test_cdk_install.py +1010 -0
- cdk/test/test_cdk_post_deploy.py +402 -0
- cdk/test/test_cdk_synth_express.py +155 -0
- cdk/test/test_cloudfront_csp.py +61 -0
- cdk/test/test_codebuild_public_github_source.py +60 -0
- cdk/test/test_delete_protection_config.py +52 -0
- cdk/test/test_dynamo_usage_log_export.py +129 -0
- cdk/test/test_ecs_vpc_endpoints.py +400 -0
- cdk/test/test_elbv2_listener_rule_upsert.py +86 -0
- cdk/test/test_ensure_codebuild_public_github.py +81 -0
- cdk/test/test_execution_role_kms_policy.py +100 -0
- cdk/test/test_express_app_config_env.py +25 -0
- cdk/test/test_express_pi.py +566 -0
- cdk/test/test_globally_unique_names.py +91 -0
- cdk/test/test_headless_app_defaults_env.py +22 -0
- cdk/test/test_headless_output_notifications.py +81 -0
- cdk/test/test_iam_policy_files.py +92 -0
- cdk/test/test_pi_agent_ecs_synth.py +169 -0
- cdk/test/test_pi_alb_routing.py +164 -0
- cdk/test/test_public_subnet_igw.py +141 -0
.dockerignore
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
*.pdf
|
| 2 |
+
*.url
|
| 3 |
+
*.jpg
|
| 4 |
+
*.png
|
| 5 |
+
*.ipynb
|
| 6 |
+
*.xls
|
| 7 |
+
*.xlsx
|
| 8 |
+
*.pyc
|
| 9 |
+
*.json.bak.*
|
| 10 |
+
examples/*
|
| 11 |
+
output/*
|
| 12 |
+
tools/__pycache__/*
|
| 13 |
+
build/*
|
| 14 |
+
dist/*
|
| 15 |
+
logs/*
|
| 16 |
+
usage/*
|
| 17 |
+
docs/*
|
| 18 |
+
guide/*
|
| 19 |
+
feedback/*
|
| 20 |
+
test_code/*
|
| 21 |
+
test/tmp/*
|
| 22 |
+
unsloth_compiled_cache/*
|
| 23 |
+
.vscode/*
|
| 24 |
+
llm_topic_modelling.egg-info/*
|
| 25 |
+
input/
|
| 26 |
+
output/
|
| 27 |
+
logs/
|
| 28 |
+
usage/
|
| 29 |
+
feedback/
|
| 30 |
+
config/
|
| 31 |
+
tmp/
|
| 32 |
+
index.qmd
|
| 33 |
+
_quarto.yml
|
| 34 |
+
!config/pi_agent.env.example
|
| 35 |
+
!config/docker_app_config.env.example
|
| 36 |
+
!config/app_config.env.example
|
| 37 |
+
workspace/*
|
| 38 |
+
user_guide/*
|
| 39 |
+
_extensions/*
|
| 40 |
+
cdk/config/*
|
| 41 |
+
!cdk/config/app_config.env.example
|
| 42 |
+
!cdk/config/lambda/
|
| 43 |
+
cdk/config/lambda/*
|
| 44 |
+
!cdk/config/lambda/lambda_function.py
|
| 45 |
+
!cdk/config/headless_s3_seed/
|
| 46 |
+
cdk/config/headless_s3_seed/*
|
| 47 |
+
!cdk/config/headless_s3_seed/input/
|
| 48 |
+
cdk/config/headless_s3_seed/input/*
|
| 49 |
+
!cdk/config/headless_s3_seed/input/config/
|
| 50 |
+
cdk/config/headless_s3_seed/input/config/*
|
| 51 |
+
!cdk/config/headless_s3_seed/input/config/example_headless_env_file.env
|
| 52 |
+
cdk/cdk.out/*
|
| 53 |
+
cdk/archive/*
|
| 54 |
+
cdk/cdk.json
|
| 55 |
+
cdk/cdk.context.json
|
| 56 |
+
cdk/precheck.context.json
|
.gitattributes
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
*.xlsx filter=lfs diff=lfs merge=lfs -text
|
.github/workflows/ci.yml
ADDED
|
@@ -0,0 +1,196 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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| 8 |
+
#schedule:
|
| 9 |
+
# Run tests daily at 2 AM UTC
|
| 10 |
+
# - cron: '0 2 * * *'
|
| 11 |
+
|
| 12 |
+
permissions:
|
| 13 |
+
contents: read
|
| 14 |
+
actions: read
|
| 15 |
+
pull-requests: write
|
| 16 |
+
issues: write
|
| 17 |
+
|
| 18 |
+
env:
|
| 19 |
+
PYTHON_VERSION: "3.11"
|
| 20 |
+
|
| 21 |
+
jobs:
|
| 22 |
+
lint:
|
| 23 |
+
runs-on: ubuntu-latest
|
| 24 |
+
steps:
|
| 25 |
+
- uses: actions/checkout@v4
|
| 26 |
+
|
| 27 |
+
- name: Set up Python
|
| 28 |
+
uses: actions/setup-python@v4
|
| 29 |
+
with:
|
| 30 |
+
python-version: ${{ env.PYTHON_VERSION }}
|
| 31 |
+
|
| 32 |
+
- name: Install dependencies
|
| 33 |
+
run: |
|
| 34 |
+
python -m pip install --upgrade pip
|
| 35 |
+
pip install ruff black
|
| 36 |
+
|
| 37 |
+
- name: Run Ruff linter
|
| 38 |
+
run: ruff check .
|
| 39 |
+
|
| 40 |
+
- name: Run Black formatter check
|
| 41 |
+
run: black --check .
|
| 42 |
+
|
| 43 |
+
test-unit:
|
| 44 |
+
runs-on: ubuntu-latest
|
| 45 |
+
strategy:
|
| 46 |
+
matrix:
|
| 47 |
+
python-version: [3.11, 3.12, 3.13]
|
| 48 |
+
|
| 49 |
+
steps:
|
| 50 |
+
- uses: actions/checkout@v4
|
| 51 |
+
|
| 52 |
+
- name: Set up Python ${{ matrix.python-version }}
|
| 53 |
+
uses: actions/setup-python@v4
|
| 54 |
+
with:
|
| 55 |
+
python-version: ${{ matrix.python-version }}
|
| 56 |
+
|
| 57 |
+
- name: Cache pip dependencies
|
| 58 |
+
uses: actions/cache@v4
|
| 59 |
+
with:
|
| 60 |
+
path: ~/.cache/pip
|
| 61 |
+
key: ${{ runner.os }}-pip-${{ hashFiles('**/requirements*.txt', '**/pyproject.toml') }}
|
| 62 |
+
restore-keys: |
|
| 63 |
+
${{ runner.os }}-pip-
|
| 64 |
+
|
| 65 |
+
- name: Install Python dependencies
|
| 66 |
+
run: |
|
| 67 |
+
python -m pip install --upgrade pip
|
| 68 |
+
pip install -r requirements_lightweight.txt
|
| 69 |
+
pip install pytest pytest-cov pytest-html pytest-xdist
|
| 70 |
+
|
| 71 |
+
- name: Verify example data files
|
| 72 |
+
run: |
|
| 73 |
+
echo "Checking if example data directory exists:"
|
| 74 |
+
ls -la example_data/ || echo "example_data directory not found"
|
| 75 |
+
echo "Checking for specific CSV files:"
|
| 76 |
+
ls -la example_data/*.csv || echo "No CSV files found"
|
| 77 |
+
|
| 78 |
+
- name: Run CLI and GUI tests
|
| 79 |
+
run: |
|
| 80 |
+
cd test
|
| 81 |
+
python run_tests.py
|
| 82 |
+
|
| 83 |
+
- name: Run tests with pytest
|
| 84 |
+
run: |
|
| 85 |
+
pytest test/test.py test/test_gui_only.py -v --tb=short --junitxml=test-results.xml
|
| 86 |
+
|
| 87 |
+
- name: Run tests with coverage
|
| 88 |
+
run: |
|
| 89 |
+
pytest test/test.py test/test_gui_only.py --cov=. --cov-report=xml --cov-report=html --cov-report=term
|
| 90 |
+
|
| 91 |
+
- name: Upload test results
|
| 92 |
+
uses: actions/upload-artifact@v4
|
| 93 |
+
if: always()
|
| 94 |
+
with:
|
| 95 |
+
name: test-results-python-${{ matrix.python-version }}
|
| 96 |
+
path: |
|
| 97 |
+
test-results.xml
|
| 98 |
+
htmlcov/
|
| 99 |
+
coverage.xml
|
| 100 |
+
|
| 101 |
+
test-integration:
|
| 102 |
+
runs-on: ubuntu-latest
|
| 103 |
+
needs: [lint, test-unit]
|
| 104 |
+
|
| 105 |
+
steps:
|
| 106 |
+
- uses: actions/checkout@v4
|
| 107 |
+
|
| 108 |
+
- name: Set up Python
|
| 109 |
+
uses: actions/setup-python@v4
|
| 110 |
+
with:
|
| 111 |
+
python-version: ${{ env.PYTHON_VERSION }}
|
| 112 |
+
|
| 113 |
+
- name: Install dependencies
|
| 114 |
+
run: |
|
| 115 |
+
python -m pip install --upgrade pip
|
| 116 |
+
pip install -r requirements_lightweight.txt
|
| 117 |
+
pip install pytest pytest-cov
|
| 118 |
+
|
| 119 |
+
- name: Verify example data files
|
| 120 |
+
run: |
|
| 121 |
+
echo "Checking if example data directory exists:"
|
| 122 |
+
ls -la example_data/
|
| 123 |
+
echo "Checking for specific CSV files:"
|
| 124 |
+
ls -la example_data/*.csv || echo "No CSV files found"
|
| 125 |
+
|
| 126 |
+
- name: Run integration tests (CLI and GUI)
|
| 127 |
+
run: |
|
| 128 |
+
cd test
|
| 129 |
+
python run_tests.py
|
| 130 |
+
|
| 131 |
+
- name: Test CLI help
|
| 132 |
+
run: |
|
| 133 |
+
python cli_topics.py --help
|
| 134 |
+
|
| 135 |
+
- name: Test CLI version
|
| 136 |
+
run: |
|
| 137 |
+
python -c "import sys; print(f'Python {sys.version}')"
|
| 138 |
+
|
| 139 |
+
security:
|
| 140 |
+
runs-on: ubuntu-latest
|
| 141 |
+
steps:
|
| 142 |
+
- uses: actions/checkout@v4
|
| 143 |
+
|
| 144 |
+
- name: Set up Python
|
| 145 |
+
uses: actions/setup-python@v4
|
| 146 |
+
with:
|
| 147 |
+
python-version: ${{ env.PYTHON_VERSION }}
|
| 148 |
+
|
| 149 |
+
- name: Install dependencies
|
| 150 |
+
run: |
|
| 151 |
+
python -m pip install --upgrade pip
|
| 152 |
+
pip install bandit
|
| 153 |
+
|
| 154 |
+
- name: Run bandit security check
|
| 155 |
+
run: |
|
| 156 |
+
bandit -r . -f json -o bandit-report.json || true
|
| 157 |
+
|
| 158 |
+
- name: Upload security report
|
| 159 |
+
uses: actions/upload-artifact@v4
|
| 160 |
+
if: always()
|
| 161 |
+
with:
|
| 162 |
+
name: security-report
|
| 163 |
+
path: bandit-report.json
|
| 164 |
+
|
| 165 |
+
build:
|
| 166 |
+
runs-on: ubuntu-latest
|
| 167 |
+
needs: [lint, test-unit]
|
| 168 |
+
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
|
| 169 |
+
|
| 170 |
+
steps:
|
| 171 |
+
- uses: actions/checkout@v4
|
| 172 |
+
|
| 173 |
+
- name: Set up Python
|
| 174 |
+
uses: actions/setup-python@v4
|
| 175 |
+
with:
|
| 176 |
+
python-version: ${{ env.PYTHON_VERSION }}
|
| 177 |
+
|
| 178 |
+
- name: Install build dependencies
|
| 179 |
+
run: |
|
| 180 |
+
python -m pip install --upgrade pip
|
| 181 |
+
pip install build twine
|
| 182 |
+
|
| 183 |
+
- name: Build package
|
| 184 |
+
run: |
|
| 185 |
+
python -m build
|
| 186 |
+
|
| 187 |
+
- name: Check package
|
| 188 |
+
run: |
|
| 189 |
+
twine check dist/*
|
| 190 |
+
|
| 191 |
+
- name: Upload build artifacts
|
| 192 |
+
uses: actions/upload-artifact@v4
|
| 193 |
+
with:
|
| 194 |
+
name: dist
|
| 195 |
+
path: dist/
|
| 196 |
+
|
.github/workflows/simple-test.yml
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
name: Simple Test Run
|
| 2 |
+
|
| 3 |
+
on:
|
| 4 |
+
push:
|
| 5 |
+
branches: [ dev ]
|
| 6 |
+
pull_request:
|
| 7 |
+
branches: [ dev ]
|
| 8 |
+
|
| 9 |
+
permissions:
|
| 10 |
+
contents: read
|
| 11 |
+
actions: read
|
| 12 |
+
|
| 13 |
+
jobs:
|
| 14 |
+
test:
|
| 15 |
+
runs-on: ubuntu-latest
|
| 16 |
+
|
| 17 |
+
steps:
|
| 18 |
+
- uses: actions/checkout@v4
|
| 19 |
+
|
| 20 |
+
- name: Set up Python 3.11
|
| 21 |
+
uses: actions/setup-python@v4
|
| 22 |
+
with:
|
| 23 |
+
python-version: "3.11"
|
| 24 |
+
|
| 25 |
+
- name: Install Python dependencies
|
| 26 |
+
run: |
|
| 27 |
+
python -m pip install --upgrade pip
|
| 28 |
+
pip install -r requirements_lightweight.txt
|
| 29 |
+
pip install pytest pytest-cov
|
| 30 |
+
|
| 31 |
+
- name: Verify example data files
|
| 32 |
+
run: |
|
| 33 |
+
echo "Checking if example data directory exists:"
|
| 34 |
+
ls -la example_data/ || echo "example_data directory not found"
|
| 35 |
+
echo "Checking for specific CSV files:"
|
| 36 |
+
ls -la example_data/*.csv || echo "No CSV files found"
|
| 37 |
+
|
| 38 |
+
- name: Run CLI and GUI tests
|
| 39 |
+
run: |
|
| 40 |
+
cd test
|
| 41 |
+
python run_tests.py
|
| 42 |
+
|
| 43 |
+
- name: Run tests with pytest
|
| 44 |
+
run: |
|
| 45 |
+
pytest test/test.py test/test_gui_only.py -v --tb=short
|
| 46 |
+
|
.github/workflows/sync_to_hf.yml
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
name: Sync to Hugging Face hub
|
| 2 |
+
on:
|
| 3 |
+
push:
|
| 4 |
+
branches: [dev]
|
| 5 |
+
|
| 6 |
+
permissions:
|
| 7 |
+
contents: read
|
| 8 |
+
|
| 9 |
+
jobs:
|
| 10 |
+
sync-to-hub:
|
| 11 |
+
runs-on: ubuntu-latest
|
| 12 |
+
steps:
|
| 13 |
+
- uses: actions/checkout@v4
|
| 14 |
+
with:
|
| 15 |
+
fetch-depth: 1 # Only get the latest state
|
| 16 |
+
lfs: true # Download actual LFS files so they can be pushed
|
| 17 |
+
|
| 18 |
+
- name: Install Git LFS
|
| 19 |
+
run: git lfs install
|
| 20 |
+
|
| 21 |
+
- name: Recreate repo history (single-commit force push)
|
| 22 |
+
run: |
|
| 23 |
+
# 1. Capture the message BEFORE we delete the .git folder
|
| 24 |
+
COMMIT_MSG=$(git log -1 --pretty=%B)
|
| 25 |
+
echo "Syncing commit message: $COMMIT_MSG"
|
| 26 |
+
|
| 27 |
+
# 2. DELETE the .git folder.
|
| 28 |
+
# This turns the repo into a standard folder of files.
|
| 29 |
+
rm -rf .git
|
| 30 |
+
|
| 31 |
+
# 3. Re-initialize a brand new git repo
|
| 32 |
+
git init -b main
|
| 33 |
+
git config --global user.name "$HF_USERNAME"
|
| 34 |
+
git config --global user.email "$HF_EMAIL"
|
| 35 |
+
|
| 36 |
+
# 4. Re-install LFS (needs to be done after git init)
|
| 37 |
+
git lfs install
|
| 38 |
+
|
| 39 |
+
# 5. Add the remote
|
| 40 |
+
git remote add hf https://$HF_USERNAME:$HF_TOKEN@huggingface.co/spaces/$HF_USERNAME/$HF_REPO_ID
|
| 41 |
+
|
| 42 |
+
# 6. Add all files
|
| 43 |
+
# Since this is a fresh init, Git sees EVERY file as "New"
|
| 44 |
+
git add .
|
| 45 |
+
|
| 46 |
+
# 7. Commit and Force Push
|
| 47 |
+
git commit -m "Sync: $COMMIT_MSG"
|
| 48 |
+
git push --force hf main
|
| 49 |
+
env:
|
| 50 |
+
HF_TOKEN: ${{ secrets.HF_TOKEN }}
|
| 51 |
+
HF_USERNAME: ${{ secrets.HF_USERNAME }}
|
| 52 |
+
HF_EMAIL: ${{ secrets.HF_EMAIL }}
|
| 53 |
+
HF_REPO_ID: ${{ secrets.HF_REPO_ID }}
|
.gitignore
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
*.pdf
|
| 2 |
+
*.url
|
| 3 |
+
*.jpg
|
| 4 |
+
*.png
|
| 5 |
+
*.ipynb
|
| 6 |
+
*.xls
|
| 7 |
+
*.pyc
|
| 8 |
+
*.json.bak.*
|
| 9 |
+
examples/*
|
| 10 |
+
output/*
|
| 11 |
+
tools/__pycache__/*
|
| 12 |
+
build/*
|
| 13 |
+
dist/*
|
| 14 |
+
logs/*
|
| 15 |
+
docs/*
|
| 16 |
+
guide/*
|
| 17 |
+
usage/*
|
| 18 |
+
feedback/*
|
| 19 |
+
test_code/*
|
| 20 |
+
config/*
|
| 21 |
+
tmp/*
|
| 22 |
+
test/tmp/*
|
| 23 |
+
unsloth_compiled_cache/*
|
| 24 |
+
.vscode/*
|
| 25 |
+
llm_topic_modelling.egg-info/*
|
| 26 |
+
index.qmd
|
| 27 |
+
_quarto.yml
|
| 28 |
+
/.quarto/
|
| 29 |
+
**/*.quarto_ipynb
|
| 30 |
+
config/*
|
| 31 |
+
!config/pi_agent.env.example
|
| 32 |
+
!config/docker_app_config.env.example
|
| 33 |
+
!config/app_config.env.example
|
| 34 |
+
workspace/*
|
| 35 |
+
user_guide/*
|
| 36 |
+
_extensions/*
|
| 37 |
+
cdk/config/*
|
| 38 |
+
!cdk/config/app_config.env.example
|
| 39 |
+
!cdk/config/lambda/
|
| 40 |
+
cdk/config/lambda/*
|
| 41 |
+
!cdk/config/lambda/lambda_function.py
|
| 42 |
+
!cdk/config/headless_s3_seed/
|
| 43 |
+
cdk/config/headless_s3_seed/*
|
| 44 |
+
!cdk/config/headless_s3_seed/input/
|
| 45 |
+
cdk/config/headless_s3_seed/input/*
|
| 46 |
+
!cdk/config/headless_s3_seed/input/config/
|
| 47 |
+
cdk/config/headless_s3_seed/input/config/*
|
| 48 |
+
!cdk/config/headless_s3_seed/input/config/example_headless_env_file.env
|
| 49 |
+
cdk/cdk.out/*
|
| 50 |
+
cdk/archive/*
|
| 51 |
+
cdk/cdk.out/*
|
| 52 |
+
cdk/cdk.json
|
| 53 |
+
cdk/cdk.context.json
|
| 54 |
+
cdk/precheck.context.json
|
| 55 |
+
|
Dockerfile
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# This Dockerfile is optimised for AWS ECS using Python 3.12, and assumes CUDA 12.6 for local models. The Dockerfile will need to be modified to install all linux CUDA / GPU dependencies.
|
| 2 |
+
|
| 3 |
+
# Stage 1: Build dependencies and download models
|
| 4 |
+
FROM public.ecr.aws/docker/library/python:3.12.12-slim-trixie AS builder
|
| 5 |
+
|
| 6 |
+
# Install system dependencies.
|
| 7 |
+
RUN apt-get update && apt-get install -y \
|
| 8 |
+
build-essential \
|
| 9 |
+
gcc \
|
| 10 |
+
g++ \
|
| 11 |
+
cmake \
|
| 12 |
+
#libopenblas-dev \
|
| 13 |
+
pkg-config \
|
| 14 |
+
python3-dev \
|
| 15 |
+
libffi-dev \
|
| 16 |
+
&& apt-get clean \
|
| 17 |
+
&& rm -rf /var/lib/apt/lists/*
|
| 18 |
+
|
| 19 |
+
WORKDIR /src
|
| 20 |
+
|
| 21 |
+
COPY requirements_lightweight.txt .
|
| 22 |
+
|
| 23 |
+
ARG INSTALL_TORCH=False
|
| 24 |
+
ENV INSTALL_TORCH=${INSTALL_TORCH}
|
| 25 |
+
|
| 26 |
+
# Local torch install requires CUDA 12.6
|
| 27 |
+
RUN if [ "$INSTALL_TORCH" = "True" ]; then \
|
| 28 |
+
pip install --no-cache-dir --target=/install torch==2.9.1 --extra-index-url https://download.pytorch.org/whl/cu126; \
|
| 29 |
+
fi
|
| 30 |
+
|
| 31 |
+
ARG INSTALL_LLAMA_CPP_PYTHON=False
|
| 32 |
+
ENV INSTALL_LLAMA_CPP_PYTHON=${INSTALL_LLAMA_CPP_PYTHON}
|
| 33 |
+
|
| 34 |
+
# Llama CPP Python install requires CUDA 12.4
|
| 35 |
+
RUN if [ "$INSTALL_LLAMA_CPP_PYTHON" = "True" ]; then \
|
| 36 |
+
pip install --no-cache-dir --target=/install https://github.com/abetlen/llama-cpp-python/releases/download/v0.3.16-cu124/llama_cpp_python-0.3.30-cp312-cp312-linux_x86_64.whl; \
|
| 37 |
+
fi
|
| 38 |
+
|
| 39 |
+
RUN pip install --no-cache-dir --target=/install -r requirements_lightweight.txt
|
| 40 |
+
|
| 41 |
+
RUN rm requirements_lightweight.txt
|
| 42 |
+
|
| 43 |
+
# ===================================================================
|
| 44 |
+
# Stage 2: A common 'base' for both Lambda and Gradio
|
| 45 |
+
# ===================================================================
|
| 46 |
+
FROM public.ecr.aws/docker/library/python:3.12.12-slim-trixie AS base
|
| 47 |
+
|
| 48 |
+
# Set build-time and runtime environment variable for whether to run in Gradio mode or Lambda mode
|
| 49 |
+
ARG APP_MODE=gradio
|
| 50 |
+
ENV APP_MODE=${APP_MODE}
|
| 51 |
+
|
| 52 |
+
# Install runtime system dependencies
|
| 53 |
+
RUN apt-get update && apt-get install -y --no-install-recommends \
|
| 54 |
+
libopenblas0 \
|
| 55 |
+
&& apt-get clean && rm -rf /var/lib/apt/lists/*
|
| 56 |
+
|
| 57 |
+
ENV APP_HOME=/home/user
|
| 58 |
+
|
| 59 |
+
# Set env variables for Gradio & other apps
|
| 60 |
+
ENV GRADIO_TEMP_DIR=/tmp/gradio_tmp/ \
|
| 61 |
+
MPLCONFIGDIR=/tmp/matplotlib_cache/ \
|
| 62 |
+
GRADIO_OUTPUT_FOLDER=$APP_HOME/app/output/ \
|
| 63 |
+
GRADIO_INPUT_FOLDER=$APP_HOME/app/input/ \
|
| 64 |
+
FEEDBACK_LOGS_FOLDER=$APP_HOME/app/feedback/ \
|
| 65 |
+
ACCESS_LOGS_FOLDER=$APP_HOME/app/logs/ \
|
| 66 |
+
USAGE_LOGS_FOLDER=$APP_HOME/app/usage/ \
|
| 67 |
+
CONFIG_FOLDER=$APP_HOME/app/config/ \
|
| 68 |
+
GRADIO_SERVER_NAME=0.0.0.0 \
|
| 69 |
+
GRADIO_SERVER_PORT=7860 \
|
| 70 |
+
PATH=$APP_HOME/.local/bin:$PATH \
|
| 71 |
+
PYTHONPATH=$APP_HOME/app \
|
| 72 |
+
PYTHONUNBUFFERED=1 \
|
| 73 |
+
PYTHONDONTWRITEBYTECODE=1 \
|
| 74 |
+
GRADIO_ALLOW_FLAGGING=never \
|
| 75 |
+
GRADIO_NUM_PORTS=1 \
|
| 76 |
+
GRADIO_THEME=huggingface \
|
| 77 |
+
SYSTEM=spaces
|
| 78 |
+
|
| 79 |
+
# Copy Python packages from the builder stage
|
| 80 |
+
COPY --from=builder /install /usr/local/lib/python3.12/site-packages/
|
| 81 |
+
COPY --from=builder /install/bin /usr/local/bin/
|
| 82 |
+
|
| 83 |
+
# Copy your application code and entrypoint
|
| 84 |
+
COPY . ${APP_HOME}/app
|
| 85 |
+
COPY entrypoint.sh ${APP_HOME}/app/entrypoint.sh
|
| 86 |
+
# Fix line endings and set execute permissions
|
| 87 |
+
RUN sed -i 's/\r$//' ${APP_HOME}/app/entrypoint.sh \
|
| 88 |
+
&& chmod +x ${APP_HOME}/app/entrypoint.sh
|
| 89 |
+
|
| 90 |
+
WORKDIR ${APP_HOME}/app
|
| 91 |
+
|
| 92 |
+
# ===================================================================
|
| 93 |
+
# FINAL Stage 3: The Lambda Image (runs as root for simplicity)
|
| 94 |
+
# ===================================================================
|
| 95 |
+
FROM base AS lambda
|
| 96 |
+
# Set runtime ENV for Lambda mode
|
| 97 |
+
ENV APP_MODE=lambda
|
| 98 |
+
ENTRYPOINT ["/home/user/app/entrypoint.sh"]
|
| 99 |
+
CMD ["lambda_entrypoint.lambda_handler"]
|
| 100 |
+
|
| 101 |
+
# ===================================================================
|
| 102 |
+
# FINAL Stage 4: The Gradio Image (runs as a secure, non-root user)
|
| 103 |
+
# ===================================================================
|
| 104 |
+
FROM base AS gradio
|
| 105 |
+
# Set runtime ENV for Gradio mode
|
| 106 |
+
ENV APP_MODE=gradio
|
| 107 |
+
|
| 108 |
+
# Create non-root user
|
| 109 |
+
RUN useradd -m -u 1000 user
|
| 110 |
+
|
| 111 |
+
# Create the base application directory and set its ownership
|
| 112 |
+
RUN mkdir -p ${APP_HOME}/app && chown user:user ${APP_HOME}/app
|
| 113 |
+
|
| 114 |
+
# Create required sub-folders within the app directory and set their permissions
|
| 115 |
+
RUN mkdir -p \
|
| 116 |
+
${APP_HOME}/app/output \
|
| 117 |
+
${APP_HOME}/app/input \
|
| 118 |
+
${APP_HOME}/app/logs \
|
| 119 |
+
${APP_HOME}/app/usage \
|
| 120 |
+
${APP_HOME}/app/feedback \
|
| 121 |
+
${APP_HOME}/app/config \
|
| 122 |
+
&& chown user:user \
|
| 123 |
+
${APP_HOME}/app/output \
|
| 124 |
+
${APP_HOME}/app/input \
|
| 125 |
+
${APP_HOME}/app/logs \
|
| 126 |
+
${APP_HOME}/app/usage \
|
| 127 |
+
${APP_HOME}/app/feedback \
|
| 128 |
+
${APP_HOME}/app/config \
|
| 129 |
+
&& chmod 755 \
|
| 130 |
+
${APP_HOME}/app/output \
|
| 131 |
+
${APP_HOME}/app/input \
|
| 132 |
+
${APP_HOME}/app/logs \
|
| 133 |
+
${APP_HOME}/app/usage \
|
| 134 |
+
${APP_HOME}/app/feedback \
|
| 135 |
+
${APP_HOME}/app/config
|
| 136 |
+
|
| 137 |
+
# Now handle the /tmp directories
|
| 138 |
+
RUN mkdir -p /tmp/gradio_tmp /tmp/matplotlib_cache /tmp /var/tmp \
|
| 139 |
+
&& chown user:user /tmp /var/tmp /tmp/gradio_tmp /tmp/matplotlib_cache \
|
| 140 |
+
&& chmod 1777 /tmp /var/tmp /tmp/gradio_tmp /tmp/matplotlib_cache
|
| 141 |
+
|
| 142 |
+
# Fix apply user ownership to all files in the home directory
|
| 143 |
+
RUN chown -R user:user /home/user
|
| 144 |
+
|
| 145 |
+
# Set permissions for Python executable
|
| 146 |
+
RUN chmod 755 /usr/local/bin/python
|
| 147 |
+
|
| 148 |
+
# Declare volumes
|
| 149 |
+
VOLUME ["/tmp/matplotlib_cache"]
|
| 150 |
+
VOLUME ["/tmp/gradio_tmp"]
|
| 151 |
+
VOLUME ["/home/user/app/output"]
|
| 152 |
+
VOLUME ["/home/user/app/input"]
|
| 153 |
+
VOLUME ["/home/user/app/logs"]
|
| 154 |
+
VOLUME ["/home/user/app/usage"]
|
| 155 |
+
VOLUME ["/home/user/app/feedback"]
|
| 156 |
+
VOLUME ["/home/user/app/config"]
|
| 157 |
+
VOLUME ["/tmp"]
|
| 158 |
+
VOLUME ["/var/tmp"]
|
| 159 |
+
|
| 160 |
+
USER user
|
| 161 |
+
|
| 162 |
+
EXPOSE $GRADIO_SERVER_PORT
|
| 163 |
+
|
| 164 |
+
ENTRYPOINT ["/home/user/app/entrypoint.sh"]
|
| 165 |
+
CMD ["python", "app.py"]
|
LICENSE
ADDED
|
@@ -0,0 +1,661 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
GNU AFFERO GENERAL PUBLIC LICENSE
|
| 2 |
+
Version 3, 19 November 2007
|
| 3 |
+
|
| 4 |
+
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
| 5 |
+
Everyone is permitted to copy and distribute verbatim copies
|
| 6 |
+
of this license document, but changing it is not allowed.
|
| 7 |
+
|
| 8 |
+
Preamble
|
| 9 |
+
|
| 10 |
+
The GNU Affero General Public License is a free, copyleft license for
|
| 11 |
+
software and other kinds of works, specifically designed to ensure
|
| 12 |
+
cooperation with the community in the case of network server software.
|
| 13 |
+
|
| 14 |
+
The licenses for most software and other practical works are designed
|
| 15 |
+
to take away your freedom to share and change the works. By contrast,
|
| 16 |
+
our General Public Licenses are intended to guarantee your freedom to
|
| 17 |
+
share and change all versions of a program--to make sure it remains free
|
| 18 |
+
software for all its users.
|
| 19 |
+
|
| 20 |
+
When we speak of free software, we are referring to freedom, not
|
| 21 |
+
price. Our General Public Licenses are designed to make sure that you
|
| 22 |
+
have the freedom to distribute copies of free software (and charge for
|
| 23 |
+
them if you wish), that you receive source code or can get it if you
|
| 24 |
+
want it, that you can change the software or use pieces of it in new
|
| 25 |
+
free programs, and that you know you can do these things.
|
| 26 |
+
|
| 27 |
+
Developers that use our General Public Licenses protect your rights
|
| 28 |
+
with two steps: (1) assert copyright on the software, and (2) offer
|
| 29 |
+
you this License which gives you legal permission to copy, distribute
|
| 30 |
+
and/or modify the software.
|
| 31 |
+
|
| 32 |
+
A secondary benefit of defending all users' freedom is that
|
| 33 |
+
improvements made in alternate versions of the program, if they
|
| 34 |
+
receive widespread use, become available for other developers to
|
| 35 |
+
incorporate. Many developers of free software are heartened and
|
| 36 |
+
encouraged by the resulting cooperation. However, in the case of
|
| 37 |
+
software used on network servers, this result may fail to come about.
|
| 38 |
+
The GNU General Public License permits making a modified version and
|
| 39 |
+
letting the public access it on a server without ever releasing its
|
| 40 |
+
source code to the public.
|
| 41 |
+
|
| 42 |
+
The GNU Affero General Public License is designed specifically to
|
| 43 |
+
ensure that, in such cases, the modified source code becomes available
|
| 44 |
+
to the community. It requires the operator of a network server to
|
| 45 |
+
provide the source code of the modified version running there to the
|
| 46 |
+
users of that server. Therefore, public use of a modified version, on
|
| 47 |
+
a publicly accessible server, gives the public access to the source
|
| 48 |
+
code of the modified version.
|
| 49 |
+
|
| 50 |
+
An older license, called the Affero General Public License and
|
| 51 |
+
published by Affero, was designed to accomplish similar goals. This is
|
| 52 |
+
a different license, not a version of the Affero GPL, but Affero has
|
| 53 |
+
released a new version of the Affero GPL which permits relicensing under
|
| 54 |
+
this license.
|
| 55 |
+
|
| 56 |
+
The precise terms and conditions for copying, distribution and
|
| 57 |
+
modification follow.
|
| 58 |
+
|
| 59 |
+
TERMS AND CONDITIONS
|
| 60 |
+
|
| 61 |
+
0. Definitions.
|
| 62 |
+
|
| 63 |
+
"This License" refers to version 3 of the GNU Affero General Public License.
|
| 64 |
+
|
| 65 |
+
"Copyright" also means copyright-like laws that apply to other kinds of
|
| 66 |
+
works, such as semiconductor masks.
|
| 67 |
+
|
| 68 |
+
"The Program" refers to any copyrightable work licensed under this
|
| 69 |
+
License. Each licensee is addressed as "you". "Licensees" and
|
| 70 |
+
"recipients" may be individuals or organizations.
|
| 71 |
+
|
| 72 |
+
To "modify" a work means to copy from or adapt all or part of the work
|
| 73 |
+
in a fashion requiring copyright permission, other than the making of an
|
| 74 |
+
exact copy. The resulting work is called a "modified version" of the
|
| 75 |
+
earlier work or a work "based on" the earlier work.
|
| 76 |
+
|
| 77 |
+
A "covered work" means either the unmodified Program or a work based
|
| 78 |
+
on the Program.
|
| 79 |
+
|
| 80 |
+
To "propagate" a work means to do anything with it that, without
|
| 81 |
+
permission, would make you directly or secondarily liable for
|
| 82 |
+
infringement under applicable copyright law, except executing it on a
|
| 83 |
+
computer or modifying a private copy. Propagation includes copying,
|
| 84 |
+
distribution (with or without modification), making available to the
|
| 85 |
+
public, and in some countries other activities as well.
|
| 86 |
+
|
| 87 |
+
To "convey" a work means any kind of propagation that enables other
|
| 88 |
+
parties to make or receive copies. Mere interaction with a user through
|
| 89 |
+
a computer network, with no transfer of a copy, is not conveying.
|
| 90 |
+
|
| 91 |
+
An interactive user interface displays "Appropriate Legal Notices"
|
| 92 |
+
to the extent that it includes a convenient and prominently visible
|
| 93 |
+
feature that (1) displays an appropriate copyright notice, and (2)
|
| 94 |
+
tells the user that there is no warranty for the work (except to the
|
| 95 |
+
extent that warranties are provided), that licensees may convey the
|
| 96 |
+
work under this License, and how to view a copy of this License. If
|
| 97 |
+
the interface presents a list of user commands or options, such as a
|
| 98 |
+
menu, a prominent item in the list meets this criterion.
|
| 99 |
+
|
| 100 |
+
1. Source Code.
|
| 101 |
+
|
| 102 |
+
The "source code" for a work means the preferred form of the work
|
| 103 |
+
for making modifications to it. "Object code" means any non-source
|
| 104 |
+
form of a work.
|
| 105 |
+
|
| 106 |
+
A "Standard Interface" means an interface that either is an official
|
| 107 |
+
standard defined by a recognized standards body, or, in the case of
|
| 108 |
+
interfaces specified for a particular programming language, one that
|
| 109 |
+
is widely used among developers working in that language.
|
| 110 |
+
|
| 111 |
+
The "System Libraries" of an executable work include anything, other
|
| 112 |
+
than the work as a whole, that (a) is included in the normal form of
|
| 113 |
+
packaging a Major Component, but which is not part of that Major
|
| 114 |
+
Component, and (b) serves only to enable use of the work with that
|
| 115 |
+
Major Component, or to implement a Standard Interface for which an
|
| 116 |
+
implementation is available to the public in source code form. A
|
| 117 |
+
"Major Component", in this context, means a major essential component
|
| 118 |
+
(kernel, window system, and so on) of the specific operating system
|
| 119 |
+
(if any) on which the executable work runs, or a compiler used to
|
| 120 |
+
produce the work, or an object code interpreter used to run it.
|
| 121 |
+
|
| 122 |
+
The "Corresponding Source" for a work in object code form means all
|
| 123 |
+
the source code needed to generate, install, and (for an executable
|
| 124 |
+
work) run the object code and to modify the work, including scripts to
|
| 125 |
+
control those activities. However, it does not include the work's
|
| 126 |
+
System Libraries, or general-purpose tools or generally available free
|
| 127 |
+
programs which are used unmodified in performing those activities but
|
| 128 |
+
which are not part of the work. For example, Corresponding Source
|
| 129 |
+
includes interface definition files associated with source files for
|
| 130 |
+
the work, and the source code for shared libraries and dynamically
|
| 131 |
+
linked subprograms that the work is specifically designed to require,
|
| 132 |
+
such as by intimate data communication or control flow between those
|
| 133 |
+
subprograms and other parts of the work.
|
| 134 |
+
|
| 135 |
+
The Corresponding Source need not include anything that users
|
| 136 |
+
can regenerate automatically from other parts of the Corresponding
|
| 137 |
+
Source.
|
| 138 |
+
|
| 139 |
+
The Corresponding Source for a work in source code form is that
|
| 140 |
+
same work.
|
| 141 |
+
|
| 142 |
+
2. Basic Permissions.
|
| 143 |
+
|
| 144 |
+
All rights granted under this License are granted for the term of
|
| 145 |
+
copyright on the Program, and are irrevocable provided the stated
|
| 146 |
+
conditions are met. This License explicitly affirms your unlimited
|
| 147 |
+
permission to run the unmodified Program. The output from running a
|
| 148 |
+
covered work is covered by this License only if the output, given its
|
| 149 |
+
content, constitutes a covered work. This License acknowledges your
|
| 150 |
+
rights of fair use or other equivalent, as provided by copyright law.
|
| 151 |
+
|
| 152 |
+
You may make, run and propagate covered works that you do not
|
| 153 |
+
convey, without conditions so long as your license otherwise remains
|
| 154 |
+
in force. You may convey covered works to others for the sole purpose
|
| 155 |
+
of having them make modifications exclusively for you, or provide you
|
| 156 |
+
with facilities for running those works, provided that you comply with
|
| 157 |
+
the terms of this License in conveying all material for which you do
|
| 158 |
+
not control copyright. Those thus making or running the covered works
|
| 159 |
+
for you must do so exclusively on your behalf, under your direction
|
| 160 |
+
and control, on terms that prohibit them from making any copies of
|
| 161 |
+
your copyrighted material outside their relationship with you.
|
| 162 |
+
|
| 163 |
+
Conveying under any other circumstances is permitted solely under
|
| 164 |
+
the conditions stated below. Sublicensing is not allowed; section 10
|
| 165 |
+
makes it unnecessary.
|
| 166 |
+
|
| 167 |
+
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
| 168 |
+
|
| 169 |
+
No covered work shall be deemed part of an effective technological
|
| 170 |
+
measure under any applicable law fulfilling obligations under article
|
| 171 |
+
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
| 172 |
+
similar laws prohibiting or restricting circumvention of such
|
| 173 |
+
measures.
|
| 174 |
+
|
| 175 |
+
When you convey a covered work, you waive any legal power to forbid
|
| 176 |
+
circumvention of technological measures to the extent such circumvention
|
| 177 |
+
is effected by exercising rights under this License with respect to
|
| 178 |
+
the covered work, and you disclaim any intention to limit operation or
|
| 179 |
+
modification of the work as a means of enforcing, against the work's
|
| 180 |
+
users, your or third parties' legal rights to forbid circumvention of
|
| 181 |
+
technological measures.
|
| 182 |
+
|
| 183 |
+
4. Conveying Verbatim Copies.
|
| 184 |
+
|
| 185 |
+
You may convey verbatim copies of the Program's source code as you
|
| 186 |
+
receive it, in any medium, provided that you conspicuously and
|
| 187 |
+
appropriately publish on each copy an appropriate copyright notice;
|
| 188 |
+
keep intact all notices stating that this License and any
|
| 189 |
+
non-permissive terms added in accord with section 7 apply to the code;
|
| 190 |
+
keep intact all notices of the absence of any warranty; and give all
|
| 191 |
+
recipients a copy of this License along with the Program.
|
| 192 |
+
|
| 193 |
+
You may charge any price or no price for each copy that you convey,
|
| 194 |
+
and you may offer support or warranty protection for a fee.
|
| 195 |
+
|
| 196 |
+
5. Conveying Modified Source Versions.
|
| 197 |
+
|
| 198 |
+
You may convey a work based on the Program, or the modifications to
|
| 199 |
+
produce it from the Program, in the form of source code under the
|
| 200 |
+
terms of section 4, provided that you also meet all of these conditions:
|
| 201 |
+
|
| 202 |
+
a) The work must carry prominent notices stating that you modified
|
| 203 |
+
it, and giving a relevant date.
|
| 204 |
+
|
| 205 |
+
b) The work must carry prominent notices stating that it is
|
| 206 |
+
released under this License and any conditions added under section
|
| 207 |
+
7. This requirement modifies the requirement in section 4 to
|
| 208 |
+
"keep intact all notices".
|
| 209 |
+
|
| 210 |
+
c) You must license the entire work, as a whole, under this
|
| 211 |
+
License to anyone who comes into possession of a copy. This
|
| 212 |
+
License will therefore apply, along with any applicable section 7
|
| 213 |
+
additional terms, to the whole of the work, and all its parts,
|
| 214 |
+
regardless of how they are packaged. This License gives no
|
| 215 |
+
permission to license the work in any other way, but it does not
|
| 216 |
+
invalidate such permission if you have separately received it.
|
| 217 |
+
|
| 218 |
+
d) If the work has interactive user interfaces, each must display
|
| 219 |
+
Appropriate Legal Notices; however, if the Program has interactive
|
| 220 |
+
interfaces that do not display Appropriate Legal Notices, your
|
| 221 |
+
work need not make them do so.
|
| 222 |
+
|
| 223 |
+
A compilation of a covered work with other separate and independent
|
| 224 |
+
works, which are not by their nature extensions of the covered work,
|
| 225 |
+
and which are not combined with it such as to form a larger program,
|
| 226 |
+
in or on a volume of a storage or distribution medium, is called an
|
| 227 |
+
"aggregate" if the compilation and its resulting copyright are not
|
| 228 |
+
used to limit the access or legal rights of the compilation's users
|
| 229 |
+
beyond what the individual works permit. Inclusion of a covered work
|
| 230 |
+
in an aggregate does not cause this License to apply to the other
|
| 231 |
+
parts of the aggregate.
|
| 232 |
+
|
| 233 |
+
6. Conveying Non-Source Forms.
|
| 234 |
+
|
| 235 |
+
You may convey a covered work in object code form under the terms
|
| 236 |
+
of sections 4 and 5, provided that you also convey the
|
| 237 |
+
machine-readable Corresponding Source under the terms of this License,
|
| 238 |
+
in one of these ways:
|
| 239 |
+
|
| 240 |
+
a) Convey the object code in, or embodied in, a physical product
|
| 241 |
+
(including a physical distribution medium), accompanied by the
|
| 242 |
+
Corresponding Source fixed on a durable physical medium
|
| 243 |
+
customarily used for software interchange.
|
| 244 |
+
|
| 245 |
+
b) Convey the object code in, or embodied in, a physical product
|
| 246 |
+
(including a physical distribution medium), accompanied by a
|
| 247 |
+
written offer, valid for at least three years and valid for as
|
| 248 |
+
long as you offer spare parts or customer support for that product
|
| 249 |
+
model, to give anyone who possesses the object code either (1) a
|
| 250 |
+
copy of the Corresponding Source for all the software in the
|
| 251 |
+
product that is covered by this License, on a durable physical
|
| 252 |
+
medium customarily used for software interchange, for a price no
|
| 253 |
+
more than your reasonable cost of physically performing this
|
| 254 |
+
conveying of source, or (2) access to copy the
|
| 255 |
+
Corresponding Source from a network server at no charge.
|
| 256 |
+
|
| 257 |
+
c) Convey individual copies of the object code with a copy of the
|
| 258 |
+
written offer to provide the Corresponding Source. This
|
| 259 |
+
alternative is allowed only occasionally and noncommercially, and
|
| 260 |
+
only if you received the object code with such an offer, in accord
|
| 261 |
+
with subsection 6b.
|
| 262 |
+
|
| 263 |
+
d) Convey the object code by offering access from a designated
|
| 264 |
+
place (gratis or for a charge), and offer equivalent access to the
|
| 265 |
+
Corresponding Source in the same way through the same place at no
|
| 266 |
+
further charge. You need not require recipients to copy the
|
| 267 |
+
Corresponding Source along with the object code. If the place to
|
| 268 |
+
copy the object code is a network server, the Corresponding Source
|
| 269 |
+
may be on a different server (operated by you or a third party)
|
| 270 |
+
that supports equivalent copying facilities, provided you maintain
|
| 271 |
+
clear directions next to the object code saying where to find the
|
| 272 |
+
Corresponding Source. Regardless of what server hosts the
|
| 273 |
+
Corresponding Source, you remain obligated to ensure that it is
|
| 274 |
+
available for as long as needed to satisfy these requirements.
|
| 275 |
+
|
| 276 |
+
e) Convey the object code using peer-to-peer transmission, provided
|
| 277 |
+
you inform other peers where the object code and Corresponding
|
| 278 |
+
Source of the work are being offered to the general public at no
|
| 279 |
+
charge under subsection 6d.
|
| 280 |
+
|
| 281 |
+
A separable portion of the object code, whose source code is excluded
|
| 282 |
+
from the Corresponding Source as a System Library, need not be
|
| 283 |
+
included in conveying the object code work.
|
| 284 |
+
|
| 285 |
+
A "User Product" is either (1) a "consumer product", which means any
|
| 286 |
+
tangible personal property which is normally used for personal, family,
|
| 287 |
+
or household purposes, or (2) anything designed or sold for incorporation
|
| 288 |
+
into a dwelling. In determining whether a product is a consumer product,
|
| 289 |
+
doubtful cases shall be resolved in favor of coverage. For a particular
|
| 290 |
+
product received by a particular user, "normally used" refers to a
|
| 291 |
+
typical or common use of that class of product, regardless of the status
|
| 292 |
+
of the particular user or of the way in which the particular user
|
| 293 |
+
actually uses, or expects or is expected to use, the product. A product
|
| 294 |
+
is a consumer product regardless of whether the product has substantial
|
| 295 |
+
commercial, industrial or non-consumer uses, unless such uses represent
|
| 296 |
+
the only significant mode of use of the product.
|
| 297 |
+
|
| 298 |
+
"Installation Information" for a User Product means any methods,
|
| 299 |
+
procedures, authorization keys, or other information required to install
|
| 300 |
+
and execute modified versions of a covered work in that User Product from
|
| 301 |
+
a modified version of its Corresponding Source. The information must
|
| 302 |
+
suffice to ensure that the continued functioning of the modified object
|
| 303 |
+
code is in no case prevented or interfered with solely because
|
| 304 |
+
modification has been made.
|
| 305 |
+
|
| 306 |
+
If you convey an object code work under this section in, or with, or
|
| 307 |
+
specifically for use in, a User Product, and the conveying occurs as
|
| 308 |
+
part of a transaction in which the right of possession and use of the
|
| 309 |
+
User Product is transferred to the recipient in perpetuity or for a
|
| 310 |
+
fixed term (regardless of how the transaction is characterized), the
|
| 311 |
+
Corresponding Source conveyed under this section must be accompanied
|
| 312 |
+
by the Installation Information. But this requirement does not apply
|
| 313 |
+
if neither you nor any third party retains the ability to install
|
| 314 |
+
modified object code on the User Product (for example, the work has
|
| 315 |
+
been installed in ROM).
|
| 316 |
+
|
| 317 |
+
The requirement to provide Installation Information does not include a
|
| 318 |
+
requirement to continue to provide support service, warranty, or updates
|
| 319 |
+
for a work that has been modified or installed by the recipient, or for
|
| 320 |
+
the User Product in which it has been modified or installed. Access to a
|
| 321 |
+
network may be denied when the modification itself materially and
|
| 322 |
+
adversely affects the operation of the network or violates the rules and
|
| 323 |
+
protocols for communication across the network.
|
| 324 |
+
|
| 325 |
+
Corresponding Source conveyed, and Installation Information provided,
|
| 326 |
+
in accord with this section must be in a format that is publicly
|
| 327 |
+
documented (and with an implementation available to the public in
|
| 328 |
+
source code form), and must require no special password or key for
|
| 329 |
+
unpacking, reading or copying.
|
| 330 |
+
|
| 331 |
+
7. Additional Terms.
|
| 332 |
+
|
| 333 |
+
"Additional permissions" are terms that supplement the terms of this
|
| 334 |
+
License by making exceptions from one or more of its conditions.
|
| 335 |
+
Additional permissions that are applicable to the entire Program shall
|
| 336 |
+
be treated as though they were included in this License, to the extent
|
| 337 |
+
that they are valid under applicable law. If additional permissions
|
| 338 |
+
apply only to part of the Program, that part may be used separately
|
| 339 |
+
under those permissions, but the entire Program remains governed by
|
| 340 |
+
this License without regard to the additional permissions.
|
| 341 |
+
|
| 342 |
+
When you convey a copy of a covered work, you may at your option
|
| 343 |
+
remove any additional permissions from that copy, or from any part of
|
| 344 |
+
it. (Additional permissions may be written to require their own
|
| 345 |
+
removal in certain cases when you modify the work.) You may place
|
| 346 |
+
additional permissions on material, added by you to a covered work,
|
| 347 |
+
for which you have or can give appropriate copyright permission.
|
| 348 |
+
|
| 349 |
+
Notwithstanding any other provision of this License, for material you
|
| 350 |
+
add to a covered work, you may (if authorized by the copyright holders of
|
| 351 |
+
that material) supplement the terms of this License with terms:
|
| 352 |
+
|
| 353 |
+
a) Disclaiming warranty or limiting liability differently from the
|
| 354 |
+
terms of sections 15 and 16 of this License; or
|
| 355 |
+
|
| 356 |
+
b) Requiring preservation of specified reasonable legal notices or
|
| 357 |
+
author attributions in that material or in the Appropriate Legal
|
| 358 |
+
Notices displayed by works containing it; or
|
| 359 |
+
|
| 360 |
+
c) Prohibiting misrepresentation of the origin of that material, or
|
| 361 |
+
requiring that modified versions of such material be marked in
|
| 362 |
+
reasonable ways as different from the original version; or
|
| 363 |
+
|
| 364 |
+
d) Limiting the use for publicity purposes of names of licensors or
|
| 365 |
+
authors of the material; or
|
| 366 |
+
|
| 367 |
+
e) Declining to grant rights under trademark law for use of some
|
| 368 |
+
trade names, trademarks, or service marks; or
|
| 369 |
+
|
| 370 |
+
f) Requiring indemnification of licensors and authors of that
|
| 371 |
+
material by anyone who conveys the material (or modified versions of
|
| 372 |
+
it) with contractual assumptions of liability to the recipient, for
|
| 373 |
+
any liability that these contractual assumptions directly impose on
|
| 374 |
+
those licensors and authors.
|
| 375 |
+
|
| 376 |
+
All other non-permissive additional terms are considered "further
|
| 377 |
+
restrictions" within the meaning of section 10. If the Program as you
|
| 378 |
+
received it, or any part of it, contains a notice stating that it is
|
| 379 |
+
governed by this License along with a term that is a further
|
| 380 |
+
restriction, you may remove that term. If a license document contains
|
| 381 |
+
a further restriction but permits relicensing or conveying under this
|
| 382 |
+
License, you may add to a covered work material governed by the terms
|
| 383 |
+
of that license document, provided that the further restriction does
|
| 384 |
+
not survive such relicensing or conveying.
|
| 385 |
+
|
| 386 |
+
If you add terms to a covered work in accord with this section, you
|
| 387 |
+
must place, in the relevant source files, a statement of the
|
| 388 |
+
additional terms that apply to those files, or a notice indicating
|
| 389 |
+
where to find the applicable terms.
|
| 390 |
+
|
| 391 |
+
Additional terms, permissive or non-permissive, may be stated in the
|
| 392 |
+
form of a separately written license, or stated as exceptions;
|
| 393 |
+
the above requirements apply either way.
|
| 394 |
+
|
| 395 |
+
8. Termination.
|
| 396 |
+
|
| 397 |
+
You may not propagate or modify a covered work except as expressly
|
| 398 |
+
provided under this License. Any attempt otherwise to propagate or
|
| 399 |
+
modify it is void, and will automatically terminate your rights under
|
| 400 |
+
this License (including any patent licenses granted under the third
|
| 401 |
+
paragraph of section 11).
|
| 402 |
+
|
| 403 |
+
However, if you cease all violation of this License, then your
|
| 404 |
+
license from a particular copyright holder is reinstated (a)
|
| 405 |
+
provisionally, unless and until the copyright holder explicitly and
|
| 406 |
+
finally terminates your license, and (b) permanently, if the copyright
|
| 407 |
+
holder fails to notify you of the violation by some reasonable means
|
| 408 |
+
prior to 60 days after the cessation.
|
| 409 |
+
|
| 410 |
+
Moreover, your license from a particular copyright holder is
|
| 411 |
+
reinstated permanently if the copyright holder notifies you of the
|
| 412 |
+
violation by some reasonable means, this is the first time you have
|
| 413 |
+
received notice of violation of this License (for any work) from that
|
| 414 |
+
copyright holder, and you cure the violation prior to 30 days after
|
| 415 |
+
your receipt of the notice.
|
| 416 |
+
|
| 417 |
+
Termination of your rights under this section does not terminate the
|
| 418 |
+
licenses of parties who have received copies or rights from you under
|
| 419 |
+
this License. If your rights have been terminated and not permanently
|
| 420 |
+
reinstated, you do not qualify to receive new licenses for the same
|
| 421 |
+
material under section 10.
|
| 422 |
+
|
| 423 |
+
9. Acceptance Not Required for Having Copies.
|
| 424 |
+
|
| 425 |
+
You are not required to accept this License in order to receive or
|
| 426 |
+
run a copy of the Program. Ancillary propagation of a covered work
|
| 427 |
+
occurring solely as a consequence of using peer-to-peer transmission
|
| 428 |
+
to receive a copy likewise does not require acceptance. However,
|
| 429 |
+
nothing other than this License grants you permission to propagate or
|
| 430 |
+
modify any covered work. These actions infringe copyright if you do
|
| 431 |
+
not accept this License. Therefore, by modifying or propagating a
|
| 432 |
+
covered work, you indicate your acceptance of this License to do so.
|
| 433 |
+
|
| 434 |
+
10. Automatic Licensing of Downstream Recipients.
|
| 435 |
+
|
| 436 |
+
Each time you convey a covered work, the recipient automatically
|
| 437 |
+
receives a license from the original licensors, to run, modify and
|
| 438 |
+
propagate that work, subject to this License. You are not responsible
|
| 439 |
+
for enforcing compliance by third parties with this License.
|
| 440 |
+
|
| 441 |
+
An "entity transaction" is a transaction transferring control of an
|
| 442 |
+
organization, or substantially all assets of one, or subdividing an
|
| 443 |
+
organization, or merging organizations. If propagation of a covered
|
| 444 |
+
work results from an entity transaction, each party to that
|
| 445 |
+
transaction who receives a copy of the work also receives whatever
|
| 446 |
+
licenses to the work the party's predecessor in interest had or could
|
| 447 |
+
give under the previous paragraph, plus a right to possession of the
|
| 448 |
+
Corresponding Source of the work from the predecessor in interest, if
|
| 449 |
+
the predecessor has it or can get it with reasonable efforts.
|
| 450 |
+
|
| 451 |
+
You may not impose any further restrictions on the exercise of the
|
| 452 |
+
rights granted or affirmed under this License. For example, you may
|
| 453 |
+
not impose a license fee, royalty, or other charge for exercise of
|
| 454 |
+
rights granted under this License, and you may not initiate litigation
|
| 455 |
+
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
| 456 |
+
any patent claim is infringed by making, using, selling, offering for
|
| 457 |
+
sale, or importing the Program or any portion of it.
|
| 458 |
+
|
| 459 |
+
11. Patents.
|
| 460 |
+
|
| 461 |
+
A "contributor" is a copyright holder who authorizes use under this
|
| 462 |
+
License of the Program or a work on which the Program is based. The
|
| 463 |
+
work thus licensed is called the contributor's "contributor version".
|
| 464 |
+
|
| 465 |
+
A contributor's "essential patent claims" are all patent claims
|
| 466 |
+
owned or controlled by the contributor, whether already acquired or
|
| 467 |
+
hereafter acquired, that would be infringed by some manner, permitted
|
| 468 |
+
by this License, of making, using, or selling its contributor version,
|
| 469 |
+
but do not include claims that would be infringed only as a
|
| 470 |
+
consequence of further modification of the contributor version. For
|
| 471 |
+
purposes of this definition, "control" includes the right to grant
|
| 472 |
+
patent sublicenses in a manner consistent with the requirements of
|
| 473 |
+
this License.
|
| 474 |
+
|
| 475 |
+
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
| 476 |
+
patent license under the contributor's essential patent claims, to
|
| 477 |
+
make, use, sell, offer for sale, import and otherwise run, modify and
|
| 478 |
+
propagate the contents of its contributor version.
|
| 479 |
+
|
| 480 |
+
In the following three paragraphs, a "patent license" is any express
|
| 481 |
+
agreement or commitment, however denominated, not to enforce a patent
|
| 482 |
+
(such as an express permission to practice a patent or covenant not to
|
| 483 |
+
sue for patent infringement). To "grant" such a patent license to a
|
| 484 |
+
party means to make such an agreement or commitment not to enforce a
|
| 485 |
+
patent against the party.
|
| 486 |
+
|
| 487 |
+
If you convey a covered work, knowingly relying on a patent license,
|
| 488 |
+
and the Corresponding Source of the work is not available for anyone
|
| 489 |
+
to copy, free of charge and under the terms of this License, through a
|
| 490 |
+
publicly available network server or other readily accessible means,
|
| 491 |
+
then you must either (1) cause the Corresponding Source to be so
|
| 492 |
+
available, or (2) arrange to deprive yourself of the benefit of the
|
| 493 |
+
patent license for this particular work, or (3) arrange, in a manner
|
| 494 |
+
consistent with the requirements of this License, to extend the patent
|
| 495 |
+
license to downstream recipients. "Knowingly relying" means you have
|
| 496 |
+
actual knowledge that, but for the patent license, your conveying the
|
| 497 |
+
covered work in a country, or your recipient's use of the covered work
|
| 498 |
+
in a country, would infringe one or more identifiable patents in that
|
| 499 |
+
country that you have reason to believe are valid.
|
| 500 |
+
|
| 501 |
+
If, pursuant to or in connection with a single transaction or
|
| 502 |
+
arrangement, you convey, or propagate by procuring conveyance of, a
|
| 503 |
+
covered work, and grant a patent license to some of the parties
|
| 504 |
+
receiving the covered work authorizing them to use, propagate, modify
|
| 505 |
+
or convey a specific copy of the covered work, then the patent license
|
| 506 |
+
you grant is automatically extended to all recipients of the covered
|
| 507 |
+
work and works based on it.
|
| 508 |
+
|
| 509 |
+
A patent license is "discriminatory" if it does not include within
|
| 510 |
+
the scope of its coverage, prohibits the exercise of, or is
|
| 511 |
+
conditioned on the non-exercise of one or more of the rights that are
|
| 512 |
+
specifically granted under this License. You may not convey a covered
|
| 513 |
+
work if you are a party to an arrangement with a third party that is
|
| 514 |
+
in the business of distributing software, under which you make payment
|
| 515 |
+
to the third party based on the extent of your activity of conveying
|
| 516 |
+
the work, and under which the third party grants, to any of the
|
| 517 |
+
parties who would receive the covered work from you, a discriminatory
|
| 518 |
+
patent license (a) in connection with copies of the covered work
|
| 519 |
+
conveyed by you (or copies made from those copies), or (b) primarily
|
| 520 |
+
for and in connection with specific products or compilations that
|
| 521 |
+
contain the covered work, unless you entered into that arrangement,
|
| 522 |
+
or that patent license was granted, prior to 28 March 2007.
|
| 523 |
+
|
| 524 |
+
Nothing in this License shall be construed as excluding or limiting
|
| 525 |
+
any implied license or other defenses to infringement that may
|
| 526 |
+
otherwise be available to you under applicable patent law.
|
| 527 |
+
|
| 528 |
+
12. No Surrender of Others' Freedom.
|
| 529 |
+
|
| 530 |
+
If conditions are imposed on you (whether by court order, agreement or
|
| 531 |
+
otherwise) that contradict the conditions of this License, they do not
|
| 532 |
+
excuse you from the conditions of this License. If you cannot convey a
|
| 533 |
+
covered work so as to satisfy simultaneously your obligations under this
|
| 534 |
+
License and any other pertinent obligations, then as a consequence you may
|
| 535 |
+
not convey it at all. For example, if you agree to terms that obligate you
|
| 536 |
+
to collect a royalty for further conveying from those to whom you convey
|
| 537 |
+
the Program, the only way you could satisfy both those terms and this
|
| 538 |
+
License would be to refrain entirely from conveying the Program.
|
| 539 |
+
|
| 540 |
+
13. Remote Network Interaction; Use with the GNU General Public License.
|
| 541 |
+
|
| 542 |
+
Notwithstanding any other provision of this License, if you modify the
|
| 543 |
+
Program, your modified version must prominently offer all users
|
| 544 |
+
interacting with it remotely through a computer network (if your version
|
| 545 |
+
supports such interaction) an opportunity to receive the Corresponding
|
| 546 |
+
Source of your version by providing access to the Corresponding Source
|
| 547 |
+
from a network server at no charge, through some standard or customary
|
| 548 |
+
means of facilitating copying of software. This Corresponding Source
|
| 549 |
+
shall include the Corresponding Source for any work covered by version 3
|
| 550 |
+
of the GNU General Public License that is incorporated pursuant to the
|
| 551 |
+
following paragraph.
|
| 552 |
+
|
| 553 |
+
Notwithstanding any other provision of this License, you have
|
| 554 |
+
permission to link or combine any covered work with a work licensed
|
| 555 |
+
under version 3 of the GNU General Public License into a single
|
| 556 |
+
combined work, and to convey the resulting work. The terms of this
|
| 557 |
+
License will continue to apply to the part which is the covered work,
|
| 558 |
+
but the work with which it is combined will remain governed by version
|
| 559 |
+
3 of the GNU General Public License.
|
| 560 |
+
|
| 561 |
+
14. Revised Versions of this License.
|
| 562 |
+
|
| 563 |
+
The Free Software Foundation may publish revised and/or new versions of
|
| 564 |
+
the GNU Affero General Public License from time to time. Such new versions
|
| 565 |
+
will be similar in spirit to the present version, but may differ in detail to
|
| 566 |
+
address new problems or concerns.
|
| 567 |
+
|
| 568 |
+
Each version is given a distinguishing version number. If the
|
| 569 |
+
Program specifies that a certain numbered version of the GNU Affero General
|
| 570 |
+
Public License "or any later version" applies to it, you have the
|
| 571 |
+
option of following the terms and conditions either of that numbered
|
| 572 |
+
version or of any later version published by the Free Software
|
| 573 |
+
Foundation. If the Program does not specify a version number of the
|
| 574 |
+
GNU Affero General Public License, you may choose any version ever published
|
| 575 |
+
by the Free Software Foundation.
|
| 576 |
+
|
| 577 |
+
If the Program specifies that a proxy can decide which future
|
| 578 |
+
versions of the GNU Affero General Public License can be used, that proxy's
|
| 579 |
+
public statement of acceptance of a version permanently authorizes you
|
| 580 |
+
to choose that version for the Program.
|
| 581 |
+
|
| 582 |
+
Later license versions may give you additional or different
|
| 583 |
+
permissions. However, no additional obligations are imposed on any
|
| 584 |
+
author or copyright holder as a result of your choosing to follow a
|
| 585 |
+
later version.
|
| 586 |
+
|
| 587 |
+
15. Disclaimer of Warranty.
|
| 588 |
+
|
| 589 |
+
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
| 590 |
+
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
| 591 |
+
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
| 592 |
+
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
| 593 |
+
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
| 594 |
+
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
| 595 |
+
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
| 596 |
+
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
| 597 |
+
|
| 598 |
+
16. Limitation of Liability.
|
| 599 |
+
|
| 600 |
+
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
| 601 |
+
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
| 602 |
+
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
| 603 |
+
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
| 604 |
+
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
| 605 |
+
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
| 606 |
+
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
| 607 |
+
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
| 608 |
+
SUCH DAMAGES.
|
| 609 |
+
|
| 610 |
+
17. Interpretation of Sections 15 and 16.
|
| 611 |
+
|
| 612 |
+
If the disclaimer of warranty and limitation of liability provided
|
| 613 |
+
above cannot be given local legal effect according to their terms,
|
| 614 |
+
reviewing courts shall apply local law that most closely approximates
|
| 615 |
+
an absolute waiver of all civil liability in connection with the
|
| 616 |
+
Program, unless a warranty or assumption of liability accompanies a
|
| 617 |
+
copy of the Program in return for a fee.
|
| 618 |
+
|
| 619 |
+
END OF TERMS AND CONDITIONS
|
| 620 |
+
|
| 621 |
+
How to Apply These Terms to Your New Programs
|
| 622 |
+
|
| 623 |
+
If you develop a new program, and you want it to be of the greatest
|
| 624 |
+
possible use to the public, the best way to achieve this is to make it
|
| 625 |
+
free software which everyone can redistribute and change under these terms.
|
| 626 |
+
|
| 627 |
+
To do so, attach the following notices to the program. It is safest
|
| 628 |
+
to attach them to the start of each source file to most effectively
|
| 629 |
+
state the exclusion of warranty; and each file should have at least
|
| 630 |
+
the "copyright" line and a pointer to where the full notice is found.
|
| 631 |
+
|
| 632 |
+
<one line to give the program's name and a brief idea of what it does.>
|
| 633 |
+
Copyright (C) <year> <name of author>
|
| 634 |
+
|
| 635 |
+
This program is free software: you can redistribute it and/or modify
|
| 636 |
+
it under the terms of the GNU Affero General Public License as published by
|
| 637 |
+
the Free Software Foundation, either version 3 of the License, or
|
| 638 |
+
(at your option) any later version.
|
| 639 |
+
|
| 640 |
+
This program is distributed in the hope that it will be useful,
|
| 641 |
+
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
| 642 |
+
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
| 643 |
+
GNU Affero General Public License for more details.
|
| 644 |
+
|
| 645 |
+
You should have received a copy of the GNU Affero General Public License
|
| 646 |
+
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
| 647 |
+
|
| 648 |
+
Also add information on how to contact you by electronic and paper mail.
|
| 649 |
+
|
| 650 |
+
If your software can interact with users remotely through a computer
|
| 651 |
+
network, you should also make sure that it provides a way for users to
|
| 652 |
+
get its source. For example, if your program is a web application, its
|
| 653 |
+
interface could display a "Source" link that leads users to an archive
|
| 654 |
+
of the code. There are many ways you could offer source, and different
|
| 655 |
+
solutions will be better for different programs; see section 13 for the
|
| 656 |
+
specific requirements.
|
| 657 |
+
|
| 658 |
+
You should also get your employer (if you work as a programmer) or school,
|
| 659 |
+
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
| 660 |
+
For more information on this, and how to apply and follow the GNU AGPL, see
|
| 661 |
+
<https://www.gnu.org/licenses/>.
|
README.md
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
title: Large language model topic modelling
|
| 3 |
+
emoji: 📚
|
| 4 |
+
colorFrom: purple
|
| 5 |
+
colorTo: yellow
|
| 6 |
+
sdk: gradio
|
| 7 |
+
sdk_version: 6.19.0
|
| 8 |
+
app_file: app.py
|
| 9 |
+
pinned: true
|
| 10 |
+
license: agpl-3.0
|
| 11 |
+
short_description: Extract topics from open text data with LLMs
|
| 12 |
+
---
|
| 13 |
+
|
| 14 |
+
# Large language model topic modelling
|
| 15 |
+
|
| 16 |
+
Version: 0.13.0
|
| 17 |
+
|
| 18 |
+
Extract topics and summarise outputs using Large Language Models (LLMs), either local, Gemini, Azure, or AWS Bedrock models (e.g. Claude, Nova models). The app will query the LLM with batches of responses to produce summary tables, which are then compared iteratively to output a table with the general topics, subtopics, topic sentiment, and a topic summary. Instructions on use can be found in the README.md file. You can try out examples by clicking on one of the example datasets on the main app page, which will show you example outputs from a local model run. API keys for AWS, Azure, and Gemini services can be entered on the settings page (note that Gemini has a free public API).
|
| 19 |
+
|
| 20 |
+
NOTE: Large language models are not 100% accurate and may produce biased or harmful outputs. All outputs from this app **absolutely need to be checked by a human** to check for harmful outputs, hallucinations, and accuracy.
|
| 21 |
+
|
| 22 |
+
Basic use:
|
| 23 |
+
1. On the front page, choose your model for inference. Gemma 3/GPT-OSS will use 'on-device' inference. Calls to Gemini or AWS will require an API key that can be input on the 'LLM and topic extraction' page.
|
| 24 |
+
1. Upload a csv/xlsx/parquet file containing at least one open text column.
|
| 25 |
+
2. Select the relevant open text column from the dropdown.
|
| 26 |
+
3. If you have your own suggested (zero shot) topics, upload this (see examples folder for an example file)
|
| 27 |
+
4. Write a one sentence description of the consultation/context of the open text.
|
| 28 |
+
5. Click 'Extract topics, deduplicate, and summarise'. This will run through the whole analysis process from topic extraction, to topic deduplication, to topic-level and overall summaries.
|
| 29 |
+
6. A summary xlsx file workbook will be created on the front page in the box 'Overall summary xlsx file'. This will combine all the results from the different processes into one workbook.
|
| 30 |
+
|
| 31 |
+
# Installation guide
|
| 32 |
+
|
| 33 |
+
Here is a step-by-step guide to clone the repository, create a virtual environment, and install dependencies from the relevant `requirements` file. This guide assumes you have **Git** and **Python 3.11** installed.
|
| 34 |
+
|
| 35 |
+
-----
|
| 36 |
+
|
| 37 |
+
### Step 1: Clone the Git Repository
|
| 38 |
+
|
| 39 |
+
First, you need to copy the project files to your local machine. Navigate to the directory where you want to store the project using the `cd` (change directory) command. Then, use `git clone` with the repository's URL.
|
| 40 |
+
|
| 41 |
+
1. **Clone the repo:**
|
| 42 |
+
|
| 43 |
+
```bash
|
| 44 |
+
git clone https://github.com/seanpedrick-case/llm_topic_modelling.git
|
| 45 |
+
```
|
| 46 |
+
|
| 47 |
+
2. **Navigate into the new project folder:**
|
| 48 |
+
|
| 49 |
+
```bash
|
| 50 |
+
cd llm_topic_modelling
|
| 51 |
+
```
|
| 52 |
+
-----
|
| 53 |
+
|
| 54 |
+
### Step 2: Create and Activate a Virtual Environment
|
| 55 |
+
|
| 56 |
+
A virtual environment is a self-contained directory that holds a specific Python interpreter and its own set of installed packages. This is crucial for isolating your project's dependencies.
|
| 57 |
+
|
| 58 |
+
NOTE: Alternatively you could also create and activate a Conda environment instead of using venv below.
|
| 59 |
+
|
| 60 |
+
1. **Create the virtual environment:** We'll use Python's built-in `venv` module. It's common practice to name the environment folder `.venv`.
|
| 61 |
+
|
| 62 |
+
```bash
|
| 63 |
+
python -m venv .venv
|
| 64 |
+
```
|
| 65 |
+
|
| 66 |
+
*This command tells Python to create a new virtual environment in a folder named `.venv`.*
|
| 67 |
+
|
| 68 |
+
2. **Activate the environment:** You must "activate" the environment to start using it. The command differs based on your operating system and shell.
|
| 69 |
+
|
| 70 |
+
* **On macOS / Linux (bash/zsh):**
|
| 71 |
+
|
| 72 |
+
```bash
|
| 73 |
+
source .venv/bin/activate
|
| 74 |
+
```
|
| 75 |
+
|
| 76 |
+
* **On Windows (Command Prompt):**
|
| 77 |
+
|
| 78 |
+
```bash
|
| 79 |
+
.\.venv\Scripts\activate
|
| 80 |
+
```
|
| 81 |
+
|
| 82 |
+
* **On Windows (PowerShell):**
|
| 83 |
+
|
| 84 |
+
```powershell
|
| 85 |
+
.\.venv\Scripts\Activate.ps1
|
| 86 |
+
```
|
| 87 |
+
|
| 88 |
+
You'll know it's active because your command prompt will be prefixed with `(.venv)`.
|
| 89 |
+
|
| 90 |
+
-----
|
| 91 |
+
|
| 92 |
+
### Step 3: Install Dependencies
|
| 93 |
+
|
| 94 |
+
Now that your virtual environment is active, you can install all the required packages. Here you have two options, install from the pyproject.toml file (recommended), or install from requirements files.
|
| 95 |
+
|
| 96 |
+
1. **Install from pyproject.toml (recommended)**
|
| 97 |
+
|
| 98 |
+
You can install the 'lightweight' version of the app to access all available cloud provider or local inference (e.g. llama server, vLLM server) APIs. This version will not allow you to run local models such as Gemma 12b or GPT-OSS-20b 'in-app', i.e. accessible from the GUI interface directly. However, you will have access to AWS, Gemma, or Azure/OpenAI models with appropriate API keys. Use the following command in your environment to install the relevant packages:
|
| 99 |
+
|
| 100 |
+
```bash
|
| 101 |
+
pip install .
|
| 102 |
+
```
|
| 103 |
+
|
| 104 |
+
#### Install torch (optional)
|
| 105 |
+
|
| 106 |
+
If you want to run inference with transformers with full/quantised models, and the associated Unsloth package, you can run the following command for CPU inference. For GPU inference, please refer to the requirements_gpu.txt guide, and the 'Install from a requirements file' section below:
|
| 107 |
+
|
| 108 |
+
```bash
|
| 109 |
+
pip install .[torch]
|
| 110 |
+
```
|
| 111 |
+
|
| 112 |
+
#### Install llama-cpp-python (optional)
|
| 113 |
+
|
| 114 |
+
You can run quantised GGUF models in-app using llama-cpp-python. However, installation of this package is not always straightforward, particularly considering that wheels are not available for the latest version apart from for linux. This package is not being updated regularly, and so support may be removed for this package in future. Long term I would advise instead looking into running GGUF models using llama-server and calling the API from this app using the lightweight version (details here: https://github.com/ggml-org/llama.cpp).
|
| 115 |
+
|
| 116 |
+
If you do want to install llama-cpp-python in app, first try the following command:
|
| 117 |
+
|
| 118 |
+
```bash
|
| 119 |
+
pip install .[llamacpp]
|
| 120 |
+
```
|
| 121 |
+
|
| 122 |
+
This will install the CPU version of llama-cpp-python. If you want GPU support, first I would try using pip install with specific wheels for your system: See files in https://github.com/abetlen/llama-cpp-python/releases . If you are still struggling, see here for more details on installation here: https://llama-cpp-python.readthedocs.io/en/latest
|
| 123 |
+
|
| 124 |
+
#### Install mcp version of gradio
|
| 125 |
+
|
| 126 |
+
You can install an mcp-compatible version of gradio for this app with the following command:
|
| 127 |
+
|
| 128 |
+
```bash
|
| 129 |
+
pip install .[mcp]
|
| 130 |
+
```
|
| 131 |
+
|
| 132 |
+
2. **Install from a requirements file (not recommended)**
|
| 133 |
+
|
| 134 |
+
The repo provides several requirements files that are relevant for different situations. To start, I advise installing using the **requirements_lightweight.txt** file, which installs the app with access to all cloud provider or local inference (e.g. llama server, vLLM server) APIs. This approach is much simpler as a first step, and avoids issues with potentially complicated llama-cpp-python installation and GPU management described below.
|
| 135 |
+
|
| 136 |
+
If you want to run models locally 'in app', then you have two further requirements files to choose from:
|
| 137 |
+
|
| 138 |
+
- **requirements_cpu.txt**: Used for Python 3.11 CPU-only environments. Uncomment the requirements under 'Windows' for Windows compatibility. Make sure you have [Openblas](https://github.com/OpenMathLib/OpenBLAS) installed!
|
| 139 |
+
- **requirements_gpu.txt**: Used for Python 3.11 GPU-enabled environments. Uncomment the requirements under 'Windows' for Windows compatibility (CUDA 12.4).
|
| 140 |
+
|
| 141 |
+
Example The below instructions will guide you in how to install the GPU-enabled version of the app for local inference.
|
| 142 |
+
|
| 143 |
+
**Install packages for local model 'in-app' inference from the requirements file:**
|
| 144 |
+
```bash
|
| 145 |
+
pip install -r requirements_gpu.txt
|
| 146 |
+
```
|
| 147 |
+
*This command reads every package name listed in the file and installs it into your `.venv` environment.*
|
| 148 |
+
|
| 149 |
+
NOTE: If default llama-cpp-python installation does not work when installing from the above, go into the requirements_gpu.txt file and uncomment the lines to install a wheel for llama-cpp-python 0.3.16 relevant to your system.
|
| 150 |
+
|
| 151 |
+
### Step 4: Verify CUDA compatibility (if using a GPU environment)
|
| 152 |
+
|
| 153 |
+
Install the relevant toolkit for CUDA from here: https://developer.nvidia.com/
|
| 154 |
+
|
| 155 |
+
Restart your computer
|
| 156 |
+
|
| 157 |
+
Ensure you have the latest drivers for your NVIDIA GPU. Check your current version and memory availability by running nvidia-smi
|
| 158 |
+
|
| 159 |
+
In command line, CUDA compatibility can be checked by running nvcc --version
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
### Step 5: Ensure you have compatible NVIDIA drivers
|
| 163 |
+
|
| 164 |
+
Make sure you have the latest NVIDIA drivers installed on your system for your GPU (be careful in particular if using WSL that you have drivers compatible with this). Official drivers can be found here: https://www.nvidia.com/en-us/drivers
|
| 165 |
+
|
| 166 |
+
Current drivers can be found by running nvidia-smi in command line
|
| 167 |
+
|
| 168 |
+
### Step 6: Run the app
|
| 169 |
+
|
| 170 |
+
Go to the app project directory. Run python app.py
|
| 171 |
+
|
| 172 |
+
### Step 7: (optional) change default configuration
|
| 173 |
+
|
| 174 |
+
A number of configuration options can be seen the tools/config.py file. You can either pass in these variables as environment variables, or you can create a file in config/app_config.env to read this into the app on initialisation.
|
app.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
cdk/__init__.py
ADDED
|
File without changes
|
cdk/app.py
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
|
| 3 |
+
from aws_cdk import App, Environment
|
| 4 |
+
from cdk_appregistry import register_llm_topic_application
|
| 5 |
+
from cdk_config import (
|
| 6 |
+
ALB_NAME,
|
| 7 |
+
APPREGISTRY_APPLICATION_NAME,
|
| 8 |
+
APPREGISTRY_ATTRIBUTE_GROUP_NAME,
|
| 9 |
+
APPREGISTRY_DESCRIPTION,
|
| 10 |
+
APPREGISTRY_REPOSITORY_URL,
|
| 11 |
+
APPREGISTRY_STACK_NAME,
|
| 12 |
+
AWS_ACCOUNT_ID,
|
| 13 |
+
AWS_REGION,
|
| 14 |
+
CDK_CONTEXT_FILE,
|
| 15 |
+
CDK_PREFIX,
|
| 16 |
+
ENABLE_APPREGISTRY,
|
| 17 |
+
RUN_USEAST_STACK,
|
| 18 |
+
USE_CLOUDFRONT,
|
| 19 |
+
)
|
| 20 |
+
from cdk_functions import (
|
| 21 |
+
create_basic_config_env,
|
| 22 |
+
is_resource_delete_protection_enabled,
|
| 23 |
+
load_context_from_file,
|
| 24 |
+
log_aws_credential_context,
|
| 25 |
+
purge_cdk_lookup_context,
|
| 26 |
+
)
|
| 27 |
+
from cdk_stack import CdkStack, CdkStackCloudfront # , CdkStackMain
|
| 28 |
+
from check_resources import CONTEXT_FILE, check_and_set_context
|
| 29 |
+
|
| 30 |
+
# Initialize the CDK app
|
| 31 |
+
app = App()
|
| 32 |
+
|
| 33 |
+
log_aws_credential_context(
|
| 34 |
+
expected_account_id=AWS_ACCOUNT_ID,
|
| 35 |
+
expected_region=AWS_REGION,
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
# Drop stale CDK lookup cache entries (require bootstrap lookup role in target account).
|
| 39 |
+
purge_cdk_lookup_context(CDK_CONTEXT_FILE)
|
| 40 |
+
|
| 41 |
+
# --- Pre-check context (boto3) — written to precheck.context.json, NOT cdk.context.json ---
|
| 42 |
+
print(f"Pre-check context file: {CONTEXT_FILE}")
|
| 43 |
+
print(f"CDK lookup cache file: {CDK_CONTEXT_FILE}")
|
| 44 |
+
if os.path.basename(CONTEXT_FILE.replace("\\", "/")) == os.path.basename(
|
| 45 |
+
CDK_CONTEXT_FILE.replace("\\", "/")
|
| 46 |
+
):
|
| 47 |
+
raise RuntimeError(
|
| 48 |
+
f"CONTEXT_FILE and CDK_CONTEXT_FILE must differ (got '{CONTEXT_FILE}' for both). "
|
| 49 |
+
"Set CONTEXT_FILE=precheck.context.json in config/cdk_config.env."
|
| 50 |
+
)
|
| 51 |
+
|
| 52 |
+
print("Running pre-check script to generate application context...")
|
| 53 |
+
try:
|
| 54 |
+
check_and_set_context()
|
| 55 |
+
if not os.path.exists(CONTEXT_FILE):
|
| 56 |
+
raise RuntimeError(
|
| 57 |
+
f"check_and_set_context() finished, but {CONTEXT_FILE} was not created."
|
| 58 |
+
)
|
| 59 |
+
print(f"Context generated successfully at {CONTEXT_FILE}.")
|
| 60 |
+
except Exception as e:
|
| 61 |
+
raise RuntimeError(f"Failed to generate context via check_and_set_context(): {e}")
|
| 62 |
+
|
| 63 |
+
# Pre-check must not repopulate CDK lookup keys; purge again if paths were ever shared.
|
| 64 |
+
purge_cdk_lookup_context(CDK_CONTEXT_FILE)
|
| 65 |
+
|
| 66 |
+
if os.path.exists(CONTEXT_FILE):
|
| 67 |
+
load_context_from_file(app, CONTEXT_FILE)
|
| 68 |
+
else:
|
| 69 |
+
raise RuntimeError(f"Could not find {CONTEXT_FILE}.")
|
| 70 |
+
|
| 71 |
+
create_basic_config_env("config")
|
| 72 |
+
|
| 73 |
+
aws_env_regional = Environment(account=AWS_ACCOUNT_ID, region=AWS_REGION)
|
| 74 |
+
|
| 75 |
+
_stack_delete_protection = is_resource_delete_protection_enabled()
|
| 76 |
+
|
| 77 |
+
regional_stack = CdkStack(
|
| 78 |
+
app, "SummarisationStack", env=aws_env_regional, cross_region_references=True
|
| 79 |
+
)
|
| 80 |
+
regional_stack.termination_protection = _stack_delete_protection
|
| 81 |
+
|
| 82 |
+
if ENABLE_APPREGISTRY == "True":
|
| 83 |
+
# Use pre-check context only — not regional_stack.params (avoids AppRegistry
|
| 84 |
+
# -> SummarisationStack dependency cycle during synth).
|
| 85 |
+
_alb_dns_context = app.node.try_get_context(f"dns:{ALB_NAME}")
|
| 86 |
+
_alb_dns_name = (
|
| 87 |
+
_alb_dns_context.strip()
|
| 88 |
+
if isinstance(_alb_dns_context, str) and _alb_dns_context.strip()
|
| 89 |
+
else None
|
| 90 |
+
)
|
| 91 |
+
appregistry_stack = register_llm_topic_application(
|
| 92 |
+
app,
|
| 93 |
+
aws_account_id=AWS_ACCOUNT_ID,
|
| 94 |
+
aws_region=AWS_REGION,
|
| 95 |
+
application_name=APPREGISTRY_APPLICATION_NAME,
|
| 96 |
+
application_description=APPREGISTRY_DESCRIPTION,
|
| 97 |
+
appregistry_stack_name=APPREGISTRY_STACK_NAME,
|
| 98 |
+
attribute_group_name=APPREGISTRY_ATTRIBUTE_GROUP_NAME,
|
| 99 |
+
repository_url=APPREGISTRY_REPOSITORY_URL,
|
| 100 |
+
cdk_prefix=CDK_PREFIX,
|
| 101 |
+
use_cloudfront=USE_CLOUDFRONT,
|
| 102 |
+
alb_dns_name=_alb_dns_name,
|
| 103 |
+
)
|
| 104 |
+
appregistry_stack.termination_protection = _stack_delete_protection
|
| 105 |
+
|
| 106 |
+
if USE_CLOUDFRONT == "True" and RUN_USEAST_STACK == "True":
|
| 107 |
+
aws_env_us_east_1 = Environment(account=AWS_ACCOUNT_ID, region="us-east-1")
|
| 108 |
+
|
| 109 |
+
cloudfront_stack = CdkStackCloudfront(
|
| 110 |
+
app,
|
| 111 |
+
"SummarisationStackCloudfront",
|
| 112 |
+
env=aws_env_us_east_1,
|
| 113 |
+
alb_arn=regional_stack.params["alb_arn_output"],
|
| 114 |
+
alb_sec_group_id=regional_stack.params["alb_security_group_id"],
|
| 115 |
+
alb_dns_name=regional_stack.params["alb_dns_name"],
|
| 116 |
+
cross_region_references=True,
|
| 117 |
+
)
|
| 118 |
+
cloudfront_stack.termination_protection = _stack_delete_protection
|
| 119 |
+
|
| 120 |
+
# CDK CLI invokes this script and expects a cloud assembly in cdk.out.
|
| 121 |
+
# Without app.synth(), Python defines constructs but never writes manifest.json
|
| 122 |
+
# (ENOENT on deploy). See: https://github.com/aws/aws-cdk/issues/11023
|
| 123 |
+
app.synth()
|
cdk/cdk.json.example
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"app": "python app.py",
|
| 3 |
+
"output": "cdk.out",
|
| 4 |
+
"context": {
|
| 5 |
+
"@aws-cdk/aws-ec2:restrictDefaultSecurityGroup": false
|
| 6 |
+
}
|
| 7 |
+
}
|
cdk/cdk_appregistry.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""AWS Console myApplications (Service Catalog AppRegistry) integration."""
|
| 2 |
+
|
| 3 |
+
from aws_cdk import App, Environment
|
| 4 |
+
from aws_cdk.aws_servicecatalogappregistry_alpha import (
|
| 5 |
+
ApplicationAssociator,
|
| 6 |
+
TargetApplication,
|
| 7 |
+
)
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def register_llm_topic_application(
|
| 11 |
+
app: App,
|
| 12 |
+
*,
|
| 13 |
+
aws_account_id: str,
|
| 14 |
+
aws_region: str,
|
| 15 |
+
application_name: str,
|
| 16 |
+
application_description: str,
|
| 17 |
+
appregistry_stack_name: str,
|
| 18 |
+
attribute_group_name: str,
|
| 19 |
+
repository_url: str,
|
| 20 |
+
cdk_prefix: str,
|
| 21 |
+
use_cloudfront: str,
|
| 22 |
+
alb_dns_name: str | None = None,
|
| 23 |
+
) -> ApplicationAssociator:
|
| 24 |
+
"""
|
| 25 |
+
Register regional CDK stacks with AWS Console myApplications.
|
| 26 |
+
|
| 27 |
+
Only stacks in ``aws_region`` are associated (phase 1). Cross-region stacks
|
| 28 |
+
such as SummarisationStackCloudfront (us-east-1) are not included.
|
| 29 |
+
|
| 30 |
+
``alb_dns_name`` must be a plain string (e.g. from pre-check context). Do not
|
| 31 |
+
pass a CloudFormation token from SummarisationStack or synth will fail with a
|
| 32 |
+
dependency cycle against the associator stack.
|
| 33 |
+
"""
|
| 34 |
+
associator = ApplicationAssociator(
|
| 35 |
+
app,
|
| 36 |
+
"SummarisationAppRegistry",
|
| 37 |
+
applications=[
|
| 38 |
+
TargetApplication.create_application_stack(
|
| 39 |
+
application_name=application_name,
|
| 40 |
+
application_description=application_description,
|
| 41 |
+
stack_name=appregistry_stack_name,
|
| 42 |
+
env=Environment(account=aws_account_id, region=aws_region),
|
| 43 |
+
)
|
| 44 |
+
],
|
| 45 |
+
)
|
| 46 |
+
|
| 47 |
+
attributes = {
|
| 48 |
+
"repository": repository_url,
|
| 49 |
+
"cdkPrefix": cdk_prefix,
|
| 50 |
+
"awsRegion": aws_region,
|
| 51 |
+
"useCloudFront": use_cloudfront,
|
| 52 |
+
"cloudFrontInAppRegistry": "false",
|
| 53 |
+
"cloudFrontNote": (
|
| 54 |
+
"CloudFront/WAF (SummarisationStackCloudfront) is in us-east-1 and is "
|
| 55 |
+
"not linked to this myApplications entry in phase 1. View it in "
|
| 56 |
+
"CloudFormation (us-east-1) or the CloudFront console."
|
| 57 |
+
),
|
| 58 |
+
}
|
| 59 |
+
if alb_dns_name:
|
| 60 |
+
attributes["albDnsName"] = alb_dns_name
|
| 61 |
+
|
| 62 |
+
associator.app_registry_application.add_attribute_group(
|
| 63 |
+
"SummarisationAttributeGroup",
|
| 64 |
+
attribute_group_name=attribute_group_name,
|
| 65 |
+
description="llm_topic_modeller deployment metadata",
|
| 66 |
+
attributes=attributes,
|
| 67 |
+
)
|
| 68 |
+
|
| 69 |
+
return associator
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def register_doc_summarisation_application(*args, **kwargs):
|
| 73 |
+
"""Deprecated alias for register_llm_topic_application."""
|
| 74 |
+
return register_llm_topic_application(*args, **kwargs)
|
cdk/cdk_cloudfront_headers.py
ADDED
|
@@ -0,0 +1,172 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""CloudFront response headers policy (CSP and related security headers)."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
from urllib.parse import urlparse
|
| 7 |
+
|
| 8 |
+
from aws_cdk import Duration
|
| 9 |
+
from aws_cdk import aws_cloudfront as cloudfront
|
| 10 |
+
from constructs import Construct
|
| 11 |
+
|
| 12 |
+
# Template exported from AWS; placeholders {APP-URL} and {COGNITO-APP-CLIENT-LOGIN-URL}.
|
| 13 |
+
_CSP_TEMPLATE = (
|
| 14 |
+
"default-src 'self'; script-src 'self' cdnjs.cloudflare.com 'unsafe-inline'; "
|
| 15 |
+
"style-src 'self' https://fonts.googleapis.com 'unsafe-inline'; "
|
| 16 |
+
"img-src 'self' data:; font-src 'self' https://fonts.gstatic.com data:; "
|
| 17 |
+
"connect-src 'self' wss://{app_hostname} https://cdnjs.cloudflare.com; "
|
| 18 |
+
"form-action 'self'; frame-ancestors 'none'; object-src 'none'; base-uri 'self'; "
|
| 19 |
+
"manifest-src 'self' {cognito_login_url}; upgrade-insecure-requests;"
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
RESPONSE_HEADERS_POLICY_TEMPLATE_PATH = (
|
| 23 |
+
Path(__file__).resolve().parent / "config" / "response-headers-policy-config.json"
|
| 24 |
+
)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def normalize_https_origin(url: str) -> str:
|
| 28 |
+
"""Return a canonical https origin (scheme + host, no path)."""
|
| 29 |
+
value = (url or "").strip()
|
| 30 |
+
if not value:
|
| 31 |
+
return ""
|
| 32 |
+
if "://" not in value:
|
| 33 |
+
value = f"https://{value}"
|
| 34 |
+
parsed = urlparse(value)
|
| 35 |
+
if not parsed.hostname:
|
| 36 |
+
return value.rstrip("/")
|
| 37 |
+
scheme = parsed.scheme or "https"
|
| 38 |
+
netloc = parsed.netloc or parsed.hostname
|
| 39 |
+
return f"{scheme}://{netloc}".rstrip("/")
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def hostname_from_origin(origin: str) -> str:
|
| 43 |
+
parsed = urlparse(origin if "://" in origin else f"https://{origin}")
|
| 44 |
+
return parsed.hostname or origin.strip()
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def cognito_hosted_ui_base_url(domain_prefix: str, region: str) -> str:
|
| 48 |
+
prefix = (domain_prefix or "").strip()
|
| 49 |
+
if not prefix:
|
| 50 |
+
return ""
|
| 51 |
+
return f"https://{prefix}.auth.{region}.amazoncognito.com"
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def build_content_security_policy(
|
| 55 |
+
*,
|
| 56 |
+
app_origin: str,
|
| 57 |
+
cognito_login_url: str,
|
| 58 |
+
) -> str:
|
| 59 |
+
origin = normalize_https_origin(app_origin)
|
| 60 |
+
hostname = hostname_from_origin(origin)
|
| 61 |
+
cognito_url = normalize_https_origin(cognito_login_url)
|
| 62 |
+
return _CSP_TEMPLATE.format(app_hostname=hostname, cognito_login_url=cognito_url)
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def create_secure_cloudfront_response_headers_policy(
|
| 66 |
+
scope: Construct,
|
| 67 |
+
construct_id: str,
|
| 68 |
+
*,
|
| 69 |
+
policy_name: str,
|
| 70 |
+
app_origin: str,
|
| 71 |
+
cognito_login_url: str,
|
| 72 |
+
comment: str = "Secure response headers with CSP for llm_topic_modeller",
|
| 73 |
+
) -> cloudfront.ResponseHeadersPolicy:
|
| 74 |
+
"""Response headers policy aligned with config/response-headers-policy-config.json."""
|
| 75 |
+
cors_origin = normalize_https_origin(app_origin)
|
| 76 |
+
csp = build_content_security_policy(
|
| 77 |
+
app_origin=app_origin,
|
| 78 |
+
cognito_login_url=cognito_login_url,
|
| 79 |
+
)
|
| 80 |
+
|
| 81 |
+
return cloudfront.ResponseHeadersPolicy(
|
| 82 |
+
scope,
|
| 83 |
+
construct_id,
|
| 84 |
+
response_headers_policy_name=policy_name,
|
| 85 |
+
comment=comment,
|
| 86 |
+
cors_behavior=cloudfront.ResponseHeadersCorsBehavior(
|
| 87 |
+
access_control_allow_credentials=False,
|
| 88 |
+
access_control_allow_headers=["*"],
|
| 89 |
+
access_control_allow_methods=["ALL"],
|
| 90 |
+
access_control_allow_origins=[cors_origin],
|
| 91 |
+
access_control_max_age=Duration.seconds(600),
|
| 92 |
+
origin_override=True,
|
| 93 |
+
),
|
| 94 |
+
security_headers_behavior=cloudfront.ResponseSecurityHeadersBehavior(
|
| 95 |
+
content_security_policy=cloudfront.ResponseHeadersContentSecurityPolicy(
|
| 96 |
+
content_security_policy=csp,
|
| 97 |
+
override=True,
|
| 98 |
+
),
|
| 99 |
+
content_type_options=cloudfront.ResponseHeadersContentTypeOptions(
|
| 100 |
+
override=True
|
| 101 |
+
),
|
| 102 |
+
frame_options=cloudfront.ResponseHeadersFrameOptions(
|
| 103 |
+
frame_option=cloudfront.HeadersFrameOption.SAMEORIGIN,
|
| 104 |
+
override=True,
|
| 105 |
+
),
|
| 106 |
+
referrer_policy=cloudfront.ResponseHeadersReferrerPolicy(
|
| 107 |
+
referrer_policy=cloudfront.HeadersReferrerPolicy.STRICT_ORIGIN_WHEN_CROSS_ORIGIN,
|
| 108 |
+
override=True,
|
| 109 |
+
),
|
| 110 |
+
strict_transport_security=cloudfront.ResponseHeadersStrictTransportSecurity(
|
| 111 |
+
access_control_max_age=Duration.seconds(31536000),
|
| 112 |
+
include_subdomains=True,
|
| 113 |
+
preload=False,
|
| 114 |
+
override=True,
|
| 115 |
+
),
|
| 116 |
+
xss_protection=cloudfront.ResponseHeadersXSSProtection(
|
| 117 |
+
protection=True,
|
| 118 |
+
mode_block=True,
|
| 119 |
+
override=True,
|
| 120 |
+
),
|
| 121 |
+
),
|
| 122 |
+
custom_headers_behavior=cloudfront.ResponseCustomHeadersBehavior(
|
| 123 |
+
custom_headers=[
|
| 124 |
+
cloudfront.ResponseCustomHeader(
|
| 125 |
+
header="Permissions-Policy",
|
| 126 |
+
value=(
|
| 127 |
+
"accelerometer=(), autoplay=(), camera=(), "
|
| 128 |
+
"cross-origin-isolated=(), display-capture=(), encrypted-media=(), "
|
| 129 |
+
"fullscreen=(), geolocation=(), gyroscope=(), keyboard-map=(), "
|
| 130 |
+
"magnetometer=(), microphone=(), midi=(), payment=(), "
|
| 131 |
+
"picture-in-picture=(), publickey-credentials-get=(), "
|
| 132 |
+
"screen-wake-lock=(), sync-xhr=(), usb=(), web-share=(), "
|
| 133 |
+
"xr-spatial-tracking=()"
|
| 134 |
+
),
|
| 135 |
+
override=True,
|
| 136 |
+
)
|
| 137 |
+
]
|
| 138 |
+
),
|
| 139 |
+
remove_headers=["Server"],
|
| 140 |
+
)
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def resolve_cloudfront_csp_urls(
|
| 144 |
+
*,
|
| 145 |
+
cognito_redirection_url: str,
|
| 146 |
+
cloudfront_domain: str,
|
| 147 |
+
cognito_user_pool_domain_prefix: str,
|
| 148 |
+
aws_region: str,
|
| 149 |
+
cognito_user_pool_login_url: str = "",
|
| 150 |
+
ssl_certificate_domain: str = "",
|
| 151 |
+
) -> tuple[str, str]:
|
| 152 |
+
"""
|
| 153 |
+
Return (app_origin, cognito_login_url) for CSP/CORS substitution.
|
| 154 |
+
|
| 155 |
+
App origin prefers COGNITO_REDIRECTION_URL (canonical browser URL), then
|
| 156 |
+
https://SSL_CERTIFICATE_DOMAIN, then https://CLOUDFRONT_DOMAIN.
|
| 157 |
+
Cognito login URL uses COGNITO_USER_POOL_LOGIN_URL when set, else the
|
| 158 |
+
hosted UI base URL derived from COGNITO_USER_POOL_DOMAIN_PREFIX.
|
| 159 |
+
"""
|
| 160 |
+
app_origin = normalize_https_origin(cognito_redirection_url)
|
| 161 |
+
if not app_origin or "placeholder" in app_origin.lower():
|
| 162 |
+
if ssl_certificate_domain.strip():
|
| 163 |
+
app_origin = normalize_https_origin(ssl_certificate_domain)
|
| 164 |
+
elif cloudfront_domain.strip():
|
| 165 |
+
app_origin = normalize_https_origin(cloudfront_domain)
|
| 166 |
+
|
| 167 |
+
login_url = (cognito_user_pool_login_url or "").strip()
|
| 168 |
+
if not login_url:
|
| 169 |
+
login_url = cognito_hosted_ui_base_url(
|
| 170 |
+
cognito_user_pool_domain_prefix, aws_region
|
| 171 |
+
)
|
| 172 |
+
return app_origin, normalize_https_origin(login_url)
|
cdk/cdk_config.py
ADDED
|
@@ -0,0 +1,851 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import tempfile
|
| 3 |
+
from typing import List
|
| 4 |
+
|
| 5 |
+
from dotenv import load_dotenv
|
| 6 |
+
|
| 7 |
+
# Set or retrieve configuration variables for CDK llm_topic_modeller deployment
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def convert_string_to_boolean(value: str) -> bool:
|
| 11 |
+
"""Convert string to boolean, handling various formats."""
|
| 12 |
+
if isinstance(value, bool):
|
| 13 |
+
return value
|
| 14 |
+
elif value in ["True", "1", "true", "TRUE"]:
|
| 15 |
+
return True
|
| 16 |
+
elif value in ["False", "0", "false", "FALSE"]:
|
| 17 |
+
return False
|
| 18 |
+
else:
|
| 19 |
+
raise ValueError(f"Invalid boolean value: {value}")
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def parse_comma_separated_list(value: str) -> List[str]:
|
| 23 |
+
"""Parse a comma-separated env value into a list of non-empty strings."""
|
| 24 |
+
if not value or not str(value).strip():
|
| 25 |
+
return []
|
| 26 |
+
cleaned = str(value).strip().strip("[]")
|
| 27 |
+
return [
|
| 28 |
+
part.strip().strip('"').strip("'")
|
| 29 |
+
for part in cleaned.split(",")
|
| 30 |
+
if part.strip()
|
| 31 |
+
]
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def get_or_create_env_var(var_name: str, default_value: str, print_val: bool = False):
|
| 35 |
+
"""
|
| 36 |
+
Get an environmental variable, and set it to a default value if it doesn't exist
|
| 37 |
+
"""
|
| 38 |
+
# Get the environment variable if it exists
|
| 39 |
+
value = os.environ.get(var_name)
|
| 40 |
+
|
| 41 |
+
# If it doesn't exist, set the environment variable to the default value
|
| 42 |
+
if value is None:
|
| 43 |
+
os.environ[var_name] = default_value
|
| 44 |
+
value = default_value
|
| 45 |
+
|
| 46 |
+
if print_val is True:
|
| 47 |
+
print(f"The value of {var_name} is {value}")
|
| 48 |
+
|
| 49 |
+
return value
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def ensure_folder_exists(output_folder: str):
|
| 53 |
+
"""Checks if the specified folder exists, creates it if not."""
|
| 54 |
+
|
| 55 |
+
if not os.path.exists(output_folder):
|
| 56 |
+
# Create the folder if it doesn't exist
|
| 57 |
+
os.makedirs(output_folder, exist_ok=True)
|
| 58 |
+
print(f"Created the {output_folder} folder.")
|
| 59 |
+
else:
|
| 60 |
+
print(f"The {output_folder} folder already exists.")
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def add_folder_to_path(folder_path: str):
|
| 64 |
+
"""
|
| 65 |
+
Check if a folder exists on your system. If so, get the absolute path and then add it to the system Path variable if it doesn't already exist. Function is only relevant for locally-created executable files based on this app (when using pyinstaller it creates a _internal folder that contains tesseract and poppler. These need to be added to the system path to enable the app to run)
|
| 66 |
+
"""
|
| 67 |
+
|
| 68 |
+
if os.path.exists(folder_path) and os.path.isdir(folder_path):
|
| 69 |
+
print(folder_path, "folder exists.")
|
| 70 |
+
|
| 71 |
+
# Resolve relative path to absolute path
|
| 72 |
+
absolute_path = os.path.abspath(folder_path)
|
| 73 |
+
|
| 74 |
+
current_path = os.environ["PATH"]
|
| 75 |
+
if absolute_path not in current_path.split(os.pathsep):
|
| 76 |
+
full_path_extension = absolute_path + os.pathsep + current_path
|
| 77 |
+
os.environ["PATH"] = full_path_extension
|
| 78 |
+
# print(f"Updated PATH with: ", full_path_extension)
|
| 79 |
+
else:
|
| 80 |
+
print(f"Directory {folder_path} already exists in PATH.")
|
| 81 |
+
else:
|
| 82 |
+
print(f"Folder not found at {folder_path} - not added to PATH")
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
###
|
| 86 |
+
# LOAD CONFIG FROM ENV FILE
|
| 87 |
+
###
|
| 88 |
+
CONFIG_FOLDER = get_or_create_env_var("CONFIG_FOLDER", "config/")
|
| 89 |
+
|
| 90 |
+
ensure_folder_exists(CONFIG_FOLDER)
|
| 91 |
+
|
| 92 |
+
# If you have an aws_config env file in the config folder, you can load in app variables this way, e.g. 'config/cdk_config.env'
|
| 93 |
+
CDK_CONFIG_PATH = get_or_create_env_var(
|
| 94 |
+
"CDK_CONFIG_PATH", "config/cdk_config.env"
|
| 95 |
+
) # e.g. config/cdk_config.env
|
| 96 |
+
|
| 97 |
+
if CDK_CONFIG_PATH:
|
| 98 |
+
if os.path.exists(CDK_CONFIG_PATH):
|
| 99 |
+
print(f"Loading CDK variables from config file {CDK_CONFIG_PATH}")
|
| 100 |
+
# override=True: stale empty defaults from an earlier cdk_config import in the
|
| 101 |
+
# same shell (e.g. cdk_install wizard calling cdk_functions) must not win.
|
| 102 |
+
load_dotenv(CDK_CONFIG_PATH, override=True)
|
| 103 |
+
else:
|
| 104 |
+
print("CDK config file not found at location:", CDK_CONFIG_PATH)
|
| 105 |
+
|
| 106 |
+
###
|
| 107 |
+
# AWS OPTIONS
|
| 108 |
+
###
|
| 109 |
+
AWS_REGION = get_or_create_env_var("AWS_REGION", "")
|
| 110 |
+
AWS_ACCOUNT_ID = get_or_create_env_var("AWS_ACCOUNT_ID", "")
|
| 111 |
+
|
| 112 |
+
###
|
| 113 |
+
# CDK OPTIONS
|
| 114 |
+
###
|
| 115 |
+
CDK_PREFIX = get_or_create_env_var("CDK_PREFIX", "")
|
| 116 |
+
|
| 117 |
+
# When True (default): CloudFormation stack termination protection, AWS
|
| 118 |
+
# deletion_protection on ALB/DynamoDB/Cognito, RemovalPolicy.RETAIN, and no S3
|
| 119 |
+
# auto-delete on stack-created resources. Set False for dev sandboxes where
|
| 120 |
+
# cdk destroy should remove resources cleanly.
|
| 121 |
+
ENABLE_RESOURCE_DELETE_PROTECTION = get_or_create_env_var(
|
| 122 |
+
"ENABLE_RESOURCE_DELETE_PROTECTION", "True"
|
| 123 |
+
)
|
| 124 |
+
|
| 125 |
+
# AWS Console myApplications (Service Catalog AppRegistry)
|
| 126 |
+
ENABLE_APPREGISTRY = get_or_create_env_var("ENABLE_APPREGISTRY", "True")
|
| 127 |
+
APPREGISTRY_APPLICATION_NAME = get_or_create_env_var(
|
| 128 |
+
"APPREGISTRY_APPLICATION_NAME", f"{CDK_PREFIX}llm-topic-modeller"
|
| 129 |
+
)
|
| 130 |
+
APPREGISTRY_DESCRIPTION = get_or_create_env_var(
|
| 131 |
+
"APPREGISTRY_DESCRIPTION",
|
| 132 |
+
"LLM topic modelling app (ALB, ECS Fargate, Cognito, S3)",
|
| 133 |
+
)
|
| 134 |
+
APPREGISTRY_STACK_NAME = get_or_create_env_var(
|
| 135 |
+
"APPREGISTRY_STACK_NAME", f"{CDK_PREFIX}AppRegistryStack"
|
| 136 |
+
)
|
| 137 |
+
APPREGISTRY_ATTRIBUTE_GROUP_NAME = get_or_create_env_var(
|
| 138 |
+
"APPREGISTRY_ATTRIBUTE_GROUP_NAME",
|
| 139 |
+
f"{APPREGISTRY_APPLICATION_NAME}-metadata",
|
| 140 |
+
)
|
| 141 |
+
APPREGISTRY_REPOSITORY_URL = get_or_create_env_var(
|
| 142 |
+
"APPREGISTRY_REPOSITORY_URL",
|
| 143 |
+
"https://github.com/seanpedrick-case/llm_topic_modeller.git",
|
| 144 |
+
)
|
| 145 |
+
|
| 146 |
+
_precheck_context_file = get_or_create_env_var("CONTEXT_FILE", "precheck.context.json")
|
| 147 |
+
# Never write boto3 pre-check output into CDK's lookup cache file (causes stale
|
| 148 |
+
# vpc-provider / load-balancer entries and wrong-account lookup validation errors).
|
| 149 |
+
if os.path.basename(_precheck_context_file.replace("\\", "/")) == "cdk.context.json":
|
| 150 |
+
print(
|
| 151 |
+
"WARNING: CONTEXT_FILE must not be 'cdk.context.json' (that file is CDK's "
|
| 152 |
+
"lookup cache). Using 'precheck.context.json' instead. Update "
|
| 153 |
+
"config/cdk_config.env and remove CONTEXT_FILE=cdk.context.json if set."
|
| 154 |
+
)
|
| 155 |
+
_precheck_context_file = "precheck.context.json"
|
| 156 |
+
CONTEXT_FILE = _precheck_context_file
|
| 157 |
+
CDK_CONTEXT_FILE = get_or_create_env_var("CDK_CONTEXT_FILE", "cdk.context.json")
|
| 158 |
+
CDK_FOLDER = get_or_create_env_var(
|
| 159 |
+
"CDK_FOLDER", ""
|
| 160 |
+
) # FULL_PATH_TO_CDK_FOLDER_HERE (with forward slash)
|
| 161 |
+
|
| 162 |
+
# App runtime config (uploaded to S3 for legacy Fargate; inlined for ECS Express Mode)
|
| 163 |
+
APP_CONFIG_ENV_BASENAME = "app_config.env"
|
| 164 |
+
_app_config_rel = os.path.join(CONFIG_FOLDER, APP_CONFIG_ENV_BASENAME).replace(
|
| 165 |
+
"\\", "/"
|
| 166 |
+
)
|
| 167 |
+
APP_CONFIG_ENV_FILE = get_or_create_env_var(
|
| 168 |
+
"APP_CONFIG_ENV_FILE",
|
| 169 |
+
(
|
| 170 |
+
os.path.normpath(os.path.join(CDK_FOLDER, _app_config_rel))
|
| 171 |
+
if CDK_FOLDER
|
| 172 |
+
else os.path.normpath(_app_config_rel)
|
| 173 |
+
),
|
| 174 |
+
)
|
| 175 |
+
RUN_USEAST_STACK = get_or_create_env_var("RUN_USEAST_STACK", "False")
|
| 176 |
+
|
| 177 |
+
### VPC and connections
|
| 178 |
+
VPC_NAME = get_or_create_env_var("VPC_NAME", "")
|
| 179 |
+
NEW_VPC_DEFAULT_NAME = get_or_create_env_var("NEW_VPC_DEFAULT_NAME", f"{CDK_PREFIX}vpc")
|
| 180 |
+
NEW_VPC_CIDR = get_or_create_env_var("NEW_VPC_CIDR", "") # "10.0.0.0/24"
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
# Internet Gateway for legacy VPC public subnets (attach + 0.0.0.0/0 routes via CDK when missing).
|
| 184 |
+
EXISTING_IGW_ID = get_or_create_env_var("EXISTING_IGW_ID", "")
|
| 185 |
+
SINGLE_NAT_GATEWAY_ID = get_or_create_env_var("SINGLE_NAT_GATEWAY_ID", "")
|
| 186 |
+
|
| 187 |
+
### SUBNETS / ROUTE TABLES / NAT GATEWAY
|
| 188 |
+
PUBLIC_SUBNETS_TO_USE = get_or_create_env_var(
|
| 189 |
+
"PUBLIC_SUBNETS_TO_USE", ""
|
| 190 |
+
) # e.g. ['PublicSubnet1', 'PublicSubnet2']
|
| 191 |
+
PUBLIC_SUBNET_CIDR_BLOCKS = get_or_create_env_var(
|
| 192 |
+
"PUBLIC_SUBNET_CIDR_BLOCKS", ""
|
| 193 |
+
) # e.g. ["10.0.1.0/24", "10.0.2.0/24"]
|
| 194 |
+
PUBLIC_SUBNET_AVAILABILITY_ZONES = get_or_create_env_var(
|
| 195 |
+
"PUBLIC_SUBNET_AVAILABILITY_ZONES", ""
|
| 196 |
+
) # e.g. ["eu-east-1b", "eu-east1b"]
|
| 197 |
+
|
| 198 |
+
PRIVATE_SUBNETS_TO_USE = get_or_create_env_var(
|
| 199 |
+
"PRIVATE_SUBNETS_TO_USE", ""
|
| 200 |
+
) # e.g. ['PrivateSubnet1', 'PrivateSubnet2']
|
| 201 |
+
PRIVATE_SUBNET_CIDR_BLOCKS = get_or_create_env_var(
|
| 202 |
+
"PRIVATE_SUBNET_CIDR_BLOCKS", ""
|
| 203 |
+
) # e.g. ["10.0.1.0/24", "10.0.2.0/24"]
|
| 204 |
+
PRIVATE_SUBNET_AVAILABILITY_ZONES = get_or_create_env_var(
|
| 205 |
+
"PRIVATE_SUBNET_AVAILABILITY_ZONES", ""
|
| 206 |
+
) # e.g. ["eu-east-1b", "eu-east1b"]
|
| 207 |
+
|
| 208 |
+
ROUTE_TABLE_BASE_NAME = get_or_create_env_var(
|
| 209 |
+
"ROUTE_TABLE_BASE_NAME", f"{CDK_PREFIX}PrivateRouteTable"
|
| 210 |
+
)
|
| 211 |
+
NAT_GATEWAY_EIP_NAME = get_or_create_env_var(
|
| 212 |
+
"NAT_GATEWAY_EIP_NAME", f"{CDK_PREFIX}NatGatewayEip"
|
| 213 |
+
)
|
| 214 |
+
NAT_GATEWAY_NAME = get_or_create_env_var("NAT_GATEWAY_NAME", f"{CDK_PREFIX}NatGateway")
|
| 215 |
+
|
| 216 |
+
# IAM roles — managed policy *names* (AWS managed) and JSON policy *files* (inline statements)
|
| 217 |
+
AWS_MANAGED_TASK_ROLES_LIST = get_or_create_env_var(
|
| 218 |
+
"AWS_MANAGED_TASK_ROLES_LIST",
|
| 219 |
+
'["AmazonCognitoReadOnly", "service-role/AmazonECSTaskExecutionRolePolicy", "AmazonDynamoDBFullAccess", "service-role/AWSAppSyncPushToCloudWatchLogs", "AmazonBedrockLimitedAccess"]',
|
| 220 |
+
)
|
| 221 |
+
ECS_EXECUTION_ROLE_MANAGED_POLICIES = get_or_create_env_var(
|
| 222 |
+
"ECS_EXECUTION_ROLE_MANAGED_POLICIES",
|
| 223 |
+
'["service-role/AmazonECSTaskExecutionRolePolicy"]',
|
| 224 |
+
)
|
| 225 |
+
# JSON IAM policy document paths (relative to CDK_FOLDER or absolute). Task role = app runtime.
|
| 226 |
+
POLICY_FILE_LOCATIONS = get_or_create_env_var(
|
| 227 |
+
"POLICY_FILE_LOCATIONS",
|
| 228 |
+
"[]",
|
| 229 |
+
)
|
| 230 |
+
# Optional extra JSON policies for the ECS task *execution* role (image pull / logs / secrets).
|
| 231 |
+
ECS_EXECUTION_ROLE_POLICY_FILES = get_or_create_env_var(
|
| 232 |
+
"ECS_EXECUTION_ROLE_POLICY_FILES",
|
| 233 |
+
"",
|
| 234 |
+
)
|
| 235 |
+
# Customer-managed policy ARNs (full ARN per entry), attached in addition to the lists above.
|
| 236 |
+
POLICY_FILE_ARNS = get_or_create_env_var("POLICY_FILE_ARNS", "")
|
| 237 |
+
ECS_EXECUTION_ROLE_POLICY_ARNS = get_or_create_env_var(
|
| 238 |
+
"ECS_EXECUTION_ROLE_POLICY_ARNS", ""
|
| 239 |
+
)
|
| 240 |
+
|
| 241 |
+
AWS_MANAGED_TASK_ROLES_LIST = parse_comma_separated_list(AWS_MANAGED_TASK_ROLES_LIST)
|
| 242 |
+
ECS_EXECUTION_ROLE_MANAGED_POLICIES = parse_comma_separated_list(
|
| 243 |
+
ECS_EXECUTION_ROLE_MANAGED_POLICIES
|
| 244 |
+
)
|
| 245 |
+
POLICY_FILE_LOCATIONS = parse_comma_separated_list(POLICY_FILE_LOCATIONS)
|
| 246 |
+
ECS_EXECUTION_ROLE_POLICY_FILES = parse_comma_separated_list(
|
| 247 |
+
ECS_EXECUTION_ROLE_POLICY_FILES
|
| 248 |
+
)
|
| 249 |
+
POLICY_FILE_ARNS = parse_comma_separated_list(POLICY_FILE_ARNS)
|
| 250 |
+
ECS_EXECUTION_ROLE_POLICY_ARNS = parse_comma_separated_list(
|
| 251 |
+
ECS_EXECUTION_ROLE_POLICY_ARNS
|
| 252 |
+
)
|
| 253 |
+
|
| 254 |
+
# GITHUB REPO
|
| 255 |
+
GITHUB_REPO_USERNAME = get_or_create_env_var("GITHUB_REPO_USERNAME", "seanpedrick-case")
|
| 256 |
+
GITHUB_REPO_NAME = get_or_create_env_var("GITHUB_REPO_NAME", "llm_topic_modeller")
|
| 257 |
+
GITHUB_REPO_BRANCH = get_or_create_env_var("GITHUB_REPO_BRANCH", "main")
|
| 258 |
+
|
| 259 |
+
### CODEBUILD
|
| 260 |
+
CODEBUILD_ROLE_NAME = get_or_create_env_var(
|
| 261 |
+
"CODEBUILD_ROLE_NAME", f"{CDK_PREFIX}CodeBuildRole"
|
| 262 |
+
)
|
| 263 |
+
CODEBUILD_PROJECT_NAME = get_or_create_env_var(
|
| 264 |
+
"CODEBUILD_PROJECT_NAME", f"{CDK_PREFIX}CodeBuildProject"
|
| 265 |
+
)
|
| 266 |
+
|
| 267 |
+
### ECR
|
| 268 |
+
ECR_REPO_NAME = get_or_create_env_var(
|
| 269 |
+
"ECR_REPO_NAME", "llm-topic-modeller"
|
| 270 |
+
) # Beware - cannot have underscores and must be lower case
|
| 271 |
+
ECR_CDK_REPO_NAME = get_or_create_env_var(
|
| 272 |
+
"ECR_CDK_REPO_NAME", f"{CDK_PREFIX}{ECR_REPO_NAME}".lower()
|
| 273 |
+
)
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
### S3
|
| 277 |
+
def _resolve_s3_bucket_name(env_key: str, suffix: str) -> str:
|
| 278 |
+
"""
|
| 279 |
+
Bucket name default is ``{CDK_PREFIX}{suffix}`` (lowercase).
|
| 280 |
+
|
| 281 |
+
If an earlier import cached a bare ``suffix`` in ``os.environ`` before
|
| 282 |
+
``CDK_PREFIX`` was loaded from dotenv, upgrade it to the prefixed name.
|
| 283 |
+
"""
|
| 284 |
+
prefix = (os.environ.get("CDK_PREFIX") or "").lower()
|
| 285 |
+
default = f"{prefix}{suffix}"
|
| 286 |
+
value = get_or_create_env_var(env_key, default)
|
| 287 |
+
if prefix and value == suffix:
|
| 288 |
+
os.environ[env_key] = default
|
| 289 |
+
return default
|
| 290 |
+
return value
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
S3_LOG_CONFIG_BUCKET_NAME = _resolve_s3_bucket_name(
|
| 294 |
+
"S3_LOG_CONFIG_BUCKET_NAME", "s3-logs"
|
| 295 |
+
) # S3 bucket names need to be lower case
|
| 296 |
+
S3_OUTPUT_BUCKET_NAME = _resolve_s3_bucket_name("S3_OUTPUT_BUCKET_NAME", "s3-output")
|
| 297 |
+
|
| 298 |
+
### VPC endpoints for ECS tasks in private subnets (ECR image pull, logs, secrets)
|
| 299 |
+
ENABLE_ECS_VPC_INTERFACE_ENDPOINTS = get_or_create_env_var(
|
| 300 |
+
"ENABLE_ECS_VPC_INTERFACE_ENDPOINTS", "True"
|
| 301 |
+
)
|
| 302 |
+
|
| 303 |
+
### KMS KEYS FOR S3 AND SECRETS MANAGER
|
| 304 |
+
USE_CUSTOM_KMS_KEY = get_or_create_env_var("USE_CUSTOM_KMS_KEY", "1")
|
| 305 |
+
CUSTOM_KMS_KEY_NAME = get_or_create_env_var(
|
| 306 |
+
"CUSTOM_KMS_KEY_NAME", f"alias/{CDK_PREFIX}kms-key".lower()
|
| 307 |
+
)
|
| 308 |
+
|
| 309 |
+
### ECS
|
| 310 |
+
FARGATE_TASK_DEFINITION_NAME = get_or_create_env_var(
|
| 311 |
+
"FARGATE_TASK_DEFINITION_NAME", f"{CDK_PREFIX}FargateTaskDefinition"
|
| 312 |
+
)
|
| 313 |
+
TASK_DEFINITION_FILE_LOCATION = get_or_create_env_var(
|
| 314 |
+
"TASK_DEFINITION_FILE_LOCATION", CDK_FOLDER + CONFIG_FOLDER + "task_definition.json"
|
| 315 |
+
)
|
| 316 |
+
|
| 317 |
+
CLUSTER_NAME = get_or_create_env_var("CLUSTER_NAME", f"{CDK_PREFIX}Cluster")
|
| 318 |
+
ECS_SERVICE_NAME = get_or_create_env_var("ECS_SERVICE_NAME", f"{CDK_PREFIX}ECSService")
|
| 319 |
+
# Second Fargate service when ENABLE_PI_AGENT_ECS_SERVICE=True (legacy path only).
|
| 320 |
+
ECS_PI_SERVICE_NAME = get_or_create_env_var(
|
| 321 |
+
"ECS_PI_SERVICE_NAME", f"{CDK_PREFIX}PiAgentService"
|
| 322 |
+
)
|
| 323 |
+
ECS_TASK_ROLE_NAME = get_or_create_env_var(
|
| 324 |
+
"ECS_TASK_ROLE_NAME", f"{CDK_PREFIX}TaskRole"
|
| 325 |
+
)
|
| 326 |
+
ECS_TASK_EXECUTION_ROLE_NAME = get_or_create_env_var(
|
| 327 |
+
"ECS_TASK_EXECUTION_ROLE_NAME", f"{CDK_PREFIX}ExecutionRole"
|
| 328 |
+
)
|
| 329 |
+
ECS_SECURITY_GROUP_NAME = get_or_create_env_var(
|
| 330 |
+
"ECS_SECURITY_GROUP_NAME", f"{CDK_PREFIX}SecurityGroupECS"
|
| 331 |
+
)
|
| 332 |
+
ECS_LOG_GROUP_NAME = get_or_create_env_var(
|
| 333 |
+
"ECS_LOG_GROUP_NAME", f"/ecs/{ECS_SERVICE_NAME}-logs".lower()
|
| 334 |
+
)
|
| 335 |
+
|
| 336 |
+
ECS_TASK_CPU_SIZE = get_or_create_env_var("ECS_TASK_CPU_SIZE", "1024")
|
| 337 |
+
ECS_TASK_MEMORY_SIZE = get_or_create_env_var("ECS_TASK_MEMORY_SIZE", "4096")
|
| 338 |
+
ECS_USE_FARGATE_SPOT = get_or_create_env_var("USE_FARGATE_SPOT", "False")
|
| 339 |
+
ECS_READ_ONLY_FILE_SYSTEM = get_or_create_env_var("ECS_READ_ONLY_FILE_SYSTEM", "True")
|
| 340 |
+
# ECS service AZ rebalancing (AWS defaults new services to ENABLED if omitted).
|
| 341 |
+
ECS_AVAILABILITY_ZONE_REBALANCING = get_or_create_env_var(
|
| 342 |
+
"ECS_AVAILABILITY_ZONE_REBALANCING", "DISABLED"
|
| 343 |
+
)
|
| 344 |
+
if ECS_AVAILABILITY_ZONE_REBALANCING not in ("ENABLED", "DISABLED"):
|
| 345 |
+
raise ValueError(
|
| 346 |
+
"ECS_AVAILABILITY_ZONE_REBALANCING must be ENABLED or DISABLED "
|
| 347 |
+
f"(got {ECS_AVAILABILITY_ZONE_REBALANCING!r})."
|
| 348 |
+
)
|
| 349 |
+
|
| 350 |
+
### Cognito
|
| 351 |
+
COGNITO_USER_POOL_NAME = get_or_create_env_var(
|
| 352 |
+
"COGNITO_USER_POOL_NAME", f"{CDK_PREFIX}UserPool"
|
| 353 |
+
)
|
| 354 |
+
COGNITO_USER_POOL_CLIENT_NAME = get_or_create_env_var(
|
| 355 |
+
"COGNITO_USER_POOL_CLIENT_NAME", f"{CDK_PREFIX}UserPoolClient"
|
| 356 |
+
)
|
| 357 |
+
COGNITO_USER_POOL_CLIENT_SECRET_NAME = get_or_create_env_var(
|
| 358 |
+
"COGNITO_USER_POOL_CLIENT_SECRET_NAME", f"{CDK_PREFIX}ParamCognitoSecret"
|
| 359 |
+
)
|
| 360 |
+
COGNITO_USER_POOL_DOMAIN_PREFIX = get_or_create_env_var(
|
| 361 |
+
"COGNITO_USER_POOL_DOMAIN_PREFIX", "llm-topic-app-domain"
|
| 362 |
+
) # Should change this to something unique or you'll probably hit an error
|
| 363 |
+
|
| 364 |
+
COGNITO_REFRESH_TOKEN_VALIDITY = int(
|
| 365 |
+
get_or_create_env_var("COGNITO_REFRESH_TOKEN_VALIDITY", "480")
|
| 366 |
+
) # Minutes
|
| 367 |
+
COGNITO_ID_TOKEN_VALIDITY = int(
|
| 368 |
+
get_or_create_env_var("COGNITO_ID_TOKEN_VALIDITY", "60")
|
| 369 |
+
) # Minutes
|
| 370 |
+
COGNITO_ACCESS_TOKEN_VALIDITY = int(
|
| 371 |
+
get_or_create_env_var("COGNITO_ACCESS_TOKEN_VALIDITY", "60")
|
| 372 |
+
) # Minutes
|
| 373 |
+
|
| 374 |
+
# Application load balancer
|
| 375 |
+
ALB_NAME = get_or_create_env_var(
|
| 376 |
+
"ALB_NAME", f"{CDK_PREFIX}Alb"[-32:]
|
| 377 |
+
) # Application load balancer name can be max 32 characters, so taking the last 32 characters of the suggested name
|
| 378 |
+
ALB_NAME_SECURITY_GROUP_NAME = get_or_create_env_var(
|
| 379 |
+
"ALB_SECURITY_GROUP_NAME", f"{CDK_PREFIX}SecurityGroupALB"
|
| 380 |
+
)
|
| 381 |
+
ALB_TARGET_GROUP_NAME = get_or_create_env_var(
|
| 382 |
+
"ALB_TARGET_GROUP_NAME", f"{CDK_PREFIX}-tg"[-32:]
|
| 383 |
+
) # Max 32 characters
|
| 384 |
+
EXISTING_LOAD_BALANCER_ARN = get_or_create_env_var("EXISTING_LOAD_BALANCER_ARN", "")
|
| 385 |
+
EXISTING_LOAD_BALANCER_DNS = get_or_create_env_var(
|
| 386 |
+
"EXISTING_LOAD_BALANCER_DNS", "placeholder_load_balancer_dns.net"
|
| 387 |
+
)
|
| 388 |
+
|
| 389 |
+
## CLOUDFRONT
|
| 390 |
+
USE_CLOUDFRONT = get_or_create_env_var("USE_CLOUDFRONT", "True")
|
| 391 |
+
CLOUDFRONT_PREFIX_LIST_ID = get_or_create_env_var(
|
| 392 |
+
"CLOUDFRONT_PREFIX_LIST_ID", "pl-93a247fa"
|
| 393 |
+
)
|
| 394 |
+
CLOUDFRONT_GEO_RESTRICTION = get_or_create_env_var(
|
| 395 |
+
"CLOUDFRONT_GEO_RESTRICTION", ""
|
| 396 |
+
) # A country that Cloudfront restricts access to. See here: https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/georestrictions.html
|
| 397 |
+
CLOUDFRONT_DISTRIBUTION_NAME = get_or_create_env_var(
|
| 398 |
+
"CLOUDFRONT_DISTRIBUTION_NAME", f"{CDK_PREFIX}CfDist"
|
| 399 |
+
)
|
| 400 |
+
CLOUDFRONT_DOMAIN = get_or_create_env_var(
|
| 401 |
+
"CLOUDFRONT_DOMAIN", "cloudfront_placeholder.net"
|
| 402 |
+
)
|
| 403 |
+
# Attach CSP / security response headers to the CDK CloudFront distribution (us-east-1 stack).
|
| 404 |
+
CLOUDFRONT_ENABLE_SECURE_RESPONSE_HEADERS = get_or_create_env_var(
|
| 405 |
+
"CLOUDFRONT_ENABLE_SECURE_RESPONSE_HEADERS", "True"
|
| 406 |
+
)
|
| 407 |
+
# Optional override for manifest-src (Cognito hosted UI). Default: https://{COGNITO_USER_POOL_DOMAIN_PREFIX}.auth.{AWS_REGION}.amazoncognito.com
|
| 408 |
+
COGNITO_USER_POOL_LOGIN_URL = get_or_create_env_var("COGNITO_USER_POOL_LOGIN_URL", "")
|
| 409 |
+
|
| 410 |
+
|
| 411 |
+
# Certificate for Application load balancer (optional, for HTTPS and logins through the ALB)
|
| 412 |
+
ACM_SSL_CERTIFICATE_ARN = get_or_create_env_var("ACM_SSL_CERTIFICATE_ARN", "")
|
| 413 |
+
SSL_CERTIFICATE_DOMAIN = get_or_create_env_var(
|
| 414 |
+
"SSL_CERTIFICATE_DOMAIN", ""
|
| 415 |
+
) # e.g. example.com or www.example.com
|
| 416 |
+
|
| 417 |
+
# ECS Express Mode (opt-in HTTPS ingress without supplying ACM_SSL_CERTIFICATE_ARN).
|
| 418 |
+
# Pilot/dev: Express PrimaryContainer does not support S3 environmentFiles or Fargate mount points.
|
| 419 |
+
USE_ECS_EXPRESS_MODE = get_or_create_env_var("USE_ECS_EXPRESS_MODE", "False")
|
| 420 |
+
ECS_EXPRESS_SERVICE_NAME = get_or_create_env_var(
|
| 421 |
+
"ECS_EXPRESS_SERVICE_NAME", ECS_SERVICE_NAME
|
| 422 |
+
)
|
| 423 |
+
ECS_EXPRESS_HEALTH_CHECK_PATH = get_or_create_env_var(
|
| 424 |
+
"ECS_EXPRESS_HEALTH_CHECK_PATH", "/"
|
| 425 |
+
)
|
| 426 |
+
ECS_EXPRESS_INFRASTRUCTURE_ROLE_NAME = get_or_create_env_var(
|
| 427 |
+
"ECS_EXPRESS_INFRASTRUCTURE_ROLE_NAME", f"{CDK_PREFIX}ExpressInfraRole"
|
| 428 |
+
)
|
| 429 |
+
# After first deploy, set to ExpressServiceEndpoint output (https://...) if not using CloudFront.
|
| 430 |
+
# The installer updates Cognito callback URLs via API (no second CDK deploy).
|
| 431 |
+
ECS_EXPRESS_COGNITO_REDIRECT_BASE = get_or_create_env_var(
|
| 432 |
+
"ECS_EXPRESS_COGNITO_REDIRECT_BASE", ""
|
| 433 |
+
)
|
| 434 |
+
# Express networkConfiguration.subnets drives both tasks and the managed ALB.
|
| 435 |
+
# Public subnets (IGW route) → internet-facing ALB; private → internal ALB only.
|
| 436 |
+
ECS_EXPRESS_USE_PUBLIC_SUBNETS = get_or_create_env_var(
|
| 437 |
+
"ECS_EXPRESS_USE_PUBLIC_SUBNETS", "True"
|
| 438 |
+
)
|
| 439 |
+
|
| 440 |
+
if USE_ECS_EXPRESS_MODE == "True" and ACM_SSL_CERTIFICATE_ARN:
|
| 441 |
+
raise ValueError(
|
| 442 |
+
"USE_ECS_EXPRESS_MODE=True cannot be used with ACM_SSL_CERTIFICATE_ARN set. "
|
| 443 |
+
"Clear ACM_SSL_CERTIFICATE_ARN or set USE_ECS_EXPRESS_MODE=False."
|
| 444 |
+
)
|
| 445 |
+
|
| 446 |
+
# ECS Service Connect (legacy Fargate only): VPC service-to-service HTTP to Gradio/FastAPI.
|
| 447 |
+
ENABLE_ECS_SERVICE_CONNECT = get_or_create_env_var(
|
| 448 |
+
"ENABLE_ECS_SERVICE_CONNECT", "False"
|
| 449 |
+
)
|
| 450 |
+
ECS_SERVICE_CONNECT_NAMESPACE = get_or_create_env_var(
|
| 451 |
+
"ECS_SERVICE_CONNECT_NAMESPACE",
|
| 452 |
+
(f"{CDK_PREFIX}local".lower().replace("_", "-").strip("-") or "llm-topic-local"),
|
| 453 |
+
)
|
| 454 |
+
ECS_SERVICE_CONNECT_DISCOVERY_NAME = get_or_create_env_var(
|
| 455 |
+
"ECS_SERVICE_CONNECT_DISCOVERY_NAME", "llm-topic"
|
| 456 |
+
)
|
| 457 |
+
# Optional friendly DNS label; defaults to discovery name when empty.
|
| 458 |
+
ECS_SERVICE_CONNECT_DNS_NAME = get_or_create_env_var("ECS_SERVICE_CONNECT_DNS_NAME", "")
|
| 459 |
+
# Client task security groups (at least one of IDs, names, or CDK prefixes required when SC on).
|
| 460 |
+
ECS_SERVICE_CONNECT_CLIENT_SECURITY_GROUP_IDS = get_or_create_env_var(
|
| 461 |
+
"ECS_SERVICE_CONNECT_CLIENT_SECURITY_GROUP_IDS", ""
|
| 462 |
+
)
|
| 463 |
+
ECS_SERVICE_CONNECT_CLIENT_SECURITY_GROUP_IDS_LIST = parse_comma_separated_list(
|
| 464 |
+
ECS_SERVICE_CONNECT_CLIENT_SECURITY_GROUP_IDS
|
| 465 |
+
)
|
| 466 |
+
ECS_SERVICE_CONNECT_CLIENT_SECURITY_GROUP_NAMES = get_or_create_env_var(
|
| 467 |
+
"ECS_SERVICE_CONNECT_CLIENT_SECURITY_GROUP_NAMES", ""
|
| 468 |
+
)
|
| 469 |
+
ECS_SERVICE_CONNECT_CLIENT_CDK_PREFIXES = get_or_create_env_var(
|
| 470 |
+
"ECS_SERVICE_CONNECT_CLIENT_CDK_PREFIXES", ""
|
| 471 |
+
)
|
| 472 |
+
|
| 473 |
+
|
| 474 |
+
def normalize_https_redirect_url(url: str) -> str:
|
| 475 |
+
"""Ensure Cognito/OAuth redirect bases use an explicit https:// scheme."""
|
| 476 |
+
raw = (url or "").strip()
|
| 477 |
+
if not raw:
|
| 478 |
+
return ""
|
| 479 |
+
if raw.startswith("https://"):
|
| 480 |
+
return raw.rstrip("/")
|
| 481 |
+
if raw.startswith("http://"):
|
| 482 |
+
return ("https://" + raw[len("http://") :]).rstrip("/")
|
| 483 |
+
return ("https://" + raw.lstrip("/")).rstrip("/")
|
| 484 |
+
|
| 485 |
+
|
| 486 |
+
# This should be the CloudFront domain, the domain linked to your ACM certificate, or the DNS of your application load balancer in console afterwards
|
| 487 |
+
if USE_CLOUDFRONT == "True":
|
| 488 |
+
COGNITO_REDIRECTION_URL = get_or_create_env_var(
|
| 489 |
+
"COGNITO_REDIRECTION_URL", "https://" + CLOUDFRONT_DOMAIN
|
| 490 |
+
)
|
| 491 |
+
elif SSL_CERTIFICATE_DOMAIN:
|
| 492 |
+
COGNITO_REDIRECTION_URL = get_or_create_env_var(
|
| 493 |
+
"COGNITO_REDIRECTION_URL", "https://" + SSL_CERTIFICATE_DOMAIN
|
| 494 |
+
)
|
| 495 |
+
elif USE_ECS_EXPRESS_MODE == "True":
|
| 496 |
+
_express_redirect_default = ECS_EXPRESS_COGNITO_REDIRECT_BASE or (
|
| 497 |
+
"https://" + EXISTING_LOAD_BALANCER_DNS
|
| 498 |
+
)
|
| 499 |
+
COGNITO_REDIRECTION_URL = get_or_create_env_var(
|
| 500 |
+
"COGNITO_REDIRECTION_URL", _express_redirect_default
|
| 501 |
+
)
|
| 502 |
+
else:
|
| 503 |
+
COGNITO_REDIRECTION_URL = get_or_create_env_var(
|
| 504 |
+
"COGNITO_REDIRECTION_URL", "https://" + EXISTING_LOAD_BALANCER_DNS
|
| 505 |
+
)
|
| 506 |
+
|
| 507 |
+
COGNITO_REDIRECTION_URL = normalize_https_redirect_url(COGNITO_REDIRECTION_URL)
|
| 508 |
+
if ECS_EXPRESS_COGNITO_REDIRECT_BASE:
|
| 509 |
+
ECS_EXPRESS_COGNITO_REDIRECT_BASE = normalize_https_redirect_url(
|
| 510 |
+
ECS_EXPRESS_COGNITO_REDIRECT_BASE
|
| 511 |
+
)
|
| 512 |
+
|
| 513 |
+
# Custom headers e.g. if routing traffic through Cloudfront
|
| 514 |
+
CUSTOM_HEADER = get_or_create_env_var(
|
| 515 |
+
"CUSTOM_HEADER", ""
|
| 516 |
+
) # Retrieving or setting CUSTOM_HEADER
|
| 517 |
+
CUSTOM_HEADER_VALUE = get_or_create_env_var(
|
| 518 |
+
"CUSTOM_HEADER_VALUE", ""
|
| 519 |
+
) # Retrieving or setting CUSTOM_HEADER_VALUE
|
| 520 |
+
|
| 521 |
+
# Firewall on top of load balancer
|
| 522 |
+
LOAD_BALANCER_WEB_ACL_NAME = get_or_create_env_var(
|
| 523 |
+
"LOAD_BALANCER_WEB_ACL_NAME", f"{CDK_PREFIX}alb-web-acl"
|
| 524 |
+
)
|
| 525 |
+
|
| 526 |
+
# Firewall on top of CloudFront
|
| 527 |
+
WEB_ACL_NAME = get_or_create_env_var("WEB_ACL_NAME", f"{CDK_PREFIX}cloudfront-web-acl")
|
| 528 |
+
|
| 529 |
+
###
|
| 530 |
+
# File I/O options
|
| 531 |
+
###
|
| 532 |
+
|
| 533 |
+
OUTPUT_FOLDER = get_or_create_env_var("GRADIO_OUTPUT_FOLDER", "output/") # 'output/'
|
| 534 |
+
INPUT_FOLDER = get_or_create_env_var("GRADIO_INPUT_FOLDER", "input/") # 'input/'
|
| 535 |
+
|
| 536 |
+
# Allow for files to be saved in a temporary folder for increased security in some instances
|
| 537 |
+
if OUTPUT_FOLDER == "TEMP" or INPUT_FOLDER == "TEMP":
|
| 538 |
+
# Create a temporary directory
|
| 539 |
+
with tempfile.TemporaryDirectory() as temp_dir:
|
| 540 |
+
print(f"Temporary directory created at: {temp_dir}")
|
| 541 |
+
|
| 542 |
+
if OUTPUT_FOLDER == "TEMP":
|
| 543 |
+
OUTPUT_FOLDER = temp_dir + "/"
|
| 544 |
+
if INPUT_FOLDER == "TEMP":
|
| 545 |
+
INPUT_FOLDER = temp_dir + "/"
|
| 546 |
+
|
| 547 |
+
###
|
| 548 |
+
# LOGGING OPTIONS
|
| 549 |
+
###
|
| 550 |
+
|
| 551 |
+
SAVE_LOGS_TO_CSV = get_or_create_env_var("SAVE_LOGS_TO_CSV", "True")
|
| 552 |
+
|
| 553 |
+
### DYNAMODB logs. Whether to save to DynamoDB, and the headers of the table
|
| 554 |
+
SAVE_LOGS_TO_DYNAMODB = get_or_create_env_var("SAVE_LOGS_TO_DYNAMODB", "True")
|
| 555 |
+
ACCESS_LOG_DYNAMODB_TABLE_NAME = get_or_create_env_var(
|
| 556 |
+
"ACCESS_LOG_DYNAMODB_TABLE_NAME", f"{CDK_PREFIX}dynamodb-access-logs".lower()
|
| 557 |
+
)
|
| 558 |
+
FEEDBACK_LOG_DYNAMODB_TABLE_NAME = get_or_create_env_var(
|
| 559 |
+
"FEEDBACK_LOG_DYNAMODB_TABLE_NAME", f"{CDK_PREFIX}dynamodb-feedback-logs".lower()
|
| 560 |
+
)
|
| 561 |
+
USAGE_LOG_DYNAMODB_TABLE_NAME = get_or_create_env_var(
|
| 562 |
+
"USAGE_LOG_DYNAMODB_TABLE_NAME", f"{CDK_PREFIX}dynamodb-usage-logs".lower()
|
| 563 |
+
)
|
| 564 |
+
|
| 565 |
+
# Optional scheduled export of usage-log DynamoDB table to CSV in S3 (EventBridge -> Lambda).
|
| 566 |
+
ENABLE_DYNAMODB_USAGE_LOG_EXPORT = get_or_create_env_var(
|
| 567 |
+
"ENABLE_DYNAMODB_USAGE_LOG_EXPORT", "False"
|
| 568 |
+
)
|
| 569 |
+
DYNAMODB_USAGE_LOG_EXPORT_LAMBDA_NAME = get_or_create_env_var(
|
| 570 |
+
"DYNAMODB_USAGE_LOG_EXPORT_LAMBDA_NAME",
|
| 571 |
+
f"{CDK_PREFIX}DynamoUsageLogExport".lower().replace("_", "-"),
|
| 572 |
+
)
|
| 573 |
+
DYNAMODB_USAGE_LOG_EXPORT_SCHEDULE = get_or_create_env_var(
|
| 574 |
+
"DYNAMODB_USAGE_LOG_EXPORT_SCHEDULE", "cron(0 6 ? * * *)"
|
| 575 |
+
)
|
| 576 |
+
DYNAMODB_USAGE_LOG_EXPORT_S3_KEY = get_or_create_env_var(
|
| 577 |
+
"DYNAMODB_USAGE_LOG_EXPORT_S3_KEY",
|
| 578 |
+
"reports/dynamodb-usage/dynamodb_logs_export.csv",
|
| 579 |
+
)
|
| 580 |
+
DYNAMODB_USAGE_LOG_EXPORT_DATE_ATTRIBUTE = get_or_create_env_var(
|
| 581 |
+
"DYNAMODB_USAGE_LOG_EXPORT_DATE_ATTRIBUTE", "timestamp"
|
| 582 |
+
)
|
| 583 |
+
DYNAMODB_USAGE_LOG_EXPORT_OUTPUT_FILENAME = get_or_create_env_var(
|
| 584 |
+
"DYNAMODB_USAGE_LOG_EXPORT_OUTPUT_FILENAME", "dynamodb_logs_export.csv"
|
| 585 |
+
)
|
| 586 |
+
|
| 587 |
+
if ENABLE_DYNAMODB_USAGE_LOG_EXPORT == "True":
|
| 588 |
+
if SAVE_LOGS_TO_DYNAMODB != "True":
|
| 589 |
+
raise ValueError(
|
| 590 |
+
"ENABLE_DYNAMODB_USAGE_LOG_EXPORT=True requires SAVE_LOGS_TO_DYNAMODB=True."
|
| 591 |
+
)
|
| 592 |
+
schedule = (DYNAMODB_USAGE_LOG_EXPORT_SCHEDULE or "").strip()
|
| 593 |
+
if not schedule.startswith("cron(") and not schedule.startswith("rate("):
|
| 594 |
+
raise ValueError(
|
| 595 |
+
"DYNAMODB_USAGE_LOG_EXPORT_SCHEDULE must be an EventBridge cron(...) or "
|
| 596 |
+
f"rate(...) expression; got {schedule!r}."
|
| 597 |
+
)
|
| 598 |
+
if not (DYNAMODB_USAGE_LOG_EXPORT_S3_KEY or "").strip():
|
| 599 |
+
raise ValueError(
|
| 600 |
+
"DYNAMODB_USAGE_LOG_EXPORT_S3_KEY is required when "
|
| 601 |
+
"ENABLE_DYNAMODB_USAGE_LOG_EXPORT=True."
|
| 602 |
+
)
|
| 603 |
+
|
| 604 |
+
###
|
| 605 |
+
# APP OPTIONS
|
| 606 |
+
###
|
| 607 |
+
|
| 608 |
+
# Get some environment variables and Launch the Gradio app
|
| 609 |
+
COGNITO_AUTH = get_or_create_env_var("COGNITO_AUTH", "False")
|
| 610 |
+
|
| 611 |
+
GRADIO_SERVER_PORT = int(get_or_create_env_var("GRADIO_SERVER_PORT", "7860"))
|
| 612 |
+
|
| 613 |
+
# Must match the named port mapping on the Fargate container (see cdk_stack.py).
|
| 614 |
+
ECS_SERVICE_CONNECT_PORT_MAPPING_NAME = get_or_create_env_var(
|
| 615 |
+
"ECS_SERVICE_CONNECT_PORT_MAPPING_NAME", f"port-{GRADIO_SERVER_PORT}"
|
| 616 |
+
)
|
| 617 |
+
|
| 618 |
+
# Suffix used with ECS_SERVICE_CONNECT_CLIENT_CDK_PREFIXES (matches this stack's ECS SG name).
|
| 619 |
+
if ECS_SECURITY_GROUP_NAME.startswith(CDK_PREFIX):
|
| 620 |
+
_default_sc_client_sg_suffix = ECS_SECURITY_GROUP_NAME[len(CDK_PREFIX) :]
|
| 621 |
+
else:
|
| 622 |
+
_default_sc_client_sg_suffix = "SecurityGroupECS"
|
| 623 |
+
ECS_SERVICE_CONNECT_CLIENT_SG_NAME_SUFFIX = get_or_create_env_var(
|
| 624 |
+
"ECS_SERVICE_CONNECT_CLIENT_SG_NAME_SUFFIX", _default_sc_client_sg_suffix
|
| 625 |
+
)
|
| 626 |
+
|
| 627 |
+
ECS_SERVICE_CONNECT_CLIENT_SECURITY_GROUP_NAMES_LIST = parse_comma_separated_list(
|
| 628 |
+
ECS_SERVICE_CONNECT_CLIENT_SECURITY_GROUP_NAMES
|
| 629 |
+
)
|
| 630 |
+
ECS_SERVICE_CONNECT_CLIENT_CDK_PREFIXES_LIST = parse_comma_separated_list(
|
| 631 |
+
ECS_SERVICE_CONNECT_CLIENT_CDK_PREFIXES
|
| 632 |
+
)
|
| 633 |
+
|
| 634 |
+
|
| 635 |
+
def build_service_connect_client_security_group_names() -> List[str]:
|
| 636 |
+
"""Explicit SG names plus {prefix}{suffix} for each client CDK_PREFIX."""
|
| 637 |
+
names: List[str] = list(ECS_SERVICE_CONNECT_CLIENT_SECURITY_GROUP_NAMES_LIST)
|
| 638 |
+
for prefix in ECS_SERVICE_CONNECT_CLIENT_CDK_PREFIXES_LIST:
|
| 639 |
+
names.append(f"{prefix}{ECS_SERVICE_CONNECT_CLIENT_SG_NAME_SUFFIX}")
|
| 640 |
+
deduped: List[str] = []
|
| 641 |
+
seen = set()
|
| 642 |
+
for name in names:
|
| 643 |
+
if name and name not in seen:
|
| 644 |
+
seen.add(name)
|
| 645 |
+
deduped.append(name)
|
| 646 |
+
return deduped
|
| 647 |
+
|
| 648 |
+
|
| 649 |
+
ECS_SERVICE_CONNECT_CLIENT_SECURITY_GROUP_NAMES_TO_LOOKUP = (
|
| 650 |
+
build_service_connect_client_security_group_names()
|
| 651 |
+
)
|
| 652 |
+
|
| 653 |
+
if ENABLE_ECS_SERVICE_CONNECT == "True" and USE_ECS_EXPRESS_MODE == "True":
|
| 654 |
+
raise ValueError(
|
| 655 |
+
"ENABLE_ECS_SERVICE_CONNECT=True is only supported on the legacy Fargate "
|
| 656 |
+
"service path. Set USE_ECS_EXPRESS_MODE=False or disable Service Connect."
|
| 657 |
+
)
|
| 658 |
+
|
| 659 |
+
# Headless deployment: S3 job .env -> Lambda -> one-shot ECS Fargate (RUN_DIRECT_MODE).
|
| 660 |
+
# No ALB, CloudFront, or always-on ECS service.
|
| 661 |
+
ENABLE_HEADLESS_DEPLOYMENT = get_or_create_env_var(
|
| 662 |
+
"ENABLE_HEADLESS_DEPLOYMENT", "False"
|
| 663 |
+
)
|
| 664 |
+
|
| 665 |
+
# S3-uploaded job .env files trigger one-shot ECS Fargate tasks (direct mode / cli_redact).
|
| 666 |
+
ENABLE_S3_BATCH_ECS_TRIGGER = get_or_create_env_var(
|
| 667 |
+
"ENABLE_S3_BATCH_ECS_TRIGGER", "False"
|
| 668 |
+
)
|
| 669 |
+
S3_BATCH_ENV_PREFIX = get_or_create_env_var("S3_BATCH_ENV_PREFIX", "input/config/")
|
| 670 |
+
S3_BATCH_ENV_SUFFIX = get_or_create_env_var("S3_BATCH_ENV_SUFFIX", ".env")
|
| 671 |
+
S3_BATCH_INPUT_PREFIX = get_or_create_env_var("S3_BATCH_INPUT_PREFIX", "input/")
|
| 672 |
+
S3_BATCH_CONFIG_PREFIX = get_or_create_env_var("S3_BATCH_CONFIG_PREFIX", "")
|
| 673 |
+
S3_BATCH_GENERAL_ENV_PREFIX = get_or_create_env_var(
|
| 674 |
+
"S3_BATCH_GENERAL_ENV_PREFIX", "general-config/"
|
| 675 |
+
)
|
| 676 |
+
S3_BATCH_DEFAULT_PARAMS_KEY = get_or_create_env_var(
|
| 677 |
+
"S3_BATCH_DEFAULT_PARAMS_KEY", "general-config/app_defaults.env"
|
| 678 |
+
)
|
| 679 |
+
S3_BATCH_LAMBDA_FUNCTION_NAME = get_or_create_env_var(
|
| 680 |
+
"S3_BATCH_LAMBDA_FUNCTION_NAME", f"{CDK_PREFIX}S3BatchEcsTrigger"
|
| 681 |
+
)
|
| 682 |
+
|
| 683 |
+
if ENABLE_S3_BATCH_ECS_TRIGGER == "True" and USE_ECS_EXPRESS_MODE == "True":
|
| 684 |
+
raise ValueError(
|
| 685 |
+
"ENABLE_S3_BATCH_ECS_TRIGGER=True requires the legacy Fargate task definition "
|
| 686 |
+
"for ecs.run_task. Set USE_ECS_EXPRESS_MODE=False or disable the batch trigger."
|
| 687 |
+
)
|
| 688 |
+
|
| 689 |
+
if ENABLE_HEADLESS_DEPLOYMENT == "True":
|
| 690 |
+
if ENABLE_S3_BATCH_ECS_TRIGGER != "True":
|
| 691 |
+
raise ValueError(
|
| 692 |
+
"ENABLE_HEADLESS_DEPLOYMENT=True requires ENABLE_S3_BATCH_ECS_TRIGGER=True."
|
| 693 |
+
)
|
| 694 |
+
if USE_ECS_EXPRESS_MODE == "True":
|
| 695 |
+
raise ValueError(
|
| 696 |
+
"ENABLE_HEADLESS_DEPLOYMENT=True requires USE_ECS_EXPRESS_MODE=False."
|
| 697 |
+
)
|
| 698 |
+
if USE_CLOUDFRONT == "True":
|
| 699 |
+
raise ValueError(
|
| 700 |
+
"ENABLE_HEADLESS_DEPLOYMENT=True is incompatible with USE_CLOUDFRONT=True."
|
| 701 |
+
)
|
| 702 |
+
|
| 703 |
+
# Optional headless follow-on: S3 output PutRequests alarm -> SNS email + IAM user for downloads.
|
| 704 |
+
ENABLE_HEADLESS_OUTPUT_NOTIFICATIONS = get_or_create_env_var(
|
| 705 |
+
"ENABLE_HEADLESS_OUTPUT_NOTIFICATIONS", "False"
|
| 706 |
+
)
|
| 707 |
+
HEADLESS_OUTPUT_NOTIFY_EMAIL = get_or_create_env_var("HEADLESS_OUTPUT_NOTIFY_EMAIL", "")
|
| 708 |
+
HEADLESS_OUTPUT_IAM_USER_NAME = get_or_create_env_var(
|
| 709 |
+
"HEADLESS_OUTPUT_IAM_USER_NAME", f"{CDK_PREFIX}s3-output-reader"
|
| 710 |
+
)
|
| 711 |
+
HEADLESS_OUTPUT_S3_METRIC_FILTER_ID = get_or_create_env_var(
|
| 712 |
+
"HEADLESS_OUTPUT_S3_METRIC_FILTER_ID",
|
| 713 |
+
f"{CDK_PREFIX}s3-output-put".lower().replace("_", "-"),
|
| 714 |
+
)
|
| 715 |
+
HEADLESS_OUTPUT_SNS_TOPIC_NAME = get_or_create_env_var(
|
| 716 |
+
"HEADLESS_OUTPUT_SNS_TOPIC_NAME",
|
| 717 |
+
f"{CDK_PREFIX}llm-topic-s3-save-sns".lower().replace("_", "-"),
|
| 718 |
+
)
|
| 719 |
+
HEADLESS_OUTPUT_ALARM_NAME = get_or_create_env_var(
|
| 720 |
+
"HEADLESS_OUTPUT_ALARM_NAME",
|
| 721 |
+
f"{CDK_PREFIX}cloudwatch-alarm-new-output-s3".lower().replace("_", "-"),
|
| 722 |
+
)
|
| 723 |
+
HEADLESS_OUTPUT_S3_PREFIX = get_or_create_env_var(
|
| 724 |
+
"HEADLESS_OUTPUT_S3_PREFIX", "output/"
|
| 725 |
+
)
|
| 726 |
+
HEADLESS_OUTPUT_IAM_SECRET_NAME = get_or_create_env_var(
|
| 727 |
+
"HEADLESS_OUTPUT_IAM_SECRET_NAME",
|
| 728 |
+
f"{CDK_PREFIX}headless-output-reader-key",
|
| 729 |
+
)
|
| 730 |
+
|
| 731 |
+
if ENABLE_HEADLESS_OUTPUT_NOTIFICATIONS == "True":
|
| 732 |
+
if ENABLE_HEADLESS_DEPLOYMENT != "True":
|
| 733 |
+
raise ValueError(
|
| 734 |
+
"ENABLE_HEADLESS_OUTPUT_NOTIFICATIONS=True requires "
|
| 735 |
+
"ENABLE_HEADLESS_DEPLOYMENT=True."
|
| 736 |
+
)
|
| 737 |
+
if not (HEADLESS_OUTPUT_NOTIFY_EMAIL or "").strip():
|
| 738 |
+
raise ValueError(
|
| 739 |
+
"HEADLESS_OUTPUT_NOTIFY_EMAIL is required when "
|
| 740 |
+
"ENABLE_HEADLESS_OUTPUT_NOTIFICATIONS=True."
|
| 741 |
+
)
|
| 742 |
+
|
| 743 |
+
# Pi agent Gradio UI (second Fargate service; shared legacy ALB + Service Connect to main app).
|
| 744 |
+
ENABLE_PI_AGENT_ECS_SERVICE = get_or_create_env_var(
|
| 745 |
+
"ENABLE_PI_AGENT_ECS_SERVICE", "False"
|
| 746 |
+
)
|
| 747 |
+
ECR_PI_REPO_NAME = get_or_create_env_var(
|
| 748 |
+
"ECR_PI_REPO_NAME", f"{CDK_PREFIX}pi-agent".lower()
|
| 749 |
+
)
|
| 750 |
+
CODEBUILD_PI_PROJECT_NAME = get_or_create_env_var(
|
| 751 |
+
"CODEBUILD_PI_PROJECT_NAME", f"{CDK_PREFIX}CodeBuildPiAgent"
|
| 752 |
+
)
|
| 753 |
+
ECS_PI_TASK_DEFINITION_NAME = get_or_create_env_var(
|
| 754 |
+
"ECS_PI_TASK_DEFINITION_NAME", f"{CDK_PREFIX}PiAgentTaskDefinition"
|
| 755 |
+
)
|
| 756 |
+
ECS_PI_SECURITY_GROUP_NAME = get_or_create_env_var(
|
| 757 |
+
"ECS_PI_SECURITY_GROUP_NAME", f"{CDK_PREFIX}SecurityGroupPiAgent"
|
| 758 |
+
)
|
| 759 |
+
ECS_PI_LOG_GROUP_NAME = get_or_create_env_var(
|
| 760 |
+
"ECS_PI_LOG_GROUP_NAME", f"/ecs/{ECS_PI_SERVICE_NAME}-logs".lower()
|
| 761 |
+
)
|
| 762 |
+
ECS_PI_TASK_CPU_SIZE = get_or_create_env_var("ECS_PI_TASK_CPU_SIZE", "1024")
|
| 763 |
+
ECS_PI_TASK_MEMORY_SIZE = get_or_create_env_var("ECS_PI_TASK_MEMORY_SIZE", "2048")
|
| 764 |
+
PI_GRADIO_PORT = get_or_create_env_var("PI_GRADIO_PORT", "7862")
|
| 765 |
+
# Pi ALB routing: path (default /pi on shared host e.g. CloudFront), host, or both.
|
| 766 |
+
PI_ALB_ROUTING = get_or_create_env_var("PI_ALB_ROUTING", "path").strip().lower()
|
| 767 |
+
PI_ALB_PATH_PREFIX = get_or_create_env_var("PI_ALB_PATH_PREFIX", "/pi")
|
| 768 |
+
PI_ALB_HOST_HEADER = get_or_create_env_var("PI_ALB_HOST_HEADER", "")
|
| 769 |
+
PI_ALB_TARGET_GROUP_NAME = get_or_create_env_var(
|
| 770 |
+
"PI_ALB_TARGET_GROUP_NAME", f"{CDK_PREFIX}PiAgentTG"[-32:]
|
| 771 |
+
)
|
| 772 |
+
PI_ALB_LISTENER_RULE_PRIORITY = int(
|
| 773 |
+
get_or_create_env_var("PI_ALB_LISTENER_RULE_PRIORITY", "3")
|
| 774 |
+
)
|
| 775 |
+
PI_AGENT_ENV_S3_KEY = get_or_create_env_var("PI_AGENT_ENV_S3_KEY", "pi_agent.env")
|
| 776 |
+
|
| 777 |
+
|
| 778 |
+
def _normalize_pi_alb_path_prefix(raw: str) -> str:
|
| 779 |
+
segment = (raw or "pi").strip().strip("/")
|
| 780 |
+
return f"/{segment}" if segment else "/pi"
|
| 781 |
+
|
| 782 |
+
|
| 783 |
+
PI_ALB_PATH_PREFIX_NORMALIZED = _normalize_pi_alb_path_prefix(PI_ALB_PATH_PREFIX)
|
| 784 |
+
_PI_ALB_ROUTING_MODES = frozenset({"path", "host", "both"})
|
| 785 |
+
|
| 786 |
+
|
| 787 |
+
def _validate_pi_alb_routing_for_enabled_pi() -> None:
|
| 788 |
+
if PI_ALB_ROUTING not in _PI_ALB_ROUTING_MODES:
|
| 789 |
+
raise ValueError(
|
| 790 |
+
f"PI_ALB_ROUTING must be one of {sorted(_PI_ALB_ROUTING_MODES)}; got '{PI_ALB_ROUTING}'."
|
| 791 |
+
)
|
| 792 |
+
if PI_ALB_ROUTING in ("host", "both") and not PI_ALB_HOST_HEADER.strip():
|
| 793 |
+
raise ValueError(
|
| 794 |
+
"PI_ALB_HOST_HEADER is required when PI_ALB_ROUTING is 'host' or 'both' "
|
| 795 |
+
"(dedicated hostname on the shared ALB)."
|
| 796 |
+
)
|
| 797 |
+
if PI_ALB_ROUTING in ("path", "both") and not PI_ALB_PATH_PREFIX_NORMALIZED:
|
| 798 |
+
raise ValueError("PI_ALB_PATH_PREFIX must resolve to a non-empty path segment.")
|
| 799 |
+
|
| 800 |
+
|
| 801 |
+
# Pi on ECS Express Mode (second Express service on shared ALB; SC via ecs:UpdateService).
|
| 802 |
+
ENABLE_PI_AGENT_EXPRESS_SERVICE = get_or_create_env_var(
|
| 803 |
+
"ENABLE_PI_AGENT_EXPRESS_SERVICE", "False"
|
| 804 |
+
)
|
| 805 |
+
ECS_PI_EXPRESS_SERVICE_NAME = get_or_create_env_var(
|
| 806 |
+
"ECS_PI_EXPRESS_SERVICE_NAME", f"{CDK_PREFIX}PiExpressService"
|
| 807 |
+
)
|
| 808 |
+
ECS_PI_EXPRESS_HEALTH_CHECK_PATH = get_or_create_env_var(
|
| 809 |
+
"ECS_PI_EXPRESS_HEALTH_CHECK_PATH", "/health"
|
| 810 |
+
)
|
| 811 |
+
ECS_PI_EXPRESS_SECURITY_GROUP_NAME = get_or_create_env_var(
|
| 812 |
+
"ECS_PI_EXPRESS_SECURITY_GROUP_NAME", f"{CDK_PREFIX}SecurityGroupPiExpress"
|
| 813 |
+
)
|
| 814 |
+
# Service Connect port names for Express services (applied in post_cdk_build_quickstart.py).
|
| 815 |
+
ECS_EXPRESS_SC_PORT_NAME = get_or_create_env_var(
|
| 816 |
+
"ECS_EXPRESS_SC_PORT_NAME", ECS_SERVICE_CONNECT_PORT_MAPPING_NAME
|
| 817 |
+
)
|
| 818 |
+
ECS_PI_EXPRESS_SC_PORT_NAME = get_or_create_env_var(
|
| 819 |
+
"ECS_PI_EXPRESS_SC_PORT_NAME", f"port-{PI_GRADIO_PORT}"
|
| 820 |
+
)
|
| 821 |
+
|
| 822 |
+
if ENABLE_PI_AGENT_ECS_SERVICE == "True" and ENABLE_PI_AGENT_EXPRESS_SERVICE == "True":
|
| 823 |
+
raise ValueError(
|
| 824 |
+
"Enable at most one Pi deployment mode: ENABLE_PI_AGENT_ECS_SERVICE (legacy Fargate) "
|
| 825 |
+
"or ENABLE_PI_AGENT_EXPRESS_SERVICE (Express), not both."
|
| 826 |
+
)
|
| 827 |
+
if ENABLE_PI_AGENT_EXPRESS_SERVICE == "True" and USE_ECS_EXPRESS_MODE != "True":
|
| 828 |
+
raise ValueError(
|
| 829 |
+
"ENABLE_PI_AGENT_EXPRESS_SERVICE=True requires USE_ECS_EXPRESS_MODE=True "
|
| 830 |
+
"(no ACM_SSL_CERTIFICATE_ARN)."
|
| 831 |
+
)
|
| 832 |
+
if ENABLE_PI_AGENT_ECS_SERVICE == "True" and USE_ECS_EXPRESS_MODE == "True":
|
| 833 |
+
raise ValueError(
|
| 834 |
+
"ENABLE_PI_AGENT_ECS_SERVICE=True requires legacy Fargate (USE_ECS_EXPRESS_MODE=False). "
|
| 835 |
+
"For Pi on Express, use ENABLE_PI_AGENT_EXPRESS_SERVICE=True instead."
|
| 836 |
+
)
|
| 837 |
+
if ENABLE_PI_AGENT_ECS_SERVICE == "True" and ENABLE_ECS_SERVICE_CONNECT != "True":
|
| 838 |
+
raise ValueError(
|
| 839 |
+
"ENABLE_PI_AGENT_ECS_SERVICE=True requires ENABLE_ECS_SERVICE_CONNECT=True "
|
| 840 |
+
"so the Pi task can reach the main app at http://<discovery>:7860."
|
| 841 |
+
)
|
| 842 |
+
if ENABLE_PI_AGENT_ECS_SERVICE == "True":
|
| 843 |
+
_validate_pi_alb_routing_for_enabled_pi()
|
| 844 |
+
|
| 845 |
+
###
|
| 846 |
+
# WHOLE DOCUMENT API OPTIONS
|
| 847 |
+
###
|
| 848 |
+
|
| 849 |
+
DAYS_TO_DISPLAY_WHOLE_DOCUMENT_JOBS = get_or_create_env_var(
|
| 850 |
+
"DAYS_TO_DISPLAY_WHOLE_DOCUMENT_JOBS", "7"
|
| 851 |
+
) # How many days into the past should whole document Textract jobs be displayed? After that, the data is not deleted from the Textract jobs csv, but it is just filtered out. Included to align with S3 buckets where the file outputs will be automatically deleted after X days.
|
cdk/cdk_functions.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
cdk/cdk_install.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
cdk/cdk_post_deploy.py
ADDED
|
@@ -0,0 +1,1408 @@
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Post-deploy helpers (boto3 only).
|
| 3 |
+
|
| 4 |
+
Use this module from post_cdk_build_quickstart.py so you do not need Node.js or
|
| 5 |
+
aws-cdk-lib installed to start CodeBuild / ECS after deployment.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
import copy
|
| 11 |
+
import json
|
| 12 |
+
import os
|
| 13 |
+
import re
|
| 14 |
+
import time
|
| 15 |
+
from typing import Any, Dict, List, Optional, Union
|
| 16 |
+
|
| 17 |
+
import boto3
|
| 18 |
+
from cdk_config import (
|
| 19 |
+
AWS_REGION,
|
| 20 |
+
CLOUDFRONT_DOMAIN,
|
| 21 |
+
)
|
| 22 |
+
|
| 23 |
+
_TASK_DEF_REGISTER_KEYS = (
|
| 24 |
+
"family",
|
| 25 |
+
"taskRoleArn",
|
| 26 |
+
"executionRoleArn",
|
| 27 |
+
"networkMode",
|
| 28 |
+
"containerDefinitions",
|
| 29 |
+
"volumes",
|
| 30 |
+
"placementConstraints",
|
| 31 |
+
"requiresCompatibilities",
|
| 32 |
+
"cpu",
|
| 33 |
+
"memory",
|
| 34 |
+
"pidMode",
|
| 35 |
+
"ipcMode",
|
| 36 |
+
"proxyConfiguration",
|
| 37 |
+
"inferenceAccelerators",
|
| 38 |
+
"ephemeralStorage",
|
| 39 |
+
"runtimePlatform",
|
| 40 |
+
)
|
| 41 |
+
|
| 42 |
+
_CONTAINER_REGISTER_OMIT_KEYS = frozenset(
|
| 43 |
+
{
|
| 44 |
+
"containerArn",
|
| 45 |
+
"taskDefinitionArn",
|
| 46 |
+
"status",
|
| 47 |
+
"lastStatus",
|
| 48 |
+
"managedAgents",
|
| 49 |
+
"networkInterfaces",
|
| 50 |
+
"healthStatus",
|
| 51 |
+
"cpu",
|
| 52 |
+
"memory",
|
| 53 |
+
"gpu",
|
| 54 |
+
}
|
| 55 |
+
)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def start_codebuild_build(project_name: str, aws_region: str = AWS_REGION) -> None:
|
| 59 |
+
"""Start an existing CodeBuild project build."""
|
| 60 |
+
client = boto3.client("codebuild", region_name=aws_region)
|
| 61 |
+
|
| 62 |
+
try:
|
| 63 |
+
print(f"Attempting to start build for project: {project_name}")
|
| 64 |
+
response = client.start_build(projectName=project_name)
|
| 65 |
+
build_id = response["build"]["id"]
|
| 66 |
+
print(f"Successfully started build with ID: {build_id}")
|
| 67 |
+
print(f"Build ARN: {response['build']['arn']}")
|
| 68 |
+
print(
|
| 69 |
+
f"https://{aws_region}.console.aws.amazon.com/codesuite/codebuild/projects/"
|
| 70 |
+
f"{project_name}/build/{build_id.split(':')[-1]}/detail"
|
| 71 |
+
)
|
| 72 |
+
except client.exceptions.ResourceNotFoundException:
|
| 73 |
+
print(f"Error: Project '{project_name}' not found in region '{aws_region}'.")
|
| 74 |
+
except Exception as e:
|
| 75 |
+
print(f"An unexpected error occurred: {e}")
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def upload_file_to_s3(
|
| 79 |
+
local_file_paths: Union[str, List[str]],
|
| 80 |
+
s3_key: str,
|
| 81 |
+
s3_bucket: str,
|
| 82 |
+
run_aws_functions: str = "1",
|
| 83 |
+
aws_region: str = AWS_REGION,
|
| 84 |
+
) -> str:
|
| 85 |
+
"""Upload local file(s) to S3."""
|
| 86 |
+
final_out_message: List[str] = []
|
| 87 |
+
final_out_message_str = ""
|
| 88 |
+
|
| 89 |
+
if run_aws_functions != "1":
|
| 90 |
+
return "App not set to run AWS functions"
|
| 91 |
+
|
| 92 |
+
try:
|
| 93 |
+
if not (s3_bucket and local_file_paths):
|
| 94 |
+
return "At least one essential variable is empty, could not upload to S3"
|
| 95 |
+
|
| 96 |
+
s3_client = boto3.client("s3", region_name=aws_region)
|
| 97 |
+
paths = (
|
| 98 |
+
[local_file_paths]
|
| 99 |
+
if isinstance(local_file_paths, str)
|
| 100 |
+
else list(local_file_paths)
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
for file_path in paths:
|
| 104 |
+
try:
|
| 105 |
+
file_name = os.path.basename(file_path)
|
| 106 |
+
s3_key_full = s3_key + file_name
|
| 107 |
+
print("S3 key: ", s3_key_full)
|
| 108 |
+
s3_client.upload_file(file_path, s3_bucket, s3_key_full)
|
| 109 |
+
out_message = f"File {file_name} uploaded successfully!"
|
| 110 |
+
print(out_message)
|
| 111 |
+
except Exception as e:
|
| 112 |
+
out_message = f"Error uploading file(s): {e}"
|
| 113 |
+
print(out_message)
|
| 114 |
+
final_out_message.append(out_message)
|
| 115 |
+
|
| 116 |
+
final_out_message_str = "\n".join(final_out_message)
|
| 117 |
+
except Exception as e:
|
| 118 |
+
final_out_message_str = "Could not upload files to S3 due to: " + str(e)
|
| 119 |
+
print(final_out_message_str)
|
| 120 |
+
|
| 121 |
+
return final_out_message_str
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def start_ecs_task(
|
| 125 |
+
cluster_name: str,
|
| 126 |
+
service_name: str,
|
| 127 |
+
aws_region: str = AWS_REGION,
|
| 128 |
+
) -> dict:
|
| 129 |
+
"""Scale a legacy Fargate ECS service to one running task."""
|
| 130 |
+
ecs_client = boto3.client("ecs", region_name=aws_region)
|
| 131 |
+
|
| 132 |
+
try:
|
| 133 |
+
ecs_client.update_service(
|
| 134 |
+
cluster=cluster_name, service=service_name, desiredCount=1
|
| 135 |
+
)
|
| 136 |
+
return {
|
| 137 |
+
"statusCode": 200,
|
| 138 |
+
"body": (
|
| 139 |
+
f"Service {service_name} in cluster {cluster_name} "
|
| 140 |
+
"has been updated to 1 task."
|
| 141 |
+
),
|
| 142 |
+
}
|
| 143 |
+
except Exception as e:
|
| 144 |
+
return {"statusCode": 500, "body": f"Error updating service: {str(e)}"}
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
EXPRESS_GATEWAY_ACTIVE_SCALING_TARGET = {
|
| 148 |
+
"minTaskCount": 1,
|
| 149 |
+
"maxTaskCount": 1,
|
| 150 |
+
"autoScalingMetric": "AVERAGE_CPU",
|
| 151 |
+
"autoScalingTargetValue": 60,
|
| 152 |
+
}
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def resolve_express_gateway_service_arn(
|
| 156 |
+
cluster_name: str,
|
| 157 |
+
service_name: str,
|
| 158 |
+
aws_region: str = AWS_REGION,
|
| 159 |
+
) -> str:
|
| 160 |
+
"""Look up an Express gateway service ARN by cluster and service name."""
|
| 161 |
+
ecs_client = boto3.client("ecs", region_name=aws_region)
|
| 162 |
+
paginator = ecs_client.get_paginator("list_services")
|
| 163 |
+
for page in paginator.paginate(cluster=cluster_name):
|
| 164 |
+
for arn in page.get("serviceArns", []):
|
| 165 |
+
if arn.rstrip("/").split("/")[-1] == service_name:
|
| 166 |
+
return arn
|
| 167 |
+
raise ValueError(
|
| 168 |
+
f"Express gateway service '{service_name}' not found in cluster "
|
| 169 |
+
f"'{cluster_name}'."
|
| 170 |
+
)
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
def _task_definition_has_port_name(
|
| 174 |
+
task_definition: Dict[str, Any], port_name: str
|
| 175 |
+
) -> bool:
|
| 176 |
+
for container in task_definition.get("containerDefinitions", []):
|
| 177 |
+
for mapping in container.get("portMappings") or []:
|
| 178 |
+
if mapping.get("name") == port_name:
|
| 179 |
+
return True
|
| 180 |
+
return False
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
def _container_definitions_with_named_port(
|
| 184 |
+
container_definitions: List[Dict[str, Any]],
|
| 185 |
+
*,
|
| 186 |
+
port_name: str,
|
| 187 |
+
container_port: int,
|
| 188 |
+
) -> List[Dict[str, Any]]:
|
| 189 |
+
updated: List[Dict[str, Any]] = []
|
| 190 |
+
has_matching_port = any(
|
| 191 |
+
mapping.get("containerPort") == container_port
|
| 192 |
+
for container in container_definitions
|
| 193 |
+
for mapping in container.get("portMappings") or []
|
| 194 |
+
)
|
| 195 |
+
for index, container in enumerate(container_definitions):
|
| 196 |
+
container = {
|
| 197 |
+
key: value
|
| 198 |
+
for key, value in container.items()
|
| 199 |
+
if key not in _CONTAINER_REGISTER_OMIT_KEYS
|
| 200 |
+
}
|
| 201 |
+
port_mappings = [
|
| 202 |
+
dict(mapping) for mapping in container.get("portMappings") or []
|
| 203 |
+
]
|
| 204 |
+
matched = False
|
| 205 |
+
for mapping in port_mappings:
|
| 206 |
+
if mapping.get("containerPort") == container_port:
|
| 207 |
+
matched = True
|
| 208 |
+
mapping["name"] = port_name
|
| 209 |
+
mapping.setdefault("protocol", "tcp")
|
| 210 |
+
if not matched and not has_matching_port and index == 0:
|
| 211 |
+
port_mappings.append(
|
| 212 |
+
{
|
| 213 |
+
"name": port_name,
|
| 214 |
+
"containerPort": container_port,
|
| 215 |
+
"protocol": "tcp",
|
| 216 |
+
}
|
| 217 |
+
)
|
| 218 |
+
container["portMappings"] = port_mappings
|
| 219 |
+
updated.append(container)
|
| 220 |
+
return updated
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
def resolve_service_task_definition_arn(
|
| 224 |
+
cluster_name: str,
|
| 225 |
+
service_name: str,
|
| 226 |
+
aws_region: str = AWS_REGION,
|
| 227 |
+
) -> str:
|
| 228 |
+
"""
|
| 229 |
+
Resolve the task definition ARN for a Fargate or Express gateway ECS service.
|
| 230 |
+
|
| 231 |
+
Express gateway services omit ``taskDefinition`` on ``describe_services``; use the
|
| 232 |
+
active service revision from ``describe_express_gateway_service`` instead.
|
| 233 |
+
"""
|
| 234 |
+
ecs_client = boto3.client("ecs", region_name=aws_region)
|
| 235 |
+
services = ecs_client.describe_services(
|
| 236 |
+
cluster=cluster_name, services=[service_name]
|
| 237 |
+
).get("services", [])
|
| 238 |
+
if services:
|
| 239 |
+
task_definition_arn = services[0].get("taskDefinition")
|
| 240 |
+
if task_definition_arn:
|
| 241 |
+
return task_definition_arn
|
| 242 |
+
service_arn = services[0].get("serviceArn")
|
| 243 |
+
else:
|
| 244 |
+
service_arn = None
|
| 245 |
+
|
| 246 |
+
if not service_arn:
|
| 247 |
+
service_arn = resolve_express_gateway_service_arn(
|
| 248 |
+
cluster_name, service_name, aws_region
|
| 249 |
+
)
|
| 250 |
+
|
| 251 |
+
express = ecs_client.describe_express_gateway_service(serviceArn=service_arn)
|
| 252 |
+
active_configs = (express.get("service") or {}).get("activeConfigurations") or []
|
| 253 |
+
if not active_configs:
|
| 254 |
+
raise ValueError(
|
| 255 |
+
f"Could not resolve task definition for service '{service_name}' in "
|
| 256 |
+
f"cluster '{cluster_name}' (no active Express gateway configuration)."
|
| 257 |
+
)
|
| 258 |
+
revision_arn = active_configs[0].get("serviceRevisionArn")
|
| 259 |
+
if not revision_arn:
|
| 260 |
+
raise ValueError(
|
| 261 |
+
f"Could not resolve task definition for service '{service_name}' "
|
| 262 |
+
"(active Express configuration has no serviceRevisionArn)."
|
| 263 |
+
)
|
| 264 |
+
revisions = ecs_client.describe_service_revisions(
|
| 265 |
+
serviceRevisionArns=[revision_arn]
|
| 266 |
+
).get("serviceRevisions", [])
|
| 267 |
+
if not revisions:
|
| 268 |
+
raise ValueError(
|
| 269 |
+
f"Service revision '{revision_arn}' not found for service "
|
| 270 |
+
f"'{service_name}'."
|
| 271 |
+
)
|
| 272 |
+
task_definition_arn = revisions[0].get("taskDefinition")
|
| 273 |
+
if not task_definition_arn:
|
| 274 |
+
raise ValueError(
|
| 275 |
+
f"Service revision '{revision_arn}' has no taskDefinition for service "
|
| 276 |
+
f"'{service_name}'."
|
| 277 |
+
)
|
| 278 |
+
return task_definition_arn
|
| 279 |
+
|
| 280 |
+
|
| 281 |
+
def ensure_ecs_service_port_mapping_name(
|
| 282 |
+
cluster_name: str,
|
| 283 |
+
service_name: str,
|
| 284 |
+
port_name: str,
|
| 285 |
+
container_port: int,
|
| 286 |
+
aws_region: str = AWS_REGION,
|
| 287 |
+
) -> str:
|
| 288 |
+
"""
|
| 289 |
+
Service Connect requires a named portMapping in the task definition.
|
| 290 |
+
Express gateway services only set containerPort at create time.
|
| 291 |
+
"""
|
| 292 |
+
ecs_client = boto3.client("ecs", region_name=aws_region)
|
| 293 |
+
task_definition_arn = resolve_service_task_definition_arn(
|
| 294 |
+
cluster_name, service_name, aws_region
|
| 295 |
+
)
|
| 296 |
+
task_definition = ecs_client.describe_task_definition(
|
| 297 |
+
taskDefinition=task_definition_arn
|
| 298 |
+
)["taskDefinition"]
|
| 299 |
+
if _task_definition_has_port_name(task_definition, port_name):
|
| 300 |
+
return task_definition_arn
|
| 301 |
+
|
| 302 |
+
new_containers = _container_definitions_with_named_port(
|
| 303 |
+
task_definition["containerDefinitions"],
|
| 304 |
+
port_name=port_name,
|
| 305 |
+
container_port=container_port,
|
| 306 |
+
)
|
| 307 |
+
register_kwargs = {
|
| 308 |
+
key: copy.deepcopy(task_definition[key])
|
| 309 |
+
for key in _TASK_DEF_REGISTER_KEYS
|
| 310 |
+
if key in task_definition
|
| 311 |
+
}
|
| 312 |
+
register_kwargs["containerDefinitions"] = new_containers
|
| 313 |
+
if task_definition.get("tags"):
|
| 314 |
+
register_kwargs["tags"] = [
|
| 315 |
+
{"key": tag["key"], "value": tag["value"]}
|
| 316 |
+
for tag in task_definition["tags"]
|
| 317 |
+
]
|
| 318 |
+
|
| 319 |
+
new_task_definition = ecs_client.register_task_definition(**register_kwargs)[
|
| 320 |
+
"taskDefinition"
|
| 321 |
+
]
|
| 322 |
+
new_arn = new_task_definition["taskDefinitionArn"]
|
| 323 |
+
ecs_client.update_service(
|
| 324 |
+
cluster=cluster_name,
|
| 325 |
+
service=service_name,
|
| 326 |
+
taskDefinition=new_arn,
|
| 327 |
+
forceNewDeployment=True,
|
| 328 |
+
)
|
| 329 |
+
print(
|
| 330 |
+
f"Registered task definition {new_arn} with Service Connect port "
|
| 331 |
+
f"name {port_name!r} on container port {container_port}."
|
| 332 |
+
)
|
| 333 |
+
return new_arn
|
| 334 |
+
|
| 335 |
+
|
| 336 |
+
def apply_ecs_service_connect(
|
| 337 |
+
cluster_name: str,
|
| 338 |
+
service_name: str,
|
| 339 |
+
service_connect_configuration: Dict[str, Any],
|
| 340 |
+
aws_region: str = AWS_REGION,
|
| 341 |
+
) -> None:
|
| 342 |
+
ecs_client = boto3.client("ecs", region_name=aws_region)
|
| 343 |
+
ecs_client.update_service(
|
| 344 |
+
cluster=cluster_name,
|
| 345 |
+
service=service_name,
|
| 346 |
+
serviceConnectConfiguration=service_connect_configuration,
|
| 347 |
+
forceNewDeployment=True,
|
| 348 |
+
)
|
| 349 |
+
print(f"Applied Service Connect to {service_name} in cluster {cluster_name}.")
|
| 350 |
+
|
| 351 |
+
|
| 352 |
+
def configure_express_pi_service_connect(
|
| 353 |
+
cluster_name: str,
|
| 354 |
+
main_service_name: str,
|
| 355 |
+
pi_service_name: str,
|
| 356 |
+
namespace: str,
|
| 357 |
+
main_port_name: str,
|
| 358 |
+
discovery_name: str,
|
| 359 |
+
main_port: int,
|
| 360 |
+
aws_region: str = AWS_REGION,
|
| 361 |
+
) -> None:
|
| 362 |
+
"""Enable Service Connect for Pi Express -> main Express (post image build)."""
|
| 363 |
+
ensure_ecs_service_port_mapping_name(
|
| 364 |
+
cluster_name,
|
| 365 |
+
main_service_name,
|
| 366 |
+
main_port_name,
|
| 367 |
+
main_port,
|
| 368 |
+
aws_region=aws_region,
|
| 369 |
+
)
|
| 370 |
+
apply_ecs_service_connect(
|
| 371 |
+
cluster_name,
|
| 372 |
+
main_service_name,
|
| 373 |
+
{
|
| 374 |
+
"enabled": True,
|
| 375 |
+
"namespace": namespace,
|
| 376 |
+
"services": [
|
| 377 |
+
{
|
| 378 |
+
"portName": main_port_name,
|
| 379 |
+
"discoveryName": discovery_name,
|
| 380 |
+
"clientAliases": [
|
| 381 |
+
{"port": int(main_port), "dnsName": discovery_name}
|
| 382 |
+
],
|
| 383 |
+
}
|
| 384 |
+
],
|
| 385 |
+
},
|
| 386 |
+
aws_region=aws_region,
|
| 387 |
+
)
|
| 388 |
+
apply_ecs_service_connect(
|
| 389 |
+
cluster_name,
|
| 390 |
+
pi_service_name,
|
| 391 |
+
{"enabled": True, "namespace": namespace},
|
| 392 |
+
aws_region=aws_region,
|
| 393 |
+
)
|
| 394 |
+
|
| 395 |
+
|
| 396 |
+
def start_express_gateway_service(
|
| 397 |
+
cluster_name: str,
|
| 398 |
+
service_name: str,
|
| 399 |
+
aws_region: str = AWS_REGION,
|
| 400 |
+
) -> dict:
|
| 401 |
+
"""Scale an ECS Express gateway service to one running task after image build."""
|
| 402 |
+
ecs_client = boto3.client("ecs", region_name=aws_region)
|
| 403 |
+
|
| 404 |
+
try:
|
| 405 |
+
service_arn = resolve_express_gateway_service_arn(
|
| 406 |
+
cluster_name, service_name, aws_region=aws_region
|
| 407 |
+
)
|
| 408 |
+
ecs_client.update_express_gateway_service(
|
| 409 |
+
serviceArn=service_arn,
|
| 410 |
+
scalingTarget=EXPRESS_GATEWAY_ACTIVE_SCALING_TARGET,
|
| 411 |
+
)
|
| 412 |
+
return {
|
| 413 |
+
"statusCode": 200,
|
| 414 |
+
"body": (
|
| 415 |
+
f"Express service {service_name} in cluster {cluster_name} "
|
| 416 |
+
"has been updated to run 1 task."
|
| 417 |
+
),
|
| 418 |
+
}
|
| 419 |
+
except Exception as e:
|
| 420 |
+
return {
|
| 421 |
+
"statusCode": 500,
|
| 422 |
+
"body": f"Error updating Express gateway service: {str(e)}",
|
| 423 |
+
}
|
| 424 |
+
|
| 425 |
+
|
| 426 |
+
_ALB_COGNITO_CALLBACK_SUFFIX = "/oauth2/idpresponse"
|
| 427 |
+
|
| 428 |
+
# Fields preserved from describe_user_pool_client when updating CallbackURLs only.
|
| 429 |
+
_USER_POOL_CLIENT_UPDATE_PASSTHROUGH_KEYS = (
|
| 430 |
+
"ClientName",
|
| 431 |
+
"RefreshTokenValidity",
|
| 432 |
+
"AccessTokenValidity",
|
| 433 |
+
"IdTokenValidity",
|
| 434 |
+
"TokenValidityUnits",
|
| 435 |
+
"ReadAttributes",
|
| 436 |
+
"WriteAttributes",
|
| 437 |
+
"ExplicitAuthFlows",
|
| 438 |
+
"SupportedIdentityProviders",
|
| 439 |
+
"DefaultRedirectURI",
|
| 440 |
+
"AllowedOAuthFlows",
|
| 441 |
+
"AllowedOAuthScopes",
|
| 442 |
+
"AllowedOAuthFlowsUserPoolClient",
|
| 443 |
+
"AnalyticsConfiguration",
|
| 444 |
+
"PreventUserExistenceErrors",
|
| 445 |
+
"EnableTokenRevocation",
|
| 446 |
+
"EnablePropagateAdditionalUserContextData",
|
| 447 |
+
"AuthSessionValidity",
|
| 448 |
+
"RefreshTokenRotation",
|
| 449 |
+
)
|
| 450 |
+
|
| 451 |
+
|
| 452 |
+
def cognito_https_callback_urls(redirect_base: str) -> List[str]:
|
| 453 |
+
"""
|
| 454 |
+
ALB authenticate-cognito requires the app URL and ``/oauth2/idpresponse``.
|
| 455 |
+
"""
|
| 456 |
+
base = (redirect_base or "").strip().rstrip("/")
|
| 457 |
+
if not base:
|
| 458 |
+
raise ValueError("redirect_base is required for Cognito callback URLs")
|
| 459 |
+
if not base.startswith("https://"):
|
| 460 |
+
base = f"https://{base.lstrip('/')}"
|
| 461 |
+
return [base, f"{base}{_ALB_COGNITO_CALLBACK_SUFFIX}"]
|
| 462 |
+
|
| 463 |
+
|
| 464 |
+
def cognito_callback_urls_match(
|
| 465 |
+
existing_callbacks: List[str],
|
| 466 |
+
desired_callbacks: List[str],
|
| 467 |
+
) -> bool:
|
| 468 |
+
return set(existing_callbacks or []) == set(desired_callbacks)
|
| 469 |
+
|
| 470 |
+
|
| 471 |
+
def get_user_pool_client_callback_urls(
|
| 472 |
+
user_pool_id: str,
|
| 473 |
+
client_id: str,
|
| 474 |
+
*,
|
| 475 |
+
aws_region: str = AWS_REGION,
|
| 476 |
+
) -> List[str]:
|
| 477 |
+
cognito_client = boto3.client("cognito-idp", region_name=aws_region)
|
| 478 |
+
existing = cognito_client.describe_user_pool_client(
|
| 479 |
+
UserPoolId=user_pool_id,
|
| 480 |
+
ClientId=client_id,
|
| 481 |
+
)["UserPoolClient"]
|
| 482 |
+
return list(existing.get("CallbackURLs") or [])
|
| 483 |
+
|
| 484 |
+
|
| 485 |
+
def cognito_alb_callbacks_need_update(
|
| 486 |
+
user_pool_id: str,
|
| 487 |
+
client_id: str,
|
| 488 |
+
redirect_base: str,
|
| 489 |
+
*,
|
| 490 |
+
aws_region: str = AWS_REGION,
|
| 491 |
+
) -> bool:
|
| 492 |
+
desired = cognito_https_callback_urls(redirect_base)
|
| 493 |
+
current = get_user_pool_client_callback_urls(
|
| 494 |
+
user_pool_id, client_id, aws_region=aws_region
|
| 495 |
+
)
|
| 496 |
+
return not cognito_callback_urls_match(current, desired)
|
| 497 |
+
|
| 498 |
+
|
| 499 |
+
def update_user_pool_client_callback_urls(
|
| 500 |
+
user_pool_id: str,
|
| 501 |
+
client_id: str,
|
| 502 |
+
callback_urls: List[str],
|
| 503 |
+
*,
|
| 504 |
+
aws_region: str = AWS_REGION,
|
| 505 |
+
) -> None:
|
| 506 |
+
"""
|
| 507 |
+
Set Cognito app client callback URLs without a CDK redeploy.
|
| 508 |
+
|
| 509 |
+
Merges existing client settings from ``describe_user_pool_client`` so OAuth
|
| 510 |
+
flows/scopes and token validity are not reset.
|
| 511 |
+
"""
|
| 512 |
+
cognito_client = boto3.client("cognito-idp", region_name=aws_region)
|
| 513 |
+
existing = cognito_client.describe_user_pool_client(
|
| 514 |
+
UserPoolId=user_pool_id,
|
| 515 |
+
ClientId=client_id,
|
| 516 |
+
)["UserPoolClient"]
|
| 517 |
+
|
| 518 |
+
update_kwargs: Dict[str, Any] = {
|
| 519 |
+
"UserPoolId": user_pool_id,
|
| 520 |
+
"ClientId": client_id,
|
| 521 |
+
"CallbackURLs": callback_urls,
|
| 522 |
+
}
|
| 523 |
+
for key in _USER_POOL_CLIENT_UPDATE_PASSTHROUGH_KEYS:
|
| 524 |
+
value = existing.get(key)
|
| 525 |
+
if value is not None:
|
| 526 |
+
update_kwargs[key] = value
|
| 527 |
+
logout_urls = existing.get("LogoutURLs")
|
| 528 |
+
if logout_urls:
|
| 529 |
+
update_kwargs["LogoutURLs"] = logout_urls
|
| 530 |
+
|
| 531 |
+
cognito_client.update_user_pool_client(**update_kwargs)
|
| 532 |
+
print("Updated Cognito app client callback URLs: " + ", ".join(callback_urls))
|
| 533 |
+
|
| 534 |
+
|
| 535 |
+
def apply_cognito_alb_callback_fixup(
|
| 536 |
+
*,
|
| 537 |
+
user_pool_id: str,
|
| 538 |
+
client_id: str,
|
| 539 |
+
redirect_base: str,
|
| 540 |
+
aws_region: str = AWS_REGION,
|
| 541 |
+
) -> bool:
|
| 542 |
+
"""
|
| 543 |
+
Update Cognito callbacks when they differ from ``redirect_base``.
|
| 544 |
+
|
| 545 |
+
Returns True if URLs were updated, False if already correct.
|
| 546 |
+
"""
|
| 547 |
+
desired = cognito_https_callback_urls(redirect_base)
|
| 548 |
+
cognito_client = boto3.client("cognito-idp", region_name=aws_region)
|
| 549 |
+
existing = cognito_client.describe_user_pool_client(
|
| 550 |
+
UserPoolId=user_pool_id,
|
| 551 |
+
ClientId=client_id,
|
| 552 |
+
)["UserPoolClient"]
|
| 553 |
+
current = existing.get("CallbackURLs") or []
|
| 554 |
+
if cognito_callback_urls_match(current, desired):
|
| 555 |
+
print("Cognito app client callback URLs already match the target endpoint.")
|
| 556 |
+
return False
|
| 557 |
+
update_user_pool_client_callback_urls(
|
| 558 |
+
user_pool_id,
|
| 559 |
+
client_id,
|
| 560 |
+
desired,
|
| 561 |
+
aws_region=aws_region,
|
| 562 |
+
)
|
| 563 |
+
return True
|
| 564 |
+
|
| 565 |
+
|
| 566 |
+
_TARGET_GROUP_REGISTER_EVENT = re.compile(
|
| 567 |
+
r"target-group (arn:aws:elasticloadbalancing:[^\s)]+)",
|
| 568 |
+
re.IGNORECASE,
|
| 569 |
+
)
|
| 570 |
+
|
| 571 |
+
EXPRESS_TARGET_GROUP_RESOLVE_MAX_WAIT_SECONDS = 600
|
| 572 |
+
EXPRESS_TARGET_GROUP_RESOLVE_POLL_INTERVAL_SECONDS = 15
|
| 573 |
+
|
| 574 |
+
|
| 575 |
+
def target_group_arn_from_ecs_register_event(message: str) -> Optional[str]:
|
| 576 |
+
"""Parse target group ARN from ECS ``registered N targets in (target-group ...)``."""
|
| 577 |
+
if "registered" not in (message or "").lower():
|
| 578 |
+
return None
|
| 579 |
+
match = _TARGET_GROUP_REGISTER_EVENT.search(message)
|
| 580 |
+
return match.group(1) if match else None
|
| 581 |
+
|
| 582 |
+
|
| 583 |
+
def _target_group_arn_from_service_events(
|
| 584 |
+
events: List[Dict[str, Any]],
|
| 585 |
+
) -> Optional[str]:
|
| 586 |
+
for event in events:
|
| 587 |
+
target_group_arn = target_group_arn_from_ecs_register_event(
|
| 588 |
+
event.get("message", "")
|
| 589 |
+
)
|
| 590 |
+
if target_group_arn:
|
| 591 |
+
return target_group_arn
|
| 592 |
+
return None
|
| 593 |
+
|
| 594 |
+
|
| 595 |
+
def _task_private_ipv4_addresses(
|
| 596 |
+
ecs_client: Any,
|
| 597 |
+
cluster_name: str,
|
| 598 |
+
service_name: str,
|
| 599 |
+
) -> set[str]:
|
| 600 |
+
task_arns = ecs_client.list_tasks(
|
| 601 |
+
cluster=cluster_name, serviceName=service_name
|
| 602 |
+
).get("taskArns", [])
|
| 603 |
+
if not task_arns:
|
| 604 |
+
return set()
|
| 605 |
+
tasks = ecs_client.describe_tasks(cluster=cluster_name, tasks=task_arns).get(
|
| 606 |
+
"tasks", []
|
| 607 |
+
)
|
| 608 |
+
addresses: set[str] = set()
|
| 609 |
+
for task in tasks:
|
| 610 |
+
for attachment in task.get("attachments", []):
|
| 611 |
+
for detail in attachment.get("details", []):
|
| 612 |
+
if detail.get("name") == "privateIPv4Address" and detail.get("value"):
|
| 613 |
+
addresses.add(detail["value"])
|
| 614 |
+
return addresses
|
| 615 |
+
|
| 616 |
+
|
| 617 |
+
def _target_group_arn_from_task_ips(
|
| 618 |
+
elbv2_client: Any,
|
| 619 |
+
load_balancer_arn: str,
|
| 620 |
+
task_ips: set[str],
|
| 621 |
+
) -> Optional[str]:
|
| 622 |
+
if not task_ips:
|
| 623 |
+
return None
|
| 624 |
+
target_groups = elbv2_client.describe_target_groups(
|
| 625 |
+
LoadBalancerArn=load_balancer_arn
|
| 626 |
+
).get("TargetGroups", [])
|
| 627 |
+
for target_group in target_groups:
|
| 628 |
+
health = elbv2_client.describe_target_health(
|
| 629 |
+
TargetGroupArn=target_group["TargetGroupArn"]
|
| 630 |
+
).get("TargetHealthDescriptions", [])
|
| 631 |
+
for description in health:
|
| 632 |
+
target_id = (description.get("Target") or {}).get("Id")
|
| 633 |
+
if target_id in task_ips:
|
| 634 |
+
return target_group["TargetGroupArn"]
|
| 635 |
+
return None
|
| 636 |
+
|
| 637 |
+
|
| 638 |
+
def resolve_express_service_target_group_arn(
|
| 639 |
+
cluster_name: str,
|
| 640 |
+
service_name: str,
|
| 641 |
+
*,
|
| 642 |
+
aws_region: str = AWS_REGION,
|
| 643 |
+
load_balancer_arn: Optional[str] = None,
|
| 644 |
+
max_wait_seconds: int = EXPRESS_TARGET_GROUP_RESOLVE_MAX_WAIT_SECONDS,
|
| 645 |
+
poll_interval_seconds: int = EXPRESS_TARGET_GROUP_RESOLVE_POLL_INTERVAL_SECONDS,
|
| 646 |
+
) -> str:
|
| 647 |
+
"""
|
| 648 |
+
Target group where Express most recently registered tasks.
|
| 649 |
+
|
| 650 |
+
After post-deploy scaling, this ARN can differ from the TG baked into the CDK
|
| 651 |
+
Cognito listener custom resource at deploy time. Polls until a registration
|
| 652 |
+
event appears or running tasks are visible in an Express ALB target group.
|
| 653 |
+
"""
|
| 654 |
+
ecs_client = boto3.client("ecs", region_name=aws_region)
|
| 655 |
+
elbv2_client = (
|
| 656 |
+
boto3.client("elbv2", region_name=aws_region) if load_balancer_arn else None
|
| 657 |
+
)
|
| 658 |
+
deadline = time.monotonic() + max_wait_seconds
|
| 659 |
+
attempt = 0
|
| 660 |
+
while True:
|
| 661 |
+
attempt += 1
|
| 662 |
+
services = ecs_client.describe_services(
|
| 663 |
+
cluster=cluster_name, services=[service_name]
|
| 664 |
+
).get("services", [])
|
| 665 |
+
if not services:
|
| 666 |
+
raise ValueError(
|
| 667 |
+
f"ECS service '{service_name}' not found in cluster '{cluster_name}'."
|
| 668 |
+
)
|
| 669 |
+
service = services[0]
|
| 670 |
+
target_group_arn = _target_group_arn_from_service_events(
|
| 671 |
+
service.get("events", [])
|
| 672 |
+
)
|
| 673 |
+
if target_group_arn:
|
| 674 |
+
if attempt > 1:
|
| 675 |
+
print(
|
| 676 |
+
f"Resolved target group for '{service_name}' "
|
| 677 |
+
f"after {attempt} poll(s)."
|
| 678 |
+
)
|
| 679 |
+
return target_group_arn
|
| 680 |
+
|
| 681 |
+
if elbv2_client and load_balancer_arn:
|
| 682 |
+
task_ips = _task_private_ipv4_addresses(
|
| 683 |
+
ecs_client, cluster_name, service_name
|
| 684 |
+
)
|
| 685 |
+
target_group_arn = _target_group_arn_from_task_ips(
|
| 686 |
+
elbv2_client, load_balancer_arn, task_ips
|
| 687 |
+
)
|
| 688 |
+
if target_group_arn:
|
| 689 |
+
print(
|
| 690 |
+
f"Resolved target group for '{service_name}' from running task IPs."
|
| 691 |
+
)
|
| 692 |
+
return target_group_arn
|
| 693 |
+
|
| 694 |
+
if time.monotonic() >= deadline:
|
| 695 |
+
running = service.get("runningCount", 0)
|
| 696 |
+
desired = service.get("desiredCount", 0)
|
| 697 |
+
raise ValueError(
|
| 698 |
+
f"No target group registration event found for service "
|
| 699 |
+
f"'{service_name}' after {max_wait_seconds}s "
|
| 700 |
+
f"(running {running}/{desired} tasks). "
|
| 701 |
+
"Ensure CodeBuild finished and the service scaled to at least one task."
|
| 702 |
+
)
|
| 703 |
+
|
| 704 |
+
if attempt == 1:
|
| 705 |
+
print(
|
| 706 |
+
f"Waiting for target group registration for '{service_name}' "
|
| 707 |
+
f"(up to {max_wait_seconds}s)..."
|
| 708 |
+
)
|
| 709 |
+
time.sleep(poll_interval_seconds)
|
| 710 |
+
|
| 711 |
+
|
| 712 |
+
def find_express_gateway_https_listener(
|
| 713 |
+
*,
|
| 714 |
+
aws_region: str = AWS_REGION,
|
| 715 |
+
) -> Dict[str, str]:
|
| 716 |
+
"""Return Express-managed ALB HTTPS listener metadata."""
|
| 717 |
+
elbv2 = boto3.client("elbv2", region_name=aws_region)
|
| 718 |
+
for load_balancer in elbv2.describe_load_balancers().get("LoadBalancers", []):
|
| 719 |
+
if not load_balancer["LoadBalancerName"].startswith("ecs-express-gateway-alb"):
|
| 720 |
+
continue
|
| 721 |
+
listeners = elbv2.describe_listeners(
|
| 722 |
+
LoadBalancerArn=load_balancer["LoadBalancerArn"]
|
| 723 |
+
).get("Listeners", [])
|
| 724 |
+
https_listener = next(
|
| 725 |
+
(listener for listener in listeners if listener.get("Port") == 443),
|
| 726 |
+
None,
|
| 727 |
+
)
|
| 728 |
+
if https_listener:
|
| 729 |
+
return {
|
| 730 |
+
"load_balancer_arn": load_balancer["LoadBalancerArn"],
|
| 731 |
+
"listener_arn": https_listener["ListenerArn"],
|
| 732 |
+
"dns_name": load_balancer["DNSName"],
|
| 733 |
+
}
|
| 734 |
+
raise ValueError(
|
| 735 |
+
"Express gateway ALB (ecs-express-gateway-alb-*) with HTTPS listener not found."
|
| 736 |
+
)
|
| 737 |
+
|
| 738 |
+
|
| 739 |
+
def listener_actions_with_target_group(
|
| 740 |
+
existing_actions: List[Dict[str, Any]],
|
| 741 |
+
target_group_arn: str,
|
| 742 |
+
) -> List[Dict[str, Any]]:
|
| 743 |
+
"""Copy listener/rule actions, replacing the forward target group ARN."""
|
| 744 |
+
updated_actions: List[Dict[str, Any]] = []
|
| 745 |
+
for action in sorted(existing_actions, key=lambda item: item.get("Order", 0)):
|
| 746 |
+
action_copy = copy.deepcopy(action)
|
| 747 |
+
if action_copy.get("Type") == "forward":
|
| 748 |
+
action_copy["TargetGroupArn"] = target_group_arn
|
| 749 |
+
forward_config = action_copy.setdefault("ForwardConfig", {})
|
| 750 |
+
forward_config["TargetGroups"] = [
|
| 751 |
+
{"TargetGroupArn": target_group_arn, "Weight": 1}
|
| 752 |
+
]
|
| 753 |
+
updated_actions.append(action_copy)
|
| 754 |
+
return updated_actions
|
| 755 |
+
|
| 756 |
+
|
| 757 |
+
def apply_express_alb_listener_target_group_fixup(
|
| 758 |
+
*,
|
| 759 |
+
cluster_name: str,
|
| 760 |
+
main_service_name: str,
|
| 761 |
+
pi_service_name: Optional[str] = None,
|
| 762 |
+
pi_path_prefixes: Optional[List[str]] = None,
|
| 763 |
+
aws_region: str = AWS_REGION,
|
| 764 |
+
) -> bool:
|
| 765 |
+
"""
|
| 766 |
+
Point ALB Cognito listener actions at the target groups Express tasks use.
|
| 767 |
+
|
| 768 |
+
Express creates fresh target groups when a service scales up after deploy; the
|
| 769 |
+
CDK custom resource may still forward authenticated traffic to an empty TG.
|
| 770 |
+
"""
|
| 771 |
+
ingress = find_express_gateway_https_listener(aws_region=aws_region)
|
| 772 |
+
load_balancer_arn = ingress["load_balancer_arn"]
|
| 773 |
+
main_target_group_arn = resolve_express_service_target_group_arn(
|
| 774 |
+
cluster_name,
|
| 775 |
+
main_service_name,
|
| 776 |
+
aws_region=aws_region,
|
| 777 |
+
load_balancer_arn=load_balancer_arn,
|
| 778 |
+
)
|
| 779 |
+
pi_target_group_arn = None
|
| 780 |
+
if pi_service_name:
|
| 781 |
+
try:
|
| 782 |
+
pi_target_group_arn = resolve_express_service_target_group_arn(
|
| 783 |
+
cluster_name,
|
| 784 |
+
pi_service_name,
|
| 785 |
+
aws_region=aws_region,
|
| 786 |
+
load_balancer_arn=load_balancer_arn,
|
| 787 |
+
)
|
| 788 |
+
except ValueError as exc:
|
| 789 |
+
print(f"Note: skipping Pi listener rule TG fixup: {exc}")
|
| 790 |
+
|
| 791 |
+
elbv2 = boto3.client("elbv2", region_name=aws_region)
|
| 792 |
+
listener_arn = ingress["listener_arn"]
|
| 793 |
+
listener = elbv2.describe_listeners(ListenerArns=[listener_arn])["Listeners"][0]
|
| 794 |
+
current_default = listener.get("DefaultActions", [])
|
| 795 |
+
current_forward_arn = next(
|
| 796 |
+
(
|
| 797 |
+
action.get("TargetGroupArn")
|
| 798 |
+
for action in current_default
|
| 799 |
+
if action.get("Type") == "forward"
|
| 800 |
+
),
|
| 801 |
+
None,
|
| 802 |
+
)
|
| 803 |
+
changed = current_forward_arn != main_target_group_arn
|
| 804 |
+
|
| 805 |
+
if changed:
|
| 806 |
+
elbv2.modify_listener(
|
| 807 |
+
ListenerArn=listener_arn,
|
| 808 |
+
DefaultActions=listener_actions_with_target_group(
|
| 809 |
+
current_default, main_target_group_arn
|
| 810 |
+
),
|
| 811 |
+
)
|
| 812 |
+
print(
|
| 813 |
+
"Updated Express ALB default listener forward target group to "
|
| 814 |
+
f"{main_target_group_arn}."
|
| 815 |
+
)
|
| 816 |
+
else:
|
| 817 |
+
print(
|
| 818 |
+
"Express ALB default listener already forwards to the active target group."
|
| 819 |
+
)
|
| 820 |
+
|
| 821 |
+
if pi_target_group_arn and pi_path_prefixes:
|
| 822 |
+
rules = elbv2.describe_rules(ListenerArn=listener_arn).get("Rules", [])
|
| 823 |
+
prefixes = {prefix.rstrip("/") for prefix in pi_path_prefixes}
|
| 824 |
+
for rule in rules:
|
| 825 |
+
if rule.get("IsDefault"):
|
| 826 |
+
continue
|
| 827 |
+
path_values = []
|
| 828 |
+
for condition in rule.get("Conditions", []):
|
| 829 |
+
if condition.get("Field") == "path-pattern":
|
| 830 |
+
path_values.extend(condition.get("Values", []))
|
| 831 |
+
if not prefixes.intersection({value.rstrip("/") for value in path_values}):
|
| 832 |
+
continue
|
| 833 |
+
current_actions = rule.get("Actions", [])
|
| 834 |
+
current_pi_forward = next(
|
| 835 |
+
(
|
| 836 |
+
action.get("TargetGroupArn")
|
| 837 |
+
for action in current_actions
|
| 838 |
+
if action.get("Type") == "forward"
|
| 839 |
+
),
|
| 840 |
+
None,
|
| 841 |
+
)
|
| 842 |
+
if current_pi_forward == pi_target_group_arn:
|
| 843 |
+
continue
|
| 844 |
+
elbv2.modify_rule(
|
| 845 |
+
RuleArn=rule["RuleArn"],
|
| 846 |
+
Actions=listener_actions_with_target_group(
|
| 847 |
+
current_actions, pi_target_group_arn
|
| 848 |
+
),
|
| 849 |
+
)
|
| 850 |
+
print(
|
| 851 |
+
"Updated Pi ALB listener rule forward target group to "
|
| 852 |
+
f"{pi_target_group_arn}."
|
| 853 |
+
)
|
| 854 |
+
changed = True
|
| 855 |
+
|
| 856 |
+
return changed
|
| 857 |
+
|
| 858 |
+
|
| 859 |
+
def listener_rule_has_cognito_auth(actions: List[Dict[str, Any]]) -> bool:
|
| 860 |
+
return any(action.get("Type") == "authenticate-cognito" for action in actions)
|
| 861 |
+
|
| 862 |
+
|
| 863 |
+
def _listener_rule_is_cloudfront_bypass_without_cognito(
|
| 864 |
+
rule: Dict[str, Any],
|
| 865 |
+
*,
|
| 866 |
+
cloudfront_host_header: str,
|
| 867 |
+
) -> bool:
|
| 868 |
+
"""True for legacy forward-only host-header rules matching the CloudFront domain."""
|
| 869 |
+
if listener_rule_has_cognito_auth(rule.get("Actions", [])):
|
| 870 |
+
return False
|
| 871 |
+
host = (cloudfront_host_header or "").strip()
|
| 872 |
+
if not host or host == "cloudfront_placeholder.net":
|
| 873 |
+
return False
|
| 874 |
+
for condition in rule.get("Conditions") or []:
|
| 875 |
+
if condition.get("Field") != "host-header":
|
| 876 |
+
continue
|
| 877 |
+
values = (condition.get("HostHeaderConfig") or {}).get("Values") or []
|
| 878 |
+
if host in values:
|
| 879 |
+
return True
|
| 880 |
+
return False
|
| 881 |
+
|
| 882 |
+
|
| 883 |
+
def remove_express_listener_rules_without_cognito(
|
| 884 |
+
*,
|
| 885 |
+
aws_region: str = AWS_REGION,
|
| 886 |
+
cloudfront_host_header: Optional[str] = None,
|
| 887 |
+
) -> bool:
|
| 888 |
+
"""
|
| 889 |
+
Delete legacy Express ALB rules that forward CloudFront host traffic without Cognito.
|
| 890 |
+
|
| 891 |
+
Only removes host-header rules whose value matches ``CLOUDFRONT_DOMAIN`` (or the
|
| 892 |
+
supplied override). ECS Express-managed ``*.ecs.*.on.aws`` host rules are left
|
| 893 |
+
intact.
|
| 894 |
+
"""
|
| 895 |
+
cloudfront_host = (cloudfront_host_header or CLOUDFRONT_DOMAIN or "").strip()
|
| 896 |
+
ingress = find_express_gateway_https_listener(aws_region=aws_region)
|
| 897 |
+
elbv2 = boto3.client("elbv2", region_name=aws_region)
|
| 898 |
+
listener_arn = ingress["listener_arn"]
|
| 899 |
+
changed = False
|
| 900 |
+
for rule in elbv2.describe_rules(ListenerArn=listener_arn).get("Rules", []):
|
| 901 |
+
if rule.get("IsDefault"):
|
| 902 |
+
continue
|
| 903 |
+
if not _listener_rule_is_cloudfront_bypass_without_cognito(
|
| 904 |
+
rule, cloudfront_host_header=cloudfront_host
|
| 905 |
+
):
|
| 906 |
+
continue
|
| 907 |
+
rule_arn = rule["RuleArn"]
|
| 908 |
+
elbv2.delete_rule(RuleArn=rule_arn)
|
| 909 |
+
print(
|
| 910 |
+
"Removed legacy Express CloudFront bypass ALB listener rule "
|
| 911 |
+
f"(host {cloudfront_host!r}): {rule_arn}"
|
| 912 |
+
)
|
| 913 |
+
changed = True
|
| 914 |
+
return changed
|
| 915 |
+
|
| 916 |
+
|
| 917 |
+
def build_cognito_secret_payload(
|
| 918 |
+
user_pool_id: str,
|
| 919 |
+
client_id: str,
|
| 920 |
+
*,
|
| 921 |
+
aws_region: str = AWS_REGION,
|
| 922 |
+
) -> Dict[str, str]:
|
| 923 |
+
"""Build Secrets Manager JSON for SUMMARISATION_* Cognito keys."""
|
| 924 |
+
cognito_client = boto3.client("cognito-idp", region_name=aws_region)
|
| 925 |
+
client = cognito_client.describe_user_pool_client(
|
| 926 |
+
UserPoolId=user_pool_id,
|
| 927 |
+
ClientId=client_id,
|
| 928 |
+
)["UserPoolClient"]
|
| 929 |
+
client_secret = client.get("ClientSecret") or ""
|
| 930 |
+
return {
|
| 931 |
+
"SUMMARISATION_USER_POOL_ID": user_pool_id,
|
| 932 |
+
"SUMMARISATION_CLIENT_ID": client_id,
|
| 933 |
+
"SUMMARISATION_CLIENT_SECRET": client_secret,
|
| 934 |
+
}
|
| 935 |
+
|
| 936 |
+
|
| 937 |
+
def cognito_secret_payload_matches(
|
| 938 |
+
existing_secret_string: str,
|
| 939 |
+
desired_payload: Dict[str, str],
|
| 940 |
+
) -> bool:
|
| 941 |
+
try:
|
| 942 |
+
current = json.loads(existing_secret_string or "{}")
|
| 943 |
+
except json.JSONDecodeError:
|
| 944 |
+
return False
|
| 945 |
+
return all(current.get(key) == value for key, value in desired_payload.items())
|
| 946 |
+
|
| 947 |
+
|
| 948 |
+
def apply_cognito_secret_fixup(
|
| 949 |
+
*,
|
| 950 |
+
secret_name: str,
|
| 951 |
+
user_pool_id: str,
|
| 952 |
+
client_id: str,
|
| 953 |
+
aws_region: str = AWS_REGION,
|
| 954 |
+
recycle_express_service: Optional[Dict[str, str]] = None,
|
| 955 |
+
) -> bool:
|
| 956 |
+
"""
|
| 957 |
+
Sync imported Secrets Manager JSON with the stack's Cognito pool and app client.
|
| 958 |
+
|
| 959 |
+
Express tasks read ``AWS_USER_POOL_ID`` / ``AWS_CLIENT_*`` from this secret.
|
| 960 |
+
When the secret predates a redeploy, values can reference a deleted user pool.
|
| 961 |
+
"""
|
| 962 |
+
desired_payload = build_cognito_secret_payload(
|
| 963 |
+
user_pool_id, client_id, aws_region=aws_region
|
| 964 |
+
)
|
| 965 |
+
secrets_client = boto3.client("secretsmanager", region_name=aws_region)
|
| 966 |
+
current = secrets_client.get_secret_value(SecretId=secret_name)
|
| 967 |
+
current_string = current.get("SecretString") or ""
|
| 968 |
+
if cognito_secret_payload_matches(current_string, desired_payload):
|
| 969 |
+
print(
|
| 970 |
+
"Cognito secret already matches Cognito user pool ID "
|
| 971 |
+
"and Cognito app client ID."
|
| 972 |
+
)
|
| 973 |
+
return False
|
| 974 |
+
|
| 975 |
+
secrets_client.put_secret_value(
|
| 976 |
+
SecretId=secret_name,
|
| 977 |
+
SecretString=json.dumps(desired_payload),
|
| 978 |
+
)
|
| 979 |
+
print(
|
| 980 |
+
"Updated Cognito secret for Cognito user pool ID " "and Cognito app client ID."
|
| 981 |
+
)
|
| 982 |
+
if recycle_express_service:
|
| 983 |
+
recycle_express_gateway_tasks(
|
| 984 |
+
recycle_express_service["cluster_name"],
|
| 985 |
+
recycle_express_service["service_name"],
|
| 986 |
+
aws_region=aws_region,
|
| 987 |
+
)
|
| 988 |
+
return True
|
| 989 |
+
|
| 990 |
+
|
| 991 |
+
def recycle_express_gateway_tasks(
|
| 992 |
+
cluster_name: str,
|
| 993 |
+
service_name: str,
|
| 994 |
+
*,
|
| 995 |
+
aws_region: str = AWS_REGION,
|
| 996 |
+
) -> None:
|
| 997 |
+
"""Stop running Express tasks so replacements pick up updated secrets/env."""
|
| 998 |
+
ecs_client = boto3.client("ecs", region_name=aws_region)
|
| 999 |
+
task_arns = ecs_client.list_tasks(
|
| 1000 |
+
cluster=cluster_name,
|
| 1001 |
+
serviceName=service_name,
|
| 1002 |
+
).get("taskArns", [])
|
| 1003 |
+
for task_arn in task_arns:
|
| 1004 |
+
ecs_client.stop_task(
|
| 1005 |
+
cluster=cluster_name,
|
| 1006 |
+
task=task_arn,
|
| 1007 |
+
reason="Recycle task after Cognito secret/config sync",
|
| 1008 |
+
)
|
| 1009 |
+
if task_arns:
|
| 1010 |
+
print(
|
| 1011 |
+
f"Stopped {len(task_arns)} task(s) for {service_name} to pick up Cognito updates."
|
| 1012 |
+
)
|
| 1013 |
+
|
| 1014 |
+
|
| 1015 |
+
def apply_express_disable_in_app_cognito_auth(
|
| 1016 |
+
cluster_name: str,
|
| 1017 |
+
service_name: str,
|
| 1018 |
+
*,
|
| 1019 |
+
aws_region: str = AWS_REGION,
|
| 1020 |
+
) -> bool:
|
| 1021 |
+
"""
|
| 1022 |
+
Set ``COGNITO_AUTH=False`` on a running Express service revision.
|
| 1023 |
+
|
| 1024 |
+
ALB ``authenticate-cognito`` already gates access; in-app Gradio login is redundant
|
| 1025 |
+
and fails when Secrets Manager still references an old user pool.
|
| 1026 |
+
"""
|
| 1027 |
+
ecs_client = boto3.client("ecs", region_name=aws_region)
|
| 1028 |
+
service_arn = resolve_express_gateway_service_arn(
|
| 1029 |
+
cluster_name, service_name, aws_region=aws_region
|
| 1030 |
+
)
|
| 1031 |
+
express = ecs_client.describe_express_gateway_service(serviceArn=service_arn)[
|
| 1032 |
+
"service"
|
| 1033 |
+
]
|
| 1034 |
+
active_configs = express.get("activeConfigurations") or []
|
| 1035 |
+
if not active_configs:
|
| 1036 |
+
raise ValueError(
|
| 1037 |
+
f"No active configuration for Express service '{service_name}'."
|
| 1038 |
+
)
|
| 1039 |
+
active = active_configs[0]
|
| 1040 |
+
primary = copy.deepcopy(active.get("primaryContainer") or {})
|
| 1041 |
+
environment = {
|
| 1042 |
+
item["name"]: item["value"]
|
| 1043 |
+
for item in primary.get("environment") or []
|
| 1044 |
+
if item.get("name")
|
| 1045 |
+
}
|
| 1046 |
+
if environment.get("COGNITO_AUTH") == "False":
|
| 1047 |
+
print(f"{service_name} already has COGNITO_AUTH=False.")
|
| 1048 |
+
return False
|
| 1049 |
+
environment["COGNITO_AUTH"] = "False"
|
| 1050 |
+
primary["environment"] = [
|
| 1051 |
+
{"name": name, "value": value} for name, value in sorted(environment.items())
|
| 1052 |
+
]
|
| 1053 |
+
update_kwargs: Dict[str, Any] = {
|
| 1054 |
+
"serviceArn": service_arn,
|
| 1055 |
+
"primaryContainer": primary,
|
| 1056 |
+
}
|
| 1057 |
+
for key in (
|
| 1058 |
+
"executionRoleArn",
|
| 1059 |
+
"taskRoleArn",
|
| 1060 |
+
"cpu",
|
| 1061 |
+
"memory",
|
| 1062 |
+
"healthCheckPath",
|
| 1063 |
+
"networkConfiguration",
|
| 1064 |
+
):
|
| 1065 |
+
value = active.get(key)
|
| 1066 |
+
if value is not None:
|
| 1067 |
+
update_kwargs[key] = value
|
| 1068 |
+
scaling = express.get("scalingTarget") or active.get("scalingTarget")
|
| 1069 |
+
if scaling is not None:
|
| 1070 |
+
update_kwargs["scalingTarget"] = scaling
|
| 1071 |
+
ecs_client.update_express_gateway_service(**update_kwargs)
|
| 1072 |
+
print(f"Set COGNITO_AUTH=False on Express service {service_name}.")
|
| 1073 |
+
return True
|
| 1074 |
+
|
| 1075 |
+
|
| 1076 |
+
def apply_cognito_secret_fixup_from_stack(
|
| 1077 |
+
*,
|
| 1078 |
+
stack_name: str,
|
| 1079 |
+
secret_name: str,
|
| 1080 |
+
cluster_name: str,
|
| 1081 |
+
main_service_name: str,
|
| 1082 |
+
aws_region: str = AWS_REGION,
|
| 1083 |
+
recycle_tasks: bool = True,
|
| 1084 |
+
) -> bool:
|
| 1085 |
+
"""Read Cognito outputs from CloudFormation and sync the app client secret."""
|
| 1086 |
+
cfn_client = boto3.client("cloudformation", region_name=aws_region)
|
| 1087 |
+
stacks = cfn_client.describe_stacks(StackName=stack_name).get("Stacks", [])
|
| 1088 |
+
outputs = {
|
| 1089 |
+
item["OutputKey"]: item["OutputValue"]
|
| 1090 |
+
for item in (stacks[0].get("Outputs") or [])
|
| 1091 |
+
}
|
| 1092 |
+
user_pool_id = outputs.get("CognitoPoolId")
|
| 1093 |
+
client_id = outputs.get("CognitoAppClientId")
|
| 1094 |
+
if not user_pool_id or not client_id:
|
| 1095 |
+
raise ValueError(
|
| 1096 |
+
f"Stack '{stack_name}' is missing CognitoPoolId or CognitoAppClientId outputs."
|
| 1097 |
+
)
|
| 1098 |
+
return apply_cognito_secret_fixup(
|
| 1099 |
+
secret_name=secret_name,
|
| 1100 |
+
user_pool_id=user_pool_id,
|
| 1101 |
+
client_id=client_id,
|
| 1102 |
+
aws_region=aws_region,
|
| 1103 |
+
recycle_express_service=(
|
| 1104 |
+
{"cluster_name": cluster_name, "service_name": main_service_name}
|
| 1105 |
+
if recycle_tasks
|
| 1106 |
+
else None
|
| 1107 |
+
),
|
| 1108 |
+
)
|
| 1109 |
+
|
| 1110 |
+
|
| 1111 |
+
def get_stack_output(
|
| 1112 |
+
stack_name: str,
|
| 1113 |
+
output_key: str,
|
| 1114 |
+
region: str,
|
| 1115 |
+
) -> Optional[str]:
|
| 1116 |
+
"""Return a CloudFormation stack output value, or None if missing."""
|
| 1117 |
+
from botocore.exceptions import ClientError
|
| 1118 |
+
|
| 1119 |
+
cfn = boto3.client("cloudformation", region_name=region)
|
| 1120 |
+
try:
|
| 1121 |
+
response = cfn.describe_stacks(StackName=stack_name)
|
| 1122 |
+
except ClientError:
|
| 1123 |
+
return None
|
| 1124 |
+
for stack in response.get("Stacks", []):
|
| 1125 |
+
for output in stack.get("Outputs", []):
|
| 1126 |
+
if output.get("OutputKey") == output_key:
|
| 1127 |
+
return output.get("OutputValue")
|
| 1128 |
+
return None
|
| 1129 |
+
|
| 1130 |
+
|
| 1131 |
+
def print_express_mode_next_steps(
|
| 1132 |
+
values: Dict[str, str],
|
| 1133 |
+
*,
|
| 1134 |
+
stack_name: str = "SummarisationStack",
|
| 1135 |
+
region: Optional[str] = None,
|
| 1136 |
+
) -> None:
|
| 1137 |
+
"""Print user-facing next steps after Express mode deploy + quickstart."""
|
| 1138 |
+
from cdk_config import normalize_https_redirect_url
|
| 1139 |
+
from cdk_functions import format_express_pi_public_url
|
| 1140 |
+
|
| 1141 |
+
aws_region = region or values.get("AWS_REGION") or AWS_REGION
|
| 1142 |
+
|
| 1143 |
+
main_raw = (values.get("ECS_EXPRESS_COGNITO_REDIRECT_BASE") or "").strip()
|
| 1144 |
+
if not main_raw:
|
| 1145 |
+
main_raw = (
|
| 1146 |
+
get_stack_output(stack_name, "ExpressServiceEndpoint", aws_region) or ""
|
| 1147 |
+
)
|
| 1148 |
+
main_url = normalize_https_redirect_url(main_raw) if main_raw else ""
|
| 1149 |
+
|
| 1150 |
+
print("\nDone. Next steps:")
|
| 1151 |
+
print(" - Wait 10 minutes for app deployment to finish.")
|
| 1152 |
+
pi_express = values.get("ENABLE_PI_AGENT_EXPRESS_SERVICE") == "True"
|
| 1153 |
+
if pi_express:
|
| 1154 |
+
print(
|
| 1155 |
+
"- Register a Cognito user in AWS Console, change password at the login page URL "
|
| 1156 |
+
"(available in the Cognito AWS console -> App Clients -> Login pages -> View login page "
|
| 1157 |
+
"and sign in at the Pi agent URL below. The main topic-modelling backend runs without "
|
| 1158 |
+
"in-app login so the Pi agent can call it over Service Connect. You can disable "
|
| 1159 |
+
"Cognito login by setting COGNITO_AUTH to False in the ECS task definition / "
|
| 1160 |
+
"ECS service options."
|
| 1161 |
+
)
|
| 1162 |
+
else:
|
| 1163 |
+
print(
|
| 1164 |
+
" - If you have enabled Cognito login in the app, register a new user "
|
| 1165 |
+
"to your Cognito user pool in AWS Console and complete sign up with the app "
|
| 1166 |
+
"client login. If you do not want Cognito login, then set COGNITO_AUTH to "
|
| 1167 |
+
"False in the ECS task definition / ECS service options."
|
| 1168 |
+
)
|
| 1169 |
+
if main_url:
|
| 1170 |
+
print(f" - The main topic modelling app can be accessed at {main_url}")
|
| 1171 |
+
else:
|
| 1172 |
+
print(
|
| 1173 |
+
" - The main topic modelling app URL: see ExpressServiceEndpoint stack output"
|
| 1174 |
+
)
|
| 1175 |
+
|
| 1176 |
+
if values.get("ENABLE_PI_AGENT_EXPRESS_SERVICE") == "True":
|
| 1177 |
+
pi_raw = get_stack_output(stack_name, "PiExpressEndpoint", aws_region) or ""
|
| 1178 |
+
pi_url = (
|
| 1179 |
+
format_express_pi_public_url(normalize_https_redirect_url(pi_raw))
|
| 1180 |
+
if pi_raw
|
| 1181 |
+
else ""
|
| 1182 |
+
)
|
| 1183 |
+
if pi_url:
|
| 1184 |
+
print(f" - The Pi agent app can be accessed at {pi_url}")
|
| 1185 |
+
else:
|
| 1186 |
+
print(" - The Pi agent app URL: see PiExpressEndpoint stack output")
|
| 1187 |
+
|
| 1188 |
+
|
| 1189 |
+
def _s3_object_exists(s3_client, bucket: str, key: str) -> bool:
|
| 1190 |
+
from botocore.exceptions import ClientError
|
| 1191 |
+
|
| 1192 |
+
try:
|
| 1193 |
+
s3_client.head_object(Bucket=bucket, Key=key)
|
| 1194 |
+
return True
|
| 1195 |
+
except ClientError as exc:
|
| 1196 |
+
code = exc.response.get("Error", {}).get("Code", "")
|
| 1197 |
+
if code in ("404", "NoSuchKey", "NotFound"):
|
| 1198 |
+
return False
|
| 1199 |
+
raise
|
| 1200 |
+
|
| 1201 |
+
|
| 1202 |
+
def seed_headless_batch_s3_layout(
|
| 1203 |
+
output_bucket: str,
|
| 1204 |
+
*,
|
| 1205 |
+
input_prefix: str = "input/",
|
| 1206 |
+
env_prefix: str = "input/config/",
|
| 1207 |
+
example_env_local_path: str,
|
| 1208 |
+
example_env_basename: str = "example_headless_env_file.env",
|
| 1209 |
+
aws_region: str = AWS_REGION,
|
| 1210 |
+
) -> None:
|
| 1211 |
+
"""
|
| 1212 |
+
Ensure headless batch prefixes and example job .env exist on the output bucket.
|
| 1213 |
+
|
| 1214 |
+
Idempotent: existing keys are left unchanged (safe to run from quickstart).
|
| 1215 |
+
"""
|
| 1216 |
+
if not output_bucket:
|
| 1217 |
+
print("Skipping headless S3 layout seed: output bucket name is empty.")
|
| 1218 |
+
return
|
| 1219 |
+
|
| 1220 |
+
input_prefix_norm = (
|
| 1221 |
+
input_prefix if input_prefix.endswith("/") else f"{input_prefix}/"
|
| 1222 |
+
)
|
| 1223 |
+
env_prefix_norm = env_prefix if env_prefix.endswith("/") else f"{env_prefix}/"
|
| 1224 |
+
if not env_prefix_norm.startswith(input_prefix_norm):
|
| 1225 |
+
env_prefix_norm = f"{input_prefix_norm}{env_prefix_norm.lstrip('/')}"
|
| 1226 |
+
if not env_prefix_norm.endswith("/"):
|
| 1227 |
+
env_prefix_norm += "/"
|
| 1228 |
+
|
| 1229 |
+
s3_client = boto3.client("s3", region_name=aws_region)
|
| 1230 |
+
markers = (
|
| 1231 |
+
input_prefix_norm,
|
| 1232 |
+
env_prefix_norm,
|
| 1233 |
+
)
|
| 1234 |
+
for key in markers:
|
| 1235 |
+
if _s3_object_exists(s3_client, output_bucket, key):
|
| 1236 |
+
print(f"S3 prefix marker already present: s3://{output_bucket}/{key}")
|
| 1237 |
+
continue
|
| 1238 |
+
s3_client.put_object(Bucket=output_bucket, Key=key, Body=b"")
|
| 1239 |
+
print(f"Created S3 prefix marker: s3://{output_bucket}/{key}")
|
| 1240 |
+
|
| 1241 |
+
example_key = f"{env_prefix_norm}{example_env_basename}"
|
| 1242 |
+
if _s3_object_exists(s3_client, output_bucket, example_key):
|
| 1243 |
+
print(f"Example job .env already present: s3://{output_bucket}/{example_key}")
|
| 1244 |
+
return
|
| 1245 |
+
|
| 1246 |
+
if not os.path.isfile(example_env_local_path):
|
| 1247 |
+
print(f"Skipping example job .env upload: {example_env_local_path} not found.")
|
| 1248 |
+
return
|
| 1249 |
+
|
| 1250 |
+
with open(example_env_local_path, "rb") as handle:
|
| 1251 |
+
s3_client.put_object(Bucket=output_bucket, Key=example_key, Body=handle.read())
|
| 1252 |
+
print(f"Uploaded example job .env to s3://{output_bucket}/{example_key}")
|
| 1253 |
+
|
| 1254 |
+
|
| 1255 |
+
def print_headless_deployment_next_steps(
|
| 1256 |
+
values: Dict[str, str],
|
| 1257 |
+
*,
|
| 1258 |
+
stack_name: str = "SummarisationStack",
|
| 1259 |
+
region: Optional[str] = None,
|
| 1260 |
+
) -> None:
|
| 1261 |
+
"""Print user-facing next steps after headless deploy + quickstart."""
|
| 1262 |
+
aws_region = region or values.get("AWS_REGION") or AWS_REGION
|
| 1263 |
+
output_bucket = (values.get("S3_OUTPUT_BUCKET_NAME") or "").strip()
|
| 1264 |
+
input_prefix = (values.get("S3_BATCH_INPUT_PREFIX") or "input/").strip("/")
|
| 1265 |
+
config_prefix = (values.get("S3_BATCH_ENV_PREFIX") or "input/config/").strip("/")
|
| 1266 |
+
|
| 1267 |
+
lambda_name = (values.get("S3_BATCH_LAMBDA_FUNCTION_NAME") or "").strip()
|
| 1268 |
+
if not lambda_name:
|
| 1269 |
+
lambda_name = (
|
| 1270 |
+
get_stack_output(stack_name, "BatchEcsTriggerLambdaName", aws_region) or ""
|
| 1271 |
+
).strip()
|
| 1272 |
+
if not lambda_name:
|
| 1273 |
+
prefix = (values.get("CDK_PREFIX") or "").strip()
|
| 1274 |
+
lambda_name = f"{prefix}S3BatchEcsTrigger" if prefix else "S3BatchEcsTrigger"
|
| 1275 |
+
|
| 1276 |
+
input_uri = (
|
| 1277 |
+
f"s3://{output_bucket}/{input_prefix}/"
|
| 1278 |
+
if output_bucket
|
| 1279 |
+
else f"<output-bucket>/{input_prefix}/"
|
| 1280 |
+
)
|
| 1281 |
+
config_uri = (
|
| 1282 |
+
f"s3://{output_bucket}/{config_prefix}/"
|
| 1283 |
+
if output_bucket
|
| 1284 |
+
else f"<output-bucket>/{config_prefix}/"
|
| 1285 |
+
)
|
| 1286 |
+
output_uri = (
|
| 1287 |
+
f"s3://{output_bucket}/output/<session-folder>/"
|
| 1288 |
+
if output_bucket
|
| 1289 |
+
else "<output-bucket>/output/<session-folder>/"
|
| 1290 |
+
)
|
| 1291 |
+
example_name = "example_headless_env_file.env"
|
| 1292 |
+
|
| 1293 |
+
print("\nDone. Next steps:")
|
| 1294 |
+
print(
|
| 1295 |
+
f" - Upload a consultation spreadsheet (.xlsx) to {input_uri}. "
|
| 1296 |
+
"You can use dummy_consultation_response.xlsx as a placeholder filename "
|
| 1297 |
+
"in the example job .env below."
|
| 1298 |
+
)
|
| 1299 |
+
print(
|
| 1300 |
+
f" - Create a job .env file for submitting a task to {config_uri}. "
|
| 1301 |
+
f"You can copy the example at cdk/config/headless_s3_seed/input/config/{example_name} "
|
| 1302 |
+
f"(also seeded at {config_uri}{example_name}) and adjust DIRECT_MODE_INPUT_FILE "
|
| 1303 |
+
"and DIRECT_MODE_TEXT_COLUMN. Further DIRECT_MODE_* variables are documented in "
|
| 1304 |
+
"tools/config.py and cli_topics.py."
|
| 1305 |
+
)
|
| 1306 |
+
print(f" - Upload your job .env file to {config_uri}")
|
| 1307 |
+
print(
|
| 1308 |
+
f" - AWS Lambda function {lambda_name} will start an ECS task to run "
|
| 1309 |
+
"topic modelling according to your job .env (RUN_DIRECT_MODE=1)."
|
| 1310 |
+
)
|
| 1311 |
+
print(
|
| 1312 |
+
f" - Outputs are written to {output_uri} when SAVE_OUTPUTS_TO_S3=True "
|
| 1313 |
+
"in your job .env (see the example file)."
|
| 1314 |
+
)
|
| 1315 |
+
log_group = (values.get("ECS_LOG_GROUP_NAME") or "").strip()
|
| 1316 |
+
if log_group:
|
| 1317 |
+
print(
|
| 1318 |
+
f" - Batch task logs: CloudWatch log group {log_group} "
|
| 1319 |
+
"(streams appear once the container starts)."
|
| 1320 |
+
)
|
| 1321 |
+
|
| 1322 |
+
|
| 1323 |
+
def print_headless_output_notification_steps(values: Dict[str, str]) -> None:
|
| 1324 |
+
"""Print follow-on steps for S3 output alarms, SNS, and IAM reader user."""
|
| 1325 |
+
email = (values.get("HEADLESS_OUTPUT_NOTIFY_EMAIL") or "").strip()
|
| 1326 |
+
iam_user = (values.get("HEADLESS_OUTPUT_IAM_USER_NAME") or "").strip()
|
| 1327 |
+
output_bucket = (values.get("S3_OUTPUT_BUCKET_NAME") or "").strip()
|
| 1328 |
+
output_prefix = (values.get("HEADLESS_OUTPUT_S3_PREFIX") or "output/").strip()
|
| 1329 |
+
alarm_name = (values.get("HEADLESS_OUTPUT_ALARM_NAME") or "").strip()
|
| 1330 |
+
secret_name = (values.get("HEADLESS_OUTPUT_IAM_SECRET_NAME") or "").strip()
|
| 1331 |
+
|
| 1332 |
+
print("\nHeadless output notifications:")
|
| 1333 |
+
if email:
|
| 1334 |
+
print(
|
| 1335 |
+
f" - Confirm the SNS email subscription sent to {email} "
|
| 1336 |
+
"(check spam; status shows Pending until confirmed)."
|
| 1337 |
+
)
|
| 1338 |
+
if output_bucket:
|
| 1339 |
+
print(
|
| 1340 |
+
f" - CloudWatch alarm fires when objects are uploaded under "
|
| 1341 |
+
f"s3://{output_bucket}/{output_prefix.rstrip('/')}/"
|
| 1342 |
+
)
|
| 1343 |
+
if alarm_name:
|
| 1344 |
+
print(f" - Alarm name: {alarm_name}")
|
| 1345 |
+
if iam_user:
|
| 1346 |
+
print(
|
| 1347 |
+
f" - IAM user {iam_user} can list/get/put/delete objects in the "
|
| 1348 |
+
f"output bucket for programmatic result download."
|
| 1349 |
+
)
|
| 1350 |
+
if secret_name:
|
| 1351 |
+
print(
|
| 1352 |
+
" - If an access key was created, credentials are stored in "
|
| 1353 |
+
"the relevantSecrets Manager secret."
|
| 1354 |
+
)
|
| 1355 |
+
|
| 1356 |
+
|
| 1357 |
+
def provision_headless_output_reader_access_key(
|
| 1358 |
+
values: Dict[str, str],
|
| 1359 |
+
*,
|
| 1360 |
+
region: Optional[str] = None,
|
| 1361 |
+
) -> Optional[str]:
|
| 1362 |
+
"""
|
| 1363 |
+
Create an IAM access key for the headless output reader user.
|
| 1364 |
+
|
| 1365 |
+
Stores JSON credentials in Secrets Manager when HEADLESS_OUTPUT_IAM_SECRET_NAME
|
| 1366 |
+
is set in cdk_config.env.
|
| 1367 |
+
"""
|
| 1368 |
+
from botocore.exceptions import ClientError
|
| 1369 |
+
|
| 1370 |
+
iam_user = (values.get("HEADLESS_OUTPUT_IAM_USER_NAME") or "").strip()
|
| 1371 |
+
if not iam_user:
|
| 1372 |
+
print("Warning: HEADLESS_OUTPUT_IAM_USER_NAME not set; skipping access key.")
|
| 1373 |
+
return None
|
| 1374 |
+
|
| 1375 |
+
aws_region = region or values.get("AWS_REGION") or AWS_REGION
|
| 1376 |
+
iam_client = boto3.client("iam", region_name=aws_region)
|
| 1377 |
+
secret_name = (values.get("HEADLESS_OUTPUT_IAM_SECRET_NAME") or "").strip()
|
| 1378 |
+
|
| 1379 |
+
try:
|
| 1380 |
+
response = iam_client.create_access_key(UserName=iam_user)
|
| 1381 |
+
except ClientError as exc:
|
| 1382 |
+
print(f"Could not create IAM access key for {iam_user}: {exc}")
|
| 1383 |
+
return None
|
| 1384 |
+
|
| 1385 |
+
access_key = response["AccessKey"]
|
| 1386 |
+
payload = json.dumps(
|
| 1387 |
+
{
|
| 1388 |
+
"aws_access_key_id": access_key["AccessKeyId"],
|
| 1389 |
+
"aws_secret_access_key": access_key["SecretAccessKey"],
|
| 1390 |
+
}
|
| 1391 |
+
)
|
| 1392 |
+
|
| 1393 |
+
if secret_name:
|
| 1394 |
+
sm_client = boto3.client("secretsmanager", region_name=aws_region)
|
| 1395 |
+
try:
|
| 1396 |
+
sm_client.create_secret(Name=secret_name, SecretString=payload)
|
| 1397 |
+
print("Stored output-reader credentials in Secrets Manager secret")
|
| 1398 |
+
except ClientError as exc:
|
| 1399 |
+
if exc.response["Error"]["Code"] == "ResourceExistsException":
|
| 1400 |
+
sm_client.put_secret_value(SecretId=secret_name, SecretString=payload)
|
| 1401 |
+
print("Updated output-reader credentials in Secrets Manager secret")
|
| 1402 |
+
else:
|
| 1403 |
+
print(f"Warning: could not store credentials in Secrets Manager: {exc}")
|
| 1404 |
+
print("IAM access key created (view in IAM console if needed):")
|
| 1405 |
+
else:
|
| 1406 |
+
print("IAM access key created (view in IAM console if needed):")
|
| 1407 |
+
|
| 1408 |
+
return access_key["AccessKeyId"]
|
cdk/cdk_stack.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
cdk/check_resources.py
ADDED
|
@@ -0,0 +1,583 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import os
|
| 3 |
+
from typing import Dict, List
|
| 4 |
+
|
| 5 |
+
from cdk_config import ( # Import necessary config
|
| 6 |
+
ALB_NAME,
|
| 7 |
+
AWS_REGION,
|
| 8 |
+
CDK_CONFIG_PATH,
|
| 9 |
+
CDK_FOLDER,
|
| 10 |
+
CODEBUILD_PROJECT_NAME,
|
| 11 |
+
CODEBUILD_ROLE_NAME,
|
| 12 |
+
COGNITO_USER_POOL_CLIENT_NAME,
|
| 13 |
+
COGNITO_USER_POOL_CLIENT_SECRET_NAME,
|
| 14 |
+
COGNITO_USER_POOL_DOMAIN_PREFIX,
|
| 15 |
+
COGNITO_USER_POOL_NAME,
|
| 16 |
+
CONTEXT_FILE,
|
| 17 |
+
ECR_CDK_REPO_NAME,
|
| 18 |
+
ECR_PI_REPO_NAME,
|
| 19 |
+
ECS_SERVICE_CONNECT_CLIENT_SECURITY_GROUP_NAMES_TO_LOOKUP,
|
| 20 |
+
ECS_TASK_EXECUTION_ROLE_NAME,
|
| 21 |
+
ECS_TASK_ROLE_NAME,
|
| 22 |
+
ENABLE_ECS_SERVICE_CONNECT,
|
| 23 |
+
ENABLE_HEADLESS_DEPLOYMENT,
|
| 24 |
+
ENABLE_PI_AGENT_ECS_SERVICE,
|
| 25 |
+
ENABLE_S3_BATCH_ECS_TRIGGER,
|
| 26 |
+
EXISTING_IGW_ID,
|
| 27 |
+
PRIVATE_SUBNET_AVAILABILITY_ZONES,
|
| 28 |
+
PRIVATE_SUBNET_CIDR_BLOCKS,
|
| 29 |
+
PRIVATE_SUBNETS_TO_USE,
|
| 30 |
+
PUBLIC_SUBNET_AVAILABILITY_ZONES,
|
| 31 |
+
PUBLIC_SUBNET_CIDR_BLOCKS,
|
| 32 |
+
PUBLIC_SUBNETS_TO_USE,
|
| 33 |
+
S3_LOG_CONFIG_BUCKET_NAME,
|
| 34 |
+
S3_OUTPUT_BUCKET_NAME,
|
| 35 |
+
USE_ECS_EXPRESS_MODE,
|
| 36 |
+
VPC_NAME,
|
| 37 |
+
WEB_ACL_NAME,
|
| 38 |
+
)
|
| 39 |
+
from cdk_functions import ( # Import your check functions (assuming they use Boto3)
|
| 40 |
+
_get_existing_subnets_in_vpc,
|
| 41 |
+
audit_public_subnet_internet_connectivity,
|
| 42 |
+
check_alb_exists,
|
| 43 |
+
check_codebuild_project_exists,
|
| 44 |
+
check_ecr_repo_exists,
|
| 45 |
+
check_for_existing_role,
|
| 46 |
+
check_for_existing_user_pool,
|
| 47 |
+
check_for_existing_user_pool_client,
|
| 48 |
+
check_for_secret,
|
| 49 |
+
check_subnet_exists_by_name,
|
| 50 |
+
check_web_acl_exists,
|
| 51 |
+
get_secret_kms_key_arn,
|
| 52 |
+
get_security_group_id_by_name,
|
| 53 |
+
get_vpc_id_by_name,
|
| 54 |
+
list_existing_vpc_endpoint_service_names,
|
| 55 |
+
resolve_cognito_domain_prefix_availability,
|
| 56 |
+
resolve_s3_bucket_availability,
|
| 57 |
+
validate_subnet_creation_parameters,
|
| 58 |
+
# Add other check functions as needed
|
| 59 |
+
)
|
| 60 |
+
|
| 61 |
+
cdk_folder = CDK_FOLDER # <FULL_PATH_TO_CDK_FOLDER_HERE>
|
| 62 |
+
|
| 63 |
+
# Full path needed to find config file
|
| 64 |
+
os.environ["CDK_CONFIG_PATH"] = cdk_folder + CDK_CONFIG_PATH
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
# --- Helper to parse environment variables into lists ---
|
| 68 |
+
def _get_env_list(env_var_name: str) -> List[str]:
|
| 69 |
+
"""Parses a comma-separated environment variable into a list of strings."""
|
| 70 |
+
value = env_var_name[1:-1].strip().replace('"', "").replace("'", "")
|
| 71 |
+
if not value:
|
| 72 |
+
return []
|
| 73 |
+
# Split by comma and filter out any empty strings that might result from extra commas
|
| 74 |
+
return [s.strip() for s in value.split(",") if s.strip()]
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
if PUBLIC_SUBNETS_TO_USE and not isinstance(PUBLIC_SUBNETS_TO_USE, list):
|
| 78 |
+
PUBLIC_SUBNETS_TO_USE = _get_env_list(PUBLIC_SUBNETS_TO_USE)
|
| 79 |
+
if PRIVATE_SUBNETS_TO_USE and not isinstance(PRIVATE_SUBNETS_TO_USE, list):
|
| 80 |
+
PRIVATE_SUBNETS_TO_USE = _get_env_list(PRIVATE_SUBNETS_TO_USE)
|
| 81 |
+
if PUBLIC_SUBNET_CIDR_BLOCKS and not isinstance(PUBLIC_SUBNET_CIDR_BLOCKS, list):
|
| 82 |
+
PUBLIC_SUBNET_CIDR_BLOCKS = _get_env_list(PUBLIC_SUBNET_CIDR_BLOCKS)
|
| 83 |
+
if PUBLIC_SUBNET_AVAILABILITY_ZONES and not isinstance(
|
| 84 |
+
PUBLIC_SUBNET_AVAILABILITY_ZONES, list
|
| 85 |
+
):
|
| 86 |
+
PUBLIC_SUBNET_AVAILABILITY_ZONES = _get_env_list(PUBLIC_SUBNET_AVAILABILITY_ZONES)
|
| 87 |
+
if PRIVATE_SUBNET_CIDR_BLOCKS and not isinstance(PRIVATE_SUBNET_CIDR_BLOCKS, list):
|
| 88 |
+
PRIVATE_SUBNET_CIDR_BLOCKS = _get_env_list(PRIVATE_SUBNET_CIDR_BLOCKS)
|
| 89 |
+
if PRIVATE_SUBNET_AVAILABILITY_ZONES and not isinstance(
|
| 90 |
+
PRIVATE_SUBNET_AVAILABILITY_ZONES, list
|
| 91 |
+
):
|
| 92 |
+
PRIVATE_SUBNET_AVAILABILITY_ZONES = _get_env_list(PRIVATE_SUBNET_AVAILABILITY_ZONES)
|
| 93 |
+
|
| 94 |
+
# Check for the existence of elements in your AWS environment to see if it's necessary to create new versions of the same
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def check_and_set_context():
|
| 98 |
+
context_data = {}
|
| 99 |
+
|
| 100 |
+
# --- Find the VPC ID first ---
|
| 101 |
+
if VPC_NAME:
|
| 102 |
+
print("VPC_NAME:", VPC_NAME)
|
| 103 |
+
vpc_lookup = get_vpc_id_by_name(VPC_NAME)
|
| 104 |
+
if not vpc_lookup:
|
| 105 |
+
raise RuntimeError(
|
| 106 |
+
f"Required VPC '{VPC_NAME}' not found. Cannot proceed with subnet checks."
|
| 107 |
+
)
|
| 108 |
+
vpc_id, nat_gateways, vpc_cidr_block, vpc_cidr_blocks = vpc_lookup
|
| 109 |
+
|
| 110 |
+
# If you expect only one, or one per AZ and you're creating one per AZ in CDK:
|
| 111 |
+
if nat_gateways:
|
| 112 |
+
# For simplicity, let's just check if *any* NAT exists in the VPC
|
| 113 |
+
# A more robust check would match by subnet, AZ, or a specific tag.
|
| 114 |
+
context_data["exists:NatGateway"] = True
|
| 115 |
+
context_data["id:NatGateway"] = nat_gateways[0][
|
| 116 |
+
"NatGatewayId"
|
| 117 |
+
] # Store the ID of the first one found
|
| 118 |
+
else:
|
| 119 |
+
context_data["exists:NatGateway"] = False
|
| 120 |
+
context_data["id:NatGateway"] = None
|
| 121 |
+
|
| 122 |
+
context_data["vpc_id"] = vpc_id # Store VPC ID in context
|
| 123 |
+
if vpc_cidr_block:
|
| 124 |
+
context_data["vpc_cidr_block"] = vpc_cidr_block
|
| 125 |
+
if vpc_cidr_blocks:
|
| 126 |
+
context_data["vpc_cidr_blocks"] = vpc_cidr_blocks
|
| 127 |
+
|
| 128 |
+
existing_endpoint_services = sorted(
|
| 129 |
+
list_existing_vpc_endpoint_service_names(vpc_id, region_name=AWS_REGION)
|
| 130 |
+
)
|
| 131 |
+
if existing_endpoint_services:
|
| 132 |
+
context_data["existing_vpc_endpoint_service_names"] = (
|
| 133 |
+
existing_endpoint_services
|
| 134 |
+
)
|
| 135 |
+
print(
|
| 136 |
+
"Existing VPC endpoints in target VPC (will be skipped on deploy): "
|
| 137 |
+
+ ", ".join(existing_endpoint_services)
|
| 138 |
+
)
|
| 139 |
+
|
| 140 |
+
# SUBNET CHECKS
|
| 141 |
+
all_proposed_subnets_data: List[Dict[str, str]] = []
|
| 142 |
+
|
| 143 |
+
# Flag to indicate if full validation mode (with CIDR/AZs) is active
|
| 144 |
+
full_validation_mode = False
|
| 145 |
+
|
| 146 |
+
# Determine if full validation mode is possible/desired
|
| 147 |
+
# It's 'desired' if CIDR/AZs are provided, and their lengths match the name lists.
|
| 148 |
+
public_ready_for_full_validation = (
|
| 149 |
+
len(PUBLIC_SUBNETS_TO_USE) > 0
|
| 150 |
+
and len(PUBLIC_SUBNET_CIDR_BLOCKS) == len(PUBLIC_SUBNETS_TO_USE)
|
| 151 |
+
and len(PUBLIC_SUBNET_AVAILABILITY_ZONES) == len(PUBLIC_SUBNETS_TO_USE)
|
| 152 |
+
)
|
| 153 |
+
private_ready_for_full_validation = (
|
| 154 |
+
len(PRIVATE_SUBNETS_TO_USE) > 0
|
| 155 |
+
and len(PRIVATE_SUBNET_CIDR_BLOCKS) == len(PRIVATE_SUBNETS_TO_USE)
|
| 156 |
+
and len(PRIVATE_SUBNET_AVAILABILITY_ZONES) == len(PRIVATE_SUBNETS_TO_USE)
|
| 157 |
+
)
|
| 158 |
+
|
| 159 |
+
# Activate full validation if *any* type of subnet (public or private) has its full details provided.
|
| 160 |
+
# You might adjust this logic if you require ALL subnet types to have CIDRs, or NONE.
|
| 161 |
+
if public_ready_for_full_validation or private_ready_for_full_validation:
|
| 162 |
+
full_validation_mode = True
|
| 163 |
+
|
| 164 |
+
# If some are ready but others aren't, print a warning or raise an error based on your strictness
|
| 165 |
+
if (
|
| 166 |
+
public_ready_for_full_validation
|
| 167 |
+
and not private_ready_for_full_validation
|
| 168 |
+
and PRIVATE_SUBNETS_TO_USE
|
| 169 |
+
):
|
| 170 |
+
print(
|
| 171 |
+
"Warning: Public subnets have CIDRs/AZs, but private subnets do not. Only public will be fully validated/created with CIDRs."
|
| 172 |
+
)
|
| 173 |
+
if (
|
| 174 |
+
private_ready_for_full_validation
|
| 175 |
+
and not public_ready_for_full_validation
|
| 176 |
+
and PUBLIC_SUBNETS_TO_USE
|
| 177 |
+
):
|
| 178 |
+
print(
|
| 179 |
+
"Warning: Private subnets have CIDRs/AZs, but public subnets do not. Only private will be fully validated/created with CIDRs."
|
| 180 |
+
)
|
| 181 |
+
|
| 182 |
+
# Prepare data for validate_subnet_creation_parameters for all subnets that have full details
|
| 183 |
+
if public_ready_for_full_validation:
|
| 184 |
+
for i, name in enumerate(PUBLIC_SUBNETS_TO_USE):
|
| 185 |
+
all_proposed_subnets_data.append(
|
| 186 |
+
{
|
| 187 |
+
"name": name,
|
| 188 |
+
"cidr": PUBLIC_SUBNET_CIDR_BLOCKS[i],
|
| 189 |
+
"az": PUBLIC_SUBNET_AVAILABILITY_ZONES[i],
|
| 190 |
+
}
|
| 191 |
+
)
|
| 192 |
+
if private_ready_for_full_validation:
|
| 193 |
+
for i, name in enumerate(PRIVATE_SUBNETS_TO_USE):
|
| 194 |
+
all_proposed_subnets_data.append(
|
| 195 |
+
{
|
| 196 |
+
"name": name,
|
| 197 |
+
"cidr": PRIVATE_SUBNET_CIDR_BLOCKS[i],
|
| 198 |
+
"az": PRIVATE_SUBNET_AVAILABILITY_ZONES[i],
|
| 199 |
+
}
|
| 200 |
+
)
|
| 201 |
+
|
| 202 |
+
print(f"Target VPC ID for Boto3 lookup: {vpc_id}")
|
| 203 |
+
|
| 204 |
+
# Fetch all existing subnets in the target VPC once to avoid repeated API calls
|
| 205 |
+
try:
|
| 206 |
+
existing_aws_subnets = _get_existing_subnets_in_vpc(vpc_id)
|
| 207 |
+
except Exception as e:
|
| 208 |
+
print(f"Failed to fetch existing VPC subnets. Aborting. Error: {e}")
|
| 209 |
+
raise SystemExit(1) # Exit immediately if we can't get baseline data
|
| 210 |
+
|
| 211 |
+
print("\n--- Running Name-Only Subnet Existence Check Mode ---")
|
| 212 |
+
# Fallback: check only by name using the existing data
|
| 213 |
+
checked_public_subnets = {}
|
| 214 |
+
if PUBLIC_SUBNETS_TO_USE:
|
| 215 |
+
for subnet_name in PUBLIC_SUBNETS_TO_USE:
|
| 216 |
+
print("subnet_name:", subnet_name)
|
| 217 |
+
exists, subnet_id = check_subnet_exists_by_name(
|
| 218 |
+
subnet_name, existing_aws_subnets
|
| 219 |
+
)
|
| 220 |
+
checked_public_subnets[subnet_name] = {
|
| 221 |
+
"exists": exists,
|
| 222 |
+
"id": subnet_id,
|
| 223 |
+
"az": (
|
| 224 |
+
existing_aws_subnets["by_name"].get(subnet_name, {}).get("az")
|
| 225 |
+
if exists
|
| 226 |
+
else None
|
| 227 |
+
),
|
| 228 |
+
"route_table_id": (
|
| 229 |
+
existing_aws_subnets["by_name"]
|
| 230 |
+
.get(subnet_name, {})
|
| 231 |
+
.get("route_table_id")
|
| 232 |
+
if exists
|
| 233 |
+
else None
|
| 234 |
+
),
|
| 235 |
+
}
|
| 236 |
+
|
| 237 |
+
# If the subnet exists, remove it from the proposed subnets list
|
| 238 |
+
if checked_public_subnets[subnet_name]["exists"] is True:
|
| 239 |
+
all_proposed_subnets_data = [
|
| 240 |
+
subnet
|
| 241 |
+
for subnet in all_proposed_subnets_data
|
| 242 |
+
if subnet["name"] != subnet_name
|
| 243 |
+
]
|
| 244 |
+
|
| 245 |
+
context_data["checked_public_subnets"] = checked_public_subnets
|
| 246 |
+
|
| 247 |
+
checked_private_subnets = {}
|
| 248 |
+
if PRIVATE_SUBNETS_TO_USE:
|
| 249 |
+
for subnet_name in PRIVATE_SUBNETS_TO_USE:
|
| 250 |
+
print("subnet_name:", subnet_name)
|
| 251 |
+
exists, subnet_id = check_subnet_exists_by_name(
|
| 252 |
+
subnet_name, existing_aws_subnets
|
| 253 |
+
)
|
| 254 |
+
checked_private_subnets[subnet_name] = {
|
| 255 |
+
"exists": exists,
|
| 256 |
+
"id": subnet_id,
|
| 257 |
+
"az": (
|
| 258 |
+
existing_aws_subnets["by_name"].get(subnet_name, {}).get("az")
|
| 259 |
+
if exists
|
| 260 |
+
else None
|
| 261 |
+
),
|
| 262 |
+
"route_table_id": (
|
| 263 |
+
existing_aws_subnets["by_name"]
|
| 264 |
+
.get(subnet_name, {})
|
| 265 |
+
.get("route_table_id")
|
| 266 |
+
if exists
|
| 267 |
+
else None
|
| 268 |
+
),
|
| 269 |
+
}
|
| 270 |
+
|
| 271 |
+
# If the subnet exists, remove it from the proposed subnets list
|
| 272 |
+
if checked_private_subnets[subnet_name]["exists"] is True:
|
| 273 |
+
all_proposed_subnets_data = [
|
| 274 |
+
subnet
|
| 275 |
+
for subnet in all_proposed_subnets_data
|
| 276 |
+
if subnet["name"] != subnet_name
|
| 277 |
+
]
|
| 278 |
+
|
| 279 |
+
context_data["checked_private_subnets"] = checked_private_subnets
|
| 280 |
+
|
| 281 |
+
# Internet Gateway + public subnet default routes (legacy ALB / NAT public subnets)
|
| 282 |
+
if PUBLIC_SUBNETS_TO_USE and vpc_id:
|
| 283 |
+
public_entries_for_igw_audit = []
|
| 284 |
+
for subnet_name in PUBLIC_SUBNETS_TO_USE:
|
| 285 |
+
info = checked_public_subnets.get(subnet_name, {})
|
| 286 |
+
if not info.get("exists"):
|
| 287 |
+
continue
|
| 288 |
+
public_entries_for_igw_audit.append(
|
| 289 |
+
{
|
| 290 |
+
"name": subnet_name,
|
| 291 |
+
"subnet_id": info.get("id"),
|
| 292 |
+
"route_table_id": info.get("route_table_id"),
|
| 293 |
+
}
|
| 294 |
+
)
|
| 295 |
+
if public_entries_for_igw_audit or EXISTING_IGW_ID:
|
| 296 |
+
print("\n--- Auditing Internet Gateway and public subnet routes ---")
|
| 297 |
+
try:
|
| 298 |
+
igw_audit = audit_public_subnet_internet_connectivity(
|
| 299 |
+
vpc_id,
|
| 300 |
+
EXISTING_IGW_ID,
|
| 301 |
+
public_entries_for_igw_audit,
|
| 302 |
+
)
|
| 303 |
+
context_data["internet_gateway_id"] = igw_audit[
|
| 304 |
+
"internet_gateway_id"
|
| 305 |
+
]
|
| 306 |
+
context_data["internet_gateway_needs_vpc_attachment"] = igw_audit[
|
| 307 |
+
"internet_gateway_needs_vpc_attachment"
|
| 308 |
+
]
|
| 309 |
+
context_data["public_subnets_needing_igw_route"] = igw_audit[
|
| 310 |
+
"public_subnets_needing_igw_route"
|
| 311 |
+
]
|
| 312 |
+
needing = igw_audit["public_subnets_needing_igw_route"]
|
| 313 |
+
if igw_audit["internet_gateway_needs_vpc_attachment"]:
|
| 314 |
+
print(
|
| 315 |
+
f"CDK will attach IGW '{igw_audit['internet_gateway_id']}' "
|
| 316 |
+
f"to VPC '{vpc_id}' on deploy."
|
| 317 |
+
)
|
| 318 |
+
if needing:
|
| 319 |
+
print(
|
| 320 |
+
f"CDK will add default internet routes on deploy for: "
|
| 321 |
+
f"{', '.join(n['name'] for n in needing)}"
|
| 322 |
+
)
|
| 323 |
+
else:
|
| 324 |
+
print(
|
| 325 |
+
"All audited public subnets already have 0.0.0.0/0 -> IGW routes."
|
| 326 |
+
)
|
| 327 |
+
except ValueError as e:
|
| 328 |
+
print(
|
| 329 |
+
f"\nFATAL ERROR: Internet Gateway / public route audit failed: {e}\n"
|
| 330 |
+
)
|
| 331 |
+
raise SystemExit(1) from e
|
| 332 |
+
|
| 333 |
+
print("\nName-only existence subnet check complete.\n")
|
| 334 |
+
|
| 335 |
+
if full_validation_mode:
|
| 336 |
+
print(
|
| 337 |
+
"\n--- Running in Full Subnet Validation Mode (CIDR/AZs provided) ---"
|
| 338 |
+
)
|
| 339 |
+
try:
|
| 340 |
+
validate_subnet_creation_parameters(
|
| 341 |
+
vpc_id, all_proposed_subnets_data, existing_aws_subnets
|
| 342 |
+
)
|
| 343 |
+
print("\nPre-synth validation successful. Proceeding with CDK synth.\n")
|
| 344 |
+
|
| 345 |
+
# Populate context_data for downstream CDK construct creation.
|
| 346 |
+
# Skip subnets that already exist in AWS (imported in the stack).
|
| 347 |
+
context_data["public_subnets_to_create"] = []
|
| 348 |
+
if public_ready_for_full_validation:
|
| 349 |
+
for i, name in enumerate(PUBLIC_SUBNETS_TO_USE):
|
| 350 |
+
if checked_public_subnets.get(name, {}).get("exists"):
|
| 351 |
+
continue
|
| 352 |
+
context_data["public_subnets_to_create"].append(
|
| 353 |
+
{
|
| 354 |
+
"name": name,
|
| 355 |
+
"cidr": PUBLIC_SUBNET_CIDR_BLOCKS[i],
|
| 356 |
+
"az": PUBLIC_SUBNET_AVAILABILITY_ZONES[i],
|
| 357 |
+
"is_public": True,
|
| 358 |
+
}
|
| 359 |
+
)
|
| 360 |
+
context_data["private_subnets_to_create"] = []
|
| 361 |
+
if private_ready_for_full_validation:
|
| 362 |
+
for i, name in enumerate(PRIVATE_SUBNETS_TO_USE):
|
| 363 |
+
if checked_private_subnets.get(name, {}).get("exists"):
|
| 364 |
+
continue
|
| 365 |
+
context_data["private_subnets_to_create"].append(
|
| 366 |
+
{
|
| 367 |
+
"name": name,
|
| 368 |
+
"cidr": PRIVATE_SUBNET_CIDR_BLOCKS[i],
|
| 369 |
+
"az": PRIVATE_SUBNET_AVAILABILITY_ZONES[i],
|
| 370 |
+
"is_public": False,
|
| 371 |
+
}
|
| 372 |
+
)
|
| 373 |
+
|
| 374 |
+
except (ValueError, Exception) as e:
|
| 375 |
+
print(f"\nFATAL ERROR: Subnet parameter validation failed: {e}\n")
|
| 376 |
+
raise SystemExit(1) # Exit if validation fails
|
| 377 |
+
|
| 378 |
+
# Example checks and setting context values
|
| 379 |
+
# IAM Roles
|
| 380 |
+
role_name = CODEBUILD_ROLE_NAME
|
| 381 |
+
exists, role_arn, _ = check_for_existing_role(role_name)
|
| 382 |
+
context_data[f"exists:{role_name}"] = exists
|
| 383 |
+
if exists:
|
| 384 |
+
context_data[f"arn:{role_name}"] = role_arn
|
| 385 |
+
|
| 386 |
+
role_name = ECS_TASK_ROLE_NAME
|
| 387 |
+
exists, role_arn, _ = check_for_existing_role(role_name)
|
| 388 |
+
context_data[f"exists:{role_name}"] = exists
|
| 389 |
+
if exists:
|
| 390 |
+
context_data[f"arn:{role_name}"] = role_arn
|
| 391 |
+
|
| 392 |
+
role_name = ECS_TASK_EXECUTION_ROLE_NAME
|
| 393 |
+
exists, role_arn, _ = check_for_existing_role(role_name)
|
| 394 |
+
context_data[f"exists:{role_name}"] = exists
|
| 395 |
+
if exists:
|
| 396 |
+
context_data[f"arn:{role_name}"] = role_arn
|
| 397 |
+
|
| 398 |
+
# S3 Buckets
|
| 399 |
+
def _record_s3_bucket_context(name: str) -> None:
|
| 400 |
+
status, _ = resolve_s3_bucket_availability(name)
|
| 401 |
+
context_data[f"exists:{name}"] = status == "owned"
|
| 402 |
+
context_data[f"globally_taken:{name}"] = status == "globally_taken"
|
| 403 |
+
|
| 404 |
+
bucket_name = S3_LOG_CONFIG_BUCKET_NAME
|
| 405 |
+
_record_s3_bucket_context(bucket_name)
|
| 406 |
+
|
| 407 |
+
output_bucket_name = S3_OUTPUT_BUCKET_NAME
|
| 408 |
+
_record_s3_bucket_context(output_bucket_name)
|
| 409 |
+
|
| 410 |
+
# ECR Repositories
|
| 411 |
+
for repo_name in (ECR_CDK_REPO_NAME, ECR_PI_REPO_NAME):
|
| 412 |
+
exists, _ = check_ecr_repo_exists(repo_name)
|
| 413 |
+
context_data[f"exists:{repo_name}"] = exists
|
| 414 |
+
|
| 415 |
+
# CodeBuild Project
|
| 416 |
+
project_name = CODEBUILD_PROJECT_NAME
|
| 417 |
+
exists, project_arn, service_role_arn = check_codebuild_project_exists(project_name)
|
| 418 |
+
context_data[f"exists:{project_name}"] = exists
|
| 419 |
+
if exists:
|
| 420 |
+
context_data[f"arn:{project_name}"] = project_arn
|
| 421 |
+
if service_role_arn:
|
| 422 |
+
context_data[f"service_role_arn:{project_name}"] = service_role_arn
|
| 423 |
+
|
| 424 |
+
# ALB (by name lookup) — skipped when Express Mode will provision its own ALB
|
| 425 |
+
alb_name = ALB_NAME[-32:] if len(ALB_NAME) > 32 else ALB_NAME
|
| 426 |
+
if USE_ECS_EXPRESS_MODE == "True":
|
| 427 |
+
context_data[f"exists:{alb_name}"] = False
|
| 428 |
+
print(
|
| 429 |
+
"USE_ECS_EXPRESS_MODE=True: skipping ALB pre-check (Express provisions ALB)."
|
| 430 |
+
)
|
| 431 |
+
elif ENABLE_HEADLESS_DEPLOYMENT == "True":
|
| 432 |
+
context_data[f"exists:{alb_name}"] = False
|
| 433 |
+
print(
|
| 434 |
+
"ENABLE_HEADLESS_DEPLOYMENT=True: skipping ALB pre-check (no web ingress)."
|
| 435 |
+
)
|
| 436 |
+
if ENABLE_HEADLESS_DEPLOYMENT == "True":
|
| 437 |
+
print(
|
| 438 |
+
"ENABLE_HEADLESS_DEPLOYMENT=True: requires ENABLE_S3_BATCH_ECS_TRIGGER=True "
|
| 439 |
+
"and USE_ECS_EXPRESS_MODE=False."
|
| 440 |
+
)
|
| 441 |
+
elif ENABLE_S3_BATCH_ECS_TRIGGER == "True":
|
| 442 |
+
print(
|
| 443 |
+
"ENABLE_S3_BATCH_ECS_TRIGGER=True: requires legacy Fargate (USE_ECS_EXPRESS_MODE=False)."
|
| 444 |
+
)
|
| 445 |
+
if ENABLE_PI_AGENT_ECS_SERVICE == "True":
|
| 446 |
+
print(
|
| 447 |
+
"ENABLE_PI_AGENT_ECS_SERVICE=True: requires legacy Fargate, Service Connect, "
|
| 448 |
+
"and PI_ALB_ROUTING (default path=/pi on shared ALB; host mode needs PI_ALB_HOST_HEADER)."
|
| 449 |
+
)
|
| 450 |
+
elif ENABLE_HEADLESS_DEPLOYMENT == "True":
|
| 451 |
+
print(
|
| 452 |
+
"ENABLE_HEADLESS_DEPLOYMENT=True: legacy Fargate task definition + "
|
| 453 |
+
"S3 batch Lambda only (no ALB pre-check)."
|
| 454 |
+
)
|
| 455 |
+
else:
|
| 456 |
+
exists, alb_object = check_alb_exists(alb_name, region_name=AWS_REGION)
|
| 457 |
+
context_data[f"exists:{alb_name}"] = exists
|
| 458 |
+
if exists:
|
| 459 |
+
print("alb_object:", alb_object)
|
| 460 |
+
context_data[f"arn:{alb_name}"] = alb_object["LoadBalancerArn"]
|
| 461 |
+
context_data[f"dns:{alb_name}"] = alb_object["DNSName"]
|
| 462 |
+
context_data[f"canonical_hosted_zone_id:{alb_name}"] = alb_object[
|
| 463 |
+
"CanonicalHostedZoneId"
|
| 464 |
+
]
|
| 465 |
+
if alb_object.get("SecurityGroups"):
|
| 466 |
+
context_data[f"security_group_id:{alb_name}"] = alb_object[
|
| 467 |
+
"SecurityGroups"
|
| 468 |
+
][0]
|
| 469 |
+
|
| 470 |
+
# Cognito (web login only; headless batch mode has no Gradio/ALB ingress)
|
| 471 |
+
if ENABLE_HEADLESS_DEPLOYMENT != "True":
|
| 472 |
+
domain_prefix = (COGNITO_USER_POOL_DOMAIN_PREFIX or "").strip().lower()
|
| 473 |
+
if domain_prefix:
|
| 474 |
+
availability = resolve_cognito_domain_prefix_availability(
|
| 475 |
+
domain_prefix, region_name=AWS_REGION
|
| 476 |
+
)
|
| 477 |
+
context_data[f"cognito_domain_taken:{domain_prefix}"] = (
|
| 478 |
+
availability == "taken"
|
| 479 |
+
)
|
| 480 |
+
|
| 481 |
+
user_pool_name = COGNITO_USER_POOL_NAME
|
| 482 |
+
exists, user_pool_id, _ = check_for_existing_user_pool(user_pool_name)
|
| 483 |
+
context_data[f"exists:{user_pool_name}"] = exists
|
| 484 |
+
if exists:
|
| 485 |
+
context_data[f"id:{user_pool_name}"] = user_pool_id
|
| 486 |
+
|
| 487 |
+
# Cognito User Pool Client (by name and pool ID) - requires User Pool ID from check
|
| 488 |
+
if user_pool_id:
|
| 489 |
+
user_pool_id_for_client_check = user_pool_id # context_data.get(f"id:{user_pool_name}") # Use ID from context
|
| 490 |
+
user_pool_client_name = COGNITO_USER_POOL_CLIENT_NAME
|
| 491 |
+
if user_pool_id_for_client_check:
|
| 492 |
+
exists, client_id, _ = check_for_existing_user_pool_client(
|
| 493 |
+
user_pool_client_name, user_pool_id_for_client_check
|
| 494 |
+
)
|
| 495 |
+
context_data[f"exists:{user_pool_client_name}"] = exists
|
| 496 |
+
if exists:
|
| 497 |
+
context_data[f"id:{user_pool_client_name}"] = client_id
|
| 498 |
+
else:
|
| 499 |
+
print(
|
| 500 |
+
f"User pool '{user_pool_name}' exists but app client "
|
| 501 |
+
f"'{user_pool_client_name}' does not; CDK will create a new client."
|
| 502 |
+
)
|
| 503 |
+
|
| 504 |
+
# Secrets Manager Secret (by name)
|
| 505 |
+
secret_name = COGNITO_USER_POOL_CLIENT_SECRET_NAME
|
| 506 |
+
exists, secret_response = check_for_secret(secret_name)
|
| 507 |
+
context_data[f"exists:{secret_name}"] = exists
|
| 508 |
+
if exists:
|
| 509 |
+
secret_arn = (
|
| 510 |
+
secret_response.get("ARN")
|
| 511 |
+
if isinstance(secret_response, dict)
|
| 512 |
+
else None
|
| 513 |
+
)
|
| 514 |
+
if secret_arn:
|
| 515 |
+
context_data[f"arn:{secret_name}"] = secret_arn
|
| 516 |
+
print("Cognito secret ARN recorded for IAM grants.")
|
| 517 |
+
secret_kms_key_arn = get_secret_kms_key_arn(
|
| 518 |
+
secret_name, region_name=AWS_REGION
|
| 519 |
+
)
|
| 520 |
+
if secret_kms_key_arn:
|
| 521 |
+
context_data[f"kms_key_arn:{secret_name}"] = secret_kms_key_arn
|
| 522 |
+
print("Cognito secret KMS key recorded for execution role decrypt.")
|
| 523 |
+
else:
|
| 524 |
+
print(
|
| 525 |
+
"Warning: Cognito secret exists but ARN was not returned; "
|
| 526 |
+
"CDK will use a name-based ARN wildcard in IAM policies."
|
| 527 |
+
)
|
| 528 |
+
else:
|
| 529 |
+
print(
|
| 530 |
+
"ENABLE_HEADLESS_DEPLOYMENT=True: skipping Cognito user pool and secret pre-checks."
|
| 531 |
+
)
|
| 532 |
+
|
| 533 |
+
# Service Connect client security groups (by name in VPC)
|
| 534 |
+
if ENABLE_ECS_SERVICE_CONNECT == "True":
|
| 535 |
+
vpc_id_for_sg = context_data.get("vpc_id")
|
| 536 |
+
if vpc_id_for_sg:
|
| 537 |
+
for sg_name in ECS_SERVICE_CONNECT_CLIENT_SECURITY_GROUP_NAMES_TO_LOOKUP:
|
| 538 |
+
exists, sg_id = get_security_group_id_by_name(
|
| 539 |
+
sg_name, vpc_id_for_sg, region_name=AWS_REGION
|
| 540 |
+
)
|
| 541 |
+
context_data[f"exists:sg:{sg_name}"] = exists
|
| 542 |
+
if exists:
|
| 543 |
+
context_data[f"security_group_id:{sg_name}"] = sg_id
|
| 544 |
+
print(f"Service Connect client SG '{sg_name}' -> {sg_id}")
|
| 545 |
+
else:
|
| 546 |
+
print(
|
| 547 |
+
f"Warning: Service Connect client SG '{sg_name}' "
|
| 548 |
+
f"not found in VPC {vpc_id_for_sg}"
|
| 549 |
+
)
|
| 550 |
+
else:
|
| 551 |
+
print(
|
| 552 |
+
"Warning: vpc_id missing from context; cannot resolve Service "
|
| 553 |
+
"Connect client security group names."
|
| 554 |
+
)
|
| 555 |
+
|
| 556 |
+
# WAF Web ACL (by name and scope)
|
| 557 |
+
web_acl_name = WEB_ACL_NAME
|
| 558 |
+
exists, existing_web_acl = check_web_acl_exists(web_acl_name, scope="CLOUDFRONT")
|
| 559 |
+
context_data[f"exists:{web_acl_name}"] = exists
|
| 560 |
+
if exists:
|
| 561 |
+
context_data[f"arn:{web_acl_name}"] = existing_web_acl["ARN"]
|
| 562 |
+
|
| 563 |
+
# Write the context data to the file
|
| 564 |
+
with open(CONTEXT_FILE, "w") as f:
|
| 565 |
+
json.dump(context_data, f, indent=2)
|
| 566 |
+
|
| 567 |
+
print(f"Context data written to {CONTEXT_FILE}")
|
| 568 |
+
|
| 569 |
+
|
| 570 |
+
if __name__ == "__main__":
|
| 571 |
+
print(f"Pre-check context file: {CONTEXT_FILE}")
|
| 572 |
+
print(
|
| 573 |
+
"Running AWS pre-check (requires credentials for the target account/region)..."
|
| 574 |
+
)
|
| 575 |
+
try:
|
| 576 |
+
check_and_set_context()
|
| 577 |
+
except SystemExit:
|
| 578 |
+
raise
|
| 579 |
+
except Exception as exc:
|
| 580 |
+
raise SystemExit(f"Pre-check failed: {exc}") from exc
|
| 581 |
+
if not os.path.exists(CONTEXT_FILE):
|
| 582 |
+
raise SystemExit(f"Pre-check finished but {CONTEXT_FILE} was not created.")
|
| 583 |
+
print(f"Pre-check complete. Context written to {os.path.abspath(CONTEXT_FILE)}")
|
cdk/config/app_config.env.example
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# AWS deployment app settings (copy to cdk/config/app_config.env — do not commit secrets).
|
| 2 |
+
# Same variable names as tools/config.py; loaded by ECS from S3 or Express env.
|
| 3 |
+
COGNITO_AUTH=True
|
| 4 |
+
RUN_AWS_FUNCTIONS=True
|
| 5 |
+
RUN_AWS_BEDROCK_MODELS=True
|
| 6 |
+
RUN_LOCAL_MODEL=False
|
| 7 |
+
RUN_GEMINI_MODELS=False
|
| 8 |
+
RUN_AZURE_MODELS=False
|
| 9 |
+
PRIORITISE_SSO_OVER_AWS_ENV_ACCESS_KEYS=True
|
| 10 |
+
DISPLAY_FILE_NAMES_IN_LOGS=False
|
| 11 |
+
SESSION_OUTPUT_FOLDER=True
|
| 12 |
+
SAVE_LOGS_TO_CSV=True
|
| 13 |
+
SAVE_LOGS_TO_DYNAMODB=True
|
| 14 |
+
SHOW_COSTS=True
|
| 15 |
+
S3_LOG_BUCKET=demo-llm-topic-s3-logs
|
| 16 |
+
S3_OUTPUTS_BUCKET=
|
| 17 |
+
S3_OUTPUTS_FOLDER=
|
| 18 |
+
SAVE_OUTPUTS_TO_S3=False
|
| 19 |
+
UPLOAD_USAGE_LOG_TO_S3_OUTPUTS=False
|
| 20 |
+
UPLOAD_PROMPT_RESPONSE_LOG_TO_S3_OUTPUTS=False
|
| 21 |
+
ACCESS_LOG_DYNAMODB_TABLE_NAME=demo-llm-topic-dynamodb-access-logs
|
| 22 |
+
FEEDBACK_LOG_DYNAMODB_TABLE_NAME=demo-llm-topic-dynamodb-feedback-logs
|
| 23 |
+
USAGE_LOG_DYNAMODB_TABLE_NAME=demo-llm-topic-dynamodb-usage-logs
|
| 24 |
+
LOG_FILE_NAME=log.csv
|
| 25 |
+
USAGE_LOG_FILE_NAME=usage_log.csv
|
| 26 |
+
FEEDBACK_LOG_FILE_NAME=feedback_log.csv
|
cdk/config/headless_s3_seed/input/config/example_headless_env_file.env
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Example job file for headless batch topic modelling.
|
| 2 |
+
# 1. Upload your consultation spreadsheet to s3://<output-bucket>/input/
|
| 3 |
+
# 2. Copy this file, set DIRECT_MODE_INPUT_FILE to that filename, save as my-job.env
|
| 4 |
+
# 3. Upload my-job.env to s3://<output-bucket>/input/config/ to start the ECS task.
|
| 5 |
+
#
|
| 6 |
+
# More DIRECT_MODE_* variables: tools/config.py and cli_topics.py in this repo.
|
| 7 |
+
|
| 8 |
+
RUN_DIRECT_MODE=1
|
| 9 |
+
DIRECT_MODE_TASK=extract
|
| 10 |
+
DIRECT_MODE_INPUT_FILE=dummy_consultation_response.xlsx
|
| 11 |
+
DIRECT_MODE_TEXT_COLUMN="Response Text"
|
| 12 |
+
SAVE_OUTPUTS_TO_S3=True
|
| 13 |
+
S3_OUTPUTS_FOLDER=output/
|
cdk/config/lambda/lambda_function.py
ADDED
|
@@ -0,0 +1,187 @@
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import urllib.parse
|
| 3 |
+
|
| 4 |
+
import boto3
|
| 5 |
+
|
| 6 |
+
ecs = boto3.client("ecs")
|
| 7 |
+
s3 = boto3.client("s3")
|
| 8 |
+
|
| 9 |
+
# Move static config to Lambda env vars for easier ops
|
| 10 |
+
BUCKET = os.environ.get("BUCKET", "lambeth-llm-topic-modelling")
|
| 11 |
+
INPUT_PREFIX = os.environ.get("INPUT_PREFIX", "input/")
|
| 12 |
+
ENV_PREFIX = os.environ.get("ENV_PREFIX", f"{INPUT_PREFIX}config/")
|
| 13 |
+
GENERAL_ENV_PREFIX = os.environ.get("GENERAL_ENV_PREFIX", "general-config/")
|
| 14 |
+
ENV_SUFFIX = os.environ.get("ENV_SUFFIX", ".env")
|
| 15 |
+
DEFAULT_PARAMS_KEY = os.environ.get(
|
| 16 |
+
"DEFAULT_PARAMS_KEY", f"{GENERAL_ENV_PREFIX}app_defaults{ENV_SUFFIX}"
|
| 17 |
+
)
|
| 18 |
+
CLUSTER = os.environ.get("ECS_CLUSTER", "analytics_fargate_cluster")
|
| 19 |
+
TASK_DEF = os.environ.get("ECS_TASK_DEF", "llm_topic_modelling_fargate_def:5")
|
| 20 |
+
SUBNETS = os.environ.get(
|
| 21 |
+
"SUBNETS", "subnet-083650a35f93a0ee5,subnet-0a41ba70470cabab8"
|
| 22 |
+
).split(",")
|
| 23 |
+
SECURITY_GROUPS = os.environ.get("SECURITY_GROUPS", "sg-051effb4c5e752df1").split(",")
|
| 24 |
+
ECS_ASSIGN_PUBLIC_IP = os.environ.get("ECS_ASSIGN_PUBLIC_IP", "DISABLED").upper()
|
| 25 |
+
DEFAULT_INPUT_S3_URI = os.environ.get(
|
| 26 |
+
"DEFAULT_INPUT_S3_URI",
|
| 27 |
+
f"s3://{BUCKET}/{INPUT_PREFIX}dummy_consultation_response.xlsx",
|
| 28 |
+
)
|
| 29 |
+
DEFAULT_TASK_TYPE = os.environ.get("DEFAULT_TASK_TYPE", "extract")
|
| 30 |
+
CONTAINER_NAME = os.environ.get("CONTAINER_NAME", "llm_topic_modelling_container")
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def _key_matches(key: str) -> bool:
|
| 34 |
+
return key.startswith(ENV_PREFIX) and key.endswith(ENV_SUFFIX)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def _derive_runtime_params_from_key(key: str) -> dict:
|
| 38 |
+
"""Optional convention: decide task type from file name."""
|
| 39 |
+
basename = key.split("/")[-1].lower()
|
| 40 |
+
if "train" in basename:
|
| 41 |
+
task_type = "train"
|
| 42 |
+
elif "infer" in basename or "staging" in basename:
|
| 43 |
+
task_type = "infer"
|
| 44 |
+
else:
|
| 45 |
+
task_type = DEFAULT_TASK_TYPE
|
| 46 |
+
|
| 47 |
+
return {
|
| 48 |
+
"DIRECT_MODE_TASK": task_type,
|
| 49 |
+
"DIRECT_MODE_INPUT_FILE": DEFAULT_INPUT_S3_URI,
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def _parse_dotenv(dotenv_bytes: bytes, bucket: str, input_prefix: str) -> dict:
|
| 54 |
+
"""
|
| 55 |
+
Parse a basic .env and prepend S3 paths to specific keys if they have values.
|
| 56 |
+
"""
|
| 57 |
+
env = {}
|
| 58 |
+
text = dotenv_bytes.decode("utf-8", errors="replace")
|
| 59 |
+
|
| 60 |
+
# 1. Parse the file (Existing Logic)
|
| 61 |
+
for raw_line in text.splitlines():
|
| 62 |
+
line = raw_line.strip()
|
| 63 |
+
if not line or line.startswith("#"):
|
| 64 |
+
continue
|
| 65 |
+
if line.startswith("export "):
|
| 66 |
+
line = line[len("export ") :].strip()
|
| 67 |
+
if "=" not in line:
|
| 68 |
+
continue
|
| 69 |
+
key, value = line.split("=", 1)
|
| 70 |
+
key = key.strip()
|
| 71 |
+
value = value.strip()
|
| 72 |
+
if (value.startswith('"') and value.endswith('"')) or (
|
| 73 |
+
value.startswith("'") and value.endswith("'")
|
| 74 |
+
):
|
| 75 |
+
value = value[1:-1]
|
| 76 |
+
env[key] = value
|
| 77 |
+
|
| 78 |
+
# 2. Apply S3 Prefix Logic (New Logic)
|
| 79 |
+
# We define the base S3 path string using the provided arguments
|
| 80 |
+
s3_base = f"s3://{bucket}/{input_prefix}"
|
| 81 |
+
|
| 82 |
+
# List of keys that need modification
|
| 83 |
+
keys_to_modify = ["DIRECT_MODE_INPUT_FILE", "DIRECT_MODE_CANDIDATE_TOPICS"]
|
| 84 |
+
|
| 85 |
+
for key in keys_to_modify:
|
| 86 |
+
# env.get(key) returns the value.
|
| 87 |
+
# The 'if' check ensures the key exists AND is not an empty string.
|
| 88 |
+
if env.get(key):
|
| 89 |
+
env[key] = s3_base + env[key]
|
| 90 |
+
|
| 91 |
+
return env
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def _build_environment_array(*env_dicts):
|
| 95 |
+
"""Merge dictionaries left→right and produce ECS environment array format."""
|
| 96 |
+
merged = {}
|
| 97 |
+
for d in env_dicts:
|
| 98 |
+
merged.update(d or {})
|
| 99 |
+
# ECS override format: [{"name": "...","value":"..."}]
|
| 100 |
+
return [{"name": k, "value": v} for k, v in merged.items()]
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def lambda_handler(event, context):
|
| 104 |
+
runs = []
|
| 105 |
+
|
| 106 |
+
# Parse default env file with default config
|
| 107 |
+
# Fetch the default .env file content from S3
|
| 108 |
+
default_obj = s3.get_object(Bucket=BUCKET, Key=DEFAULT_PARAMS_KEY)
|
| 109 |
+
default_dotenv_bytes = default_obj["Body"].read()
|
| 110 |
+
|
| 111 |
+
# Parse .env → dict of env vars
|
| 112 |
+
default_file_env = _parse_dotenv(default_dotenv_bytes, BUCKET, INPUT_PREFIX)
|
| 113 |
+
|
| 114 |
+
for record in event.get("Records", []):
|
| 115 |
+
|
| 116 |
+
# Parse env file from user
|
| 117 |
+
s3rec = record.get("s3", {})
|
| 118 |
+
bucket = s3rec.get("bucket", {}).get("name")
|
| 119 |
+
raw_key = s3rec.get("object", {}).get("key")
|
| 120 |
+
if not bucket or not raw_key:
|
| 121 |
+
print(f"Object in bucket {bucket} and key {raw_key} not found, exiting.")
|
| 122 |
+
continue
|
| 123 |
+
|
| 124 |
+
key = urllib.parse.unquote_plus(raw_key)
|
| 125 |
+
|
| 126 |
+
# combined_key = ENV_PREFIX + key
|
| 127 |
+
combined_key = key
|
| 128 |
+
|
| 129 |
+
print("combined_key:", combined_key)
|
| 130 |
+
|
| 131 |
+
# Only process the intended prefix/suffix
|
| 132 |
+
if not _key_matches(combined_key):
|
| 133 |
+
print(f"Key does not match: {combined_key}, exiting")
|
| 134 |
+
continue
|
| 135 |
+
|
| 136 |
+
# Fetch the .env file content from S3
|
| 137 |
+
obj = s3.get_object(Bucket=bucket, Key=combined_key)
|
| 138 |
+
dotenv_bytes = obj["Body"].read()
|
| 139 |
+
|
| 140 |
+
# Parse .env → dict of env vars
|
| 141 |
+
file_env = _parse_dotenv(dotenv_bytes, BUCKET, INPUT_PREFIX)
|
| 142 |
+
|
| 143 |
+
# Optionally derive run-time params from naming
|
| 144 |
+
# run_params = _derive_runtime_params_from_key(key)
|
| 145 |
+
|
| 146 |
+
# Merge: file env (dominant), overwrites default values.
|
| 147 |
+
environment = _build_environment_array(file_env, default_file_env)
|
| 148 |
+
|
| 149 |
+
print("Combined environment variables:", environment)
|
| 150 |
+
|
| 151 |
+
# Execute ECS Fargate task with fully dynamic environment overrides
|
| 152 |
+
response = ecs.run_task(
|
| 153 |
+
cluster=CLUSTER,
|
| 154 |
+
launchType="FARGATE",
|
| 155 |
+
taskDefinition=TASK_DEF,
|
| 156 |
+
networkConfiguration={
|
| 157 |
+
"awsvpcConfiguration": {
|
| 158 |
+
"subnets": SUBNETS,
|
| 159 |
+
"securityGroups": SECURITY_GROUPS,
|
| 160 |
+
"assignPublicIp": (
|
| 161 |
+
ECS_ASSIGN_PUBLIC_IP
|
| 162 |
+
if ECS_ASSIGN_PUBLIC_IP in ("ENABLED", "DISABLED")
|
| 163 |
+
else "DISABLED"
|
| 164 |
+
),
|
| 165 |
+
}
|
| 166 |
+
},
|
| 167 |
+
overrides={
|
| 168 |
+
"containerOverrides": [
|
| 169 |
+
{
|
| 170 |
+
"name": CONTAINER_NAME,
|
| 171 |
+
"environment": environment,
|
| 172 |
+
}
|
| 173 |
+
]
|
| 174 |
+
},
|
| 175 |
+
)
|
| 176 |
+
|
| 177 |
+
runs.append(
|
| 178 |
+
{
|
| 179 |
+
"bucket": bucket,
|
| 180 |
+
"key": key,
|
| 181 |
+
"taskArns": [t["taskArn"] for t in response.get("tasks", [])],
|
| 182 |
+
"failures": response.get("failures", []),
|
| 183 |
+
"envCount": len(environment),
|
| 184 |
+
}
|
| 185 |
+
)
|
| 186 |
+
|
| 187 |
+
return {"runs": runs}
|
cdk/docs/express_pi_service_connect_spike.md
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Phase 0: Express Service Connect validation (dev account)
|
| 2 |
+
|
| 3 |
+
Service Connect for Express is applied in `post_cdk_build_quickstart.py` (not during
|
| 4 |
+
`cdk deploy`). Express primary containers do not define named `portMappings` at create
|
| 5 |
+
time, so the post-deploy step registers a task-definition revision with
|
| 6 |
+
`port-{port}` and then calls `ecs:UpdateService` with `serviceConnectConfiguration`.
|
| 7 |
+
Use this checklist to confirm behaviour in a dev account before relying on Pi Express demos.
|
| 8 |
+
|
| 9 |
+
## Prerequisites
|
| 10 |
+
|
| 11 |
+
- Main Express stack deployed (`USE_ECS_EXPRESS_MODE=True`).
|
| 12 |
+
- Optional: deploy with `ENABLE_PI_AGENT_EXPRESS_SERVICE=True` and run
|
| 13 |
+
`python post_cdk_build_quickstart.py` (Service Connect is configured there).
|
| 14 |
+
|
| 15 |
+
## Manual validation (without Pi CDK flag)
|
| 16 |
+
|
| 17 |
+
1. Note cluster name, main Express **service name**, and task security group from stack outputs.
|
| 18 |
+
2. Ensure the cluster has a default Cloud Map namespace (CDK creates one when Pi Express is enabled).
|
| 19 |
+
3. Update the main Express service (server):
|
| 20 |
+
|
| 21 |
+
```bash
|
| 22 |
+
aws ecs update-service \
|
| 23 |
+
--cluster <CLUSTER_NAME> \
|
| 24 |
+
--service <ECS_EXPRESS_SERVICE_NAME> \
|
| 25 |
+
--force-new-deployment \
|
| 26 |
+
--service-connect-configuration '{
|
| 27 |
+
"enabled": true,
|
| 28 |
+
"namespace": "<ECS_SERVICE_CONNECT_NAMESPACE>",
|
| 29 |
+
"services": [{
|
| 30 |
+
"portName": "port-7860",
|
| 31 |
+
"discoveryName": "summarisation",
|
| 32 |
+
"clientAliases": [{"port": 7860, "dnsName": "summarisation"}]
|
| 33 |
+
}]
|
| 34 |
+
}'
|
| 35 |
+
```
|
| 36 |
+
|
| 37 |
+
4. Deploy a second Express service (Pi image, port **7862**) or use CDK Pi Express.
|
| 38 |
+
5. Update the Pi Express service (client only):
|
| 39 |
+
|
| 40 |
+
```bash
|
| 41 |
+
aws ecs update-service \
|
| 42 |
+
--cluster <CLUSTER_NAME> \
|
| 43 |
+
--service <ECS_PI_EXPRESS_SERVICE_NAME> \
|
| 44 |
+
--force-new-deployment \
|
| 45 |
+
--service-connect-configuration '{
|
| 46 |
+
"enabled": true,
|
| 47 |
+
"namespace": "<ECS_SERVICE_CONNECT_NAMESPACE>"
|
| 48 |
+
}'
|
| 49 |
+
```
|
| 50 |
+
|
| 51 |
+
6. Exec into a Pi task (ECS Exec enabled on the service):
|
| 52 |
+
|
| 53 |
+
```bash
|
| 54 |
+
curl -sS -o /dev/null -w "%{http_code}\n" http://summarisation:7860/
|
| 55 |
+
```
|
| 56 |
+
|
| 57 |
+
Expect HTTP **200** (or Gradio redirect) without Cognito.
|
| 58 |
+
|
| 59 |
+
7. Optional: run a minimal `gradio_client` predict against `/doc_redact` from the Pi task.
|
| 60 |
+
|
| 61 |
+
## Exit criteria
|
| 62 |
+
|
| 63 |
+
- Service Connect DNS `summarisation` resolves inside the Pi task network namespace.
|
| 64 |
+
- Gradio responds on port 7860 without ALB Cognito.
|
| 65 |
+
- If `update-service` fails or `portName` is rejected, stop and use legacy Fargate Pi +
|
| 66 |
+
`ENABLE_ECS_SERVICE_CONNECT` until AWS/CDK support is confirmed (plan Phase 2 hybrid).
|
| 67 |
+
|
| 68 |
+
## CDK deploy path
|
| 69 |
+
|
| 70 |
+
With `ENABLE_PI_AGENT_EXPRESS_SERVICE=True`, run `post_cdk_build_quickstart.py` after
|
| 71 |
+
`cdk deploy`. Check its output for Service Connect / task-definition errors.
|
cdk/example_headless_env_file.env
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
DIRECT_MODE_INPUT_FILE=example_of_emails_sent_to_a_professor_before_applying.pdf
|
cdk/lambda_dynamo_logs_export/lambda_function.py
ADDED
|
@@ -0,0 +1,316 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Lambda handler to export DynamoDB usage log table to CSV and upload to S3.
|
| 3 |
+
|
| 4 |
+
All inputs are read from environment variables (no argparse).
|
| 5 |
+
Intended to run as an AWS Lambda function; can also be invoked locally
|
| 6 |
+
by setting env vars and calling lambda_handler({}, None).
|
| 7 |
+
|
| 8 |
+
Environment variables (same semantics as load_dynamo_logs.py CLI):
|
| 9 |
+
DYNAMODB_TABLE_NAME - DynamoDB table name (default: summarisation_usage)
|
| 10 |
+
AWS_REGION - AWS region (optional; if unset, uses AWS_DEFAULT_REGION,
|
| 11 |
+
then region from Lambda context ARN, then eu-west-2)
|
| 12 |
+
OUTPUT_FOLDER - Local output directory, e.g. /tmp (optional)
|
| 13 |
+
OUTPUT_FILENAME - Local output file name (default: dynamodb_logs_export.csv)
|
| 14 |
+
OUTPUT - Full local output path (overrides folder + filename if set).
|
| 15 |
+
In Lambda only /tmp is writable; relative paths are auto-resolved to /tmp.
|
| 16 |
+
FROM_DATE - Only include entries on/after this date YYYY-MM-DD (optional)
|
| 17 |
+
TO_DATE - Only include entries on/before this date YYYY-MM-DD (optional)
|
| 18 |
+
DATE_ATTRIBUTE - Attribute name for date filtering (default: timestamp)
|
| 19 |
+
S3_OUTPUT_BUCKET - S3 bucket for the output CSV (required for upload)
|
| 20 |
+
S3_OUTPUT_KEY - S3 object key/path for the output CSV (required for upload)
|
| 21 |
+
"""
|
| 22 |
+
|
| 23 |
+
import csv
|
| 24 |
+
import datetime
|
| 25 |
+
import os
|
| 26 |
+
from decimal import Decimal
|
| 27 |
+
from io import StringIO
|
| 28 |
+
|
| 29 |
+
import boto3
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def _get_region_from_context(context):
|
| 33 |
+
"""Extract region from Lambda context invoked_function_arn (arn:aws:lambda:REGION:ACCOUNT:function:NAME)."""
|
| 34 |
+
if context is None:
|
| 35 |
+
return None
|
| 36 |
+
arn = getattr(context, "invoked_function_arn", None)
|
| 37 |
+
if not arn or not isinstance(arn, str):
|
| 38 |
+
return None
|
| 39 |
+
parts = arn.split(":")
|
| 40 |
+
if len(parts) >= 4:
|
| 41 |
+
return parts[3] # region is 4th segment
|
| 42 |
+
return None
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def get_config_from_env(context=None):
|
| 46 |
+
"""Read all settings from environment variables (same inputs as load_dynamo_logs.py).
|
| 47 |
+
When running in Lambda, context can be passed to derive region from the function ARN if env is not set.
|
| 48 |
+
"""
|
| 49 |
+
today = datetime.datetime.now().date()
|
| 50 |
+
one_year_ago = today - datetime.timedelta(days=365)
|
| 51 |
+
|
| 52 |
+
table_name = os.environ.get("DYNAMODB_TABLE_NAME") or os.environ.get(
|
| 53 |
+
"USAGE_LOG_DYNAMODB_TABLE_NAME", "summarisation_usage"
|
| 54 |
+
)
|
| 55 |
+
region = (
|
| 56 |
+
os.environ.get("AWS_REGION") or os.environ.get("AWS_DEFAULT_REGION") or ""
|
| 57 |
+
).strip()
|
| 58 |
+
output = os.environ.get("OUTPUT")
|
| 59 |
+
output_folder = os.environ.get("OUTPUT_FOLDER", "output/")
|
| 60 |
+
output_filename = os.environ.get("OUTPUT_FILENAME", "dynamodb_logs_export.csv")
|
| 61 |
+
from_date_str = os.environ.get("FROM_DATE")
|
| 62 |
+
to_date_str = os.environ.get("TO_DATE")
|
| 63 |
+
date_attribute = os.environ.get("DATE_ATTRIBUTE", "timestamp")
|
| 64 |
+
s3_output_bucket = os.environ.get("S3_OUTPUT_BUCKET")
|
| 65 |
+
s3_output_key = os.environ.get("S3_OUTPUT_KEY")
|
| 66 |
+
|
| 67 |
+
if output:
|
| 68 |
+
local_output_path = output
|
| 69 |
+
else:
|
| 70 |
+
folder = output_folder.rstrip("/").rstrip("\\")
|
| 71 |
+
local_output_path = os.path.join(folder, output_filename)
|
| 72 |
+
|
| 73 |
+
# In AWS Lambda only /tmp is writable; resolve relative paths to /tmp to avoid read-only FS errors
|
| 74 |
+
if os.environ.get("AWS_LAMBDA_FUNCTION_NAME"):
|
| 75 |
+
resolved = os.path.abspath(local_output_path)
|
| 76 |
+
if not resolved.startswith("/tmp"):
|
| 77 |
+
local_output_path = os.path.join(
|
| 78 |
+
"/tmp", os.path.basename(local_output_path)
|
| 79 |
+
)
|
| 80 |
+
|
| 81 |
+
# Region: env (AWS_REGION / AWS_DEFAULT_REGION) → Lambda context ARN → hardcoded fallback
|
| 82 |
+
if not region and context is not None:
|
| 83 |
+
region = _get_region_from_context(context) or ""
|
| 84 |
+
if not region:
|
| 85 |
+
region = "eu-west-2"
|
| 86 |
+
|
| 87 |
+
from_date = None
|
| 88 |
+
to_date = None
|
| 89 |
+
if from_date_str:
|
| 90 |
+
from_date = datetime.datetime.strptime(from_date_str, "%Y-%m-%d").date()
|
| 91 |
+
if to_date_str:
|
| 92 |
+
to_date = datetime.datetime.strptime(to_date_str, "%Y-%m-%d").date()
|
| 93 |
+
if from_date is None and to_date is None:
|
| 94 |
+
from_date = one_year_ago
|
| 95 |
+
to_date = today
|
| 96 |
+
elif from_date is None:
|
| 97 |
+
from_date = one_year_ago
|
| 98 |
+
elif to_date is None:
|
| 99 |
+
to_date = today
|
| 100 |
+
|
| 101 |
+
return {
|
| 102 |
+
"table_name": table_name,
|
| 103 |
+
"region": region,
|
| 104 |
+
"local_output_path": local_output_path,
|
| 105 |
+
"from_date": from_date,
|
| 106 |
+
"to_date": to_date,
|
| 107 |
+
"date_attribute": date_attribute,
|
| 108 |
+
"s3_output_bucket": s3_output_bucket,
|
| 109 |
+
"s3_output_key": s3_output_key,
|
| 110 |
+
}
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def convert_types(item):
|
| 114 |
+
new_item = {}
|
| 115 |
+
for key, value in item.items():
|
| 116 |
+
if isinstance(value, Decimal):
|
| 117 |
+
new_item[key] = int(value) if value % 1 == 0 else float(value)
|
| 118 |
+
elif isinstance(value, str):
|
| 119 |
+
try:
|
| 120 |
+
dt_obj = datetime.datetime.fromisoformat(value.replace("Z", "+00:00"))
|
| 121 |
+
new_item[key] = dt_obj.strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
|
| 122 |
+
except (ValueError, TypeError):
|
| 123 |
+
new_item[key] = value
|
| 124 |
+
else:
|
| 125 |
+
new_item[key] = value
|
| 126 |
+
return new_item
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def _parse_item_date(value):
|
| 130 |
+
"""Parse a DynamoDB attribute value to datetime for comparison. Returns None if unparseable."""
|
| 131 |
+
if value is None:
|
| 132 |
+
return None
|
| 133 |
+
if isinstance(value, Decimal):
|
| 134 |
+
try:
|
| 135 |
+
return datetime.datetime.utcfromtimestamp(float(value))
|
| 136 |
+
except (ValueError, OSError):
|
| 137 |
+
return None
|
| 138 |
+
if isinstance(value, (int, float)):
|
| 139 |
+
try:
|
| 140 |
+
return datetime.datetime.utcfromtimestamp(float(value))
|
| 141 |
+
except (ValueError, OSError):
|
| 142 |
+
return None
|
| 143 |
+
if isinstance(value, str):
|
| 144 |
+
for fmt in (
|
| 145 |
+
"%Y-%m-%d %H:%M:%S.%f",
|
| 146 |
+
"%Y-%m-%d %H:%M:%S",
|
| 147 |
+
"%Y-%m-%d",
|
| 148 |
+
"%Y-%m-%dT%H:%M:%S",
|
| 149 |
+
):
|
| 150 |
+
try:
|
| 151 |
+
return datetime.datetime.strptime(value, fmt)
|
| 152 |
+
except (ValueError, TypeError):
|
| 153 |
+
continue
|
| 154 |
+
try:
|
| 155 |
+
return datetime.datetime.fromisoformat(value.replace("Z", "+00:00"))
|
| 156 |
+
except (ValueError, TypeError):
|
| 157 |
+
pass
|
| 158 |
+
return None
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def filter_items_by_date(items, from_date, to_date, date_attribute: str):
|
| 162 |
+
"""Return items whose date attribute falls within [from_date, to_date] (inclusive)."""
|
| 163 |
+
if from_date is None and to_date is None:
|
| 164 |
+
return items
|
| 165 |
+
start = datetime.datetime.combine(from_date, datetime.time.min)
|
| 166 |
+
end = datetime.datetime.combine(to_date, datetime.time.max)
|
| 167 |
+
filtered = []
|
| 168 |
+
for item in items:
|
| 169 |
+
raw = item.get(date_attribute)
|
| 170 |
+
dt = _parse_item_date(raw)
|
| 171 |
+
if dt is None:
|
| 172 |
+
continue
|
| 173 |
+
if dt.tzinfo:
|
| 174 |
+
dt = dt.replace(tzinfo=None)
|
| 175 |
+
if start <= dt <= end:
|
| 176 |
+
filtered.append(item)
|
| 177 |
+
return filtered
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
def scan_table(table):
|
| 181 |
+
"""Paginated scan of DynamoDB table."""
|
| 182 |
+
items = []
|
| 183 |
+
response = table.scan()
|
| 184 |
+
items.extend(response["Items"])
|
| 185 |
+
while "LastEvaluatedKey" in response:
|
| 186 |
+
response = table.scan(ExclusiveStartKey=response["LastEvaluatedKey"])
|
| 187 |
+
items.extend(response["Items"])
|
| 188 |
+
return items
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
def export_to_csv_buffer(items, fields_to_drop=None):
|
| 192 |
+
"""
|
| 193 |
+
Write items to a CSV in memory; return (csv_string, fieldnames).
|
| 194 |
+
Use for uploading to S3 without writing to disk.
|
| 195 |
+
"""
|
| 196 |
+
if not items:
|
| 197 |
+
return "", []
|
| 198 |
+
|
| 199 |
+
drop_set = set(fields_to_drop or [])
|
| 200 |
+
all_keys = set()
|
| 201 |
+
for item in items:
|
| 202 |
+
all_keys.update(item.keys())
|
| 203 |
+
fieldnames = sorted(list(all_keys - drop_set))
|
| 204 |
+
|
| 205 |
+
buf = StringIO()
|
| 206 |
+
writer = csv.DictWriter(
|
| 207 |
+
buf, fieldnames=fieldnames, extrasaction="ignore", restval=""
|
| 208 |
+
)
|
| 209 |
+
writer.writeheader()
|
| 210 |
+
for item in items:
|
| 211 |
+
writer.writerow(convert_types(item))
|
| 212 |
+
return buf.getvalue(), fieldnames
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
def export_to_csv_file(items, output_path, fields_to_drop=None):
|
| 216 |
+
"""Write items to a CSV file (for optional /tmp or local path)."""
|
| 217 |
+
csv_string, _ = export_to_csv_buffer(items, fields_to_drop)
|
| 218 |
+
if not csv_string:
|
| 219 |
+
return
|
| 220 |
+
os.makedirs(os.path.dirname(os.path.abspath(output_path)) or ".", exist_ok=True)
|
| 221 |
+
with open(output_path, "w", newline="", encoding="utf-8-sig") as f:
|
| 222 |
+
f.write(csv_string)
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
def run_export(config):
|
| 226 |
+
"""
|
| 227 |
+
Run the full export: scan DynamoDB, filter by date, write CSV (buffer and/or file), upload to S3.
|
| 228 |
+
"""
|
| 229 |
+
table_name = config["table_name"]
|
| 230 |
+
region = config["region"]
|
| 231 |
+
local_output_path = config["local_output_path"]
|
| 232 |
+
from_date = config["from_date"]
|
| 233 |
+
to_date = config["to_date"]
|
| 234 |
+
date_attribute = config["date_attribute"]
|
| 235 |
+
s3_output_bucket = config["s3_output_bucket"]
|
| 236 |
+
s3_output_key = config["s3_output_key"]
|
| 237 |
+
|
| 238 |
+
if from_date > to_date:
|
| 239 |
+
raise ValueError("FROM_DATE must be on or before TO_DATE")
|
| 240 |
+
|
| 241 |
+
dynamodb = boto3.resource("dynamodb", region_name=region or None)
|
| 242 |
+
table = dynamodb.Table(table_name)
|
| 243 |
+
|
| 244 |
+
items = scan_table(table)
|
| 245 |
+
items = filter_items_by_date(items, from_date, to_date, date_attribute)
|
| 246 |
+
|
| 247 |
+
csv_string, fieldnames = export_to_csv_buffer(items, fields_to_drop=[])
|
| 248 |
+
result = {
|
| 249 |
+
"item_count": len(items),
|
| 250 |
+
"from_date": str(from_date),
|
| 251 |
+
"to_date": str(to_date),
|
| 252 |
+
"columns": fieldnames,
|
| 253 |
+
}
|
| 254 |
+
|
| 255 |
+
if csv_string:
|
| 256 |
+
try:
|
| 257 |
+
export_to_csv_file(items, local_output_path, fields_to_drop=[])
|
| 258 |
+
result["local_path"] = local_output_path
|
| 259 |
+
except Exception as e:
|
| 260 |
+
result["local_write_error"] = str(e)
|
| 261 |
+
|
| 262 |
+
if s3_output_bucket and s3_output_key:
|
| 263 |
+
s3 = boto3.client("s3", region_name=region or None)
|
| 264 |
+
s3.put_object(
|
| 265 |
+
Bucket=s3_output_bucket,
|
| 266 |
+
Key=s3_output_key,
|
| 267 |
+
Body=csv_string.encode("utf-8-sig"),
|
| 268 |
+
ContentType="text/csv; charset=utf-8",
|
| 269 |
+
)
|
| 270 |
+
result["s3_uri"] = f"s3://{s3_output_bucket}/{s3_output_key}"
|
| 271 |
+
elif s3_output_bucket or s3_output_key:
|
| 272 |
+
result["s3_skip_reason"] = (
|
| 273 |
+
"Both S3_OUTPUT_BUCKET and S3_OUTPUT_KEY must be set"
|
| 274 |
+
)
|
| 275 |
+
|
| 276 |
+
return result
|
| 277 |
+
|
| 278 |
+
|
| 279 |
+
def lambda_handler(event, context):
|
| 280 |
+
"""
|
| 281 |
+
AWS Lambda entrypoint. Config is read from environment variables.
|
| 282 |
+
|
| 283 |
+
Event is not required for config; it can be used to override env vars
|
| 284 |
+
(e.g. pass table_name, from_date, to_date, s3_output_bucket, s3_output_key).
|
| 285 |
+
"""
|
| 286 |
+
config = get_config_from_env(context=context)
|
| 287 |
+
|
| 288 |
+
if isinstance(event, dict):
|
| 289 |
+
if event.get("table_name"):
|
| 290 |
+
config["table_name"] = event["table_name"]
|
| 291 |
+
if event.get("region"):
|
| 292 |
+
config["region"] = event["region"]
|
| 293 |
+
if event.get("from_date"):
|
| 294 |
+
config["from_date"] = datetime.datetime.strptime(
|
| 295 |
+
event["from_date"], "%Y-%m-%d"
|
| 296 |
+
).date()
|
| 297 |
+
if event.get("to_date"):
|
| 298 |
+
config["to_date"] = datetime.datetime.strptime(
|
| 299 |
+
event["to_date"], "%Y-%m-%d"
|
| 300 |
+
).date()
|
| 301 |
+
if event.get("date_attribute"):
|
| 302 |
+
config["date_attribute"] = event["date_attribute"]
|
| 303 |
+
if event.get("s3_output_bucket"):
|
| 304 |
+
config["s3_output_bucket"] = event["s3_output_bucket"]
|
| 305 |
+
if event.get("s3_output_key"):
|
| 306 |
+
config["s3_output_key"] = event["s3_output_key"]
|
| 307 |
+
|
| 308 |
+
result = run_export(config)
|
| 309 |
+
return {"statusCode": 200, "body": result}
|
| 310 |
+
|
| 311 |
+
|
| 312 |
+
if __name__ == "__main__":
|
| 313 |
+
import json
|
| 314 |
+
|
| 315 |
+
result = lambda_handler({}, None)
|
| 316 |
+
print(json.dumps(result, indent=2))
|
cdk/lambda_elbv2_listener_rule_upsert/lambda_function.py
ADD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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
CloudFormation custom resource: create or update an ALB listener rule (upsert by priority).
|
| 3 |
+
|
| 4 |
+
If a rule already exists at the requested priority with matching conditions, it is
|
| 5 |
+
modified in place. This supports stack retries after partial deploys left orphaned rules.
|
| 6 |
+
If priority is taken by a rule with different conditions, the operation fails with a
|
| 7 |
+
clear error so operators can choose another PI_ALB_LISTENER_RULE_PRIORITY.
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
from __future__ import annotations
|
| 11 |
+
|
| 12 |
+
import json
|
| 13 |
+
import logging
|
| 14 |
+
from typing import Any
|
| 15 |
+
|
| 16 |
+
import boto3
|
| 17 |
+
from botocore.exceptions import ClientError
|
| 18 |
+
|
| 19 |
+
LOGGER = logging.getLogger()
|
| 20 |
+
LOGGER.setLevel(logging.INFO)
|
| 21 |
+
|
| 22 |
+
elbv2 = boto3.client("elbv2")
|
| 23 |
+
|
| 24 |
+
_DELETE_NOT_FOUND = frozenset(
|
| 25 |
+
{
|
| 26 |
+
"RuleNotFound",
|
| 27 |
+
"ResourceNotFound",
|
| 28 |
+
"ValidationError",
|
| 29 |
+
}
|
| 30 |
+
)
|
| 31 |
+
# CloudFormation custom-resource properties are strings; ELBv2 expects typed fields.
|
| 32 |
+
_ELBV2_INT_KEYS = frozenset(
|
| 33 |
+
{
|
| 34 |
+
"Order",
|
| 35 |
+
"Priority",
|
| 36 |
+
"SessionTimeout",
|
| 37 |
+
"DurationSeconds",
|
| 38 |
+
"SessionCookieName",
|
| 39 |
+
}
|
| 40 |
+
)
|
| 41 |
+
_ELBV2_BOOL_KEYS = frozenset({"Enabled"})
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def _parse_json(value: Any) -> Any:
|
| 45 |
+
if isinstance(value, str):
|
| 46 |
+
return json.loads(value)
|
| 47 |
+
return value
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def _coerce_elbv2_api_value(key: str, value: Any) -> Any:
|
| 51 |
+
"""Coerce CloudFormation string properties to types boto3 elbv2 expects."""
|
| 52 |
+
if isinstance(value, dict):
|
| 53 |
+
return {k: _coerce_elbv2_api_value(k, v) for k, v in value.items()}
|
| 54 |
+
if isinstance(value, list):
|
| 55 |
+
return [_coerce_elbv2_api_value(key, item) for item in value]
|
| 56 |
+
if isinstance(value, str):
|
| 57 |
+
if key in _ELBV2_INT_KEYS:
|
| 58 |
+
try:
|
| 59 |
+
return int(value)
|
| 60 |
+
except ValueError:
|
| 61 |
+
return value
|
| 62 |
+
if key in _ELBV2_BOOL_KEYS:
|
| 63 |
+
lowered = value.lower()
|
| 64 |
+
if lowered == "true":
|
| 65 |
+
return True
|
| 66 |
+
if lowered == "false":
|
| 67 |
+
return False
|
| 68 |
+
return value
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def _normalize_listener_rule_payload(
|
| 72 |
+
conditions: list[dict[str, Any]],
|
| 73 |
+
actions: list[dict[str, Any]],
|
| 74 |
+
) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
|
| 75 |
+
return (
|
| 76 |
+
[_coerce_elbv2_api_value("", c) for c in conditions],
|
| 77 |
+
[_coerce_elbv2_api_value("", a) for a in actions],
|
| 78 |
+
)
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def _condition_values(condition: dict[str, Any]) -> list[str]:
|
| 82 |
+
field = condition.get("Field")
|
| 83 |
+
if field == "path-pattern":
|
| 84 |
+
cfg = condition.get("PathPatternConfig") or {}
|
| 85 |
+
return sorted(cfg.get("Values") or condition.get("Values") or [])
|
| 86 |
+
if field == "host-header":
|
| 87 |
+
cfg = condition.get("HostHeaderConfig") or {}
|
| 88 |
+
return sorted(cfg.get("Values") or condition.get("Values") or [])
|
| 89 |
+
return sorted(condition.get("Values") or [])
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def _conditions_match(
|
| 93 |
+
rule_conditions: list[dict[str, Any]], expected: list[dict[str, Any]]
|
| 94 |
+
) -> bool:
|
| 95 |
+
if len(rule_conditions) != len(expected):
|
| 96 |
+
return False
|
| 97 |
+
for exp in expected:
|
| 98 |
+
exp_field = exp.get("Field")
|
| 99 |
+
exp_vals = _condition_values(exp)
|
| 100 |
+
if not any(
|
| 101 |
+
rc.get("Field") == exp_field and _condition_values(rc) == exp_vals
|
| 102 |
+
for rc in rule_conditions
|
| 103 |
+
):
|
| 104 |
+
return False
|
| 105 |
+
return True
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def _rule_at_priority(
|
| 109 |
+
rules: list[dict[str, Any]], priority: int
|
| 110 |
+
) -> dict[str, Any] | None:
|
| 111 |
+
target = str(priority)
|
| 112 |
+
for rule in rules:
|
| 113 |
+
if rule.get("Priority") == target:
|
| 114 |
+
return rule
|
| 115 |
+
return None
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def _upsert_rule(
|
| 119 |
+
*,
|
| 120 |
+
listener_arn: str,
|
| 121 |
+
priority: int,
|
| 122 |
+
conditions: list[dict[str, Any]],
|
| 123 |
+
actions: list[dict[str, Any]],
|
| 124 |
+
) -> str:
|
| 125 |
+
described = elbv2.describe_rules(ListenerArn=listener_arn)
|
| 126 |
+
existing = _rule_at_priority(described.get("Rules", []), priority)
|
| 127 |
+
if existing:
|
| 128 |
+
if _conditions_match(existing.get("Conditions", []), conditions):
|
| 129 |
+
rule_arn = existing["RuleArn"]
|
| 130 |
+
LOGGER.info(
|
| 131 |
+
"Modifying existing listener rule %s at priority %s", rule_arn, priority
|
| 132 |
+
)
|
| 133 |
+
elbv2.modify_rule(RuleArn=rule_arn, Conditions=conditions, Actions=actions)
|
| 134 |
+
return rule_arn
|
| 135 |
+
raise RuntimeError(
|
| 136 |
+
f"Listener rule priority {priority} is already in use by {existing['RuleArn']} "
|
| 137 |
+
"with different conditions. Delete that rule in the ELB console or set "
|
| 138 |
+
"PI_ALB_LISTENER_RULE_PRIORITY to a free value, then redeploy."
|
| 139 |
+
)
|
| 140 |
+
LOGGER.info("Creating listener rule at priority %s on %s", priority, listener_arn)
|
| 141 |
+
created = elbv2.create_rule(
|
| 142 |
+
ListenerArn=listener_arn,
|
| 143 |
+
Priority=priority,
|
| 144 |
+
Conditions=conditions,
|
| 145 |
+
Actions=actions,
|
| 146 |
+
)
|
| 147 |
+
return created["Rules"][0]["RuleArn"]
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def _delete_rule(rule_arn: str) -> None:
|
| 151 |
+
if not rule_arn:
|
| 152 |
+
return
|
| 153 |
+
try:
|
| 154 |
+
elbv2.delete_rule(RuleArn=rule_arn)
|
| 155 |
+
except ClientError as exc:
|
| 156 |
+
code = exc.response.get("Error", {}).get("Code", "")
|
| 157 |
+
if code in _DELETE_NOT_FOUND:
|
| 158 |
+
LOGGER.info("Rule %s already deleted (%s)", rule_arn, code)
|
| 159 |
+
return
|
| 160 |
+
raise
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def handler(event, context):
|
| 164 |
+
request_type = event["RequestType"]
|
| 165 |
+
props = event["ResourceProperties"]
|
| 166 |
+
listener_arn = props["ListenerArn"]
|
| 167 |
+
priority = int(props["Priority"])
|
| 168 |
+
conditions, actions = _normalize_listener_rule_payload(
|
| 169 |
+
_parse_json(props["Conditions"]),
|
| 170 |
+
_parse_json(props["Actions"]),
|
| 171 |
+
)
|
| 172 |
+
|
| 173 |
+
if request_type == "Delete":
|
| 174 |
+
_delete_rule(event.get("PhysicalResourceId", ""))
|
| 175 |
+
return {"PhysicalResourceId": event.get("PhysicalResourceId", "deleted")}
|
| 176 |
+
|
| 177 |
+
rule_arn = _upsert_rule(
|
| 178 |
+
listener_arn=listener_arn,
|
| 179 |
+
priority=priority,
|
| 180 |
+
conditions=conditions,
|
| 181 |
+
actions=actions,
|
| 182 |
+
)
|
| 183 |
+
if request_type == "Update":
|
| 184 |
+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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import time
|
| 3 |
+
|
| 4 |
+
from cdk_config import (
|
| 5 |
+
AWS_REGION,
|
| 6 |
+
CDK_PREFIX,
|
| 7 |
+
CLUSTER_NAME,
|
| 8 |
+
CODEBUILD_PI_PROJECT_NAME,
|
| 9 |
+
CODEBUILD_PROJECT_NAME,
|
| 10 |
+
COGNITO_USER_POOL_CLIENT_SECRET_NAME,
|
| 11 |
+
ECS_EXPRESS_COGNITO_REDIRECT_BASE,
|
| 12 |
+
ECS_EXPRESS_SC_PORT_NAME,
|
| 13 |
+
ECS_EXPRESS_SERVICE_NAME,
|
| 14 |
+
ECS_LOG_GROUP_NAME,
|
| 15 |
+
ECS_PI_EXPRESS_SERVICE_NAME,
|
| 16 |
+
ECS_PI_SERVICE_NAME,
|
| 17 |
+
ECS_SERVICE_CONNECT_DISCOVERY_NAME,
|
| 18 |
+
ECS_SERVICE_CONNECT_NAMESPACE,
|
| 19 |
+
ECS_SERVICE_NAME,
|
| 20 |
+
ENABLE_HEADLESS_DEPLOYMENT,
|
| 21 |
+
ENABLE_PI_AGENT_ECS_SERVICE,
|
| 22 |
+
ENABLE_PI_AGENT_EXPRESS_SERVICE,
|
| 23 |
+
GITHUB_REPO_BRANCH,
|
| 24 |
+
GITHUB_REPO_NAME,
|
| 25 |
+
GITHUB_REPO_USERNAME,
|
| 26 |
+
GRADIO_SERVER_PORT,
|
| 27 |
+
PI_AGENT_ENV_S3_KEY,
|
| 28 |
+
S3_BATCH_ENV_PREFIX,
|
| 29 |
+
S3_BATCH_INPUT_PREFIX,
|
| 30 |
+
S3_BATCH_LAMBDA_FUNCTION_NAME,
|
| 31 |
+
S3_LOG_CONFIG_BUCKET_NAME,
|
| 32 |
+
S3_OUTPUT_BUCKET_NAME,
|
| 33 |
+
USE_ECS_EXPRESS_MODE,
|
| 34 |
+
)
|
| 35 |
+
from cdk_functions import create_basic_config_env, ensure_codebuild_public_github_source
|
| 36 |
+
|
| 37 |
+
# boto3-only module (does not import aws-cdk / Node.js)
|
| 38 |
+
from cdk_post_deploy import (
|
| 39 |
+
apply_cognito_secret_fixup_from_stack,
|
| 40 |
+
configure_express_pi_service_connect,
|
| 41 |
+
print_headless_deployment_next_steps,
|
| 42 |
+
seed_headless_batch_s3_layout,
|
| 43 |
+
start_codebuild_build,
|
| 44 |
+
start_ecs_task,
|
| 45 |
+
start_express_gateway_service,
|
| 46 |
+
upload_file_to_s3,
|
| 47 |
+
)
|
| 48 |
+
from tqdm import tqdm
|
| 49 |
+
|
| 50 |
+
# Create basic app_config.env file that user can use to run the app later. Input is the folder it is saved into.
|
| 51 |
+
create_basic_config_env(
|
| 52 |
+
"config",
|
| 53 |
+
headless=ENABLE_HEADLESS_DEPLOYMENT == "True",
|
| 54 |
+
pi_express_backend=ENABLE_PI_AGENT_EXPRESS_SERVICE == "True",
|
| 55 |
+
)
|
| 56 |
+
|
| 57 |
+
# Ensure CodeBuild clones the public GitHub repo (not CodeConnections/OAuth).
|
| 58 |
+
ensure_codebuild_public_github_source(
|
| 59 |
+
CODEBUILD_PROJECT_NAME,
|
| 60 |
+
GITHUB_REPO_USERNAME,
|
| 61 |
+
GITHUB_REPO_NAME,
|
| 62 |
+
GITHUB_REPO_BRANCH,
|
| 63 |
+
aws_region=AWS_REGION,
|
| 64 |
+
)
|
| 65 |
+
|
| 66 |
+
# Start CodeBuild for the main app image
|
| 67 |
+
print("Starting main app CodeBuild project.")
|
| 68 |
+
start_codebuild_build(project_name=CODEBUILD_PROJECT_NAME)
|
| 69 |
+
|
| 70 |
+
_enable_pi_image_build = (
|
| 71 |
+
ENABLE_PI_AGENT_ECS_SERVICE == "True" or ENABLE_PI_AGENT_EXPRESS_SERVICE == "True"
|
| 72 |
+
)
|
| 73 |
+
if _enable_pi_image_build:
|
| 74 |
+
ensure_codebuild_public_github_source(
|
| 75 |
+
CODEBUILD_PI_PROJECT_NAME,
|
| 76 |
+
GITHUB_REPO_USERNAME,
|
| 77 |
+
GITHUB_REPO_NAME,
|
| 78 |
+
GITHUB_REPO_BRANCH,
|
| 79 |
+
aws_region=AWS_REGION,
|
| 80 |
+
)
|
| 81 |
+
print("Starting Pi agent CodeBuild project.")
|
| 82 |
+
start_codebuild_build(project_name=CODEBUILD_PI_PROJECT_NAME)
|
| 83 |
+
|
| 84 |
+
# Upload app_config.env file to S3 bucket
|
| 85 |
+
upload_file_to_s3(
|
| 86 |
+
local_file_paths="config/app_config.env",
|
| 87 |
+
s3_key="",
|
| 88 |
+
s3_bucket=S3_LOG_CONFIG_BUCKET_NAME,
|
| 89 |
+
)
|
| 90 |
+
|
| 91 |
+
if _enable_pi_image_build:
|
| 92 |
+
pi_env_local = os.path.join("config", "pi_agent.env")
|
| 93 |
+
if os.path.isfile(pi_env_local):
|
| 94 |
+
print(
|
| 95 |
+
f"Uploading {pi_env_local} to s3://{S3_LOG_CONFIG_BUCKET_NAME}/{PI_AGENT_ENV_S3_KEY}"
|
| 96 |
+
)
|
| 97 |
+
upload_file_to_s3(
|
| 98 |
+
local_file_paths=pi_env_local,
|
| 99 |
+
s3_key="",
|
| 100 |
+
s3_bucket=S3_LOG_CONFIG_BUCKET_NAME,
|
| 101 |
+
)
|
| 102 |
+
else:
|
| 103 |
+
print(
|
| 104 |
+
f"Skipping Pi env upload: {pi_env_local} not found. "
|
| 105 |
+
f"Create it (from config/pi_agent.env.example) and upload to "
|
| 106 |
+
f"s3://{S3_LOG_CONFIG_BUCKET_NAME}/{PI_AGENT_ENV_S3_KEY} before scaling the Pi service."
|
| 107 |
+
)
|
| 108 |
+
|
| 109 |
+
total_seconds = 480 # 8 minutes
|
| 110 |
+
update_interval = 1 # Update every second
|
| 111 |
+
|
| 112 |
+
print("Waiting 8 minutes for CodeBuild container image(s) to build.")
|
| 113 |
+
|
| 114 |
+
# tqdm iterates over a range, and you perform a small sleep in each iteration
|
| 115 |
+
for i in tqdm(range(total_seconds), desc="Building container"):
|
| 116 |
+
time.sleep(update_interval)
|
| 117 |
+
|
| 118 |
+
# Scale main ECS service to one task (skipped for headless batch-only deployments)
|
| 119 |
+
if ENABLE_HEADLESS_DEPLOYMENT != "True":
|
| 120 |
+
if USE_ECS_EXPRESS_MODE == "True":
|
| 121 |
+
print(f"Starting Express ECS service {ECS_EXPRESS_SERVICE_NAME}")
|
| 122 |
+
start_express_gateway_service(
|
| 123 |
+
cluster_name=CLUSTER_NAME, service_name=ECS_EXPRESS_SERVICE_NAME
|
| 124 |
+
)
|
| 125 |
+
if ENABLE_PI_AGENT_EXPRESS_SERVICE == "True":
|
| 126 |
+
print(
|
| 127 |
+
"Configuring Service Connect for main Express (server) and "
|
| 128 |
+
"Pi Express (client)."
|
| 129 |
+
)
|
| 130 |
+
try:
|
| 131 |
+
configure_express_pi_service_connect(
|
| 132 |
+
cluster_name=CLUSTER_NAME,
|
| 133 |
+
main_service_name=ECS_EXPRESS_SERVICE_NAME,
|
| 134 |
+
pi_service_name=ECS_PI_EXPRESS_SERVICE_NAME,
|
| 135 |
+
namespace=ECS_SERVICE_CONNECT_NAMESPACE,
|
| 136 |
+
main_port_name=ECS_EXPRESS_SC_PORT_NAME,
|
| 137 |
+
discovery_name=ECS_SERVICE_CONNECT_DISCOVERY_NAME,
|
| 138 |
+
main_port=int(GRADIO_SERVER_PORT),
|
| 139 |
+
)
|
| 140 |
+
except Exception as exc:
|
| 141 |
+
print("Warning: could not configure Express Service Connect: " f"{exc}")
|
| 142 |
+
print("Syncing Cognito app client secret for in-app authentication.")
|
| 143 |
+
apply_cognito_secret_fixup_from_stack(
|
| 144 |
+
stack_name="SummarisationStack",
|
| 145 |
+
secret_name=COGNITO_USER_POOL_CLIENT_SECRET_NAME,
|
| 146 |
+
cluster_name=CLUSTER_NAME,
|
| 147 |
+
main_service_name=ECS_EXPRESS_SERVICE_NAME,
|
| 148 |
+
recycle_tasks=False,
|
| 149 |
+
)
|
| 150 |
+
else:
|
| 151 |
+
print(f"Starting ECS service {ECS_SERVICE_NAME}")
|
| 152 |
+
start_ecs_task(cluster_name=CLUSTER_NAME, service_name=ECS_SERVICE_NAME)
|
| 153 |
+
else:
|
| 154 |
+
print(
|
| 155 |
+
"Headless deployment: skipping always-on ECS service start "
|
| 156 |
+
"(tasks are started by the S3 batch Lambda)."
|
| 157 |
+
)
|
| 158 |
+
seed_headless_batch_s3_layout(
|
| 159 |
+
S3_OUTPUT_BUCKET_NAME,
|
| 160 |
+
input_prefix=S3_BATCH_INPUT_PREFIX,
|
| 161 |
+
env_prefix=S3_BATCH_ENV_PREFIX,
|
| 162 |
+
example_env_local_path=os.path.join("config", "example_headless_env_file.env"),
|
| 163 |
+
)
|
| 164 |
+
print_headless_deployment_next_steps(
|
| 165 |
+
{
|
| 166 |
+
"AWS_REGION": AWS_REGION,
|
| 167 |
+
"S3_OUTPUT_BUCKET_NAME": S3_OUTPUT_BUCKET_NAME,
|
| 168 |
+
"S3_BATCH_INPUT_PREFIX": S3_BATCH_INPUT_PREFIX,
|
| 169 |
+
"S3_BATCH_ENV_PREFIX": S3_BATCH_ENV_PREFIX,
|
| 170 |
+
"ECS_LOG_GROUP_NAME": ECS_LOG_GROUP_NAME,
|
| 171 |
+
"S3_BATCH_LAMBDA_FUNCTION_NAME": S3_BATCH_LAMBDA_FUNCTION_NAME,
|
| 172 |
+
"CDK_PREFIX": CDK_PREFIX,
|
| 173 |
+
}
|
| 174 |
+
)
|
| 175 |
+
|
| 176 |
+
if ENABLE_PI_AGENT_ECS_SERVICE == "True":
|
| 177 |
+
print(f"Starting Pi agent ECS service {ECS_PI_SERVICE_NAME}")
|
| 178 |
+
start_ecs_task(cluster_name=CLUSTER_NAME, service_name=ECS_PI_SERVICE_NAME)
|
| 179 |
+
|
| 180 |
+
if ENABLE_PI_AGENT_EXPRESS_SERVICE == "True":
|
| 181 |
+
print(f"Starting Pi Express ECS service {ECS_PI_EXPRESS_SERVICE_NAME}")
|
| 182 |
+
start_express_gateway_service(
|
| 183 |
+
cluster_name=CLUSTER_NAME, service_name=ECS_PI_EXPRESS_SERVICE_NAME
|
| 184 |
+
)
|
| 185 |
+
|
| 186 |
+
if USE_ECS_EXPRESS_MODE == "True" and ENABLE_HEADLESS_DEPLOYMENT != "True":
|
| 187 |
+
from cdk_post_deploy import print_express_mode_next_steps
|
| 188 |
+
|
| 189 |
+
print_express_mode_next_steps(
|
| 190 |
+
{
|
| 191 |
+
"AWS_REGION": AWS_REGION,
|
| 192 |
+
"ECS_EXPRESS_COGNITO_REDIRECT_BASE": ECS_EXPRESS_COGNITO_REDIRECT_BASE,
|
| 193 |
+
"ENABLE_PI_AGENT_EXPRESS_SERVICE": ENABLE_PI_AGENT_EXPRESS_SERVICE,
|
| 194 |
+
}
|
| 195 |
+
)
|
cdk/requirements.txt
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
aws-cdk-lib==2.257.0
|
| 2 |
+
aws-cdk.aws-servicecatalogappregistry-alpha~=2.257.0a0
|
| 3 |
+
boto3
|
| 4 |
+
pandas
|
| 5 |
+
nodejs
|
| 6 |
+
python-dotenv
|
cdk/test/test_cdk_install.py
ADDED
|
@@ -0,0 +1,1010 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Unit tests for cdk_install.py (no live AWS or cdk deploy)."""
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
import json
|
| 5 |
+
import os
|
| 6 |
+
import subprocess
|
| 7 |
+
import sys
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
|
| 10 |
+
import pytest
|
| 11 |
+
|
| 12 |
+
CDK_DIR = Path(__file__).resolve().parents[1]
|
| 13 |
+
sys.path.insert(0, str(CDK_DIR))
|
| 14 |
+
|
| 15 |
+
import cdk_install as inst
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def _demo_answers() -> inst.InstallAnswers:
|
| 19 |
+
return inst.InstallAnswers(
|
| 20 |
+
profile="demo",
|
| 21 |
+
aws_account_id="123456789012",
|
| 22 |
+
aws_region="eu-west-2",
|
| 23 |
+
cdk_prefix="Test-Summarisation-",
|
| 24 |
+
cognito_domain_prefix="test-summarisation",
|
| 25 |
+
vpc_mode="existing",
|
| 26 |
+
vpc_name="test-vpc",
|
| 27 |
+
public_subnet_mode="auto",
|
| 28 |
+
private_subnet_mode="auto",
|
| 29 |
+
)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def _production_answers() -> inst.InstallAnswers:
|
| 33 |
+
a = _demo_answers()
|
| 34 |
+
a.profile = "production"
|
| 35 |
+
a.acm_cert_arn = "arn:aws:acm:eu-west-2:123:certificate/abc"
|
| 36 |
+
a.ssl_domain = "summarisation.example.com"
|
| 37 |
+
a.cloudfront_geo = "GB"
|
| 38 |
+
return a
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def _headless_answers() -> inst.InstallAnswers:
|
| 42 |
+
return inst.InstallAnswers(
|
| 43 |
+
profile="headless",
|
| 44 |
+
aws_account_id="123456789012",
|
| 45 |
+
aws_region="eu-west-2",
|
| 46 |
+
cdk_prefix="Headless-Summarisation-",
|
| 47 |
+
cognito_domain_prefix="headless-summarisation",
|
| 48 |
+
vpc_mode="existing",
|
| 49 |
+
vpc_name="test-vpc",
|
| 50 |
+
public_subnet_mode="auto",
|
| 51 |
+
private_subnet_mode="auto",
|
| 52 |
+
enable_s3_batch=True,
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def test_default_cognito_domain_prefix_strips_reserved_words_from_cdk_prefix():
|
| 57 |
+
prefix = inst.default_cognito_domain_prefix_from_cdk_prefix(
|
| 58 |
+
"Lambeth-AWS-SharedServices-Dev-Summarisation-"
|
| 59 |
+
)
|
| 60 |
+
assert prefix == "lambeth-sharedservic"
|
| 61 |
+
assert "aws" not in prefix
|
| 62 |
+
assert "amazon" not in prefix
|
| 63 |
+
assert "cognito" not in prefix
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def test_sanitize_cognito_domain_prefix_removes_reserved_substrings():
|
| 67 |
+
assert (
|
| 68 |
+
inst.sanitize_cognito_domain_prefix("lambeth-aws-sharedse")
|
| 69 |
+
== "lambeth-sharedse"
|
| 70 |
+
)
|
| 71 |
+
assert inst.sanitize_cognito_domain_prefix("my-cognito-login") == "my-login"
|
| 72 |
+
assert (
|
| 73 |
+
inst.sanitize_cognito_domain_prefix("amazon-summarisation-dev")
|
| 74 |
+
== "summarisation-dev"
|
| 75 |
+
)
|
| 76 |
+
assert inst.sanitize_cognito_domain_prefix("aws") == "llm-topic-app"
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def test_validate_cognito_domain_prefix_rejects_reserved_words():
|
| 80 |
+
assert inst.validate_cognito_domain_prefix("lambeth-aws-sharedse") is not None
|
| 81 |
+
assert inst.validate_cognito_domain_prefix("lambeth-sharedse-dev") is None
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def test_build_env_values_demo():
|
| 85 |
+
values = inst.build_env_values(_demo_answers())
|
| 86 |
+
assert values["USE_ECS_EXPRESS_MODE"] == "True"
|
| 87 |
+
assert values["ECS_EXPRESS_USE_PUBLIC_SUBNETS"] == "True"
|
| 88 |
+
assert values["PRIVATE_SUBNETS_TO_USE"] == ""
|
| 89 |
+
assert values["USE_CLOUDFRONT"] == "False"
|
| 90 |
+
assert values["ENABLE_RESOURCE_DELETE_PROTECTION"] == "False"
|
| 91 |
+
assert values["VPC_NAME"] == "test-vpc"
|
| 92 |
+
assert values["CONTEXT_FILE"] == "precheck.context.json"
|
| 93 |
+
assert values["CDK_FOLDER"].endswith("/cdk/")
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def test_build_env_values_production():
|
| 97 |
+
values = inst.build_env_values(_production_answers())
|
| 98 |
+
assert values["USE_ECS_EXPRESS_MODE"] == "False"
|
| 99 |
+
assert values["USE_CLOUDFRONT"] == "True"
|
| 100 |
+
assert values["RUN_USEAST_STACK"] == "True"
|
| 101 |
+
assert values["ENABLE_RESOURCE_DELETE_PROTECTION"] == "True"
|
| 102 |
+
assert values["ACM_SSL_CERTIFICATE_ARN"].startswith("arn:aws:acm:")
|
| 103 |
+
assert values["SSL_CERTIFICATE_DOMAIN"] == "summarisation.example.com"
|
| 104 |
+
assert values["APPREGISTRY_STACK_NAME"] == "Test-Summarisation-AppRegistryStack"
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def test_build_env_values_uses_custom_s3_bucket_names():
|
| 108 |
+
answers = _demo_answers()
|
| 109 |
+
answers.s3_log_bucket_name = "063418083240-demo-summarisation-s3-logs"
|
| 110 |
+
answers.s3_output_bucket_name = "063418083240-demo-summarisation-s3-output"
|
| 111 |
+
values = inst.build_env_values(answers)
|
| 112 |
+
assert (
|
| 113 |
+
values["S3_LOG_CONFIG_BUCKET_NAME"] == "063418083240-demo-summarisation-s3-logs"
|
| 114 |
+
)
|
| 115 |
+
assert (
|
| 116 |
+
values["S3_OUTPUT_BUCKET_NAME"] == "063418083240-demo-summarisation-s3-output"
|
| 117 |
+
)
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def test_normalize_s3_bucket_name_truncates_and_sanitizes():
|
| 121 |
+
long_name = "A" * 80 + "/underscores"
|
| 122 |
+
normalized = inst.normalize_s3_bucket_name(long_name)
|
| 123 |
+
assert normalized == normalized.lower()
|
| 124 |
+
assert len(normalized) <= inst.S3_BUCKET_NAME_MAX_LEN
|
| 125 |
+
assert "_" not in normalized
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def test_suggest_available_s3_bucket_name_prefers_account_prefix(monkeypatch):
|
| 129 |
+
calls: list[str] = []
|
| 130 |
+
|
| 131 |
+
def fake_resolve(name: str, **kwargs):
|
| 132 |
+
calls.append(name)
|
| 133 |
+
if name.startswith("123456789012-"):
|
| 134 |
+
return ("available", name)
|
| 135 |
+
return ("globally_taken", name)
|
| 136 |
+
|
| 137 |
+
monkeypatch.setattr("cdk_functions.resolve_s3_bucket_availability", fake_resolve)
|
| 138 |
+
suggested = inst.suggest_available_s3_bucket_name(
|
| 139 |
+
"demo-summarisation-s3-logs", "123456789012"
|
| 140 |
+
)
|
| 141 |
+
assert suggested == "123456789012-demo-summarisation-s3-logs"
|
| 142 |
+
assert calls[0] == "demo-summarisation-s3-logs"
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def test_validate_globally_unique_env_values_flags_taken_bucket(monkeypatch):
|
| 146 |
+
monkeypatch.setattr(
|
| 147 |
+
"cdk_functions.resolve_s3_bucket_availability",
|
| 148 |
+
lambda name, **kwargs: ("globally_taken", name),
|
| 149 |
+
)
|
| 150 |
+
monkeypatch.setattr(
|
| 151 |
+
"cdk_functions.resolve_cognito_domain_prefix_availability",
|
| 152 |
+
lambda prefix, **kwargs: "available",
|
| 153 |
+
)
|
| 154 |
+
values = inst.build_env_values(_demo_answers())
|
| 155 |
+
errors = inst.validate_globally_unique_env_values(values)
|
| 156 |
+
assert any("taken globally" in err for err in errors)
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def test_prompt_globally_unique_cognito_prefix_suggests_when_taken(monkeypatch):
|
| 160 |
+
monkeypatch.setattr(
|
| 161 |
+
"cdk_functions.resolve_cognito_domain_prefix_availability",
|
| 162 |
+
lambda prefix, **kwargs: (
|
| 163 |
+
"taken" if prefix == "demo-summarisation" else "available"
|
| 164 |
+
),
|
| 165 |
+
)
|
| 166 |
+
monkeypatch.setattr(
|
| 167 |
+
inst,
|
| 168 |
+
"suggest_available_cognito_domain_prefix",
|
| 169 |
+
lambda preferred, account_id, region, **kwargs: "063418083240-demo-summarisation",
|
| 170 |
+
)
|
| 171 |
+
monkeypatch.setattr(inst, "ask_yes_no", lambda *args, **kwargs: True)
|
| 172 |
+
result = inst._prompt_globally_unique_cognito_prefix(
|
| 173 |
+
"demo-summarisation",
|
| 174 |
+
"063418083240",
|
| 175 |
+
"eu-west-2",
|
| 176 |
+
interactive=True,
|
| 177 |
+
assume_yes=False,
|
| 178 |
+
)
|
| 179 |
+
assert result == "063418083240-demo-summarisation"
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
def test_prompt_globally_unique_cognito_prefix_rejects_taken_cli_override(monkeypatch):
|
| 183 |
+
monkeypatch.setattr(
|
| 184 |
+
"cdk_functions.resolve_cognito_domain_prefix_availability",
|
| 185 |
+
lambda prefix, **kwargs: "taken",
|
| 186 |
+
)
|
| 187 |
+
with pytest.raises(SystemExit):
|
| 188 |
+
inst._prompt_globally_unique_cognito_prefix(
|
| 189 |
+
"demo-summarisation",
|
| 190 |
+
"063418083240",
|
| 191 |
+
"eu-west-2",
|
| 192 |
+
interactive=False,
|
| 193 |
+
assume_yes=False,
|
| 194 |
+
cli_override="demo-summarisation",
|
| 195 |
+
)
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
def test_subnet_cidr_prefix_len_for_express_demo():
|
| 199 |
+
answers = _demo_answers()
|
| 200 |
+
assert inst.subnet_cidr_prefix_len_for_tier(answers, "public") == 27
|
| 201 |
+
assert inst.subnet_cidr_prefix_len_for_tier(answers, "private") == 28
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
def test_validate_public_subnet_cidr_for_express_rejects_small_blocks():
|
| 205 |
+
assert inst.validate_public_subnet_cidr_for_express("10.0.0.0/28") is not None
|
| 206 |
+
assert inst.validate_public_subnet_cidr_for_express("10.0.0.0/27") is None
|
| 207 |
+
assert inst.validate_public_subnet_cidr_for_express("10.0.0.0/26") is None
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
def test_validate_env_values_rejects_express_public_subnets_too_small():
|
| 211 |
+
values = inst.build_env_values(_demo_answers())
|
| 212 |
+
values["PUBLIC_SUBNET_CIDR_BLOCKS"] = "['10.0.0.0/28', '10.0.0.16/28']"
|
| 213 |
+
errors = inst.validate_env_values(values)
|
| 214 |
+
assert any("too small for ECS Express" in err for err in errors)
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
def test_build_env_values_headless():
|
| 218 |
+
values = inst.build_env_values(_headless_answers())
|
| 219 |
+
assert values["USE_ECS_EXPRESS_MODE"] == "False"
|
| 220 |
+
assert values["USE_CLOUDFRONT"] == "False"
|
| 221 |
+
assert values["RUN_USEAST_STACK"] == "False"
|
| 222 |
+
assert values["ENABLE_HEADLESS_DEPLOYMENT"] == "True"
|
| 223 |
+
assert values["ENABLE_S3_BATCH_ECS_TRIGGER"] == "True"
|
| 224 |
+
assert values["COGNITO_AUTH"] == "False"
|
| 225 |
+
assert values["ECS_EXPRESS_USE_PUBLIC_SUBNETS"] == "True"
|
| 226 |
+
assert values["PRIVATE_SUBNETS_TO_USE"] == ""
|
| 227 |
+
assert values["S3_LOG_CONFIG_BUCKET_NAME"] == "headless-summarisation-s3-logs"
|
| 228 |
+
assert values["S3_OUTPUT_BUCKET_NAME"] == "headless-summarisation-s3-output"
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
def test_validate_env_values_rejects_bare_s3_bucket_names():
|
| 232 |
+
values = inst.build_env_values(_headless_answers())
|
| 233 |
+
values["S3_LOG_CONFIG_BUCKET_NAME"] = "s3-logs"
|
| 234 |
+
errors = inst.validate_env_values(values)
|
| 235 |
+
assert any("S3_LOG_CONFIG_BUCKET_NAME" in e for e in errors)
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
def test_headless_profile_uses_public_subnets_only():
|
| 239 |
+
assert inst.answers_use_public_subnets_only(_headless_answers()) is True
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
def test_build_env_values_production_headless():
|
| 243 |
+
answers = _production_answers()
|
| 244 |
+
answers.enable_headless = True
|
| 245 |
+
values = inst.build_env_values(answers)
|
| 246 |
+
assert values["USE_ECS_EXPRESS_MODE"] == "False"
|
| 247 |
+
assert values["USE_CLOUDFRONT"] == "False"
|
| 248 |
+
assert values["ENABLE_HEADLESS_DEPLOYMENT"] == "True"
|
| 249 |
+
assert values["ENABLE_RESOURCE_DELETE_PROTECTION"] == "True"
|
| 250 |
+
assert values.get("ECS_EXPRESS_USE_PUBLIC_SUBNETS") != "True"
|
| 251 |
+
assert "PRIVATE_SUBNET_CIDR_BLOCKS" in values
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
def test_validate_install_answers_rejects_demo_headless():
|
| 255 |
+
answers = _demo_answers()
|
| 256 |
+
answers.enable_headless = True
|
| 257 |
+
errors = inst.validate_install_answers(answers)
|
| 258 |
+
assert any("Demonstration" in err for err in errors)
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
def test_validate_install_answers_rejects_custom_express_headless():
|
| 262 |
+
answers = inst.InstallAnswers(profile="custom", enable_headless=True)
|
| 263 |
+
answers.custom_overrides["USE_ECS_EXPRESS_MODE"] = "True"
|
| 264 |
+
errors = inst.validate_install_answers(answers)
|
| 265 |
+
assert any("USE_ECS_EXPRESS_MODE=False" in err for err in errors)
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
def test_profile_allows_headless_add_on():
|
| 269 |
+
assert inst.profile_allows_headless_add_on(_demo_answers()) is False
|
| 270 |
+
assert inst.profile_allows_headless_add_on(_production_answers()) is True
|
| 271 |
+
assert inst.profile_allows_headless_add_on(_headless_answers()) is True
|
| 272 |
+
custom = inst.InstallAnswers(profile="custom")
|
| 273 |
+
assert inst.profile_allows_headless_add_on(custom) is True
|
| 274 |
+
custom.custom_overrides["USE_ECS_EXPRESS_MODE"] = "True"
|
| 275 |
+
assert inst.profile_allows_headless_add_on(custom) is False
|
| 276 |
+
|
| 277 |
+
|
| 278 |
+
def test_validate_install_answers_skips_cognito_prefix_for_headless():
|
| 279 |
+
values = inst.build_env_values(_headless_answers())
|
| 280 |
+
values["COGNITO_USER_POOL_DOMAIN_PREFIX"] = ""
|
| 281 |
+
assert inst.validate_env_values(values) == []
|
| 282 |
+
|
| 283 |
+
|
| 284 |
+
def test_validate_headless_rejects_pi():
|
| 285 |
+
values = inst.build_env_values(_headless_answers())
|
| 286 |
+
values["ENABLE_ECS_SERVICE_CONNECT"] = "True"
|
| 287 |
+
errors = inst.validate_env_values(values)
|
| 288 |
+
assert any("HEADLESS" in e for e in errors)
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
def test_validate_rejects_express_with_acm():
|
| 292 |
+
values = inst.build_env_values(_demo_answers())
|
| 293 |
+
values["ACM_SSL_CERTIFICATE_ARN"] = "arn:aws:acm:eu-west-2:123:certificate/x"
|
| 294 |
+
errors = inst.validate_env_values(values)
|
| 295 |
+
assert any("ACM_SSL_CERTIFICATE_ARN" in e for e in errors)
|
| 296 |
+
|
| 297 |
+
|
| 298 |
+
def test_build_env_values_mixed_subnet_tiers():
|
| 299 |
+
answers = _production_answers()
|
| 300 |
+
answers.public_subnet_mode = "existing"
|
| 301 |
+
answers.private_subnet_mode = "create"
|
| 302 |
+
answers.public_subnet_names = ["existing-public-a", "existing-public-b"]
|
| 303 |
+
answers.public_subnet_cidrs = ["10.244.1.0/28", "10.244.2.0/28"]
|
| 304 |
+
answers.public_subnet_azs = ["eu-west-2a", "eu-west-2b"]
|
| 305 |
+
answers.private_subnet_names = ["Demo-Summarisation-PrivateSubnet1"]
|
| 306 |
+
answers.private_subnet_cidrs = ["10.0.10.0/28"]
|
| 307 |
+
answers.private_subnet_azs = ["eu-west-2a"]
|
| 308 |
+
values = inst.build_env_values(answers)
|
| 309 |
+
assert (
|
| 310 |
+
values["PUBLIC_SUBNETS_TO_USE"] == '["existing-public-a", "existing-public-b"]'
|
| 311 |
+
)
|
| 312 |
+
assert values["PUBLIC_SUBNET_CIDR_BLOCKS"] == "['10.244.1.0/28', '10.244.2.0/28']"
|
| 313 |
+
assert values["PUBLIC_SUBNET_AVAILABILITY_ZONES"] == "['eu-west-2a', 'eu-west-2b']"
|
| 314 |
+
assert values["PRIVATE_SUBNETS_TO_USE"] == '["Demo-Summarisation-PrivateSubnet1"]'
|
| 315 |
+
assert values["PRIVATE_SUBNET_CIDR_BLOCKS"] == "['10.0.10.0/28']"
|
| 316 |
+
assert values["PRIVATE_SUBNET_AVAILABILITY_ZONES"] == "['eu-west-2a']"
|
| 317 |
+
|
| 318 |
+
|
| 319 |
+
def test_enrich_existing_subnet_details_from_aws(monkeypatch):
|
| 320 |
+
answers = _demo_answers()
|
| 321 |
+
answers.vpc_name = "test-vpc"
|
| 322 |
+
answers.public_subnet_mode = "existing"
|
| 323 |
+
answers.public_subnet_names = ["pub-a", "pub-b"]
|
| 324 |
+
answers.private_subnet_mode = "create"
|
| 325 |
+
|
| 326 |
+
monkeypatch.setattr(
|
| 327 |
+
inst,
|
| 328 |
+
"list_vpcs",
|
| 329 |
+
lambda _region: [{"name": "test-vpc", "id": "vpc-123", "cidr": "10.0.0.0/16"}],
|
| 330 |
+
)
|
| 331 |
+
monkeypatch.setattr(
|
| 332 |
+
inst,
|
| 333 |
+
"list_subnets_in_vpc",
|
| 334 |
+
lambda _vpc_id, _region: [
|
| 335 |
+
{"name": "pub-a", "cidr": "10.244.1.0/28", "az": "eu-west-2a"},
|
| 336 |
+
{"name": "pub-b", "cidr": "10.244.2.0/28", "az": "eu-west-2b"},
|
| 337 |
+
],
|
| 338 |
+
)
|
| 339 |
+
|
| 340 |
+
errors = inst.enrich_existing_subnet_details_from_aws(answers)
|
| 341 |
+
assert errors == []
|
| 342 |
+
assert answers.public_subnet_cidrs == ["10.244.1.0/28", "10.244.2.0/28"]
|
| 343 |
+
assert answers.public_subnet_azs == ["eu-west-2a", "eu-west-2b"]
|
| 344 |
+
|
| 345 |
+
|
| 346 |
+
def test_validate_subnet_answers_mixed_requires_public_names():
|
| 347 |
+
answers = _demo_answers()
|
| 348 |
+
answers.public_subnet_mode = "existing"
|
| 349 |
+
answers.private_subnet_mode = "create"
|
| 350 |
+
answers.private_subnet_names = ["new-private"]
|
| 351 |
+
errors = inst.validate_subnet_answers(answers)
|
| 352 |
+
assert any("Public subnets" in err for err in errors)
|
| 353 |
+
|
| 354 |
+
|
| 355 |
+
def test_resolve_subnet_tier_modes_per_tier_override():
|
| 356 |
+
args = argparse.Namespace(
|
| 357 |
+
subnet_mode="auto",
|
| 358 |
+
public_subnet_mode="existing",
|
| 359 |
+
private_subnet_mode="create",
|
| 360 |
+
)
|
| 361 |
+
public, private = inst.resolve_subnet_tier_modes(args)
|
| 362 |
+
assert public == "existing"
|
| 363 |
+
assert private == "create"
|
| 364 |
+
|
| 365 |
+
|
| 366 |
+
def test_suggest_vpc_cidr_block_empty_region():
|
| 367 |
+
assert inst.suggest_vpc_cidr_block([]) == "10.0.0.0/24"
|
| 368 |
+
|
| 369 |
+
|
| 370 |
+
def test_suggest_vpc_cidr_block_skips_overlaps():
|
| 371 |
+
assert inst.suggest_vpc_cidr_block(["10.0.0.0/24"]) == "10.0.1.0/24"
|
| 372 |
+
assert inst.suggest_vpc_cidr_block(["10.0.0.0/16"]) == "10.1.0.0/24"
|
| 373 |
+
|
| 374 |
+
|
| 375 |
+
def test_validate_new_vpc_cidr_rejects_overlap_and_public_space():
|
| 376 |
+
err = inst.validate_new_vpc_cidr("10.0.0.0/24", ["10.0.0.0/16"])
|
| 377 |
+
assert err is not None
|
| 378 |
+
assert "overlaps" in err
|
| 379 |
+
err = inst.validate_new_vpc_cidr("8.8.8.0/24", [])
|
| 380 |
+
assert err is not None
|
| 381 |
+
assert "RFC1918" in err
|
| 382 |
+
|
| 383 |
+
|
| 384 |
+
def test_validate_new_vpc_cidr_accepts_available_block():
|
| 385 |
+
assert inst.validate_new_vpc_cidr("10.2.0.0/24", ["10.0.0.0/16"]) is None
|
| 386 |
+
|
| 387 |
+
|
| 388 |
+
def test_prompt_new_vpc_cidr_validates_cli_override(monkeypatch):
|
| 389 |
+
answers = inst.InstallAnswers(aws_region="eu-west-2", new_vpc_cidr="10.0.0.0/24")
|
| 390 |
+
monkeypatch.setattr(
|
| 391 |
+
inst, "list_vpc_cidr_blocks_in_region", lambda _r: ["10.0.0.0/16"]
|
| 392 |
+
)
|
| 393 |
+
with pytest.raises(SystemExit):
|
| 394 |
+
inst.prompt_new_vpc_cidr(answers, interactive=False)
|
| 395 |
+
|
| 396 |
+
|
| 397 |
+
def test_prompt_new_vpc_cidr_auto_select_noninteractive(monkeypatch):
|
| 398 |
+
answers = inst.InstallAnswers(aws_region="eu-west-2")
|
| 399 |
+
monkeypatch.setattr(inst, "list_vpc_cidr_blocks_in_region", lambda _r: [])
|
| 400 |
+
inst.prompt_new_vpc_cidr(answers, interactive=False)
|
| 401 |
+
assert answers.new_vpc_cidr == "10.0.0.0/24"
|
| 402 |
+
|
| 403 |
+
|
| 404 |
+
def test_suggest_subnet_cidr_blocks_lowest_available():
|
| 405 |
+
blocks = inst.suggest_subnet_cidr_blocks("10.0.0.0/24", ["10.0.0.0/28"], 2)
|
| 406 |
+
assert blocks == ["10.0.0.16/28", "10.0.0.32/28"]
|
| 407 |
+
|
| 408 |
+
|
| 409 |
+
def test_suggest_subnet_cidr_blocks_respects_reserved():
|
| 410 |
+
blocks = inst.suggest_subnet_cidr_blocks(
|
| 411 |
+
"10.0.0.0/24",
|
| 412 |
+
[],
|
| 413 |
+
1,
|
| 414 |
+
reserved_cidrs=["10.0.0.0/28"],
|
| 415 |
+
)
|
| 416 |
+
assert blocks == ["10.0.0.16/28"]
|
| 417 |
+
|
| 418 |
+
|
| 419 |
+
def test_vpc_cidr_blocks_from_describe_includes_associations():
|
| 420 |
+
vpc = {
|
| 421 |
+
"CidrBlock": "10.0.0.0/16",
|
| 422 |
+
"CidrBlockAssociationSet": [{"CidrBlock": "10.1.0.0/16"}],
|
| 423 |
+
}
|
| 424 |
+
assert inst.vpc_cidr_blocks_from_describe(vpc) == [
|
| 425 |
+
"10.0.0.0/16",
|
| 426 |
+
"10.1.0.0/16",
|
| 427 |
+
]
|
| 428 |
+
|
| 429 |
+
|
| 430 |
+
def test_build_app_config_env_values_express_uses_in_app_cognito():
|
| 431 |
+
values = inst.build_env_values(_demo_answers())
|
| 432 |
+
updates = inst.build_app_config_env_values(values)
|
| 433 |
+
assert updates["COGNITO_AUTH"] == "True"
|
| 434 |
+
assert updates["RUN_AWS_FUNCTIONS"] == "True"
|
| 435 |
+
assert updates["S3_LOG_BUCKET"].endswith("s3-logs")
|
| 436 |
+
|
| 437 |
+
|
| 438 |
+
def test_build_app_config_env_values_express_pi_disables_main_cognito():
|
| 439 |
+
values = inst.build_env_values(_demo_answers())
|
| 440 |
+
values["ENABLE_PI_AGENT_EXPRESS_SERVICE"] = "True"
|
| 441 |
+
updates = inst.build_app_config_env_values(values)
|
| 442 |
+
assert updates["COGNITO_AUTH"] == "False"
|
| 443 |
+
|
| 444 |
+
|
| 445 |
+
def test_build_app_config_env_values_headless():
|
| 446 |
+
answers = _headless_answers()
|
| 447 |
+
values = inst.build_env_values(answers)
|
| 448 |
+
updates = inst.build_app_config_env_values(values)
|
| 449 |
+
assert updates["COGNITO_AUTH"] == "False"
|
| 450 |
+
|
| 451 |
+
|
| 452 |
+
def test_write_app_config_env_from_example(tmp_path, monkeypatch):
|
| 453 |
+
example = tmp_path / "app_config.env.example"
|
| 454 |
+
example.write_text(
|
| 455 |
+
"RUN_AWS_FUNCTIONS=True\nS3_LOG_BUCKET=placeholder\n",
|
| 456 |
+
encoding="utf-8",
|
| 457 |
+
)
|
| 458 |
+
target = tmp_path / "app_config.env"
|
| 459 |
+
monkeypatch.setattr(inst, "APP_CONFIG_ENV_EXAMPLE", example)
|
| 460 |
+
monkeypatch.setattr(inst, "APP_CONFIG_ENV_PATH", target)
|
| 461 |
+
|
| 462 |
+
answers = _demo_answers()
|
| 463 |
+
answers.write_app_config_env = True
|
| 464 |
+
values = inst.build_env_values(answers)
|
| 465 |
+
inst.write_app_config_env_file(answers, values)
|
| 466 |
+
|
| 467 |
+
written = inst.read_env_file(target)
|
| 468 |
+
assert written["RUN_AWS_FUNCTIONS"] == "True"
|
| 469 |
+
assert written["S3_LOG_BUCKET"].endswith("s3-logs")
|
| 470 |
+
assert written["COGNITO_AUTH"] == "True"
|
| 471 |
+
|
| 472 |
+
|
| 473 |
+
def test_format_list_env():
|
| 474 |
+
assert inst.format_list_env(["a", "b"]) == '["a", "b"]'
|
| 475 |
+
assert (
|
| 476 |
+
inst.format_list_env(["10.0.0.0/28"], use_single_quotes=True)
|
| 477 |
+
== "['10.0.0.0/28']"
|
| 478 |
+
)
|
| 479 |
+
assert inst.format_list_env([]) == "[]"
|
| 480 |
+
|
| 481 |
+
|
| 482 |
+
def test_write_env_file_backs_up(tmp_path):
|
| 483 |
+
env_path = tmp_path / "cdk_config.env"
|
| 484 |
+
env_path.write_text("OLD=1\n", encoding="utf-8")
|
| 485 |
+
inst.write_env_file(env_path, {"NEW": "2"})
|
| 486 |
+
backups = list(tmp_path.glob("cdk_config.env.bak.*"))
|
| 487 |
+
assert len(backups) == 1
|
| 488 |
+
assert "NEW=2" in env_path.read_text(encoding="utf-8")
|
| 489 |
+
|
| 490 |
+
|
| 491 |
+
def test_write_cdk_json_preserves_context(tmp_path, monkeypatch):
|
| 492 |
+
cdk_json = tmp_path / "cdk.json"
|
| 493 |
+
cdk_json.write_text(
|
| 494 |
+
json.dumps(
|
| 495 |
+
{
|
| 496 |
+
"app": "old-python app.py",
|
| 497 |
+
"context": {"@aws-cdk/custom:flag": True, "keep": 1},
|
| 498 |
+
}
|
| 499 |
+
),
|
| 500 |
+
encoding="utf-8",
|
| 501 |
+
)
|
| 502 |
+
monkeypatch.setattr(inst, "CDK_JSON_PATH", cdk_json)
|
| 503 |
+
monkeypatch.setattr(inst, "CDK_JSON_EXAMPLE", tmp_path / "missing.example")
|
| 504 |
+
|
| 505 |
+
py = Path(sys.executable)
|
| 506 |
+
inst.write_cdk_json(py, force=True)
|
| 507 |
+
|
| 508 |
+
data = json.loads(cdk_json.read_text(encoding="utf-8"))
|
| 509 |
+
assert data["context"]["@aws-cdk/custom:flag"] is True
|
| 510 |
+
assert data["context"]["keep"] == 1
|
| 511 |
+
assert data["app"].endswith("app.py")
|
| 512 |
+
assert "output" in data
|
| 513 |
+
backups = list(tmp_path.glob("cdk.json.bak.*"))
|
| 514 |
+
assert len(backups) == 1
|
| 515 |
+
|
| 516 |
+
|
| 517 |
+
def test_format_cdk_app_command():
|
| 518 |
+
cmd = inst.format_cdk_app_command(Path(sys.executable))
|
| 519 |
+
assert cmd.endswith("app.py")
|
| 520 |
+
assert str(sys.executable).replace("/", "\\") in cmd or sys.executable in cmd
|
| 521 |
+
|
| 522 |
+
|
| 523 |
+
def test_venv_python_paths_includes_sys_executable():
|
| 524 |
+
paths = inst._venv_python_paths()
|
| 525 |
+
assert Path(sys.executable).resolve() == paths[0].resolve()
|
| 526 |
+
|
| 527 |
+
|
| 528 |
+
def test_merge_preset_custom():
|
| 529 |
+
merged = inst.merge_preset("demo", {"ECS_TASK_MEMORY_SIZE": "8192"})
|
| 530 |
+
assert merged["USE_ECS_EXPRESS_MODE"] == "True"
|
| 531 |
+
assert merged["ECS_TASK_MEMORY_SIZE"] == "8192"
|
| 532 |
+
|
| 533 |
+
|
| 534 |
+
def test_build_env_values_pi_express_forced_off():
|
| 535 |
+
answers = _demo_answers()
|
| 536 |
+
answers.enable_pi_express = True
|
| 537 |
+
values = inst.build_env_values(answers)
|
| 538 |
+
assert values["ENABLE_PI_AGENT_EXPRESS_SERVICE"] == "False"
|
| 539 |
+
assert values["ENABLE_PI_AGENT_ECS_SERVICE"] == "False"
|
| 540 |
+
|
| 541 |
+
|
| 542 |
+
def test_build_pi_agent_env_values_express_skips_root_path():
|
| 543 |
+
answers = _demo_answers()
|
| 544 |
+
answers.enable_pi_express = True
|
| 545 |
+
env = inst.build_pi_agent_env_values(answers)
|
| 546 |
+
assert env["RUN_FASTAPI"] == "True"
|
| 547 |
+
assert "PI_ROOT_PATH" not in env
|
| 548 |
+
|
| 549 |
+
|
| 550 |
+
def test_build_env_values_pi_production_host_forced_off():
|
| 551 |
+
answers = _production_answers()
|
| 552 |
+
answers.enable_pi_legacy = True
|
| 553 |
+
answers.enable_service_connect = True
|
| 554 |
+
answers.pi_alb_routing = "host"
|
| 555 |
+
answers.pi_alb_host_header = "agent.example.com"
|
| 556 |
+
values = inst.build_env_values(answers)
|
| 557 |
+
assert values["ENABLE_PI_AGENT_ECS_SERVICE"] == "False"
|
| 558 |
+
assert values["ENABLE_PI_AGENT_EXPRESS_SERVICE"] == "False"
|
| 559 |
+
|
| 560 |
+
|
| 561 |
+
def test_validate_pi_host_requires_header():
|
| 562 |
+
values = inst.build_env_values(_production_answers())
|
| 563 |
+
values["ENABLE_PI_AGENT_ECS_SERVICE"] = "True"
|
| 564 |
+
values["ENABLE_ECS_SERVICE_CONNECT"] = "True"
|
| 565 |
+
values["PI_ALB_ROUTING"] = "host"
|
| 566 |
+
values["PI_ALB_HOST_HEADER"] = ""
|
| 567 |
+
errors = inst.validate_env_values(values)
|
| 568 |
+
assert any("PI_ALB_HOST_HEADER" in e for e in errors)
|
| 569 |
+
|
| 570 |
+
|
| 571 |
+
def test_validate_pi_express_skips_alb_routing():
|
| 572 |
+
values = inst.build_env_values(_demo_answers())
|
| 573 |
+
values["ENABLE_PI_AGENT_EXPRESS_SERVICE"] = "True"
|
| 574 |
+
values["USE_ECS_EXPRESS_MODE"] = "True"
|
| 575 |
+
assert inst.validate_env_values(values) == []
|
| 576 |
+
|
| 577 |
+
|
| 578 |
+
def test_build_pi_agent_env_values():
|
| 579 |
+
answers = _demo_answers()
|
| 580 |
+
answers.enable_pi_express = False
|
| 581 |
+
answers.enable_pi_legacy = True
|
| 582 |
+
answers.pi_alb_routing = "path"
|
| 583 |
+
answers.pi_alb_path_prefix = "/pi"
|
| 584 |
+
values = inst.build_pi_agent_env_values(answers)
|
| 585 |
+
assert values["PI_DEPLOYMENT_PROFILE"] == "aws-ecs"
|
| 586 |
+
assert values["DOC_SUMMARISATION_GRADIO_URL"] == "http://llm-topic:7860"
|
| 587 |
+
assert values["PI_ROOT_PATH"] == "/pi"
|
| 588 |
+
|
| 589 |
+
|
| 590 |
+
def test_apply_pi_cli_flags_enable_pi_demo():
|
| 591 |
+
answers = inst.InstallAnswers(profile="demo")
|
| 592 |
+
args = argparse.Namespace(
|
| 593 |
+
enable_pi=True,
|
| 594 |
+
enable_pi_express=False,
|
| 595 |
+
enable_pi_legacy=False,
|
| 596 |
+
pi_alb_routing=None,
|
| 597 |
+
pi_path_prefix="",
|
| 598 |
+
pi_host_header="",
|
| 599 |
+
pi_listener_priority="",
|
| 600 |
+
pi_gradio_port="",
|
| 601 |
+
sc_discovery_name="",
|
| 602 |
+
pi_provider="",
|
| 603 |
+
skip_pi_agent_env=False,
|
| 604 |
+
)
|
| 605 |
+
inst.apply_pi_cli_flags(args, answers)
|
| 606 |
+
assert answers.enable_pi_express is True
|
| 607 |
+
|
| 608 |
+
|
| 609 |
+
def test_stacks_to_check_includes_appregistry_when_enabled():
|
| 610 |
+
checks = inst.stacks_to_check(
|
| 611 |
+
"eu-west-2",
|
| 612 |
+
{
|
| 613 |
+
"ENABLE_APPREGISTRY": "True",
|
| 614 |
+
"APPREGISTRY_STACK_NAME": "Demo-Summarisation-AppRegistryStack",
|
| 615 |
+
},
|
| 616 |
+
)
|
| 617 |
+
names = [name for name, _ in checks]
|
| 618 |
+
assert names == [
|
| 619 |
+
inst.CLOUDFRONT_STACK,
|
| 620 |
+
"Demo-Summarisation-AppRegistryStack",
|
| 621 |
+
inst.REGIONAL_STACK,
|
| 622 |
+
]
|
| 623 |
+
assert checks[0][1] == inst.CLOUDFRONT_STACK_REGION
|
| 624 |
+
assert checks[-1] == (inst.REGIONAL_STACK, "eu-west-2")
|
| 625 |
+
|
| 626 |
+
|
| 627 |
+
def test_stacks_to_check_without_appregistry():
|
| 628 |
+
checks = inst.stacks_to_check("eu-west-2", {"ENABLE_APPREGISTRY": "False"})
|
| 629 |
+
assert [name for name, _ in checks] == [
|
| 630 |
+
inst.CLOUDFRONT_STACK,
|
| 631 |
+
inst.REGIONAL_STACK,
|
| 632 |
+
]
|
| 633 |
+
|
| 634 |
+
|
| 635 |
+
def test_derived_appregistry_stack_name_from_cdk_prefix():
|
| 636 |
+
name = inst.derived_appregistry_stack_name(
|
| 637 |
+
{"CDK_PREFIX": "Demo-Summarisation-", "ENABLE_APPREGISTRY": "True"}
|
| 638 |
+
)
|
| 639 |
+
assert name == "Demo-Summarisation-AppRegistryStack"
|
| 640 |
+
|
| 641 |
+
|
| 642 |
+
def test_stacks_to_check_derives_appregistry_from_cdk_prefix():
|
| 643 |
+
checks = inst.stacks_to_check(
|
| 644 |
+
"eu-west-2",
|
| 645 |
+
{
|
| 646 |
+
"CDK_PREFIX": "Demo-Summarisation-",
|
| 647 |
+
"ENABLE_APPREGISTRY": "True",
|
| 648 |
+
},
|
| 649 |
+
)
|
| 650 |
+
assert "Demo-Summarisation-AppRegistryStack" in [name for name, _ in checks]
|
| 651 |
+
|
| 652 |
+
|
| 653 |
+
def test_stacks_to_check_skips_cloudfront_when_disabled():
|
| 654 |
+
checks = inst.stacks_to_check(
|
| 655 |
+
"eu-west-2",
|
| 656 |
+
{
|
| 657 |
+
"USE_CLOUDFRONT": "False",
|
| 658 |
+
"RUN_USEAST_STACK": "False",
|
| 659 |
+
"ENABLE_APPREGISTRY": "False",
|
| 660 |
+
},
|
| 661 |
+
)
|
| 662 |
+
assert checks == [(inst.REGIONAL_STACK, "eu-west-2")]
|
| 663 |
+
|
| 664 |
+
|
| 665 |
+
def test_discover_existing_doc_summarisation_stacks_order(monkeypatch):
|
| 666 |
+
monkeypatch.setattr(
|
| 667 |
+
inst, "list_regional_appregistry_stack_names", lambda _region: []
|
| 668 |
+
)
|
| 669 |
+
|
| 670 |
+
def fake_describe(stack_name: str, region: str):
|
| 671 |
+
if stack_name == inst.REGIONAL_STACK and region == "eu-west-2":
|
| 672 |
+
return inst.ExistingStack(
|
| 673 |
+
name=stack_name,
|
| 674 |
+
region=region,
|
| 675 |
+
status="UPDATE_COMPLETE",
|
| 676 |
+
)
|
| 677 |
+
if (
|
| 678 |
+
stack_name == inst.CLOUDFRONT_STACK
|
| 679 |
+
and region == inst.CLOUDFRONT_STACK_REGION
|
| 680 |
+
):
|
| 681 |
+
return inst.ExistingStack(
|
| 682 |
+
name=stack_name,
|
| 683 |
+
region=region,
|
| 684 |
+
status="CREATE_COMPLETE",
|
| 685 |
+
termination_protection=True,
|
| 686 |
+
)
|
| 687 |
+
return None
|
| 688 |
+
|
| 689 |
+
monkeypatch.setattr(inst, "describe_existing_stack", fake_describe)
|
| 690 |
+
found = inst.discover_existing_llm_topic_stacks("eu-west-2")
|
| 691 |
+
assert [s.name for s in found] == [inst.CLOUDFRONT_STACK, inst.REGIONAL_STACK]
|
| 692 |
+
assert found[0].termination_protection is True
|
| 693 |
+
|
| 694 |
+
|
| 695 |
+
def test_discover_existing_stacks_continues_after_access_denied(monkeypatch):
|
| 696 |
+
from botocore.exceptions import ClientError
|
| 697 |
+
|
| 698 |
+
monkeypatch.setattr(
|
| 699 |
+
inst, "list_regional_appregistry_stack_names", lambda _region: []
|
| 700 |
+
)
|
| 701 |
+
|
| 702 |
+
def fake_describe(stack_name: str, region: str):
|
| 703 |
+
if (
|
| 704 |
+
stack_name == inst.CLOUDFRONT_STACK
|
| 705 |
+
and region == inst.CLOUDFRONT_STACK_REGION
|
| 706 |
+
):
|
| 707 |
+
raise ClientError(
|
| 708 |
+
{
|
| 709 |
+
"Error": {
|
| 710 |
+
"Code": "AccessDenied",
|
| 711 |
+
"Message": "explicit deny in SCP",
|
| 712 |
+
}
|
| 713 |
+
},
|
| 714 |
+
"DescribeStacks",
|
| 715 |
+
)
|
| 716 |
+
if stack_name == inst.REGIONAL_STACK and region == "eu-west-2":
|
| 717 |
+
return inst.ExistingStack(
|
| 718 |
+
name=stack_name,
|
| 719 |
+
region=region,
|
| 720 |
+
status="UPDATE_COMPLETE",
|
| 721 |
+
)
|
| 722 |
+
return None
|
| 723 |
+
|
| 724 |
+
monkeypatch.setattr(inst, "describe_existing_stack", fake_describe)
|
| 725 |
+
found = inst.discover_existing_llm_topic_stacks("eu-west-2")
|
| 726 |
+
assert [s.name for s in found] == [inst.REGIONAL_STACK]
|
| 727 |
+
|
| 728 |
+
|
| 729 |
+
def test_discover_includes_orphan_appregistry_when_disabled_in_config(monkeypatch):
|
| 730 |
+
monkeypatch.setattr(
|
| 731 |
+
inst,
|
| 732 |
+
"list_regional_appregistry_stack_names",
|
| 733 |
+
lambda _region: ["Old-Summarisation-AppRegistryStack"],
|
| 734 |
+
)
|
| 735 |
+
|
| 736 |
+
def fake_describe(stack_name: str, region: str):
|
| 737 |
+
if stack_name == "Old-Summarisation-AppRegistryStack":
|
| 738 |
+
return inst.ExistingStack(
|
| 739 |
+
name=stack_name,
|
| 740 |
+
region=region,
|
| 741 |
+
status="CREATE_COMPLETE",
|
| 742 |
+
)
|
| 743 |
+
return None
|
| 744 |
+
|
| 745 |
+
monkeypatch.setattr(inst, "describe_existing_stack", fake_describe)
|
| 746 |
+
found = inst.discover_existing_llm_topic_stacks(
|
| 747 |
+
"eu-west-2",
|
| 748 |
+
{"ENABLE_APPREGISTRY": "False"},
|
| 749 |
+
)
|
| 750 |
+
assert [s.name for s in found] == ["Old-Summarisation-AppRegistryStack"]
|
| 751 |
+
|
| 752 |
+
|
| 753 |
+
def test_handle_existing_stacks_force_delete(monkeypatch):
|
| 754 |
+
stacks = [
|
| 755 |
+
inst.ExistingStack(
|
| 756 |
+
name=inst.CLOUDFRONT_STACK,
|
| 757 |
+
region=inst.CLOUDFRONT_STACK_REGION,
|
| 758 |
+
status="CREATE_COMPLETE",
|
| 759 |
+
)
|
| 760 |
+
]
|
| 761 |
+
deleted: list = []
|
| 762 |
+
|
| 763 |
+
monkeypatch.setattr(
|
| 764 |
+
inst,
|
| 765 |
+
"discover_existing_llm_topic_stacks",
|
| 766 |
+
lambda *_a, **_k: stacks,
|
| 767 |
+
)
|
| 768 |
+
monkeypatch.setattr(
|
| 769 |
+
inst,
|
| 770 |
+
"force_delete_cloudformation_stacks",
|
| 771 |
+
lambda s, **kwargs: deleted.extend(s),
|
| 772 |
+
)
|
| 773 |
+
|
| 774 |
+
args = argparse.Namespace(
|
| 775 |
+
skip_stack_check=False,
|
| 776 |
+
config_only=False,
|
| 777 |
+
synth_only=False,
|
| 778 |
+
force_delete_stacks=True,
|
| 779 |
+
yes=True,
|
| 780 |
+
)
|
| 781 |
+
inst.handle_existing_stacks_at_start(args, "eu-west-2")
|
| 782 |
+
assert deleted == stacks
|
| 783 |
+
|
| 784 |
+
|
| 785 |
+
def test_handle_existing_stacks_yes_without_force_skips_delete(monkeypatch):
|
| 786 |
+
monkeypatch.setattr(
|
| 787 |
+
inst,
|
| 788 |
+
"discover_existing_llm_topic_stacks",
|
| 789 |
+
lambda *_a, **_k: [
|
| 790 |
+
inst.ExistingStack(
|
| 791 |
+
name=inst.REGIONAL_STACK,
|
| 792 |
+
region="eu-west-2",
|
| 793 |
+
status="CREATE_COMPLETE",
|
| 794 |
+
)
|
| 795 |
+
],
|
| 796 |
+
)
|
| 797 |
+
monkeypatch.setattr(
|
| 798 |
+
inst,
|
| 799 |
+
"force_delete_cloudformation_stacks",
|
| 800 |
+
lambda *_a, **_k: (_ for _ in ()).throw(AssertionError("should not delete")),
|
| 801 |
+
)
|
| 802 |
+
|
| 803 |
+
args = argparse.Namespace(
|
| 804 |
+
skip_stack_check=False,
|
| 805 |
+
config_only=False,
|
| 806 |
+
synth_only=False,
|
| 807 |
+
force_delete_stacks=False,
|
| 808 |
+
yes=True,
|
| 809 |
+
)
|
| 810 |
+
inst.handle_existing_stacks_at_start(args, "eu-west-2")
|
| 811 |
+
|
| 812 |
+
|
| 813 |
+
def test_write_pi_agent_env_file_minimal(tmp_path, monkeypatch):
|
| 814 |
+
answers = _demo_answers()
|
| 815 |
+
answers.enable_pi_express = True
|
| 816 |
+
target = tmp_path / "pi_agent.env"
|
| 817 |
+
monkeypatch.setattr(inst, "PI_AGENT_ENV_PATH", target)
|
| 818 |
+
monkeypatch.setattr(inst, "PI_AGENT_ENV_EXAMPLE", tmp_path / "missing.example")
|
| 819 |
+
inst.write_pi_agent_env_file(answers)
|
| 820 |
+
text = target.read_text(encoding="utf-8")
|
| 821 |
+
assert "PI_DEPLOYMENT_PROFILE=aws-ecs" in text
|
| 822 |
+
assert "DOC_SUMMARISATION_GRADIO_URL=http://llm-topic:7860" in text
|
| 823 |
+
|
| 824 |
+
|
| 825 |
+
def test_run_cdk_command_invokes_cdk_cli_not_python(monkeypatch):
|
| 826 |
+
calls: list = []
|
| 827 |
+
|
| 828 |
+
def fake_run(cmd, **kwargs):
|
| 829 |
+
calls.append((cmd, kwargs))
|
| 830 |
+
return subprocess.CompletedProcess(cmd, 0)
|
| 831 |
+
|
| 832 |
+
monkeypatch.setattr(inst, "resolve_cdk_executable", lambda: r"C:\npm\cdk.cmd")
|
| 833 |
+
monkeypatch.setattr(inst.subprocess, "run", fake_run)
|
| 834 |
+
inst.run_cdk_command(["synth"], check=False)
|
| 835 |
+
cmd, kwargs = calls[0]
|
| 836 |
+
assert cmd == [r"C:\npm\cdk.cmd", "synth"]
|
| 837 |
+
assert "executable" not in kwargs
|
| 838 |
+
|
| 839 |
+
|
| 840 |
+
def test_build_cdk_subprocess_env_overrides_stale_defaults(tmp_path, monkeypatch):
|
| 841 |
+
env_path = tmp_path / "config" / "cdk_config.env"
|
| 842 |
+
env_path.parent.mkdir(parents=True)
|
| 843 |
+
env_path.write_text(
|
| 844 |
+
"VPC_NAME=my-vpc\nCDK_PREFIX=MyPrefix-\nAWS_REGION=eu-west-2\n",
|
| 845 |
+
encoding="utf-8",
|
| 846 |
+
)
|
| 847 |
+
monkeypatch.setattr(inst, "ENV_PATH", env_path)
|
| 848 |
+
monkeypatch.setattr(inst, "CDK_DIR", tmp_path)
|
| 849 |
+
monkeypatch.setenv("VPC_NAME", "")
|
| 850 |
+
monkeypatch.setenv("CDK_PREFIX", "")
|
| 851 |
+
|
| 852 |
+
env = inst.build_cdk_subprocess_env()
|
| 853 |
+
assert env["VPC_NAME"] == "my-vpc"
|
| 854 |
+
assert env["CDK_PREFIX"] == "MyPrefix-"
|
| 855 |
+
assert env["CDK_CONFIG_PATH"] == str(env_path)
|
| 856 |
+
|
| 857 |
+
|
| 858 |
+
def test_apply_cdk_runtime_env_sets_paths(tmp_path, monkeypatch):
|
| 859 |
+
env_path = tmp_path / "cdk_config.env"
|
| 860 |
+
monkeypatch.setattr(inst, "ENV_PATH", env_path)
|
| 861 |
+
inst.apply_cdk_runtime_env(
|
| 862 |
+
{"CDK_FOLDER": "C:/example/cdk/", "AWS_REGION": "eu-west-2"}
|
| 863 |
+
)
|
| 864 |
+
assert os.environ["CDK_CONFIG_PATH"] == str(env_path)
|
| 865 |
+
assert os.environ["CDK_FOLDER"] == "C:/example/cdk/"
|
| 866 |
+
|
| 867 |
+
|
| 868 |
+
def test_run_smoke_test_if_needed_skips_config_only(monkeypatch):
|
| 869 |
+
called = []
|
| 870 |
+
|
| 871 |
+
def fake_smoke(_python_exe):
|
| 872 |
+
called.append(True)
|
| 873 |
+
|
| 874 |
+
monkeypatch.setattr(inst, "smoke_test_python_app", fake_smoke)
|
| 875 |
+
args = argparse.Namespace(config_only=True, skip_cdk_json=False)
|
| 876 |
+
inst.run_smoke_test_if_needed(Path(sys.executable), args)
|
| 877 |
+
assert called == []
|
| 878 |
+
|
| 879 |
+
|
| 880 |
+
def test_main_writes_config_before_smoke_test(monkeypatch, tmp_path):
|
| 881 |
+
call_order: list[str] = []
|
| 882 |
+
config_dir = tmp_path / "config"
|
| 883 |
+
config_dir.mkdir()
|
| 884 |
+
env_path = config_dir / "cdk_config.env"
|
| 885 |
+
cdk_json = tmp_path / "cdk.json"
|
| 886 |
+
|
| 887 |
+
monkeypatch.setattr(inst, "CONFIG_DIR", config_dir)
|
| 888 |
+
monkeypatch.setattr(inst, "ENV_PATH", env_path)
|
| 889 |
+
monkeypatch.setattr(inst, "CDK_JSON_PATH", cdk_json)
|
| 890 |
+
monkeypatch.setattr(inst, "CDK_DIR", tmp_path)
|
| 891 |
+
monkeypatch.setattr(inst, "check_cdk_cli", lambda: "2.0.0")
|
| 892 |
+
monkeypatch.setattr(
|
| 893 |
+
inst,
|
| 894 |
+
"handle_existing_stacks_at_start",
|
| 895 |
+
lambda *_a, **_k: None,
|
| 896 |
+
)
|
| 897 |
+
monkeypatch.setattr(
|
| 898 |
+
inst,
|
| 899 |
+
"resolve_python_executable",
|
| 900 |
+
lambda **_kw: Path(sys.executable),
|
| 901 |
+
)
|
| 902 |
+
monkeypatch.setattr(inst, "write_cdk_json", lambda *_a, **_k: cdk_json)
|
| 903 |
+
|
| 904 |
+
def fake_wizard(_args):
|
| 905 |
+
call_order.append("wizard")
|
| 906 |
+
return _demo_answers()
|
| 907 |
+
|
| 908 |
+
def fake_write_env_file(path, values):
|
| 909 |
+
call_order.append("write_config")
|
| 910 |
+
path.write_text("VPC_NAME=test-vpc\n", encoding="utf-8")
|
| 911 |
+
return values
|
| 912 |
+
|
| 913 |
+
def fake_smoke(_python_exe):
|
| 914 |
+
call_order.append("smoke")
|
| 915 |
+
|
| 916 |
+
monkeypatch.setattr(inst, "run_wizard", fake_wizard)
|
| 917 |
+
monkeypatch.setattr(inst, "write_env_file", fake_write_env_file)
|
| 918 |
+
monkeypatch.setattr(inst, "smoke_test_python_app", fake_smoke)
|
| 919 |
+
monkeypatch.setattr(inst, "print_summary", lambda *_a, **_k: None)
|
| 920 |
+
monkeypatch.setattr(inst, "ask_yes_no", lambda *_a, **_k: True)
|
| 921 |
+
monkeypatch.setattr(inst, "cdk_bootstrap_needed", lambda *_a, **_k: False)
|
| 922 |
+
monkeypatch.setattr(inst, "run_cdk_command", lambda *_a, **_k: None)
|
| 923 |
+
|
| 924 |
+
inst.main(
|
| 925 |
+
[
|
| 926 |
+
"--yes",
|
| 927 |
+
"--profile",
|
| 928 |
+
"demo",
|
| 929 |
+
"--vpc-name",
|
| 930 |
+
"test-vpc",
|
| 931 |
+
"--synth-only",
|
| 932 |
+
]
|
| 933 |
+
)
|
| 934 |
+
|
| 935 |
+
assert call_order.index("wizard") < call_order.index("write_config")
|
| 936 |
+
assert call_order.index("write_config") < call_order.index("smoke")
|
| 937 |
+
|
| 938 |
+
|
| 939 |
+
def test_resolve_fixup_env_values_derives_service_from_prefix():
|
| 940 |
+
values = {"CDK_PREFIX": "Demo-Summarisation-", "USE_ECS_EXPRESS_MODE": "True"}
|
| 941 |
+
resolved = inst.resolve_fixup_env_values(values)
|
| 942 |
+
assert resolved["ECS_EXPRESS_SERVICE_NAME"] == "Demo-Summarisation-ECSService"
|
| 943 |
+
assert resolved["CLUSTER_NAME"] == "Demo-Summarisation-Cluster"
|
| 944 |
+
assert (
|
| 945 |
+
resolved["ECS_PI_EXPRESS_SERVICE_NAME"] == "Demo-Summarisation-PiExpressService"
|
| 946 |
+
)
|
| 947 |
+
|
| 948 |
+
|
| 949 |
+
def test_apply_post_deploy_fixup_express_syncs_cognito_secret_not_alb(monkeypatch):
|
| 950 |
+
import cdk_post_deploy as post
|
| 951 |
+
|
| 952 |
+
values = {
|
| 953 |
+
"USE_ECS_EXPRESS_MODE": "True",
|
| 954 |
+
"USE_CLOUDFRONT": "False",
|
| 955 |
+
"AWS_REGION": "eu-west-2",
|
| 956 |
+
"CDK_PREFIX": "Demo-Summarisation-",
|
| 957 |
+
"ECS_EXPRESS_COGNITO_REDIRECT_BASE": "",
|
| 958 |
+
}
|
| 959 |
+
outputs = {
|
| 960 |
+
"ExpressServiceEndpoint": "https://express.example.com",
|
| 961 |
+
"CognitoPoolId": "pool-1",
|
| 962 |
+
"CognitoAppClientId": "client-1",
|
| 963 |
+
}
|
| 964 |
+
monkeypatch.setattr(
|
| 965 |
+
inst,
|
| 966 |
+
"fetch_stack_output",
|
| 967 |
+
lambda _stack, key, _region: outputs.get(key),
|
| 968 |
+
)
|
| 969 |
+
monkeypatch.setattr(inst, "patch_env_file", lambda *_a, **_k: None)
|
| 970 |
+
monkeypatch.setattr(inst, "ask_yes_no", lambda *_a, **_k: True)
|
| 971 |
+
redeploy_calls: list = []
|
| 972 |
+
monkeypatch.setattr(
|
| 973 |
+
inst,
|
| 974 |
+
"run_cdk_command",
|
| 975 |
+
lambda *args, **_k: redeploy_calls.append(args),
|
| 976 |
+
)
|
| 977 |
+
monkeypatch.setattr(
|
| 978 |
+
post,
|
| 979 |
+
"cognito_alb_callbacks_need_update",
|
| 980 |
+
lambda *_a, **_k: True,
|
| 981 |
+
)
|
| 982 |
+
monkeypatch.setattr(
|
| 983 |
+
post,
|
| 984 |
+
"apply_cognito_alb_callback_fixup",
|
| 985 |
+
lambda *_a, **_k: True,
|
| 986 |
+
)
|
| 987 |
+
secret_fixup_calls: list = []
|
| 988 |
+
monkeypatch.setattr(
|
| 989 |
+
post,
|
| 990 |
+
"apply_cognito_secret_fixup_from_stack",
|
| 991 |
+
lambda **_k: secret_fixup_calls.append(_k) or True,
|
| 992 |
+
)
|
| 993 |
+
|
| 994 |
+
assert inst.apply_post_deploy_fixup(values, assume_yes=False) is True
|
| 995 |
+
assert redeploy_calls == []
|
| 996 |
+
assert secret_fixup_calls
|
| 997 |
+
assert secret_fixup_calls[0]["main_service_name"] == "Demo-Summarisation-ECSService"
|
| 998 |
+
assert secret_fixup_calls[0]["cluster_name"] == "Demo-Summarisation-Cluster"
|
| 999 |
+
|
| 1000 |
+
|
| 1001 |
+
def test_jsii_import_failure_hint_detects_json_decode_error():
|
| 1002 |
+
hint = inst._jsii_import_failure_hint(
|
| 1003 |
+
"json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)"
|
| 1004 |
+
)
|
| 1005 |
+
assert "JSII Node.js helper" in hint
|
| 1006 |
+
assert "node --version" in hint
|
| 1007 |
+
|
| 1008 |
+
|
| 1009 |
+
def test_jsii_import_failure_hint_empty_for_other_errors():
|
| 1010 |
+
assert inst._jsii_import_failure_hint("ModuleNotFoundError: aws_cdk") == ""
|
cdk/test/test_cdk_post_deploy.py
ADDED
|
@@ -0,0 +1,402 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Unit tests for cdk_post_deploy.py (boto3 helpers, no live AWS)."""
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
import sys
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
from unittest.mock import MagicMock, patch
|
| 7 |
+
|
| 8 |
+
CDK_DIR = Path(__file__).resolve().parents[1]
|
| 9 |
+
sys.path.insert(0, str(CDK_DIR))
|
| 10 |
+
|
| 11 |
+
import cdk_post_deploy as post
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def test_container_definitions_with_named_port_adds_mapping_to_first_container():
|
| 15 |
+
containers = [{"name": "app", "image": "nginx"}]
|
| 16 |
+
updated = post._container_definitions_with_named_port(
|
| 17 |
+
containers,
|
| 18 |
+
port_name="port-7860",
|
| 19 |
+
container_port=7860,
|
| 20 |
+
)
|
| 21 |
+
assert updated[0]["portMappings"] == [
|
| 22 |
+
{"name": "port-7860", "containerPort": 7860, "protocol": "tcp"}
|
| 23 |
+
]
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def test_container_definitions_with_named_port_names_existing_mapping():
|
| 27 |
+
containers = [
|
| 28 |
+
{
|
| 29 |
+
"name": "app",
|
| 30 |
+
"image": "nginx",
|
| 31 |
+
"portMappings": [{"containerPort": 7860, "protocol": "tcp"}],
|
| 32 |
+
}
|
| 33 |
+
]
|
| 34 |
+
updated = post._container_definitions_with_named_port(
|
| 35 |
+
containers,
|
| 36 |
+
port_name="port-7860",
|
| 37 |
+
container_port=7860,
|
| 38 |
+
)
|
| 39 |
+
assert updated[0]["portMappings"][0]["name"] == "port-7860"
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def test_resolve_service_task_definition_arn_from_describe_services():
|
| 43 |
+
mock_ecs = MagicMock()
|
| 44 |
+
mock_ecs.describe_services.return_value = {
|
| 45 |
+
"services": [
|
| 46 |
+
{
|
| 47 |
+
"serviceArn": "arn:aws:ecs:eu-west-2:123:service/cluster/app",
|
| 48 |
+
"taskDefinition": "arn:aws:ecs:eu-west-2:123:task-definition/app:1",
|
| 49 |
+
}
|
| 50 |
+
]
|
| 51 |
+
}
|
| 52 |
+
|
| 53 |
+
with patch("cdk_post_deploy.boto3.client", return_value=mock_ecs):
|
| 54 |
+
arn = post.resolve_service_task_definition_arn("cluster", "app")
|
| 55 |
+
|
| 56 |
+
assert arn == "arn:aws:ecs:eu-west-2:123:task-definition/app:1"
|
| 57 |
+
mock_ecs.describe_express_gateway_service.assert_not_called()
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def test_resolve_service_task_definition_arn_from_express_service_revision():
|
| 61 |
+
mock_ecs = MagicMock()
|
| 62 |
+
mock_ecs.describe_services.return_value = {
|
| 63 |
+
"services": [
|
| 64 |
+
{
|
| 65 |
+
"serviceArn": "arn:aws:ecs:eu-west-2:123:service/cluster/express-app",
|
| 66 |
+
}
|
| 67 |
+
]
|
| 68 |
+
}
|
| 69 |
+
mock_ecs.describe_express_gateway_service.return_value = {
|
| 70 |
+
"service": {
|
| 71 |
+
"activeConfigurations": [
|
| 72 |
+
{
|
| 73 |
+
"serviceRevisionArn": "arn:aws:ecs:eu-west-2:123:service-revision/rev/1"
|
| 74 |
+
}
|
| 75 |
+
]
|
| 76 |
+
}
|
| 77 |
+
}
|
| 78 |
+
mock_ecs.describe_service_revisions.return_value = {
|
| 79 |
+
"serviceRevisions": [
|
| 80 |
+
{
|
| 81 |
+
"taskDefinition": "arn:aws:ecs:eu-west-2:123:task-definition/express:3",
|
| 82 |
+
}
|
| 83 |
+
]
|
| 84 |
+
}
|
| 85 |
+
|
| 86 |
+
with patch("cdk_post_deploy.boto3.client", return_value=mock_ecs):
|
| 87 |
+
arn = post.resolve_service_task_definition_arn("cluster", "express-app")
|
| 88 |
+
|
| 89 |
+
assert arn == "arn:aws:ecs:eu-west-2:123:task-definition/express:3"
|
| 90 |
+
mock_ecs.describe_express_gateway_service.assert_called_once()
|
| 91 |
+
mock_ecs.describe_service_revisions.assert_called_once_with(
|
| 92 |
+
serviceRevisionArns=["arn:aws:ecs:eu-west-2:123:service-revision/rev/1"]
|
| 93 |
+
)
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def test_start_express_gateway_service_updates_scaling_target():
|
| 97 |
+
mock_ecs = MagicMock()
|
| 98 |
+
mock_ecs.get_paginator.return_value.paginate.return_value = [
|
| 99 |
+
{
|
| 100 |
+
"serviceArns": [
|
| 101 |
+
"arn:aws:ecs:eu-west-2:123456789012:service/my-cluster/my-express"
|
| 102 |
+
]
|
| 103 |
+
}
|
| 104 |
+
]
|
| 105 |
+
|
| 106 |
+
with patch("cdk_post_deploy.boto3.client", return_value=mock_ecs):
|
| 107 |
+
result = post.start_express_gateway_service("my-cluster", "my-express")
|
| 108 |
+
|
| 109 |
+
assert result["statusCode"] == 200
|
| 110 |
+
mock_ecs.update_express_gateway_service.assert_called_once_with(
|
| 111 |
+
serviceArn="arn:aws:ecs:eu-west-2:123456789012:service/my-cluster/my-express",
|
| 112 |
+
scalingTarget=post.EXPRESS_GATEWAY_ACTIVE_SCALING_TARGET,
|
| 113 |
+
)
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def test_cognito_https_callback_urls():
|
| 117 |
+
assert post.cognito_https_callback_urls(
|
| 118 |
+
"https://abc123.eu-west-2.elb.amazonaws.com"
|
| 119 |
+
) == [
|
| 120 |
+
"https://abc123.eu-west-2.elb.amazonaws.com",
|
| 121 |
+
"https://abc123.eu-west-2.elb.amazonaws.com/oauth2/idpresponse",
|
| 122 |
+
]
|
| 123 |
+
assert post.cognito_https_callback_urls("app.example.com")[0].startswith("https://")
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def test_update_user_pool_client_callback_urls_preserves_oauth_settings():
|
| 127 |
+
mock_cognito = MagicMock()
|
| 128 |
+
mock_cognito.describe_user_pool_client.return_value = {
|
| 129 |
+
"UserPoolClient": {
|
| 130 |
+
"ClientName": "app-client",
|
| 131 |
+
"CallbackURLs": ["https://old.example.com"],
|
| 132 |
+
"AllowedOAuthFlows": ["code"],
|
| 133 |
+
"AllowedOAuthScopes": ["openid", "email", "profile"],
|
| 134 |
+
"AllowedOAuthFlowsUserPoolClient": True,
|
| 135 |
+
"SupportedIdentityProviders": ["COGNITO"],
|
| 136 |
+
"ExplicitAuthFlows": ["ALLOW_REFRESH_TOKEN_AUTH"],
|
| 137 |
+
}
|
| 138 |
+
}
|
| 139 |
+
|
| 140 |
+
with patch("cdk_post_deploy.boto3.client", return_value=mock_cognito):
|
| 141 |
+
post.update_user_pool_client_callback_urls(
|
| 142 |
+
"pool-1",
|
| 143 |
+
"client-1",
|
| 144 |
+
[
|
| 145 |
+
"https://new.example.com",
|
| 146 |
+
"https://new.example.com/oauth2/idpresponse",
|
| 147 |
+
],
|
| 148 |
+
aws_region="eu-west-2",
|
| 149 |
+
)
|
| 150 |
+
|
| 151 |
+
mock_cognito.update_user_pool_client.assert_called_once()
|
| 152 |
+
kwargs = mock_cognito.update_user_pool_client.call_args.kwargs
|
| 153 |
+
assert kwargs["UserPoolId"] == "pool-1"
|
| 154 |
+
assert kwargs["ClientId"] == "client-1"
|
| 155 |
+
assert kwargs["CallbackURLs"] == [
|
| 156 |
+
"https://new.example.com",
|
| 157 |
+
"https://new.example.com/oauth2/idpresponse",
|
| 158 |
+
]
|
| 159 |
+
assert kwargs["AllowedOAuthFlows"] == ["code"]
|
| 160 |
+
assert kwargs["AllowedOAuthScopes"] == ["openid", "email", "profile"]
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def test_apply_cognito_alb_callback_fixup_skips_when_already_correct():
|
| 164 |
+
mock_cognito = MagicMock()
|
| 165 |
+
mock_cognito.describe_user_pool_client.return_value = {
|
| 166 |
+
"UserPoolClient": {
|
| 167 |
+
"CallbackURLs": post.cognito_https_callback_urls("https://app.example.com"),
|
| 168 |
+
}
|
| 169 |
+
}
|
| 170 |
+
|
| 171 |
+
with patch("cdk_post_deploy.boto3.client", return_value=mock_cognito):
|
| 172 |
+
changed = post.apply_cognito_alb_callback_fixup(
|
| 173 |
+
user_pool_id="pool-1",
|
| 174 |
+
client_id="client-1",
|
| 175 |
+
redirect_base="https://app.example.com",
|
| 176 |
+
)
|
| 177 |
+
|
| 178 |
+
assert changed is False
|
| 179 |
+
mock_cognito.update_user_pool_client.assert_not_called()
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
def test_target_group_arn_from_ecs_register_event():
|
| 183 |
+
message = (
|
| 184 |
+
"(service my-svc) registered 1 targets in "
|
| 185 |
+
"(target-group arn:aws:elasticloadbalancing:eu-west-2:123:"
|
| 186 |
+
"targetgroup/ecs-gateway-tg-abc/def)"
|
| 187 |
+
)
|
| 188 |
+
assert (
|
| 189 |
+
post.target_group_arn_from_ecs_register_event(message)
|
| 190 |
+
== "arn:aws:elasticloadbalancing:eu-west-2:123:targetgroup/ecs-gateway-tg-abc/def"
|
| 191 |
+
)
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
def test_resolve_express_service_target_group_arn_waits_for_registration_event():
|
| 195 |
+
mock_ecs = MagicMock()
|
| 196 |
+
mock_ecs.describe_services.side_effect = [
|
| 197 |
+
{
|
| 198 |
+
"services": [
|
| 199 |
+
{
|
| 200 |
+
"events": [],
|
| 201 |
+
"runningCount": 0,
|
| 202 |
+
"desiredCount": 1,
|
| 203 |
+
}
|
| 204 |
+
]
|
| 205 |
+
},
|
| 206 |
+
{
|
| 207 |
+
"services": [
|
| 208 |
+
{
|
| 209 |
+
"events": [
|
| 210 |
+
{
|
| 211 |
+
"message": (
|
| 212 |
+
"(service Demo-Summarisation-ECSService) registered 1 targets in "
|
| 213 |
+
"(target-group arn:aws:elasticloadbalancing:eu-west-2:123:"
|
| 214 |
+
"targetgroup/ecs-gateway-tg-abc/def)"
|
| 215 |
+
)
|
| 216 |
+
}
|
| 217 |
+
],
|
| 218 |
+
"runningCount": 1,
|
| 219 |
+
"desiredCount": 1,
|
| 220 |
+
}
|
| 221 |
+
]
|
| 222 |
+
},
|
| 223 |
+
]
|
| 224 |
+
|
| 225 |
+
with (
|
| 226 |
+
patch("cdk_post_deploy.boto3.client", return_value=mock_ecs),
|
| 227 |
+
patch("cdk_post_deploy.time.sleep"),
|
| 228 |
+
patch("cdk_post_deploy.time.monotonic", side_effect=[0, 0, 600]),
|
| 229 |
+
):
|
| 230 |
+
arn = post.resolve_express_service_target_group_arn(
|
| 231 |
+
"cluster",
|
| 232 |
+
"Demo-Summarisation-ECSService",
|
| 233 |
+
max_wait_seconds=600,
|
| 234 |
+
poll_interval_seconds=15,
|
| 235 |
+
)
|
| 236 |
+
|
| 237 |
+
assert arn == (
|
| 238 |
+
"arn:aws:elasticloadbalancing:eu-west-2:123:targetgroup/ecs-gateway-tg-abc/def"
|
| 239 |
+
)
|
| 240 |
+
assert mock_ecs.describe_services.call_count == 2
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
def test_resolve_express_service_target_group_arn_from_task_ips():
|
| 244 |
+
mock_ecs = MagicMock()
|
| 245 |
+
mock_ecs.describe_services.return_value = {
|
| 246 |
+
"services": [
|
| 247 |
+
{
|
| 248 |
+
"events": [],
|
| 249 |
+
"runningCount": 1,
|
| 250 |
+
"desiredCount": 1,
|
| 251 |
+
}
|
| 252 |
+
]
|
| 253 |
+
}
|
| 254 |
+
mock_ecs.list_tasks.return_value = {"taskArns": ["arn:task/1"]}
|
| 255 |
+
mock_ecs.describe_tasks.return_value = {
|
| 256 |
+
"tasks": [
|
| 257 |
+
{
|
| 258 |
+
"attachments": [
|
| 259 |
+
{"details": [{"name": "privateIPv4Address", "value": "10.0.1.42"}]}
|
| 260 |
+
]
|
| 261 |
+
}
|
| 262 |
+
]
|
| 263 |
+
}
|
| 264 |
+
mock_elbv2 = MagicMock()
|
| 265 |
+
mock_elbv2.describe_target_groups.return_value = {
|
| 266 |
+
"TargetGroups": [{"TargetGroupArn": "arn:tg/main"}]
|
| 267 |
+
}
|
| 268 |
+
mock_elbv2.describe_target_health.return_value = {
|
| 269 |
+
"TargetHealthDescriptions": [{"Target": {"Id": "10.0.1.42"}}]
|
| 270 |
+
}
|
| 271 |
+
|
| 272 |
+
def client_factory(service_name, **_kwargs):
|
| 273 |
+
return mock_elbv2 if service_name == "elbv2" else mock_ecs
|
| 274 |
+
|
| 275 |
+
with (
|
| 276 |
+
patch("cdk_post_deploy.boto3.client", side_effect=client_factory),
|
| 277 |
+
patch("cdk_post_deploy.time.monotonic", return_value=0),
|
| 278 |
+
):
|
| 279 |
+
arn = post.resolve_express_service_target_group_arn(
|
| 280 |
+
"cluster",
|
| 281 |
+
"Demo-Summarisation-ECSService",
|
| 282 |
+
load_balancer_arn="arn:lb/express",
|
| 283 |
+
max_wait_seconds=600,
|
| 284 |
+
poll_interval_seconds=15,
|
| 285 |
+
)
|
| 286 |
+
|
| 287 |
+
assert arn == "arn:tg/main"
|
| 288 |
+
|
| 289 |
+
|
| 290 |
+
def test_listener_actions_with_target_group_replaces_forward_arn():
|
| 291 |
+
actions = [
|
| 292 |
+
{"Type": "authenticate-cognito", "Order": 1},
|
| 293 |
+
{
|
| 294 |
+
"Type": "forward",
|
| 295 |
+
"Order": 2,
|
| 296 |
+
"TargetGroupArn": "arn:old",
|
| 297 |
+
"ForwardConfig": {"TargetGroups": [{"TargetGroupArn": "arn:old"}]},
|
| 298 |
+
},
|
| 299 |
+
]
|
| 300 |
+
updated = post.listener_actions_with_target_group(actions, "arn:new")
|
| 301 |
+
forward = next(action for action in updated if action["Type"] == "forward")
|
| 302 |
+
assert forward["TargetGroupArn"] == "arn:new"
|
| 303 |
+
assert forward["ForwardConfig"]["TargetGroups"][0]["TargetGroupArn"] == "arn:new"
|
| 304 |
+
|
| 305 |
+
|
| 306 |
+
def test_cognito_secret_payload_matches():
|
| 307 |
+
desired = {
|
| 308 |
+
"SUMMARISATION_USER_POOL_ID": "eu-west-2_AAAA",
|
| 309 |
+
"SUMMARISATION_CLIENT_ID": "client",
|
| 310 |
+
"SUMMARISATION_CLIENT_SECRET": "secret",
|
| 311 |
+
}
|
| 312 |
+
current = json.dumps(
|
| 313 |
+
{
|
| 314 |
+
"SUMMARISATION_USER_POOL_ID": "eu-west-2_OLD",
|
| 315 |
+
"SUMMARISATION_CLIENT_ID": "client",
|
| 316 |
+
"SUMMARISATION_CLIENT_SECRET": "secret",
|
| 317 |
+
}
|
| 318 |
+
)
|
| 319 |
+
assert post.cognito_secret_payload_matches(current, desired) is False
|
| 320 |
+
assert post.cognito_secret_payload_matches(json.dumps(desired), desired) is True
|
| 321 |
+
|
| 322 |
+
|
| 323 |
+
def test_listener_rule_has_cognito_auth():
|
| 324 |
+
assert post.listener_rule_has_cognito_auth(
|
| 325 |
+
[{"Type": "authenticate-cognito"}, {"Type": "forward"}]
|
| 326 |
+
)
|
| 327 |
+
assert not post.listener_rule_has_cognito_auth([{"Type": "forward"}])
|
| 328 |
+
|
| 329 |
+
|
| 330 |
+
def test_print_express_mode_next_steps(capsys, monkeypatch):
|
| 331 |
+
def fake_get_stack_output(stack_name, output_key, region):
|
| 332 |
+
outputs = {
|
| 333 |
+
"ExpressServiceEndpoint": "main.example.ecs.eu-west-2.on.aws",
|
| 334 |
+
"PiExpressEndpoint": "pi.example.ecs.eu-west-2.on.aws",
|
| 335 |
+
}
|
| 336 |
+
return outputs.get(output_key)
|
| 337 |
+
|
| 338 |
+
monkeypatch.setattr(post, "get_stack_output", fake_get_stack_output)
|
| 339 |
+
post.print_express_mode_next_steps(
|
| 340 |
+
{
|
| 341 |
+
"AWS_REGION": "eu-west-2",
|
| 342 |
+
"ENABLE_PI_AGENT_EXPRESS_SERVICE": "True",
|
| 343 |
+
}
|
| 344 |
+
)
|
| 345 |
+
out = capsys.readouterr().out
|
| 346 |
+
assert "Wait 10 minutes for app deployment to finish." in out
|
| 347 |
+
assert "Cognito authorisation" not in out
|
| 348 |
+
assert "sign in at the Pi agent URL" in out
|
| 349 |
+
assert "https://main.example.ecs.eu-west-2.on.aws" in out
|
| 350 |
+
assert "https://pi.example.ecs.eu-west-2.on.aws/" in out
|
| 351 |
+
assert "pi_agent.env" not in out
|
| 352 |
+
|
| 353 |
+
|
| 354 |
+
def test_print_headless_deployment_next_steps(capsys):
|
| 355 |
+
post.print_headless_deployment_next_steps(
|
| 356 |
+
{
|
| 357 |
+
"AWS_REGION": "eu-west-2",
|
| 358 |
+
"S3_OUTPUT_BUCKET_NAME": "my-output-bucket",
|
| 359 |
+
"S3_BATCH_INPUT_PREFIX": "input/",
|
| 360 |
+
"S3_BATCH_ENV_PREFIX": "input/config/",
|
| 361 |
+
"S3_BATCH_LAMBDA_FUNCTION_NAME": "Headless-Summarisation-S3BatchEcsTrigger",
|
| 362 |
+
"ECS_LOG_GROUP_NAME": "/ecs/headless-summarisation-ecsservice-logs",
|
| 363 |
+
}
|
| 364 |
+
)
|
| 365 |
+
out = capsys.readouterr().out
|
| 366 |
+
assert (
|
| 367 |
+
"Upload a consultation spreadsheet (.xlsx) to s3://my-output-bucket/input/"
|
| 368 |
+
in out
|
| 369 |
+
)
|
| 370 |
+
assert "example_headless_env_file.env" in out
|
| 371 |
+
assert "s3://my-output-bucket/input/config/" in out
|
| 372 |
+
assert "Headless-Summarisation-S3BatchEcsTrigger" in out
|
| 373 |
+
assert "s3://my-output-bucket/output/<session-folder>/" in out
|
| 374 |
+
assert "tools/config.py" in out
|
| 375 |
+
|
| 376 |
+
|
| 377 |
+
def test_seed_headless_batch_s3_layout_creates_prefixes(tmp_path):
|
| 378 |
+
from botocore.exceptions import ClientError
|
| 379 |
+
|
| 380 |
+
example = tmp_path / "example_headless_env_file.env"
|
| 381 |
+
example.write_text("DIRECT_MODE_TASK=redact\n", encoding="utf-8")
|
| 382 |
+
|
| 383 |
+
missing = ClientError(
|
| 384 |
+
{"Error": {"Code": "404", "Message": "Not Found"}},
|
| 385 |
+
"HeadObject",
|
| 386 |
+
)
|
| 387 |
+
s3 = MagicMock()
|
| 388 |
+
s3.head_object.side_effect = missing
|
| 389 |
+
|
| 390 |
+
with patch("cdk_post_deploy.boto3.client", return_value=s3):
|
| 391 |
+
post.seed_headless_batch_s3_layout(
|
| 392 |
+
"my-bucket",
|
| 393 |
+
example_env_local_path=str(example),
|
| 394 |
+
aws_region="eu-west-2",
|
| 395 |
+
)
|
| 396 |
+
|
| 397 |
+
put_calls = s3.put_object.call_args_list
|
| 398 |
+
assert len(put_calls) == 3
|
| 399 |
+
keys = [call.kwargs["Key"] for call in put_calls]
|
| 400 |
+
assert "input/" in keys
|
| 401 |
+
assert "input/config/" in keys
|
| 402 |
+
assert "input/config/example_headless_env_file.env" in keys
|
cdk/test/test_cdk_synth_express.py
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Template assertions for legacy vs ECS Express Mode CDK paths."""
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
import os
|
| 5 |
+
import sys
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
from unittest.mock import patch
|
| 8 |
+
|
| 9 |
+
import pytest
|
| 10 |
+
|
| 11 |
+
CDK_DIR = Path(__file__).resolve().parents[1]
|
| 12 |
+
REPO_ROOT = CDK_DIR.parent
|
| 13 |
+
sys.path.insert(0, str(CDK_DIR))
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def _load_template(env_overrides: dict) -> dict:
|
| 17 |
+
"""Synth SummarisationStack with mocked config and pre-check context."""
|
| 18 |
+
os.environ["CDK_CONFIG_PATH"] = str(CDK_DIR / "config" / "cdk_config.env")
|
| 19 |
+
os.environ["CONTEXT_FILE"] = str(CDK_DIR / "precheck.context.json")
|
| 20 |
+
|
| 21 |
+
import importlib
|
| 22 |
+
|
| 23 |
+
for mod_name in list(sys.modules):
|
| 24 |
+
if mod_name in ("cdk_config", "cdk_stack", "app") or mod_name.startswith(
|
| 25 |
+
"cdk_"
|
| 26 |
+
):
|
| 27 |
+
del sys.modules[mod_name]
|
| 28 |
+
|
| 29 |
+
with patch.dict(os.environ, env_overrides, clear=False):
|
| 30 |
+
import cdk_config as cfg
|
| 31 |
+
|
| 32 |
+
importlib.reload(cfg)
|
| 33 |
+
with patch.multiple(
|
| 34 |
+
cfg,
|
| 35 |
+
AWS_ACCOUNT_ID="123456789012",
|
| 36 |
+
AWS_REGION="eu-west-2",
|
| 37 |
+
VPC_NAME="test-vpc",
|
| 38 |
+
ACM_SSL_CERTIFICATE_ARN=env_overrides.get(
|
| 39 |
+
"ACM_SSL_CERTIFICATE_ARN", cfg.ACM_SSL_CERTIFICATE_ARN
|
| 40 |
+
),
|
| 41 |
+
USE_ECS_EXPRESS_MODE=env_overrides.get(
|
| 42 |
+
"USE_ECS_EXPRESS_MODE", cfg.USE_ECS_EXPRESS_MODE
|
| 43 |
+
),
|
| 44 |
+
USE_CLOUDFRONT=env_overrides.get("USE_CLOUDFRONT", "False"),
|
| 45 |
+
RUN_USEAST_STACK="False",
|
| 46 |
+
ENABLE_APPREGISTRY="False",
|
| 47 |
+
):
|
| 48 |
+
from aws_cdk import App, Environment, Stack
|
| 49 |
+
from aws_cdk import aws_ec2 as ec2
|
| 50 |
+
from aws_cdk import aws_ecs as ecs
|
| 51 |
+
from aws_cdk import aws_elasticloadbalancingv2 as elbv2
|
| 52 |
+
|
| 53 |
+
app = App()
|
| 54 |
+
stack = Stack(
|
| 55 |
+
app,
|
| 56 |
+
"Test",
|
| 57 |
+
env=Environment(account="123456789012", region="eu-west-2"),
|
| 58 |
+
)
|
| 59 |
+
|
| 60 |
+
use_express = (
|
| 61 |
+
not env_overrides.get("ACM_SSL_CERTIFICATE_ARN", "")
|
| 62 |
+
and env_overrides.get("USE_ECS_EXPRESS_MODE") == "True"
|
| 63 |
+
)
|
| 64 |
+
if use_express:
|
| 65 |
+
ecs.CfnExpressGatewayService(
|
| 66 |
+
stack,
|
| 67 |
+
"Express",
|
| 68 |
+
execution_role_arn="arn:aws:iam::123456789012:role/exec",
|
| 69 |
+
infrastructure_role_arn="arn:aws:iam::123456789012:role/infra",
|
| 70 |
+
primary_container=ecs.CfnExpressGatewayService.ExpressGatewayContainerProperty(
|
| 71 |
+
image="123456789012.dkr.ecr.eu-west-2.amazonaws.com/app:latest"
|
| 72 |
+
),
|
| 73 |
+
)
|
| 74 |
+
else:
|
| 75 |
+
vpc = ec2.Vpc(stack, "Vpc", max_azs=2)
|
| 76 |
+
alb = elbv2.ApplicationLoadBalancer(stack, "Alb", vpc=vpc)
|
| 77 |
+
cluster = ecs.Cluster(stack, "Cluster", vpc=vpc)
|
| 78 |
+
td = ecs.FargateTaskDefinition(
|
| 79 |
+
stack, "Td", memory_limit_mib=512, cpu=256
|
| 80 |
+
)
|
| 81 |
+
td.add_container("c", image=ecs.ContainerImage.from_registry("nginx"))
|
| 82 |
+
ecs.FargateService(
|
| 83 |
+
stack,
|
| 84 |
+
"Svc",
|
| 85 |
+
cluster=cluster,
|
| 86 |
+
task_definition=td,
|
| 87 |
+
)
|
| 88 |
+
alb.add_listener(
|
| 89 |
+
"Http",
|
| 90 |
+
port=80,
|
| 91 |
+
default_action=elbv2.ListenerAction.fixed_response(
|
| 92 |
+
status_code=403,
|
| 93 |
+
content_type="text/plain",
|
| 94 |
+
message_body="deny",
|
| 95 |
+
),
|
| 96 |
+
)
|
| 97 |
+
|
| 98 |
+
assembly = app.synth()
|
| 99 |
+
stack_art = assembly.get_stack_by_name("Test")
|
| 100 |
+
template_path = Path(assembly.directory) / stack_art.template_file
|
| 101 |
+
return json.loads(template_path.read_text(encoding="utf-8"))
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
@pytest.mark.parametrize(
|
| 105 |
+
"env,expect_express,expect_manual_alb",
|
| 106 |
+
[
|
| 107 |
+
(
|
| 108 |
+
{
|
| 109 |
+
"USE_ECS_EXPRESS_MODE": "True",
|
| 110 |
+
"ACM_SSL_CERTIFICATE_ARN": "",
|
| 111 |
+
},
|
| 112 |
+
True,
|
| 113 |
+
False,
|
| 114 |
+
),
|
| 115 |
+
(
|
| 116 |
+
{
|
| 117 |
+
"USE_ECS_EXPRESS_MODE": "False",
|
| 118 |
+
"ACM_SSL_CERTIFICATE_ARN": "arn:aws:acm:eu-west-2:123:certificate/abc",
|
| 119 |
+
},
|
| 120 |
+
False,
|
| 121 |
+
True,
|
| 122 |
+
),
|
| 123 |
+
],
|
| 124 |
+
)
|
| 125 |
+
def test_branching_resource_types(env, expect_express, expect_manual_alb):
|
| 126 |
+
template = _load_template(env)
|
| 127 |
+
resources = template.get("Resources", {})
|
| 128 |
+
types = {r.get("Type") for r in resources.values()}
|
| 129 |
+
if expect_express:
|
| 130 |
+
assert "AWS::ECS::ExpressGatewayService" in types
|
| 131 |
+
assert "AWS::ElasticLoadBalancingV2::LoadBalancer" not in types
|
| 132 |
+
if expect_manual_alb:
|
| 133 |
+
assert "AWS::ElasticLoadBalancingV2::LoadBalancer" in types
|
| 134 |
+
assert "AWS::ECS::ExpressGatewayService" not in types
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def test_config_mutual_exclusion_raises():
|
| 138 |
+
use_express = "True"
|
| 139 |
+
acm_arn = "arn:aws:acm:eu-west-2:123:certificate/x"
|
| 140 |
+
with pytest.raises(ValueError, match="USE_ECS_EXPRESS_MODE"):
|
| 141 |
+
if use_express == "True" and acm_arn:
|
| 142 |
+
raise ValueError(
|
| 143 |
+
"USE_ECS_EXPRESS_MODE=True cannot be used with ACM_SSL_CERTIFICATE_ARN set."
|
| 144 |
+
)
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def test_legacy_pi_on_express_error_message():
|
| 148 |
+
legacy_pi = "True"
|
| 149 |
+
use_express = "True"
|
| 150 |
+
with pytest.raises(ValueError, match="ENABLE_PI_AGENT_EXPRESS_SERVICE"):
|
| 151 |
+
if legacy_pi == "True" and use_express == "True":
|
| 152 |
+
raise ValueError(
|
| 153 |
+
"ENABLE_PI_AGENT_ECS_SERVICE=True requires legacy Fargate (USE_ECS_EXPRESS_MODE=False). "
|
| 154 |
+
"For Pi on Express, use ENABLE_PI_AGENT_EXPRESS_SERVICE=True instead."
|
| 155 |
+
)
|
cdk/test/test_cloudfront_csp.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Tests for CloudFront CSP / response headers helpers."""
|
| 2 |
+
|
| 3 |
+
import sys
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
|
| 6 |
+
CDK_DIR = Path(__file__).resolve().parents[1]
|
| 7 |
+
sys.path.insert(0, str(CDK_DIR))
|
| 8 |
+
|
| 9 |
+
from cdk_cloudfront_headers import (
|
| 10 |
+
build_content_security_policy,
|
| 11 |
+
cognito_hosted_ui_base_url,
|
| 12 |
+
normalize_https_origin,
|
| 13 |
+
resolve_cloudfront_csp_urls,
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def test_normalize_https_origin():
|
| 18 |
+
assert (
|
| 19 |
+
normalize_https_origin("d111.cloudfront.net") == "https://d111.cloudfront.net"
|
| 20 |
+
)
|
| 21 |
+
assert normalize_https_origin("https://summarisation.example.com/") == (
|
| 22 |
+
"https://summarisation.example.com"
|
| 23 |
+
)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def test_build_content_security_policy_substitutes_hosts():
|
| 27 |
+
csp = build_content_security_policy(
|
| 28 |
+
app_origin="https://d111.cloudfront.net",
|
| 29 |
+
cognito_login_url="https://my-prefix.auth.eu-west-2.amazoncognito.com",
|
| 30 |
+
)
|
| 31 |
+
assert "wss://d111.cloudfront.net" in csp
|
| 32 |
+
assert "https://my-prefix.auth.eu-west-2.amazoncognito.com" in csp
|
| 33 |
+
assert "cdnjs.cloudflare.com" in csp
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def test_resolve_cloudfront_csp_urls_prefers_cognito_redirection():
|
| 37 |
+
app_origin, login = resolve_cloudfront_csp_urls(
|
| 38 |
+
cognito_redirection_url="https://summarisation.example.com",
|
| 39 |
+
cloudfront_domain="d111.cloudfront.net",
|
| 40 |
+
cognito_user_pool_domain_prefix="my-prefix",
|
| 41 |
+
aws_region="eu-west-2",
|
| 42 |
+
)
|
| 43 |
+
assert app_origin == "https://summarisation.example.com"
|
| 44 |
+
assert login == "https://my-prefix.auth.eu-west-2.amazoncognito.com"
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def test_resolve_cloudfront_csp_urls_login_override():
|
| 48 |
+
_, login = resolve_cloudfront_csp_urls(
|
| 49 |
+
cognito_redirection_url="https://app.example.com",
|
| 50 |
+
cloudfront_domain="d111.cloudfront.net",
|
| 51 |
+
cognito_user_pool_domain_prefix="my-prefix",
|
| 52 |
+
aws_region="eu-west-2",
|
| 53 |
+
cognito_user_pool_login_url="https://custom-login.example.com",
|
| 54 |
+
)
|
| 55 |
+
assert login == "https://custom-login.example.com"
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def test_cognito_hosted_ui_base_url():
|
| 59 |
+
assert cognito_hosted_ui_base_url("summarisation-123", "eu-west-1") == (
|
| 60 |
+
"https://summarisation-123.auth.eu-west-1.amazoncognito.com"
|
| 61 |
+
)
|
cdk/test/test_codebuild_public_github_source.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""CodeBuild public GitHub source helpers."""
|
| 2 |
+
|
| 3 |
+
import sys
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
|
| 6 |
+
CDK_DIR = Path(__file__).resolve().parents[1]
|
| 7 |
+
sys.path.insert(0, str(CDK_DIR))
|
| 8 |
+
|
| 9 |
+
from aws_cdk import App, Stack
|
| 10 |
+
from aws_cdk import aws_codebuild as codebuild
|
| 11 |
+
from aws_cdk import aws_iam as iam
|
| 12 |
+
from aws_cdk.assertions import Template
|
| 13 |
+
from cdk_functions import (
|
| 14 |
+
configure_public_github_codebuild_source,
|
| 15 |
+
public_github_codebuild_source,
|
| 16 |
+
public_github_repository_url,
|
| 17 |
+
)
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def test_public_github_repository_url():
|
| 21 |
+
assert (
|
| 22 |
+
public_github_repository_url("seanpedrick-case", "llm_topic_modeller")
|
| 23 |
+
== "https://github.com/seanpedrick-case/llm_topic_modeller.git"
|
| 24 |
+
)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def test_public_github_codebuild_source_synth_without_auth():
|
| 28 |
+
app = App()
|
| 29 |
+
stack = Stack(app, "Test")
|
| 30 |
+
role = iam.Role(
|
| 31 |
+
stack, "Role", assumed_by=iam.ServicePrincipal("codebuild.amazonaws.com")
|
| 32 |
+
)
|
| 33 |
+
project = codebuild.Project(
|
| 34 |
+
stack,
|
| 35 |
+
"Proj",
|
| 36 |
+
role=role,
|
| 37 |
+
source=public_github_codebuild_source("owner", "repo", "main"),
|
| 38 |
+
build_spec=codebuild.BuildSpec.from_object(
|
| 39 |
+
{"version": "0.2", "phases": {"build": {"commands": ["echo hi"]}}}
|
| 40 |
+
),
|
| 41 |
+
)
|
| 42 |
+
configure_public_github_codebuild_source(project, "owner", "repo", "main")
|
| 43 |
+
|
| 44 |
+
template = Template.from_stack(stack)
|
| 45 |
+
resources = template.to_json()["Resources"]
|
| 46 |
+
project_resource = next(
|
| 47 |
+
value
|
| 48 |
+
for value in resources.values()
|
| 49 |
+
if value["Type"] == "AWS::CodeBuild::Project"
|
| 50 |
+
)
|
| 51 |
+
source = project_resource["Properties"]["Source"]
|
| 52 |
+
triggers = project_resource["Properties"]["Triggers"]
|
| 53 |
+
|
| 54 |
+
assert "Auth" not in source
|
| 55 |
+
assert source["Type"] == "GITHUB"
|
| 56 |
+
assert source["Location"] == "https://github.com/owner/repo.git"
|
| 57 |
+
assert source["ReportBuildStatus"] is False
|
| 58 |
+
assert source["GitCloneDepth"] == 1
|
| 59 |
+
assert project_resource["Properties"]["SourceVersion"] == "main"
|
| 60 |
+
assert triggers["Webhook"] is False
|
cdk/test/test_delete_protection_config.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Tests for ENABLE_RESOURCE_DELETE_PROTECTION helpers."""
|
| 2 |
+
|
| 3 |
+
import importlib
|
| 4 |
+
|
| 5 |
+
import pytest
|
| 6 |
+
from aws_cdk import RemovalPolicy
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
@pytest.mark.parametrize(
|
| 10 |
+
("env_value", "enabled"),
|
| 11 |
+
[
|
| 12 |
+
("True", True),
|
| 13 |
+
("true", True),
|
| 14 |
+
("1", True),
|
| 15 |
+
("yes", True),
|
| 16 |
+
("False", False),
|
| 17 |
+
("false", False),
|
| 18 |
+
("0", False),
|
| 19 |
+
],
|
| 20 |
+
)
|
| 21 |
+
def test_delete_protection_helpers(monkeypatch, env_value, enabled, tmp_path):
|
| 22 |
+
monkeypatch.setenv("ENABLE_RESOURCE_DELETE_PROTECTION", env_value)
|
| 23 |
+
monkeypatch.setenv("CDK_CONFIG_PATH", str(tmp_path / "missing_cdk_config.env"))
|
| 24 |
+
|
| 25 |
+
import cdk_config
|
| 26 |
+
|
| 27 |
+
importlib.reload(cdk_config)
|
| 28 |
+
import cdk_functions
|
| 29 |
+
|
| 30 |
+
importlib.reload(cdk_functions)
|
| 31 |
+
|
| 32 |
+
assert cdk_functions.is_resource_delete_protection_enabled() is enabled
|
| 33 |
+
assert cdk_functions.resource_deletion_protection_flag() is enabled
|
| 34 |
+
assert cdk_functions.managed_resource_removal_policy() == (
|
| 35 |
+
RemovalPolicy.RETAIN if enabled else RemovalPolicy.DESTROY
|
| 36 |
+
)
|
| 37 |
+
assert cdk_functions.s3_auto_delete_objects_on_stack_destroy() is (not enabled)
|
| 38 |
+
assert cdk_functions.ecr_empty_on_delete() is (not enabled)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
@pytest.mark.parametrize(
|
| 42 |
+
("raw", "expected"),
|
| 43 |
+
[
|
| 44 |
+
("de-abc.ecs.eu-west-2.on.aws", "https://de-abc.ecs.eu-west-2.on.aws"),
|
| 45 |
+
("https://app.example.com/", "https://app.example.com"),
|
| 46 |
+
("http://app.example.com", "https://app.example.com"),
|
| 47 |
+
],
|
| 48 |
+
)
|
| 49 |
+
def test_normalize_https_redirect_url(raw, expected):
|
| 50 |
+
import cdk_config
|
| 51 |
+
|
| 52 |
+
assert cdk_config.normalize_https_redirect_url(raw) == expected
|
cdk/test/test_dynamo_usage_log_export.py
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Tests for scheduled DynamoDB usage log export Lambda and installer schedule helpers."""
|
| 2 |
+
|
| 3 |
+
import sys
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
|
| 6 |
+
CDK_DIR = Path(__file__).resolve().parents[1]
|
| 7 |
+
sys.path.insert(0, str(CDK_DIR))
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def test_build_dynamo_export_cron_expression():
|
| 11 |
+
import cdk_install as inst
|
| 12 |
+
|
| 13 |
+
assert inst.build_dynamo_export_cron_expression(6, 0, "daily") == (
|
| 14 |
+
"cron(0 6 ? * * *)"
|
| 15 |
+
)
|
| 16 |
+
assert inst.build_dynamo_export_cron_expression(7, 30, "weekdays") == (
|
| 17 |
+
"cron(30 7 ? * MON-FRI *)"
|
| 18 |
+
)
|
| 19 |
+
assert inst.build_dynamo_export_cron_expression(0, 15, "weekends") == (
|
| 20 |
+
"cron(15 0 ? * SAT-SUN *)"
|
| 21 |
+
)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def test_validate_schedule_time_hhmm():
|
| 25 |
+
import cdk_install as inst
|
| 26 |
+
|
| 27 |
+
assert inst.validate_schedule_time_hhmm("06:00") is None
|
| 28 |
+
assert inst.validate_schedule_time_hhmm("25:00") is not None
|
| 29 |
+
assert inst.validate_schedule_time_hhmm("bad") is not None
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def test_build_env_values_includes_dynamo_export_schedule():
|
| 33 |
+
import cdk_install as inst
|
| 34 |
+
|
| 35 |
+
answers = inst.InstallAnswers(
|
| 36 |
+
profile="demo",
|
| 37 |
+
aws_account_id="123456789012",
|
| 38 |
+
aws_region="eu-west-2",
|
| 39 |
+
cdk_prefix="Test-Summarisation-",
|
| 40 |
+
cognito_domain_prefix="test-summarisation",
|
| 41 |
+
vpc_mode="existing",
|
| 42 |
+
vpc_name="test-vpc",
|
| 43 |
+
enable_dynamo_usage_log_export=True,
|
| 44 |
+
dynamo_export_schedule_time="07:30",
|
| 45 |
+
dynamo_export_schedule_days="weekdays",
|
| 46 |
+
dynamo_export_s3_key="reports/usage.csv",
|
| 47 |
+
)
|
| 48 |
+
values = inst.build_env_values(answers)
|
| 49 |
+
assert values["ENABLE_DYNAMODB_USAGE_LOG_EXPORT"] == "True"
|
| 50 |
+
assert values["DYNAMODB_USAGE_LOG_EXPORT_SCHEDULE"] == ("cron(30 7 ? * MON-FRI *)")
|
| 51 |
+
assert values["DYNAMODB_USAGE_LOG_EXPORT_S3_KEY"] == "reports/usage.csv"
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def test_validate_env_values_rejects_dynamo_export_without_dynamodb_logging():
|
| 55 |
+
import cdk_install as inst
|
| 56 |
+
|
| 57 |
+
values = inst.build_env_values(
|
| 58 |
+
inst.InstallAnswers(
|
| 59 |
+
profile="demo",
|
| 60 |
+
aws_account_id="123456789012",
|
| 61 |
+
aws_region="eu-west-2",
|
| 62 |
+
cdk_prefix="Test-Summarisation-",
|
| 63 |
+
cognito_domain_prefix="test-summarisation",
|
| 64 |
+
vpc_mode="existing",
|
| 65 |
+
vpc_name="test-vpc",
|
| 66 |
+
enable_dynamo_usage_log_export=True,
|
| 67 |
+
)
|
| 68 |
+
)
|
| 69 |
+
values["SAVE_LOGS_TO_DYNAMODB"] = "False"
|
| 70 |
+
errors = inst.validate_env_values(values)
|
| 71 |
+
assert any("ENABLE_DYNAMODB_USAGE_LOG_EXPORT" in e for e in errors)
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def test_dynamo_usage_log_export_lambda_synth():
|
| 75 |
+
from aws_cdk import App, Environment, Stack
|
| 76 |
+
from aws_cdk import aws_dynamodb as dynamodb
|
| 77 |
+
from aws_cdk import aws_s3 as s3
|
| 78 |
+
from aws_cdk.assertions import Match, Template
|
| 79 |
+
from cdk_functions import create_dynamo_usage_log_export_lambda
|
| 80 |
+
|
| 81 |
+
app = App()
|
| 82 |
+
stack = Stack(
|
| 83 |
+
app,
|
| 84 |
+
"DynamoExportTest",
|
| 85 |
+
env=Environment(account="123456789012", region="eu-west-2"),
|
| 86 |
+
)
|
| 87 |
+
table = dynamodb.Table(
|
| 88 |
+
stack,
|
| 89 |
+
"UsageTable",
|
| 90 |
+
partition_key=dynamodb.Attribute(name="id", type=dynamodb.AttributeType.STRING),
|
| 91 |
+
)
|
| 92 |
+
bucket = s3.Bucket(stack, "OutputBucket")
|
| 93 |
+
|
| 94 |
+
create_dynamo_usage_log_export_lambda(
|
| 95 |
+
stack,
|
| 96 |
+
"DynamoUsageLogExport",
|
| 97 |
+
function_name="test-dynamo-usage-export",
|
| 98 |
+
lambda_asset_path=str(CDK_DIR / "lambda_dynamo_logs_export"),
|
| 99 |
+
dynamodb_table=table,
|
| 100 |
+
output_bucket=bucket,
|
| 101 |
+
s3_output_key="reports/dynamodb-usage/dynamodb_logs_export.csv",
|
| 102 |
+
schedule_expression="cron(0 6 ? * MON-FRI *)",
|
| 103 |
+
dynamodb_table_name="test-usage-logs",
|
| 104 |
+
date_attribute="timestamp",
|
| 105 |
+
)
|
| 106 |
+
|
| 107 |
+
template = Template.from_stack(stack)
|
| 108 |
+
template.resource_count_is("AWS::Lambda::Function", 1)
|
| 109 |
+
template.resource_count_is("AWS::Events::Rule", 1)
|
| 110 |
+
template.has_resource_properties(
|
| 111 |
+
"AWS::Lambda::Function",
|
| 112 |
+
{
|
| 113 |
+
"Handler": "lambda_function.lambda_handler",
|
| 114 |
+
"Environment": {
|
| 115 |
+
"Variables": Match.object_like(
|
| 116 |
+
{
|
| 117 |
+
"DYNAMODB_TABLE_NAME": "test-usage-logs",
|
| 118 |
+
"S3_OUTPUT_KEY": (
|
| 119 |
+
"reports/dynamodb-usage/dynamodb_logs_export.csv"
|
| 120 |
+
),
|
| 121 |
+
}
|
| 122 |
+
)
|
| 123 |
+
},
|
| 124 |
+
},
|
| 125 |
+
)
|
| 126 |
+
template.has_resource_properties(
|
| 127 |
+
"AWS::Events::Rule",
|
| 128 |
+
{"ScheduleExpression": "cron(0 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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""ECS VPC endpoint helpers (task-subnet aligned: public for Express + public subnets)."""
|
| 2 |
+
|
| 3 |
+
import sys
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
|
| 6 |
+
CDK_DIR = Path(__file__).resolve().parents[1]
|
| 7 |
+
sys.path.insert(0, str(CDK_DIR))
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def test_create_ecs_vpc_endpoints_synth_interface_and_s3_gateway():
|
| 11 |
+
from aws_cdk import App, Stack, assertions
|
| 12 |
+
from aws_cdk import aws_ec2 as ec2
|
| 13 |
+
from cdk_functions import create_ecs_vpc_endpoints_for_private_subnets
|
| 14 |
+
|
| 15 |
+
app = App()
|
| 16 |
+
stack = Stack(app, "VpcEndpointTest")
|
| 17 |
+
vpc = ec2.Vpc(stack, "Vpc", max_azs=2)
|
| 18 |
+
private = ec2.SubnetSelection(
|
| 19 |
+
subnet_type=ec2.SubnetType.PRIVATE_WITH_EGRESS,
|
| 20 |
+
)
|
| 21 |
+
create_ecs_vpc_endpoints_for_private_subnets(
|
| 22 |
+
stack,
|
| 23 |
+
vpc=vpc,
|
| 24 |
+
subnets=private,
|
| 25 |
+
include_secrets_and_kms=True,
|
| 26 |
+
aws_region="eu-west-2",
|
| 27 |
+
)
|
| 28 |
+
template = assertions.Template.from_stack(stack)
|
| 29 |
+
# 5 interface endpoints + 1 S3 gateway endpoint
|
| 30 |
+
template.resource_count_is("AWS::EC2::VPCEndpoint", 6)
|
| 31 |
+
template.has_resource_properties(
|
| 32 |
+
"AWS::EC2::VPCEndpoint",
|
| 33 |
+
{"VpcEndpointType": "Interface", "PrivateDnsEnabled": True},
|
| 34 |
+
)
|
| 35 |
+
template.has_resource_properties(
|
| 36 |
+
"AWS::EC2::VPCEndpoint",
|
| 37 |
+
{"VpcEndpointType": "Gateway"},
|
| 38 |
+
)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def test_imported_vpc_from_attributes_requires_cidr_block():
|
| 42 |
+
"""Imported VPCs must pass vpc_cidr_block or endpoint/SG helpers fail at synth."""
|
| 43 |
+
from aws_cdk import App, Stack
|
| 44 |
+
from aws_cdk import aws_ec2 as ec2
|
| 45 |
+
|
| 46 |
+
app = App()
|
| 47 |
+
stack = Stack(app, "ImportedVpcTest")
|
| 48 |
+
vpc = ec2.Vpc.from_vpc_attributes(
|
| 49 |
+
stack,
|
| 50 |
+
"ImportedVpc",
|
| 51 |
+
vpc_id="vpc-12345678",
|
| 52 |
+
availability_zones=["eu-west-2a", "eu-west-2b"],
|
| 53 |
+
vpc_cidr_block="10.0.0.0/16",
|
| 54 |
+
)
|
| 55 |
+
assert vpc.vpc_cidr_block == "10.0.0.0/16"
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def test_create_ecs_vpc_endpoints_skips_existing_service_names():
|
| 59 |
+
from aws_cdk import App, Stack, assertions
|
| 60 |
+
from aws_cdk import aws_ec2 as ec2
|
| 61 |
+
from cdk_functions import create_ecs_vpc_endpoints_for_private_subnets
|
| 62 |
+
|
| 63 |
+
app = App()
|
| 64 |
+
stack = Stack(app, "SkipEndpointTest")
|
| 65 |
+
vpc = ec2.Vpc(stack, "Vpc", max_azs=2)
|
| 66 |
+
private = ec2.SubnetSelection(
|
| 67 |
+
subnet_type=ec2.SubnetType.PRIVATE_WITH_EGRESS,
|
| 68 |
+
)
|
| 69 |
+
skip = frozenset(
|
| 70 |
+
{
|
| 71 |
+
"com.amazonaws.eu-west-2.kms",
|
| 72 |
+
"com.amazonaws.eu-west-2.secretsmanager",
|
| 73 |
+
}
|
| 74 |
+
)
|
| 75 |
+
create_ecs_vpc_endpoints_for_private_subnets(
|
| 76 |
+
stack,
|
| 77 |
+
vpc=vpc,
|
| 78 |
+
subnets=private,
|
| 79 |
+
skip_service_names=skip,
|
| 80 |
+
include_secrets_and_kms=True,
|
| 81 |
+
aws_region="eu-west-2",
|
| 82 |
+
)
|
| 83 |
+
template = assertions.Template.from_stack(stack)
|
| 84 |
+
template.resource_count_is("AWS::EC2::VPCEndpoint", 4)
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def test_create_ecs_vpc_endpoints_skips_precheck_shared_vpc_endpoints():
|
| 88 |
+
"""Regression: skip list must use AWS ServiceName strings, not CDK service.name tokens."""
|
| 89 |
+
from aws_cdk import App, Stack, assertions
|
| 90 |
+
from aws_cdk import aws_ec2 as ec2
|
| 91 |
+
from cdk_functions import create_ecs_vpc_endpoints_for_private_subnets
|
| 92 |
+
|
| 93 |
+
app = App()
|
| 94 |
+
stack = Stack(app, "SharedVpcSkipTest")
|
| 95 |
+
vpc = ec2.Vpc(stack, "Vpc", max_azs=2)
|
| 96 |
+
private = ec2.SubnetSelection(
|
| 97 |
+
subnet_type=ec2.SubnetType.PRIVATE_WITH_EGRESS,
|
| 98 |
+
)
|
| 99 |
+
precheck_skip = frozenset(
|
| 100 |
+
{
|
| 101 |
+
"com.amazonaws.eu-west-2.kms",
|
| 102 |
+
"com.amazonaws.eu-west-2.s3",
|
| 103 |
+
"com.amazonaws.eu-west-2.secretsmanager",
|
| 104 |
+
}
|
| 105 |
+
)
|
| 106 |
+
create_ecs_vpc_endpoints_for_private_subnets(
|
| 107 |
+
stack,
|
| 108 |
+
vpc=vpc,
|
| 109 |
+
subnets=private,
|
| 110 |
+
skip_service_names=precheck_skip,
|
| 111 |
+
include_secrets_and_kms=True,
|
| 112 |
+
aws_region="eu-west-2",
|
| 113 |
+
)
|
| 114 |
+
template = assertions.Template.from_stack(stack)
|
| 115 |
+
# ecr.api, ecr.dkr, logs only (kms, secretsmanager, s3 skipped)
|
| 116 |
+
template.resource_count_is("AWS::EC2::VPCEndpoint", 3)
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def test_list_existing_vpc_endpoint_service_names(monkeypatch):
|
| 120 |
+
from cdk_functions import list_existing_vpc_endpoint_service_names
|
| 121 |
+
|
| 122 |
+
class FakePaginator:
|
| 123 |
+
def paginate(self, **kwargs):
|
| 124 |
+
return [
|
| 125 |
+
{
|
| 126 |
+
"VpcEndpoints": [
|
| 127 |
+
{
|
| 128 |
+
"ServiceName": "com.amazonaws.eu-west-2.kms",
|
| 129 |
+
"State": "available",
|
| 130 |
+
},
|
| 131 |
+
{
|
| 132 |
+
"ServiceName": "com.amazonaws.eu-west-2.s3",
|
| 133 |
+
"State": "available",
|
| 134 |
+
},
|
| 135 |
+
{
|
| 136 |
+
"ServiceName": "com.amazonaws.eu-west-2.ecr.api",
|
| 137 |
+
"State": "deleted",
|
| 138 |
+
},
|
| 139 |
+
]
|
| 140 |
+
}
|
| 141 |
+
]
|
| 142 |
+
|
| 143 |
+
class FakeEc2:
|
| 144 |
+
def get_paginator(self, name):
|
| 145 |
+
assert name == "describe_vpc_endpoints"
|
| 146 |
+
return FakePaginator()
|
| 147 |
+
|
| 148 |
+
monkeypatch.setattr(
|
| 149 |
+
"cdk_functions.boto3.client",
|
| 150 |
+
lambda service, region_name=None: FakeEc2(),
|
| 151 |
+
)
|
| 152 |
+
names = list_existing_vpc_endpoint_service_names("vpc-123", region_name="eu-west-2")
|
| 153 |
+
assert names == frozenset(
|
| 154 |
+
{
|
| 155 |
+
"com.amazonaws.eu-west-2.kms",
|
| 156 |
+
"com.amazonaws.eu-west-2.s3",
|
| 157 |
+
}
|
| 158 |
+
)
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def test_resolve_ecs_vpc_endpoint_subnet_selection_express_public():
|
| 162 |
+
from aws_cdk import App, Stack
|
| 163 |
+
from aws_cdk import aws_ec2 as ec2
|
| 164 |
+
from cdk_functions import resolve_ecs_vpc_endpoint_subnet_selection
|
| 165 |
+
|
| 166 |
+
app = App()
|
| 167 |
+
stack = Stack(app, "SubnetSelectTest")
|
| 168 |
+
vpc = ec2.Vpc(stack, "Vpc", max_azs=2)
|
| 169 |
+
public_sel = resolve_ecs_vpc_endpoint_subnet_selection(
|
| 170 |
+
use_express_ingress=True,
|
| 171 |
+
express_use_public_subnets=True,
|
| 172 |
+
public_subnets=vpc.public_subnets,
|
| 173 |
+
private_subnets=vpc.private_subnets,
|
| 174 |
+
)
|
| 175 |
+
assert public_sel is not None
|
| 176 |
+
assert {s.subnet_id for s in public_sel.subnets} == {
|
| 177 |
+
s.subnet_id for s in vpc.public_subnets
|
| 178 |
+
}
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
def test_resolve_ecs_vpc_endpoint_subnet_selection_express_private():
|
| 182 |
+
from aws_cdk import App, Stack
|
| 183 |
+
from aws_cdk import aws_ec2 as ec2
|
| 184 |
+
from cdk_functions import resolve_ecs_vpc_endpoint_subnet_selection
|
| 185 |
+
|
| 186 |
+
app = App()
|
| 187 |
+
stack = Stack(app, "SubnetSelectPrivateTest")
|
| 188 |
+
vpc = ec2.Vpc(stack, "Vpc", max_azs=2)
|
| 189 |
+
private_sel = resolve_ecs_vpc_endpoint_subnet_selection(
|
| 190 |
+
use_express_ingress=True,
|
| 191 |
+
express_use_public_subnets=False,
|
| 192 |
+
public_subnets=vpc.public_subnets,
|
| 193 |
+
private_subnets=vpc.private_subnets,
|
| 194 |
+
)
|
| 195 |
+
assert private_sel is not None
|
| 196 |
+
assert {s.subnet_id for s in private_sel.subnets} == {
|
| 197 |
+
s.subnet_id for s in vpc.private_subnets
|
| 198 |
+
}
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
def test_resolve_ecs_vpc_endpoint_subnet_selection_legacy_fargate():
|
| 202 |
+
from aws_cdk import App, Stack
|
| 203 |
+
from aws_cdk import aws_ec2 as ec2
|
| 204 |
+
from cdk_functions import resolve_ecs_vpc_endpoint_subnet_selection
|
| 205 |
+
|
| 206 |
+
app = App()
|
| 207 |
+
stack = Stack(app, "SubnetSelectLegacyTest")
|
| 208 |
+
vpc = ec2.Vpc(stack, "Vpc", max_azs=2)
|
| 209 |
+
private_sel = resolve_ecs_vpc_endpoint_subnet_selection(
|
| 210 |
+
use_express_ingress=False,
|
| 211 |
+
express_use_public_subnets=True,
|
| 212 |
+
public_subnets=vpc.public_subnets,
|
| 213 |
+
private_subnets=vpc.private_subnets,
|
| 214 |
+
)
|
| 215 |
+
assert private_sel is not None
|
| 216 |
+
assert {s.subnet_id for s in private_sel.subnets} == {
|
| 217 |
+
s.subnet_id for s in vpc.private_subnets
|
| 218 |
+
}
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
def test_resolve_ecs_vpc_endpoint_subnet_selection_public_only_legacy():
|
| 222 |
+
from aws_cdk import App, Stack
|
| 223 |
+
from aws_cdk import aws_ec2 as ec2
|
| 224 |
+
from cdk_functions import resolve_ecs_vpc_endpoint_subnet_selection
|
| 225 |
+
|
| 226 |
+
app = App()
|
| 227 |
+
stack = Stack(app, "SubnetSelectPublicOnlyTest")
|
| 228 |
+
vpc = ec2.Vpc(stack, "Vpc", max_azs=2)
|
| 229 |
+
public_sel = resolve_ecs_vpc_endpoint_subnet_selection(
|
| 230 |
+
use_express_ingress=False,
|
| 231 |
+
express_use_public_subnets=True,
|
| 232 |
+
public_subnets=vpc.public_subnets,
|
| 233 |
+
private_subnets=[],
|
| 234 |
+
)
|
| 235 |
+
assert public_sel is not None
|
| 236 |
+
assert {s.subnet_id for s in public_sel.subnets} == {
|
| 237 |
+
s.subnet_id for s in vpc.public_subnets
|
| 238 |
+
}
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
def test_create_ecs_vpc_endpoints_on_public_subnets():
|
| 242 |
+
from aws_cdk import App, Stack, assertions
|
| 243 |
+
from aws_cdk import aws_ec2 as ec2
|
| 244 |
+
from cdk_functions import create_ecs_vpc_endpoints_for_private_subnets
|
| 245 |
+
|
| 246 |
+
app = App()
|
| 247 |
+
stack = Stack(app, "PublicEndpointTest")
|
| 248 |
+
vpc = ec2.Vpc(stack, "Vpc", max_azs=2)
|
| 249 |
+
public = ec2.SubnetSelection(subnet_type=ec2.SubnetType.PUBLIC)
|
| 250 |
+
create_ecs_vpc_endpoints_for_private_subnets(
|
| 251 |
+
stack,
|
| 252 |
+
vpc=vpc,
|
| 253 |
+
subnets=public,
|
| 254 |
+
include_secrets_and_kms=True,
|
| 255 |
+
aws_region="eu-west-2",
|
| 256 |
+
)
|
| 257 |
+
template = assertions.Template.from_stack(stack)
|
| 258 |
+
template.resource_count_is("AWS::EC2::VPCEndpoint", 6)
|
| 259 |
+
public_logical_ids = {
|
| 260 |
+
stack.get_logical_id(s.node.default_child) for s in vpc.public_subnets
|
| 261 |
+
}
|
| 262 |
+
interface_endpoints = [
|
| 263 |
+
r
|
| 264 |
+
for r in template.find_resources("AWS::EC2::VPCEndpoint").values()
|
| 265 |
+
if r.get("Properties", {}).get("VpcEndpointType") == "Interface"
|
| 266 |
+
]
|
| 267 |
+
assert len(interface_endpoints) == 5
|
| 268 |
+
for resource in interface_endpoints:
|
| 269 |
+
subnet_ids = resource["Properties"]["SubnetIds"]
|
| 270 |
+
assert len(subnet_ids) == len(vpc.public_subnets)
|
| 271 |
+
for ref in subnet_ids:
|
| 272 |
+
assert ref.get("Ref") in public_logical_ids
|
| 273 |
+
|
| 274 |
+
|
| 275 |
+
def test_resolve_ecs_s3_gateway_subnet_selection_all_stack_subnets():
|
| 276 |
+
from aws_cdk import App, Stack
|
| 277 |
+
from aws_cdk import aws_ec2 as ec2
|
| 278 |
+
from cdk_functions import resolve_ecs_s3_gateway_subnet_selection
|
| 279 |
+
|
| 280 |
+
app = App()
|
| 281 |
+
stack = Stack(app, "S3SubnetSelectTest")
|
| 282 |
+
vpc = ec2.Vpc(stack, "Vpc", max_azs=2)
|
| 283 |
+
s3_sel = resolve_ecs_s3_gateway_subnet_selection(
|
| 284 |
+
public_subnets=vpc.public_subnets,
|
| 285 |
+
private_subnets=vpc.private_subnets,
|
| 286 |
+
)
|
| 287 |
+
assert s3_sel is not None
|
| 288 |
+
expected_ids = {s.subnet_id for s in vpc.public_subnets + vpc.private_subnets}
|
| 289 |
+
assert {s.subnet_id for s in s3_sel.subnets} == expected_ids
|
| 290 |
+
|
| 291 |
+
|
| 292 |
+
def test_s3_gateway_endpoint_uses_all_stack_subnets_not_only_task_tier():
|
| 293 |
+
from aws_cdk import App, Stack, assertions
|
| 294 |
+
from aws_cdk import aws_ec2 as ec2
|
| 295 |
+
from cdk_functions import (
|
| 296 |
+
create_ecs_vpc_endpoints_for_private_subnets,
|
| 297 |
+
resolve_ecs_s3_gateway_subnet_selection,
|
| 298 |
+
)
|
| 299 |
+
|
| 300 |
+
app = App()
|
| 301 |
+
stack = Stack(app, "MixedS3GatewayTest")
|
| 302 |
+
vpc = ec2.Vpc(stack, "Vpc", max_azs=2)
|
| 303 |
+
public = ec2.SubnetSelection(subnets=vpc.public_subnets)
|
| 304 |
+
all_stack_subnets = resolve_ecs_s3_gateway_subnet_selection(
|
| 305 |
+
public_subnets=vpc.public_subnets,
|
| 306 |
+
private_subnets=vpc.private_subnets,
|
| 307 |
+
)
|
| 308 |
+
create_ecs_vpc_endpoints_for_private_subnets(
|
| 309 |
+
stack,
|
| 310 |
+
vpc=vpc,
|
| 311 |
+
subnets=public,
|
| 312 |
+
s3_gateway_subnets=all_stack_subnets,
|
| 313 |
+
include_secrets_and_kms=True,
|
| 314 |
+
aws_region="eu-west-2",
|
| 315 |
+
)
|
| 316 |
+
template = assertions.Template.from_stack(stack)
|
| 317 |
+
gateway_endpoints = [
|
| 318 |
+
r
|
| 319 |
+
for r in template.find_resources("AWS::EC2::VPCEndpoint").values()
|
| 320 |
+
if r.get("Properties", {}).get("VpcEndpointType") == "Gateway"
|
| 321 |
+
]
|
| 322 |
+
assert len(gateway_endpoints) == 1
|
| 323 |
+
route_table_ids = gateway_endpoints[0]["Properties"]["RouteTableIds"]
|
| 324 |
+
assert len(route_table_ids) == len(vpc.public_subnets) + len(vpc.private_subnets)
|
| 325 |
+
interface_endpoints = [
|
| 326 |
+
r
|
| 327 |
+
for r in template.find_resources("AWS::EC2::VPCEndpoint").values()
|
| 328 |
+
if r.get("Properties", {}).get("VpcEndpointType") == "Interface"
|
| 329 |
+
]
|
| 330 |
+
public_logical_ids = {
|
| 331 |
+
stack.get_logical_id(s.node.default_child) for s in vpc.public_subnets
|
| 332 |
+
}
|
| 333 |
+
for resource in interface_endpoints:
|
| 334 |
+
for ref in resource["Properties"]["SubnetIds"]:
|
| 335 |
+
assert ref.get("Ref") in public_logical_ids
|
| 336 |
+
|
| 337 |
+
|
| 338 |
+
def test_list_vpc_associated_cidr_blocks_primary_and_secondary():
|
| 339 |
+
from cdk_functions import list_vpc_associated_cidr_blocks
|
| 340 |
+
|
| 341 |
+
vpc = {
|
| 342 |
+
"CidrBlock": "10.0.0.0/16",
|
| 343 |
+
"CidrBlockAssociationSet": [
|
| 344 |
+
{
|
| 345 |
+
"CidrBlock": "10.0.0.0/16",
|
| 346 |
+
"CidrBlockState": {"State": "associated"},
|
| 347 |
+
},
|
| 348 |
+
{
|
| 349 |
+
"CidrBlock": "10.1.0.0/16",
|
| 350 |
+
"CidrBlockState": {"State": "associated"},
|
| 351 |
+
},
|
| 352 |
+
],
|
| 353 |
+
}
|
| 354 |
+
assert list_vpc_associated_cidr_blocks(vpc) == [
|
| 355 |
+
"10.0.0.0/16",
|
| 356 |
+
"10.1.0.0/16",
|
| 357 |
+
]
|
| 358 |
+
|
| 359 |
+
|
| 360 |
+
def test_vpc_endpoint_security_group_ingress_covers_all_vpc_cidrs():
|
| 361 |
+
from aws_cdk import App, Stack, assertions
|
| 362 |
+
from aws_cdk import aws_ec2 as ec2
|
| 363 |
+
from cdk_functions import add_vpc_endpoint_https_ingress_from_vpc_cidrs
|
| 364 |
+
|
| 365 |
+
app = App()
|
| 366 |
+
stack = Stack(app, "DualCidrEndpointSgTest")
|
| 367 |
+
vpc = ec2.Vpc.from_vpc_attributes(
|
| 368 |
+
stack,
|
| 369 |
+
"ImportedVpc",
|
| 370 |
+
vpc_id="vpc-dual-cidr",
|
| 371 |
+
availability_zones=["eu-west-2a"],
|
| 372 |
+
vpc_cidr_block="10.0.0.0/16",
|
| 373 |
+
)
|
| 374 |
+
endpoint_sg = ec2.SecurityGroup(
|
| 375 |
+
stack,
|
| 376 |
+
"EndpointSg",
|
| 377 |
+
vpc=vpc,
|
| 378 |
+
description="test",
|
| 379 |
+
)
|
| 380 |
+
add_vpc_endpoint_https_ingress_from_vpc_cidrs(
|
| 381 |
+
endpoint_sg,
|
| 382 |
+
vpc_cidr_block="10.0.0.0/16",
|
| 383 |
+
vpc_cidr_blocks=["10.0.0.0/16", "10.1.0.0/16"],
|
| 384 |
+
)
|
| 385 |
+
template = assertions.Template.from_stack(stack)
|
| 386 |
+
template.has_resource_properties(
|
| 387 |
+
"AWS::EC2::SecurityGroup",
|
| 388 |
+
{
|
| 389 |
+
"SecurityGroupIngress": assertions.Match.array_with(
|
| 390 |
+
[
|
| 391 |
+
assertions.Match.object_like(
|
| 392 |
+
{"CidrIp": "10.0.0.0/16", "FromPort": 443, "ToPort": 443}
|
| 393 |
+
),
|
| 394 |
+
assertions.Match.object_like(
|
| 395 |
+
{"CidrIp": "10.1.0.0/16", "FromPort": 443, "ToPort": 443}
|
| 396 |
+
),
|
| 397 |
+
]
|
| 398 |
+
)
|
| 399 |
+
},
|
| 400 |
+
)
|
cdk/test/test_elbv2_listener_rule_upsert.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Unit tests for ALB listener rule upsert Lambda helpers."""
|
| 2 |
+
|
| 3 |
+
import importlib.util
|
| 4 |
+
import sys
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
|
| 7 |
+
_LAMBDA_PATH = (
|
| 8 |
+
Path(__file__).resolve().parents[1]
|
| 9 |
+
/ "lambda_elbv2_listener_rule_upsert"
|
| 10 |
+
/ "lambda_function.py"
|
| 11 |
+
)
|
| 12 |
+
_spec = importlib.util.spec_from_file_location(
|
| 13 |
+
"elbv2_listener_rule_upsert", _LAMBDA_PATH
|
| 14 |
+
)
|
| 15 |
+
_mod = importlib.util.module_from_spec(_spec)
|
| 16 |
+
assert _spec and _spec.loader
|
| 17 |
+
sys.modules[_spec.name] = _mod
|
| 18 |
+
_spec.loader.exec_module(_mod)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def test_conditions_match_path_pattern():
|
| 22 |
+
expected = [
|
| 23 |
+
{
|
| 24 |
+
"Field": "path-pattern",
|
| 25 |
+
"PathPatternConfig": {"Values": ["/agent", "/agent/*"]},
|
| 26 |
+
}
|
| 27 |
+
]
|
| 28 |
+
from_api = [
|
| 29 |
+
{
|
| 30 |
+
"Field": "path-pattern",
|
| 31 |
+
"PathPatternConfig": {"Values": ["/agent", "/agent/*"]},
|
| 32 |
+
"Values": ["/agent", "/agent/*"],
|
| 33 |
+
}
|
| 34 |
+
]
|
| 35 |
+
assert _mod._conditions_match(from_api, expected)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def test_conditions_do_not_match_different_path():
|
| 39 |
+
expected = [
|
| 40 |
+
{
|
| 41 |
+
"Field": "path-pattern",
|
| 42 |
+
"PathPatternConfig": {"Values": ["/agent", "/agent/*"]},
|
| 43 |
+
}
|
| 44 |
+
]
|
| 45 |
+
other = [
|
| 46 |
+
{
|
| 47 |
+
"Field": "path-pattern",
|
| 48 |
+
"PathPatternConfig": {"Values": ["/other", "/other/*"]},
|
| 49 |
+
}
|
| 50 |
+
]
|
| 51 |
+
assert not _mod._conditions_match(other, expected)
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def test_normalize_listener_rule_payload_coerces_cfn_string_types():
|
| 55 |
+
raw_actions = [
|
| 56 |
+
{
|
| 57 |
+
"Type": "authenticate-cognito",
|
| 58 |
+
"Order": "1",
|
| 59 |
+
"AuthenticateCognitoConfig": {
|
| 60 |
+
"UserPoolArn": "arn:aws:cognito-idp:eu-west-2:1:userpool/pool",
|
| 61 |
+
"UserPoolClientId": "client",
|
| 62 |
+
"UserPoolDomain": "demo",
|
| 63 |
+
"SessionTimeout": "28800",
|
| 64 |
+
},
|
| 65 |
+
},
|
| 66 |
+
{
|
| 67 |
+
"Type": "forward",
|
| 68 |
+
"Order": "2",
|
| 69 |
+
"ForwardConfig": {
|
| 70 |
+
"TargetGroups": [
|
| 71 |
+
{"TargetGroupArn": "arn:aws:elasticloadbalancing:1:tg"}
|
| 72 |
+
],
|
| 73 |
+
"TargetGroupStickinessConfig": {
|
| 74 |
+
"Enabled": "true",
|
| 75 |
+
"DurationSeconds": "28800",
|
| 76 |
+
},
|
| 77 |
+
},
|
| 78 |
+
},
|
| 79 |
+
]
|
| 80 |
+
_, actions = _mod._normalize_listener_rule_payload([], raw_actions)
|
| 81 |
+
assert actions[0]["Order"] == 1
|
| 82 |
+
assert actions[0]["AuthenticateCognitoConfig"]["SessionTimeout"] == 28800
|
| 83 |
+
assert actions[1]["Order"] == 2
|
| 84 |
+
stickiness = actions[1]["ForwardConfig"]["TargetGroupStickinessConfig"]
|
| 85 |
+
assert stickiness["Enabled"] is True
|
| 86 |
+
assert stickiness["DurationSeconds"] == 28800
|
cdk/test/test_ensure_codebuild_public_github.py
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Tests for runtime CodeBuild public GitHub source fixup."""
|
| 2 |
+
|
| 3 |
+
import sys
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
from unittest.mock import MagicMock
|
| 6 |
+
|
| 7 |
+
CDK_DIR = Path(__file__).resolve().parents[1]
|
| 8 |
+
sys.path.insert(0, str(CDK_DIR))
|
| 9 |
+
|
| 10 |
+
from cdk_functions import ensure_codebuild_public_github_source
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def test_ensure_codebuild_updates_oauth_project(monkeypatch):
|
| 14 |
+
client = MagicMock()
|
| 15 |
+
client.batch_get_projects.return_value = {
|
| 16 |
+
"projects": [
|
| 17 |
+
{
|
| 18 |
+
"name": "MyProject",
|
| 19 |
+
"source": {
|
| 20 |
+
"type": "GITHUB",
|
| 21 |
+
"location": "https://github.com/old/repo.git",
|
| 22 |
+
"auth": {"type": "CODECONNECTIONS", "resource": "arn:connection"},
|
| 23 |
+
"reportBuildStatus": True,
|
| 24 |
+
"buildspec": "version: 0.2\nphases: {}\n",
|
| 25 |
+
},
|
| 26 |
+
"sourceVersion": "main",
|
| 27 |
+
"triggers": {"webhook": True},
|
| 28 |
+
}
|
| 29 |
+
]
|
| 30 |
+
}
|
| 31 |
+
monkeypatch.setattr("cdk_functions.boto3.client", lambda *args, **kwargs: client)
|
| 32 |
+
|
| 33 |
+
updated = ensure_codebuild_public_github_source(
|
| 34 |
+
"MyProject",
|
| 35 |
+
"seanpedrick-case",
|
| 36 |
+
"llm_topic_modeller",
|
| 37 |
+
"main",
|
| 38 |
+
aws_region="eu-west-2",
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
assert updated is True
|
| 42 |
+
client.update_project.assert_called_once()
|
| 43 |
+
kwargs = client.update_project.call_args.kwargs
|
| 44 |
+
assert kwargs["name"] == "MyProject"
|
| 45 |
+
assert kwargs["source"]["type"] == "GITHUB"
|
| 46 |
+
assert (
|
| 47 |
+
kwargs["source"]["location"]
|
| 48 |
+
== "https://github.com/seanpedrick-case/llm_topic_modeller.git"
|
| 49 |
+
)
|
| 50 |
+
assert "auth" not in kwargs["source"]
|
| 51 |
+
assert kwargs["sourceVersion"] == "main"
|
| 52 |
+
assert kwargs["triggers"] == {"webhook": False}
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def test_ensure_codebuild_skips_when_already_public(monkeypatch):
|
| 56 |
+
client = MagicMock()
|
| 57 |
+
client.batch_get_projects.return_value = {
|
| 58 |
+
"projects": [
|
| 59 |
+
{
|
| 60 |
+
"name": "MyProject",
|
| 61 |
+
"source": {
|
| 62 |
+
"type": "GITHUB",
|
| 63 |
+
"location": "https://github.com/seanpedrick-case/llm_topic_modeller.git",
|
| 64 |
+
"reportBuildStatus": False,
|
| 65 |
+
},
|
| 66 |
+
"sourceVersion": "main",
|
| 67 |
+
}
|
| 68 |
+
]
|
| 69 |
+
}
|
| 70 |
+
monkeypatch.setattr("cdk_functions.boto3.client", lambda *args, **kwargs: client)
|
| 71 |
+
|
| 72 |
+
updated = ensure_codebuild_public_github_source(
|
| 73 |
+
"MyProject",
|
| 74 |
+
"seanpedrick-case",
|
| 75 |
+
"llm_topic_modeller",
|
| 76 |
+
"main",
|
| 77 |
+
aws_region="eu-west-2",
|
| 78 |
+
)
|
| 79 |
+
|
| 80 |
+
assert updated is False
|
| 81 |
+
client.update_project.assert_not_called()
|
cdk/test/test_execution_role_kms_policy.py
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""ECS task vs execution role KMS inline policy helpers."""
|
| 2 |
+
|
| 3 |
+
import sys
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
|
| 6 |
+
CDK_DIR = Path(__file__).resolve().parents[1]
|
| 7 |
+
sys.path.insert(0, str(CDK_DIR))
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def test_task_and_execution_role_kms_policies_use_different_key_arns():
|
| 11 |
+
from cdk_functions import (
|
| 12 |
+
build_ecs_execution_role_kms_policy,
|
| 13 |
+
build_ecs_task_role_kms_policy,
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
s3_key = "arn:aws:kms:eu-west-2:123456789012:key/s3-shared-key"
|
| 17 |
+
secret_key = "arn:aws:kms:eu-west-2:123456789012:key/secret-key"
|
| 18 |
+
|
| 19 |
+
task_policy = build_ecs_task_role_kms_policy(shared_kms_key_arn=s3_key)
|
| 20 |
+
exec_policy = build_ecs_execution_role_kms_policy(secret_kms_key_arn=secret_key)
|
| 21 |
+
|
| 22 |
+
task_kms = next(
|
| 23 |
+
s for s in task_policy["Statement"] if s.get("Sid") == "KMSS3Access"
|
| 24 |
+
)
|
| 25 |
+
secret_kms = next(
|
| 26 |
+
s for s in exec_policy["Statement"] if s.get("Sid") == "KMSSecretDecrypt"
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
assert task_kms["Resource"] == s3_key
|
| 30 |
+
assert secret_kms["Resource"] == secret_key
|
| 31 |
+
assert "kms:GenerateDataKey" in task_kms["Action"]
|
| 32 |
+
assert "kms:DescribeKey" in task_kms["Action"]
|
| 33 |
+
assert secret_kms["Action"] == ["kms:Decrypt"]
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def test_task_role_inline_policy_scopes_s3_to_output_and_log_buckets():
|
| 37 |
+
from cdk_functions import build_ecs_task_role_inline_policy
|
| 38 |
+
|
| 39 |
+
policy = build_ecs_task_role_inline_policy(
|
| 40 |
+
output_bucket_name="lambeth-aws-sharedservices-prod-summarisation-s3-output",
|
| 41 |
+
log_config_bucket_name="lambeth-aws-sharedservices-prod-summarisation-s3-logs",
|
| 42 |
+
shared_kms_key_arn="arn:aws:kms:eu-west-2:123456789012:key/s3-shared-key",
|
| 43 |
+
)
|
| 44 |
+
s3_statements = [
|
| 45 |
+
s for s in policy["Statement"] if s.get("Sid", "").startswith("S3")
|
| 46 |
+
]
|
| 47 |
+
assert len(s3_statements) == 2
|
| 48 |
+
output_stmt = next(s for s in s3_statements if s["Sid"] == "S3Output")
|
| 49 |
+
log_stmt = next(s for s in s3_statements if s["Sid"] == "S3LogConfig")
|
| 50 |
+
assert output_stmt["Action"] == [
|
| 51 |
+
"s3:GetObject*",
|
| 52 |
+
"s3:GetBucket*",
|
| 53 |
+
"s3:PutObject",
|
| 54 |
+
"s3:DeleteObject",
|
| 55 |
+
"s3:List*",
|
| 56 |
+
]
|
| 57 |
+
assert output_stmt["Resource"] == [
|
| 58 |
+
"arn:aws:s3:::lambeth-aws-sharedservices-prod-summarisation-s3-output",
|
| 59 |
+
"arn:aws:s3:::lambeth-aws-sharedservices-prod-summarisation-s3-output/*",
|
| 60 |
+
]
|
| 61 |
+
assert log_stmt["Resource"] == [
|
| 62 |
+
"arn:aws:s3:::lambeth-aws-sharedservices-prod-summarisation-s3-logs",
|
| 63 |
+
"arn:aws:s3:::lambeth-aws-sharedservices-prod-summarisation-s3-logs/*",
|
| 64 |
+
]
|
| 65 |
+
kms_stmt = next(s for s in policy["Statement"] if s.get("Sid") == "KMSS3Access")
|
| 66 |
+
assert (
|
| 67 |
+
kms_stmt["Resource"] == "arn:aws:kms:eu-west-2:123456789012:key/s3-shared-key"
|
| 68 |
+
)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def test_execution_role_policy_without_custom_s3_key_uses_secret_kms_only():
|
| 72 |
+
from cdk_functions import build_ecs_execution_role_kms_policy
|
| 73 |
+
|
| 74 |
+
secret_key = "arn:aws:kms:eu-west-2:123456789012:key/aws/secretsmanager"
|
| 75 |
+
policy = build_ecs_execution_role_kms_policy(secret_kms_key_arn=secret_key)
|
| 76 |
+
kms_statements = [
|
| 77 |
+
s for s in policy["Statement"] if s.get("Action") == ["kms:Decrypt"]
|
| 78 |
+
]
|
| 79 |
+
assert len(kms_statements) == 1
|
| 80 |
+
assert kms_statements[0]["Resource"] == secret_key
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def test_get_secret_kms_key_arn_from_describe_secret(monkeypatch):
|
| 84 |
+
from cdk_functions import get_secret_kms_key_arn
|
| 85 |
+
|
| 86 |
+
class FakeSecretsManager:
|
| 87 |
+
def describe_secret(self, SecretId):
|
| 88 |
+
assert SecretId == "my-secret"
|
| 89 |
+
return {
|
| 90 |
+
"KmsKeyId": "arn:aws:kms:eu-west-2:123456789012:key/abc-123",
|
| 91 |
+
}
|
| 92 |
+
|
| 93 |
+
monkeypatch.setattr(
|
| 94 |
+
"cdk_functions.boto3.client",
|
| 95 |
+
lambda service, region_name=None: FakeSecretsManager(),
|
| 96 |
+
)
|
| 97 |
+
assert (
|
| 98 |
+
get_secret_kms_key_arn("my-secret", region_name="eu-west-2")
|
| 99 |
+
== "arn:aws:kms:eu-west-2:123456789012:key/abc-123"
|
| 100 |
+
)
|
cdk/test/test_express_app_config_env.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Tests for loading config/app_config.env into Express container environment."""
|
| 2 |
+
|
| 3 |
+
import sys
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
|
| 6 |
+
CDK_DIR = Path(__file__).resolve().parents[1]
|
| 7 |
+
sys.path.insert(0, str(CDK_DIR))
|
| 8 |
+
|
| 9 |
+
from cdk_functions import load_app_config_env_for_express
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def test_load_app_config_env_for_express_reads_config_env():
|
| 13 |
+
config_path = CDK_DIR / "config" / "app_config.env"
|
| 14 |
+
env_vars = load_app_config_env_for_express(str(config_path))
|
| 15 |
+
names = {p.name for p in env_vars}
|
| 16 |
+
assert "RUN_AWS_FUNCTIONS" in names
|
| 17 |
+
assert "S3_LOG_BUCKET" in names
|
| 18 |
+
assert "AWS_CLIENT_ID" not in names
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def test_load_app_config_env_missing_file_returns_empty():
|
| 22 |
+
assert (
|
| 23 |
+
load_app_config_env_for_express(str(CDK_DIR / "config" / "nonexistent.env"))
|
| 24 |
+
== []
|
| 25 |
+
)
|
cdk/test/test_express_pi.py
ADDED
|
@@ -0,0 +1,566 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
| 8 |
+
CDK_DIR = Path(__file__).resolve().parents[1]
|
| 9 |
+
sys.path.insert(0, str(CDK_DIR))
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def test_pi_express_mutual_exclusion_with_legacy_pi():
|
| 13 |
+
legacy = "True"
|
| 14 |
+
express = "True"
|
| 15 |
+
with pytest.raises(ValueError, match="at most one Pi deployment"):
|
| 16 |
+
if legacy == "True" and express == "True":
|
| 17 |
+
raise ValueError(
|
| 18 |
+
"Enable at most one Pi deployment mode: ENABLE_PI_AGENT_ECS_SERVICE (legacy Fargate) "
|
| 19 |
+
"or ENABLE_PI_AGENT_EXPRESS_SERVICE (Express), not both."
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def test_pi_express_requires_express_mode():
|
| 24 |
+
express_pi = "True"
|
| 25 |
+
use_express = "False"
|
| 26 |
+
with pytest.raises(ValueError, match="ENABLE_PI_AGENT_EXPRESS_SERVICE"):
|
| 27 |
+
if express_pi == "True" and use_express != "True":
|
| 28 |
+
raise ValueError(
|
| 29 |
+
"ENABLE_PI_AGENT_EXPRESS_SERVICE=True requires USE_ECS_EXPRESS_MODE=True "
|
| 30 |
+
"(no ACM_SSL_CERTIFICATE_ARN)."
|
| 31 |
+
)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def test_build_pi_express_container_environment():
|
| 35 |
+
from cdk_functions import build_pi_express_container_environment
|
| 36 |
+
|
| 37 |
+
env = build_pi_express_container_environment(
|
| 38 |
+
service_connect_discovery_name="summarisation",
|
| 39 |
+
main_app_port=7860,
|
| 40 |
+
pi_gradio_port=7862,
|
| 41 |
+
)
|
| 42 |
+
assert env["DOC_SUMMARISATION_GRADIO_URL"] == "http://summarisation:7860"
|
| 43 |
+
assert env["PI_WORKSPACE_DIR"] == "/tmp/pi-workspace"
|
| 44 |
+
assert env["PI_UPLOAD_ROOT"] == "/tmp/gradio"
|
| 45 |
+
assert env["PI_DEPLOYMENT_PROFILE"] == "aws-ecs"
|
| 46 |
+
assert env["COGNITO_AUTH"] == "True"
|
| 47 |
+
assert env["RUN_FASTAPI"] == "True"
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def test_build_express_pi_primary_container_includes_cognito_secrets():
|
| 51 |
+
from aws_cdk import App, Stack
|
| 52 |
+
from aws_cdk import aws_secretsmanager as sm
|
| 53 |
+
from cdk_functions import build_express_pi_primary_container
|
| 54 |
+
|
| 55 |
+
app = App()
|
| 56 |
+
stack = Stack(app, "PiSecretTest")
|
| 57 |
+
secret = sm.Secret(stack, "CognitoSecret", secret_name="demo-cognito-secret")
|
| 58 |
+
|
| 59 |
+
container = build_express_pi_primary_container(
|
| 60 |
+
image_uri="123456789012.dkr.ecr.eu-west-2.amazonaws.com/pi:latest",
|
| 61 |
+
container_port=7862,
|
| 62 |
+
log_group_name="/ecs/pi-logs",
|
| 63 |
+
aws_region="eu-west-2",
|
| 64 |
+
secret=secret,
|
| 65 |
+
cognito_auth=True,
|
| 66 |
+
)
|
| 67 |
+
assert container.secrets is not None
|
| 68 |
+
secret_names = {item.name for item in container.secrets}
|
| 69 |
+
assert secret_names == {"AWS_USER_POOL_ID", "AWS_CLIENT_ID", "AWS_CLIENT_SECRET"}
|
| 70 |
+
|
| 71 |
+
no_auth = build_express_pi_primary_container(
|
| 72 |
+
image_uri="123456789012.dkr.ecr.eu-west-2.amazonaws.com/pi:latest",
|
| 73 |
+
container_port=7862,
|
| 74 |
+
log_group_name="/ecs/pi-logs",
|
| 75 |
+
aws_region="eu-west-2",
|
| 76 |
+
secret=secret,
|
| 77 |
+
cognito_auth=False,
|
| 78 |
+
)
|
| 79 |
+
assert no_auth.secrets is None
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def test_format_express_pi_public_url():
|
| 83 |
+
from cdk_functions import format_express_pi_public_url
|
| 84 |
+
|
| 85 |
+
assert (
|
| 86 |
+
format_express_pi_public_url("https://pi.example.ecs.eu-west-2.on.aws")
|
| 87 |
+
== "https://pi.example.ecs.eu-west-2.on.aws/"
|
| 88 |
+
)
|
| 89 |
+
assert format_express_pi_public_url("") == ""
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def test_express_service_connect_configuration_server_and_client():
|
| 93 |
+
from cdk_functions import _express_service_connect_configuration
|
| 94 |
+
|
| 95 |
+
server = _express_service_connect_configuration(
|
| 96 |
+
namespace="demo-ns",
|
| 97 |
+
port_name="port-7860",
|
| 98 |
+
discovery_name="summarisation",
|
| 99 |
+
port=7860,
|
| 100 |
+
)
|
| 101 |
+
assert server["enabled"] is True
|
| 102 |
+
assert server["namespace"] == "demo-ns"
|
| 103 |
+
assert server["services"][0]["portName"] == "port-7860"
|
| 104 |
+
assert server["services"][0]["discoveryName"] == "summarisation"
|
| 105 |
+
|
| 106 |
+
client = _express_service_connect_configuration(namespace="demo-ns")
|
| 107 |
+
assert "services" not in client
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def test_apply_service_connect_custom_resource_synth():
|
| 111 |
+
from aws_cdk import App, Environment, Stack, assertions
|
| 112 |
+
from aws_cdk import aws_ecs as ecs
|
| 113 |
+
from cdk_functions import apply_service_connect_to_express_service
|
| 114 |
+
|
| 115 |
+
app = App()
|
| 116 |
+
stack = Stack(
|
| 117 |
+
app,
|
| 118 |
+
"ScExpressTest",
|
| 119 |
+
env=Environment(account="123456789012", region="eu-west-2"),
|
| 120 |
+
)
|
| 121 |
+
express = ecs.CfnExpressGatewayService(
|
| 122 |
+
stack,
|
| 123 |
+
"MainExpress",
|
| 124 |
+
service_name="main-express",
|
| 125 |
+
cluster="test-cluster",
|
| 126 |
+
execution_role_arn="arn:aws:iam::123456789012:role/exec",
|
| 127 |
+
infrastructure_role_arn="arn:aws:iam::123456789012:role/infra",
|
| 128 |
+
primary_container=ecs.CfnExpressGatewayService.ExpressGatewayContainerProperty(
|
| 129 |
+
image="123456789012.dkr.ecr.eu-west-2.amazonaws.com/app:latest",
|
| 130 |
+
container_port=7860,
|
| 131 |
+
),
|
| 132 |
+
)
|
| 133 |
+
apply_service_connect_to_express_service(
|
| 134 |
+
stack,
|
| 135 |
+
"MainSc",
|
| 136 |
+
cluster_name="test-cluster",
|
| 137 |
+
service_name="main-express",
|
| 138 |
+
namespace="test-ns",
|
| 139 |
+
express_service=express,
|
| 140 |
+
port_name="port-7860",
|
| 141 |
+
discovery_name="summarisation",
|
| 142 |
+
port=7860,
|
| 143 |
+
)
|
| 144 |
+
template = assertions.Template.from_stack(stack)
|
| 145 |
+
template.resource_count_is("Custom::AWS", 1)
|
| 146 |
+
template.has_resource_properties(
|
| 147 |
+
"Custom::AWS",
|
| 148 |
+
{
|
| 149 |
+
"Create": assertions.Match.string_like_regexp(
|
| 150 |
+
r'"portName":"port-7860".*"discoveryName":"summarisation"'
|
| 151 |
+
),
|
| 152 |
+
},
|
| 153 |
+
)
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
def test_express_alb_ingress_uses_security_group_id_not_arn():
|
| 157 |
+
from aws_cdk import App, Stack, assertions
|
| 158 |
+
from aws_cdk import aws_ec2 as ec2
|
| 159 |
+
from aws_cdk import aws_ecs as ecs
|
| 160 |
+
from cdk_functions import allow_express_load_balancer_to_ecs_security_group
|
| 161 |
+
|
| 162 |
+
app = App()
|
| 163 |
+
stack = Stack(app, "ExpressAlbIngressTest")
|
| 164 |
+
vpc = ec2.Vpc(stack, "Vpc", max_azs=2)
|
| 165 |
+
task_sg = ec2.SecurityGroup(stack, "TaskSg", vpc=vpc)
|
| 166 |
+
express = ecs.CfnExpressGatewayService(
|
| 167 |
+
stack,
|
| 168 |
+
"Express",
|
| 169 |
+
service_name="main-express",
|
| 170 |
+
cluster="test-cluster",
|
| 171 |
+
execution_role_arn="arn:aws:iam::123456789012:role/exec",
|
| 172 |
+
infrastructure_role_arn="arn:aws:iam::123456789012:role/infra",
|
| 173 |
+
primary_container=ecs.CfnExpressGatewayService.ExpressGatewayContainerProperty(
|
| 174 |
+
image="123456789012.dkr.ecr.eu-west-2.amazonaws.com/app:latest",
|
| 175 |
+
container_port=7860,
|
| 176 |
+
),
|
| 177 |
+
)
|
| 178 |
+
allow_express_load_balancer_to_ecs_security_group(
|
| 179 |
+
stack,
|
| 180 |
+
"ExpressAlbToTask",
|
| 181 |
+
express_service=express,
|
| 182 |
+
ecs_security_group=task_sg,
|
| 183 |
+
container_port=7860,
|
| 184 |
+
)
|
| 185 |
+
template = assertions.Template.from_stack(stack)
|
| 186 |
+
template.has_resource_properties(
|
| 187 |
+
"AWS::EC2::SecurityGroupIngress",
|
| 188 |
+
{
|
| 189 |
+
"SourceSecurityGroupId": {
|
| 190 |
+
"Fn::Select": [
|
| 191 |
+
1,
|
| 192 |
+
{
|
| 193 |
+
"Fn::Split": [
|
| 194 |
+
"security-group/",
|
| 195 |
+
{
|
| 196 |
+
"Fn::Select": [
|
| 197 |
+
0,
|
| 198 |
+
{
|
| 199 |
+
"Fn::GetAtt": [
|
| 200 |
+
"Express",
|
| 201 |
+
"ECSManagedResourceArns.IngressPath.LoadBalancerSecurityGroups",
|
| 202 |
+
]
|
| 203 |
+
},
|
| 204 |
+
]
|
| 205 |
+
},
|
| 206 |
+
]
|
| 207 |
+
},
|
| 208 |
+
]
|
| 209 |
+
}
|
| 210 |
+
},
|
| 211 |
+
)
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
def test_express_gateway_service_defaults_to_idle_scaling_target():
|
| 215 |
+
from aws_cdk import App, Stack, assertions
|
| 216 |
+
from aws_cdk import aws_ecs as ecs
|
| 217 |
+
from cdk_functions import create_express_gateway_service
|
| 218 |
+
|
| 219 |
+
app = App()
|
| 220 |
+
stack = Stack(app, "ExpressIdleScalingTest")
|
| 221 |
+
create_express_gateway_service(
|
| 222 |
+
stack,
|
| 223 |
+
"Express",
|
| 224 |
+
service_name="main-express",
|
| 225 |
+
cluster_name="test-cluster",
|
| 226 |
+
execution_role_arn="arn:aws:iam::123456789012:role/exec",
|
| 227 |
+
infrastructure_role_arn="arn:aws:iam::123456789012:role/infra",
|
| 228 |
+
task_role_arn="arn:aws:iam::123456789012:role/task",
|
| 229 |
+
cpu="1024",
|
| 230 |
+
memory="4096",
|
| 231 |
+
health_check_path="/",
|
| 232 |
+
primary_container=ecs.CfnExpressGatewayService.ExpressGatewayContainerProperty(
|
| 233 |
+
image="123456789012.dkr.ecr.eu-west-2.amazonaws.com/app:latest",
|
| 234 |
+
container_port=7860,
|
| 235 |
+
),
|
| 236 |
+
subnet_ids=["subnet-abc"],
|
| 237 |
+
security_group_ids=["sg-main"],
|
| 238 |
+
)
|
| 239 |
+
template = assertions.Template.from_stack(stack)
|
| 240 |
+
template.has_resource_properties(
|
| 241 |
+
"AWS::ECS::ExpressGatewayService",
|
| 242 |
+
{
|
| 243 |
+
"ScalingTarget": {
|
| 244 |
+
"MinTaskCount": 0,
|
| 245 |
+
"MaxTaskCount": 1,
|
| 246 |
+
"AutoScalingMetric": "AVERAGE_CPU",
|
| 247 |
+
"AutoScalingTargetValue": 60,
|
| 248 |
+
}
|
| 249 |
+
},
|
| 250 |
+
)
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
def test_express_infrastructure_role_uses_service_role_managed_policy():
|
| 254 |
+
from aws_cdk import App, Stack, assertions
|
| 255 |
+
from cdk_functions import create_ecs_express_infrastructure_role
|
| 256 |
+
|
| 257 |
+
app = App()
|
| 258 |
+
stack = Stack(app, "ExpressInfraRoleTest")
|
| 259 |
+
create_ecs_express_infrastructure_role(
|
| 260 |
+
stack, "ExpressInfrastructureRole", "test-express-infra"
|
| 261 |
+
)
|
| 262 |
+
template = assertions.Template.from_stack(stack)
|
| 263 |
+
template.has_resource_properties(
|
| 264 |
+
"AWS::IAM::Role",
|
| 265 |
+
{
|
| 266 |
+
"ManagedPolicyArns": assertions.Match.array_with(
|
| 267 |
+
[
|
| 268 |
+
{
|
| 269 |
+
"Fn::Join": [
|
| 270 |
+
"",
|
| 271 |
+
[
|
| 272 |
+
"arn:",
|
| 273 |
+
{"Ref": "AWS::Partition"},
|
| 274 |
+
":iam::aws:policy/service-role/AmazonECSInfrastructureRoleforExpressGatewayServices",
|
| 275 |
+
],
|
| 276 |
+
]
|
| 277 |
+
}
|
| 278 |
+
]
|
| 279 |
+
)
|
| 280 |
+
},
|
| 281 |
+
)
|
| 282 |
+
|
| 283 |
+
|
| 284 |
+
def test_express_listener_helpers_synth_without_reference_error():
|
| 285 |
+
"""Fn.select on Express list attrs must use typed attr_* list properties."""
|
| 286 |
+
from aws_cdk import App, Environment, Stack, assertions
|
| 287 |
+
from aws_cdk import aws_ec2 as ec2
|
| 288 |
+
from aws_cdk import aws_ecs as ecs
|
| 289 |
+
from cdk_functions import (
|
| 290 |
+
allow_express_load_balancer_to_ecs_security_group,
|
| 291 |
+
configure_express_listener_cognito_and_cloudfront,
|
| 292 |
+
configure_express_pi_listener_rules,
|
| 293 |
+
create_express_gateway_service,
|
| 294 |
+
)
|
| 295 |
+
|
| 296 |
+
app = App()
|
| 297 |
+
stack = Stack(
|
| 298 |
+
app,
|
| 299 |
+
"ExpressListenerHelpers",
|
| 300 |
+
env=Environment(account="123456789012", region="eu-west-2"),
|
| 301 |
+
)
|
| 302 |
+
vpc = ec2.Vpc(stack, "Vpc", max_azs=2)
|
| 303 |
+
sg = ec2.SecurityGroup(stack, "TaskSg", vpc=vpc)
|
| 304 |
+
main = create_express_gateway_service(
|
| 305 |
+
stack,
|
| 306 |
+
"Main",
|
| 307 |
+
service_name="main-svc",
|
| 308 |
+
cluster_name="cl",
|
| 309 |
+
execution_role_arn="arn:aws:iam::123456789012:role/exec",
|
| 310 |
+
infrastructure_role_arn="arn:aws:iam::123456789012:role/infra",
|
| 311 |
+
task_role_arn="arn:aws:iam::123456789012:role/task",
|
| 312 |
+
cpu="1024",
|
| 313 |
+
memory="2048",
|
| 314 |
+
health_check_path="/",
|
| 315 |
+
primary_container=ecs.CfnExpressGatewayService.ExpressGatewayContainerProperty(
|
| 316 |
+
image="123456789012.dkr.ecr.eu-west-2.amazonaws.com/app:latest",
|
| 317 |
+
container_port=7860,
|
| 318 |
+
),
|
| 319 |
+
subnet_ids=["subnet-abc"],
|
| 320 |
+
security_group_ids=["sg-main"],
|
| 321 |
+
)
|
| 322 |
+
pi = create_express_gateway_service(
|
| 323 |
+
stack,
|
| 324 |
+
"Pi",
|
| 325 |
+
service_name="pi-svc",
|
| 326 |
+
cluster_name="cl",
|
| 327 |
+
execution_role_arn="arn:aws:iam::123456789012:role/exec",
|
| 328 |
+
infrastructure_role_arn="arn:aws:iam::123456789012:role/infra",
|
| 329 |
+
task_role_arn="arn:aws:iam::123456789012:role/task",
|
| 330 |
+
cpu="1024",
|
| 331 |
+
memory="2048",
|
| 332 |
+
health_check_path="/pi/",
|
| 333 |
+
primary_container=ecs.CfnExpressGatewayService.ExpressGatewayContainerProperty(
|
| 334 |
+
image="123456789012.dkr.ecr.eu-west-2.amazonaws.com/pi:latest",
|
| 335 |
+
container_port=7862,
|
| 336 |
+
),
|
| 337 |
+
subnet_ids=["subnet-abc"],
|
| 338 |
+
security_group_ids=["sg-pi"],
|
| 339 |
+
)
|
| 340 |
+
allow_express_load_balancer_to_ecs_security_group(
|
| 341 |
+
stack,
|
| 342 |
+
"MainLbToTask",
|
| 343 |
+
express_service=main,
|
| 344 |
+
ecs_security_group=sg,
|
| 345 |
+
container_port=7860,
|
| 346 |
+
)
|
| 347 |
+
configure_express_listener_cognito_and_cloudfront(
|
| 348 |
+
stack,
|
| 349 |
+
"MainListener",
|
| 350 |
+
express_service=main,
|
| 351 |
+
user_pool_arn="arn:aws:cognito-idp:eu-west-2:123456789012:userpool/pool",
|
| 352 |
+
user_pool_client_id="client",
|
| 353 |
+
user_pool_domain_prefix="demo-auth",
|
| 354 |
+
use_cloudfront=False,
|
| 355 |
+
cloudfront_host_header="",
|
| 356 |
+
)
|
| 357 |
+
configure_express_pi_listener_rules(
|
| 358 |
+
stack,
|
| 359 |
+
"PiRules",
|
| 360 |
+
express_main_service=main,
|
| 361 |
+
express_pi_service=pi,
|
| 362 |
+
routing_mode="path",
|
| 363 |
+
path_prefix="/pi",
|
| 364 |
+
pi_host_header="",
|
| 365 |
+
rule_priority=3,
|
| 366 |
+
user_pool_arn="arn:aws:cognito-idp:eu-west-2:123456789012:userpool/pool",
|
| 367 |
+
user_pool_client_id="client",
|
| 368 |
+
user_pool_domain_prefix="demo-auth",
|
| 369 |
+
)
|
| 370 |
+
app.synth()
|
| 371 |
+
template = assertions.Template.from_stack(stack)
|
| 372 |
+
template.resource_count_is("AWS::ECS::ExpressGatewayService", 2)
|
| 373 |
+
# modifyListener (Custom::AWS) + Pi path rule (Custom::Elbv2ListenerRuleUpsert)
|
| 374 |
+
template.resource_count_is("Custom::AWS", 1)
|
| 375 |
+
template.resource_count_is("Custom::Elbv2ListenerRuleUpsert", 1)
|
| 376 |
+
# authenticate-cognito on ALB requires DescribeUserPoolClient on the CR Lambda role
|
| 377 |
+
cr_policy_actions: list[str] = []
|
| 378 |
+
for props in template.find_resources("AWS::IAM::Policy").values():
|
| 379 |
+
for stmt in (
|
| 380 |
+
props.get("Properties", {}).get("PolicyDocument", {}).get("Statement", [])
|
| 381 |
+
):
|
| 382 |
+
action = stmt.get("Action", [])
|
| 383 |
+
if isinstance(action, str):
|
| 384 |
+
cr_policy_actions.append(action)
|
| 385 |
+
else:
|
| 386 |
+
cr_policy_actions.extend(action)
|
| 387 |
+
assert "cognito-idp:DescribeUserPoolClient" in cr_policy_actions
|
| 388 |
+
assert "elasticloadbalancing:ModifyListener" in cr_policy_actions
|
| 389 |
+
|
| 390 |
+
|
| 391 |
+
def test_express_cloudfront_does_not_add_cognito_bypass_host_rule_by_default():
|
| 392 |
+
"""With ALB Cognito, CloudFront must not add a forward-only host-header rule."""
|
| 393 |
+
from aws_cdk import App, Environment, Stack, assertions
|
| 394 |
+
from aws_cdk import aws_ec2 as ec2
|
| 395 |
+
from aws_cdk import aws_ecs as ecs
|
| 396 |
+
from cdk_functions import (
|
| 397 |
+
configure_express_listener_cognito_and_cloudfront,
|
| 398 |
+
create_express_gateway_service,
|
| 399 |
+
)
|
| 400 |
+
|
| 401 |
+
app = App()
|
| 402 |
+
stack = Stack(
|
| 403 |
+
app,
|
| 404 |
+
"ExpressCloudFrontCognitoTest",
|
| 405 |
+
env=Environment(account="123456789012", region="eu-west-2"),
|
| 406 |
+
)
|
| 407 |
+
vpc = ec2.Vpc(stack, "Vpc", max_azs=2)
|
| 408 |
+
main = create_express_gateway_service(
|
| 409 |
+
stack,
|
| 410 |
+
"Main",
|
| 411 |
+
service_name="main-svc",
|
| 412 |
+
cluster_name="cl",
|
| 413 |
+
execution_role_arn="arn:aws:iam::123456789012:role/exec",
|
| 414 |
+
infrastructure_role_arn="arn:aws:iam::123456789012:role/infra",
|
| 415 |
+
task_role_arn="arn:aws:iam::123456789012:role/task",
|
| 416 |
+
cpu="1024",
|
| 417 |
+
memory="2048",
|
| 418 |
+
health_check_path="/",
|
| 419 |
+
primary_container=ecs.CfnExpressGatewayService.ExpressGatewayContainerProperty(
|
| 420 |
+
image="123456789012.dkr.ecr.eu-west-2.amazonaws.com/app:latest",
|
| 421 |
+
container_port=7860,
|
| 422 |
+
),
|
| 423 |
+
subnet_ids=[vpc.public_subnets[0].subnet_id],
|
| 424 |
+
security_group_ids=["sg-main"],
|
| 425 |
+
)
|
| 426 |
+
configure_express_listener_cognito_and_cloudfront(
|
| 427 |
+
stack,
|
| 428 |
+
"MainListener",
|
| 429 |
+
express_service=main,
|
| 430 |
+
user_pool_arn="arn:aws:cognito-idp:eu-west-2:123456789012:userpool/pool",
|
| 431 |
+
user_pool_client_id="client",
|
| 432 |
+
user_pool_domain_prefix="demo-auth",
|
| 433 |
+
use_cloudfront=True,
|
| 434 |
+
cloudfront_host_header="app.example.com",
|
| 435 |
+
)
|
| 436 |
+
template = assertions.Template.from_stack(stack)
|
| 437 |
+
template.resource_count_is("Custom::Elbv2ListenerRuleUpsert", 0)
|
| 438 |
+
|
| 439 |
+
|
| 440 |
+
def test_express_cloudfront_can_opt_in_to_origin_bypass_without_cognito():
|
| 441 |
+
from aws_cdk import App, Environment, Stack, assertions
|
| 442 |
+
from aws_cdk import aws_ec2 as ec2
|
| 443 |
+
from aws_cdk import aws_ecs as ecs
|
| 444 |
+
from cdk_functions import (
|
| 445 |
+
configure_express_listener_cognito_and_cloudfront,
|
| 446 |
+
create_express_gateway_service,
|
| 447 |
+
)
|
| 448 |
+
|
| 449 |
+
app = App()
|
| 450 |
+
stack = Stack(
|
| 451 |
+
app,
|
| 452 |
+
"ExpressCloudFrontBypassTest",
|
| 453 |
+
env=Environment(account="123456789012", region="eu-west-2"),
|
| 454 |
+
)
|
| 455 |
+
vpc = ec2.Vpc(stack, "Vpc", max_azs=2)
|
| 456 |
+
main = create_express_gateway_service(
|
| 457 |
+
stack,
|
| 458 |
+
"Main",
|
| 459 |
+
service_name="main-svc",
|
| 460 |
+
cluster_name="cl",
|
| 461 |
+
execution_role_arn="arn:aws:iam::123456789012:role/exec",
|
| 462 |
+
infrastructure_role_arn="arn:aws:iam::123456789012:role/infra",
|
| 463 |
+
task_role_arn="arn:aws:iam::123456789012:role/task",
|
| 464 |
+
cpu="1024",
|
| 465 |
+
memory="2048",
|
| 466 |
+
health_check_path="/",
|
| 467 |
+
primary_container=ecs.CfnExpressGatewayService.ExpressGatewayContainerProperty(
|
| 468 |
+
image="123456789012.dkr.ecr.eu-west-2.amazonaws.com/app:latest",
|
| 469 |
+
container_port=7860,
|
| 470 |
+
),
|
| 471 |
+
subnet_ids=[vpc.public_subnets[0].subnet_id],
|
| 472 |
+
security_group_ids=["sg-main"],
|
| 473 |
+
)
|
| 474 |
+
configure_express_listener_cognito_and_cloudfront(
|
| 475 |
+
stack,
|
| 476 |
+
"MainListener",
|
| 477 |
+
express_service=main,
|
| 478 |
+
user_pool_arn="arn:aws:cognito-idp:eu-west-2:123456789012:userpool/pool",
|
| 479 |
+
user_pool_client_id="client",
|
| 480 |
+
user_pool_domain_prefix="demo-auth",
|
| 481 |
+
use_cloudfront=True,
|
| 482 |
+
cloudfront_host_header="app.example.com",
|
| 483 |
+
allow_cloudfront_origin_without_cognito=True,
|
| 484 |
+
)
|
| 485 |
+
template = assertions.Template.from_stack(stack)
|
| 486 |
+
template.resource_count_is("Custom::Elbv2ListenerRuleUpsert", 1)
|
| 487 |
+
|
| 488 |
+
|
| 489 |
+
def test_dual_express_gateway_services_synth():
|
| 490 |
+
"""Two ExpressGatewayService resources when wiring main + Pi helpers."""
|
| 491 |
+
from aws_cdk import App, Environment, Stack, assertions
|
| 492 |
+
from aws_cdk import aws_ecs as ecs
|
| 493 |
+
from cdk_functions import (
|
| 494 |
+
apply_service_connect_to_express_service,
|
| 495 |
+
build_express_pi_primary_container,
|
| 496 |
+
create_express_gateway_service,
|
| 497 |
+
)
|
| 498 |
+
|
| 499 |
+
app = App()
|
| 500 |
+
stack = Stack(
|
| 501 |
+
app,
|
| 502 |
+
"DualExpressTest",
|
| 503 |
+
env=Environment(account="123456789012", region="eu-west-2"),
|
| 504 |
+
)
|
| 505 |
+
main = create_express_gateway_service(
|
| 506 |
+
stack,
|
| 507 |
+
"Main",
|
| 508 |
+
service_name="main-svc",
|
| 509 |
+
cluster_name="cl",
|
| 510 |
+
execution_role_arn="arn:aws:iam::123456789012:role/exec",
|
| 511 |
+
infrastructure_role_arn="arn:aws:iam::123456789012:role/infra",
|
| 512 |
+
task_role_arn="arn:aws:iam::123456789012:role/task",
|
| 513 |
+
cpu="1024",
|
| 514 |
+
memory="2048",
|
| 515 |
+
health_check_path="/",
|
| 516 |
+
primary_container=ecs.CfnExpressGatewayService.ExpressGatewayContainerProperty(
|
| 517 |
+
image="123456789012.dkr.ecr.eu-west-2.amazonaws.com/app:latest",
|
| 518 |
+
container_port=7860,
|
| 519 |
+
),
|
| 520 |
+
subnet_ids=["subnet-abc"],
|
| 521 |
+
security_group_ids=["sg-main"],
|
| 522 |
+
)
|
| 523 |
+
pi_container = build_express_pi_primary_container(
|
| 524 |
+
image_uri="123456789012.dkr.ecr.eu-west-2.amazonaws.com/pi:latest",
|
| 525 |
+
container_port=7862,
|
| 526 |
+
log_group_name="/ecs/pi-logs",
|
| 527 |
+
aws_region="eu-west-2",
|
| 528 |
+
environment={"PI_WORKSPACE_DIR": "/tmp/pi-workspace"},
|
| 529 |
+
)
|
| 530 |
+
pi = create_express_gateway_service(
|
| 531 |
+
stack,
|
| 532 |
+
"Pi",
|
| 533 |
+
service_name="pi-svc",
|
| 534 |
+
cluster_name="cl",
|
| 535 |
+
execution_role_arn="arn:aws:iam::123456789012:role/exec",
|
| 536 |
+
infrastructure_role_arn="arn:aws:iam::123456789012:role/infra",
|
| 537 |
+
task_role_arn="arn:aws:iam::123456789012:role/task",
|
| 538 |
+
cpu="1024",
|
| 539 |
+
memory="2048",
|
| 540 |
+
health_check_path="/",
|
| 541 |
+
primary_container=pi_container,
|
| 542 |
+
subnet_ids=["subnet-abc"],
|
| 543 |
+
security_group_ids=["sg-pi"],
|
| 544 |
+
)
|
| 545 |
+
apply_service_connect_to_express_service(
|
| 546 |
+
stack,
|
| 547 |
+
"MainSc",
|
| 548 |
+
cluster_name="cl",
|
| 549 |
+
service_name="main-svc",
|
| 550 |
+
namespace="ns",
|
| 551 |
+
express_service=main,
|
| 552 |
+
port_name="port-7860",
|
| 553 |
+
discovery_name="summarisation",
|
| 554 |
+
port=7860,
|
| 555 |
+
)
|
| 556 |
+
apply_service_connect_to_express_service(
|
| 557 |
+
stack,
|
| 558 |
+
"PiSc",
|
| 559 |
+
cluster_name="cl",
|
| 560 |
+
service_name="pi-svc",
|
| 561 |
+
namespace="ns",
|
| 562 |
+
express_service=pi,
|
| 563 |
+
)
|
| 564 |
+
template = assertions.Template.from_stack(stack)
|
| 565 |
+
template.resource_count_is("AWS::ECS::ExpressGatewayService", 2)
|
| 566 |
+
template.resource_count_is("Custom::AWS", 2)
|
cdk/test/test_globally_unique_names.py
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Tests for globally unique AWS name checks (S3, Cognito)."""
|
| 2 |
+
|
| 3 |
+
import sys
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
from unittest.mock import MagicMock
|
| 6 |
+
|
| 7 |
+
from botocore.exceptions import ClientError
|
| 8 |
+
|
| 9 |
+
CDK_DIR = Path(__file__).resolve().parents[1]
|
| 10 |
+
sys.path.insert(0, str(CDK_DIR))
|
| 11 |
+
|
| 12 |
+
from cdk_functions import ( # noqa: E402
|
| 13 |
+
resolve_cognito_domain_prefix_availability,
|
| 14 |
+
resolve_s3_bucket_availability,
|
| 15 |
+
)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def _client_error(code: str) -> ClientError:
|
| 19 |
+
return ClientError({"Error": {"Code": code, "Message": code}}, "HeadBucket")
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def test_resolve_s3_bucket_available_on_404():
|
| 23 |
+
s3 = MagicMock()
|
| 24 |
+
s3.head_bucket.side_effect = _client_error("404")
|
| 25 |
+
status, name = resolve_s3_bucket_availability("free-bucket", s3_client=s3)
|
| 26 |
+
assert status == "available"
|
| 27 |
+
assert name == "free-bucket"
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def test_resolve_s3_bucket_owned_on_success():
|
| 31 |
+
s3 = MagicMock()
|
| 32 |
+
s3.head_bucket.return_value = {}
|
| 33 |
+
status, name = resolve_s3_bucket_availability("my-bucket", s3_client=s3)
|
| 34 |
+
assert status == "owned"
|
| 35 |
+
assert name == "my-bucket"
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def test_resolve_s3_bucket_globally_taken_on_403_not_listed():
|
| 39 |
+
s3 = MagicMock()
|
| 40 |
+
s3.head_bucket.side_effect = _client_error("403")
|
| 41 |
+
s3.list_buckets.return_value = {"Buckets": [{"Name": "other-bucket"}]}
|
| 42 |
+
status, name = resolve_s3_bucket_availability(
|
| 43 |
+
"demo-summarisation-s3-logs", s3_client=s3
|
| 44 |
+
)
|
| 45 |
+
assert status == "globally_taken"
|
| 46 |
+
assert name == "demo-summarisation-s3-logs"
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def test_resolve_s3_bucket_owned_on_403_listed_in_account():
|
| 50 |
+
s3 = MagicMock()
|
| 51 |
+
s3.head_bucket.side_effect = _client_error("403")
|
| 52 |
+
s3.list_buckets.return_value = {"Buckets": [{"Name": "my-bucket"}]}
|
| 53 |
+
status, _ = resolve_s3_bucket_availability("my-bucket", s3_client=s3)
|
| 54 |
+
assert status == "owned"
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def test_resolve_cognito_domain_taken_when_owned_elsewhere():
|
| 58 |
+
cognito = MagicMock()
|
| 59 |
+
cognito.describe_user_pool_domain.side_effect = _client_error(
|
| 60 |
+
"ResourceNotFoundException"
|
| 61 |
+
)
|
| 62 |
+
assert (
|
| 63 |
+
resolve_cognito_domain_prefix_availability(
|
| 64 |
+
"demo-summarisation", region_name="eu-west-2", cognito_client=cognito
|
| 65 |
+
)
|
| 66 |
+
== "taken"
|
| 67 |
+
)
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def test_resolve_cognito_domain_available_when_empty_description():
|
| 71 |
+
cognito = MagicMock()
|
| 72 |
+
cognito.describe_user_pool_domain.return_value = {"DomainDescription": {}}
|
| 73 |
+
assert (
|
| 74 |
+
resolve_cognito_domain_prefix_availability(
|
| 75 |
+
"my-prefix", region_name="eu-west-2", cognito_client=cognito
|
| 76 |
+
)
|
| 77 |
+
== "available"
|
| 78 |
+
)
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def test_resolve_cognito_domain_taken_when_user_pool_present():
|
| 82 |
+
cognito = MagicMock()
|
| 83 |
+
cognito.describe_user_pool_domain.return_value = {
|
| 84 |
+
"DomainDescription": {"UserPoolId": "eu-west-2_abc"}
|
| 85 |
+
}
|
| 86 |
+
assert (
|
| 87 |
+
resolve_cognito_domain_prefix_availability(
|
| 88 |
+
"taken-prefix", region_name="eu-west-2", cognito_client=cognito
|
| 89 |
+
)
|
| 90 |
+
== "taken"
|
| 91 |
+
)
|
cdk/test/test_headless_app_defaults_env.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Headless batch app_defaults.env rendering."""
|
| 2 |
+
|
| 3 |
+
import sys
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
|
| 6 |
+
CDK_DIR = Path(__file__).resolve().parents[1]
|
| 7 |
+
sys.path.insert(0, str(CDK_DIR))
|
| 8 |
+
|
| 9 |
+
from cdk_functions import build_headless_app_defaults_env_content
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def test_build_headless_app_defaults_env_sets_outputs_bucket():
|
| 13 |
+
seed_dir = str(CDK_DIR / "config" / "headless_s3_seed")
|
| 14 |
+
content = build_headless_app_defaults_env_content(
|
| 15 |
+
seed_dir,
|
| 16 |
+
s3_outputs_bucket_name="lambeth-prod-summarisation-s3-output",
|
| 17 |
+
)
|
| 18 |
+
|
| 19 |
+
assert "S3_OUTPUTS_BUCKET=lambeth-prod-summarisation-s3-output" in content
|
| 20 |
+
assert "RUN_DIRECT_MODE=1" in content
|
| 21 |
+
assert "SAVE_OUTPUTS_TO_S3=True" in content
|
| 22 |
+
assert content.count("S3_OUTPUTS_BUCKET=") == 1
|
cdk/test/test_headless_output_notifications.py
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Headless S3 output notification resources and installer validation."""
|
| 2 |
+
|
| 3 |
+
import sys
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
|
| 6 |
+
CDK_DIR = Path(__file__).resolve().parents[1]
|
| 7 |
+
sys.path.insert(0, str(CDK_DIR))
|
| 8 |
+
|
| 9 |
+
from cdk_functions import sanitize_headless_metric_filter_id
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def test_sanitize_headless_metric_filter_id():
|
| 13 |
+
assert sanitize_headless_metric_filter_id("Prod-Summarisation-s3-output-put") == (
|
| 14 |
+
"Prod-Summarisation-s3-output-put"
|
| 15 |
+
)
|
| 16 |
+
assert sanitize_headless_metric_filter_id("bad id!!") == "bad-id"
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def test_validate_notify_email():
|
| 20 |
+
from cdk_install import validate_notify_email
|
| 21 |
+
|
| 22 |
+
assert validate_notify_email("user@example.com") is None
|
| 23 |
+
assert validate_notify_email("") is not None
|
| 24 |
+
assert validate_notify_email("not-an-email") is not None
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def test_headless_output_notifications_synth():
|
| 28 |
+
from aws_cdk import App, Environment, Stack
|
| 29 |
+
from aws_cdk import aws_s3 as s3
|
| 30 |
+
from aws_cdk.assertions import Match, Template
|
| 31 |
+
from cdk_functions import create_headless_output_notifications
|
| 32 |
+
|
| 33 |
+
app = App()
|
| 34 |
+
stack = Stack(
|
| 35 |
+
app,
|
| 36 |
+
"HeadlessNotifyTest",
|
| 37 |
+
env=Environment(account="123456789012", region="eu-west-2"),
|
| 38 |
+
)
|
| 39 |
+
bucket = s3.Bucket(stack, "OutputBucket", bucket_name="test-output-bucket")
|
| 40 |
+
|
| 41 |
+
create_headless_output_notifications(
|
| 42 |
+
stack,
|
| 43 |
+
"Notify",
|
| 44 |
+
output_bucket=bucket,
|
| 45 |
+
output_prefix="output/",
|
| 46 |
+
notify_email="analyst@example.com",
|
| 47 |
+
iam_user_name="test-s3-output-reader",
|
| 48 |
+
metric_filter_id="test-s3-output-put",
|
| 49 |
+
sns_topic_name="test-llm-topic-s3-save-sns",
|
| 50 |
+
alarm_name="test-cloudwatch-alarm-new-output-s3",
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
template = Template.from_stack(stack)
|
| 54 |
+
template.resource_count_is("AWS::SNS::Topic", 1)
|
| 55 |
+
template.resource_count_is("AWS::CloudWatch::Alarm", 1)
|
| 56 |
+
template.resource_count_is("AWS::IAM::User", 1)
|
| 57 |
+
template.has_resource_properties(
|
| 58 |
+
"AWS::S3::BucketPolicy",
|
| 59 |
+
{
|
| 60 |
+
"PolicyDocument": {
|
| 61 |
+
"Statement": Match.array_with(
|
| 62 |
+
[
|
| 63 |
+
Match.object_like(
|
| 64 |
+
{
|
| 65 |
+
"Effect": "Allow",
|
| 66 |
+
"Action": Match.array_with(["s3:GetObject"]),
|
| 67 |
+
}
|
| 68 |
+
)
|
| 69 |
+
]
|
| 70 |
+
)
|
| 71 |
+
}
|
| 72 |
+
},
|
| 73 |
+
)
|
| 74 |
+
template.has_resource_properties(
|
| 75 |
+
"AWS::CloudWatch::Alarm",
|
| 76 |
+
{
|
| 77 |
+
"MetricName": "PutRequests",
|
| 78 |
+
"Namespace": "AWS/S3",
|
| 79 |
+
"ComparisonOperator": "GreaterThanThreshold",
|
| 80 |
+
},
|
| 81 |
+
)
|
cdk/test/test_iam_policy_files.py
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Tests for custom IAM policy file lists on ECS task / execution roles."""
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
import sys
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
|
| 7 |
+
from aws_cdk import App, Stack
|
| 8 |
+
from aws_cdk import aws_iam as iam
|
| 9 |
+
|
| 10 |
+
CDK_DIR = Path(__file__).resolve().parents[1]
|
| 11 |
+
sys.path.insert(0, str(CDK_DIR))
|
| 12 |
+
|
| 13 |
+
from cdk_config import ( # noqa: E402
|
| 14 |
+
AWS_MANAGED_TASK_ROLES_LIST,
|
| 15 |
+
ECS_EXECUTION_ROLE_MANAGED_POLICIES,
|
| 16 |
+
POLICY_FILE_LOCATIONS,
|
| 17 |
+
parse_comma_separated_list,
|
| 18 |
+
)
|
| 19 |
+
from cdk_functions import ( # noqa: E402
|
| 20 |
+
add_custom_policies,
|
| 21 |
+
resolve_policy_file_paths,
|
| 22 |
+
)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def test_parse_comma_separated_list_json_and_plain():
|
| 26 |
+
assert parse_comma_separated_list('["a.json", "b.json"]') == ["a.json", "b.json"]
|
| 27 |
+
assert parse_comma_separated_list("textract_policy.json") == [
|
| 28 |
+
"textract_policy.json"
|
| 29 |
+
]
|
| 30 |
+
assert parse_comma_separated_list("a.json, b.json") == ["a.json", "b.json"]
|
| 31 |
+
assert parse_comma_separated_list("") == []
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def test_policy_file_locations_default_is_empty_list():
|
| 35 |
+
assert isinstance(POLICY_FILE_LOCATIONS, list)
|
| 36 |
+
assert POLICY_FILE_LOCATIONS == []
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def test_task_role_managed_policies_exclude_s3_full_access():
|
| 40 |
+
assert "AmazonS3FullAccess" not in AWS_MANAGED_TASK_ROLES_LIST
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def test_execution_role_managed_policies_default_minimal():
|
| 44 |
+
assert "service-role/AmazonECSTaskExecutionRolePolicy" in (
|
| 45 |
+
ECS_EXECUTION_ROLE_MANAGED_POLICIES
|
| 46 |
+
)
|
| 47 |
+
assert "AmazonS3FullAccess" not in ECS_EXECUTION_ROLE_MANAGED_POLICIES
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def test_resolve_policy_file_paths_relative_to_cdk_folder(tmp_path):
|
| 51 |
+
policy = tmp_path / "custom.json"
|
| 52 |
+
policy.write_text("{}", encoding="utf-8")
|
| 53 |
+
resolved = resolve_policy_file_paths(["custom.json"], cdk_folder=str(tmp_path))
|
| 54 |
+
assert resolved == [str(policy.resolve())]
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def test_add_custom_policies_loads_json_statements(tmp_path):
|
| 58 |
+
policy_path = tmp_path / "extra.json"
|
| 59 |
+
policy_path.write_text(
|
| 60 |
+
json.dumps(
|
| 61 |
+
{
|
| 62 |
+
"Version": "2012-10-17",
|
| 63 |
+
"Statement": [
|
| 64 |
+
{
|
| 65 |
+
"Sid": "TestAllow",
|
| 66 |
+
"Effect": "Allow",
|
| 67 |
+
"Action": "s3:ListBucket",
|
| 68 |
+
"Resource": "*",
|
| 69 |
+
}
|
| 70 |
+
],
|
| 71 |
+
}
|
| 72 |
+
),
|
| 73 |
+
encoding="utf-8",
|
| 74 |
+
)
|
| 75 |
+
|
| 76 |
+
app = App()
|
| 77 |
+
stack = Stack(app, "TestStack")
|
| 78 |
+
role = iam.Role(
|
| 79 |
+
stack,
|
| 80 |
+
"TaskRole",
|
| 81 |
+
assumed_by=iam.ServicePrincipal("ecs-tasks.amazonaws.com"),
|
| 82 |
+
)
|
| 83 |
+
add_custom_policies(stack, role, policy_file_locations=[str(policy_path)])
|
| 84 |
+
|
| 85 |
+
template = app.synth().get_stack_by_name("TestStack").template
|
| 86 |
+
policies = template["Resources"]
|
| 87 |
+
inline = [
|
| 88 |
+
r
|
| 89 |
+
for r in policies.values()
|
| 90 |
+
if r.get("Type") == "AWS::IAM::Policy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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Synth assertions for optional Pi agent ECS service on shared ALB."""
|
| 2 |
+
|
| 3 |
+
import sys
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
|
| 6 |
+
import pytest
|
| 7 |
+
|
| 8 |
+
CDK_DIR = Path(__file__).resolve().parents[1]
|
| 9 |
+
sys.path.insert(0, str(CDK_DIR))
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def test_pi_agent_requires_service_connect():
|
| 13 |
+
enable_pi = "True"
|
| 14 |
+
enable_sc = "False"
|
| 15 |
+
with pytest.raises(ValueError, match="ENABLE_PI_AGENT_ECS_SERVICE"):
|
| 16 |
+
if enable_pi == "True" and enable_sc != "True":
|
| 17 |
+
raise ValueError(
|
| 18 |
+
"ENABLE_PI_AGENT_ECS_SERVICE=True requires ENABLE_ECS_SERVICE_CONNECT=True "
|
| 19 |
+
"so the Pi task can reach the main app at http://<discovery>:7860."
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def test_build_pi_agent_container_environment():
|
| 24 |
+
from cdk_functions import build_pi_agent_container_environment
|
| 25 |
+
|
| 26 |
+
env = build_pi_agent_container_environment(
|
| 27 |
+
service_connect_discovery_name="summarisation",
|
| 28 |
+
main_app_port=7860,
|
| 29 |
+
pi_gradio_port=7862,
|
| 30 |
+
)
|
| 31 |
+
assert env["DOC_SUMMARISATION_GRADIO_URL"] == "http://summarisation:7860"
|
| 32 |
+
assert env["PI_DEFAULT_PROVIDER"] == "amazon-bedrock"
|
| 33 |
+
assert env["PI_GRADIO_PORT"] == "7862"
|
| 34 |
+
assert env["PI_CODING_AGENT_DIR"] == "/tmp/pi-agent"
|
| 35 |
+
assert env["ACCESS_LOGS_FOLDER"] == "/tmp/pi-logs/"
|
| 36 |
+
assert env["RUN_FASTAPI"] == "True"
|
| 37 |
+
assert env["RUN_AWS_FUNCTIONS"] == "True"
|
| 38 |
+
assert env["SAVE_OUTPUTS_TO_S3"] == "True"
|
| 39 |
+
assert env["S3_OUTPUTS_BUCKET"]
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def test_ecs_availability_zone_rebalancing_default_disabled():
|
| 43 |
+
from aws_cdk import aws_ecs as ecs
|
| 44 |
+
from cdk_functions import ecs_availability_zone_rebalancing
|
| 45 |
+
|
| 46 |
+
assert (
|
| 47 |
+
ecs_availability_zone_rebalancing("DISABLED")
|
| 48 |
+
== ecs.AvailabilityZoneRebalancing.DISABLED
|
| 49 |
+
)
|
| 50 |
+
assert (
|
| 51 |
+
ecs_availability_zone_rebalancing("ENABLED")
|
| 52 |
+
== ecs.AvailabilityZoneRebalancing.ENABLED
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def test_pi_agent_alb_attachment_synth():
|
| 57 |
+
from aws_cdk import App, Duration, Environment, Stack
|
| 58 |
+
from aws_cdk import aws_ec2 as ec2
|
| 59 |
+
from aws_cdk import aws_ecs as ecs
|
| 60 |
+
from aws_cdk import aws_elasticloadbalancingv2 as elbv2
|
| 61 |
+
from aws_cdk import aws_iam as iam
|
| 62 |
+
from aws_cdk import aws_s3 as s3
|
| 63 |
+
from cdk_functions import (
|
| 64 |
+
attach_pi_agent_to_shared_alb,
|
| 65 |
+
create_pi_agent_ecs_resources,
|
| 66 |
+
)
|
| 67 |
+
|
| 68 |
+
app = App()
|
| 69 |
+
stack = Stack(
|
| 70 |
+
app,
|
| 71 |
+
"PiAgentAlbTest",
|
| 72 |
+
env=Environment(account="123456789012", region="eu-west-2"),
|
| 73 |
+
)
|
| 74 |
+
vpc = ec2.Vpc(stack, "Vpc", max_azs=2)
|
| 75 |
+
alb_sg = ec2.SecurityGroup(stack, "AlbSg", vpc=vpc)
|
| 76 |
+
alb = elbv2.ApplicationLoadBalancer(
|
| 77 |
+
stack,
|
| 78 |
+
"Alb",
|
| 79 |
+
vpc=vpc,
|
| 80 |
+
internet_facing=True,
|
| 81 |
+
security_group=alb_sg,
|
| 82 |
+
)
|
| 83 |
+
cluster = ecs.Cluster(stack, "Cluster", vpc=vpc)
|
| 84 |
+
config_bucket = s3.Bucket(stack, "ConfigBucket")
|
| 85 |
+
task_role = iam.Role(
|
| 86 |
+
stack,
|
| 87 |
+
"TaskRole",
|
| 88 |
+
assumed_by=iam.ServicePrincipal("ecs-tasks.amazonaws.com"),
|
| 89 |
+
)
|
| 90 |
+
execution_role = iam.Role(
|
| 91 |
+
stack,
|
| 92 |
+
"ExecRole",
|
| 93 |
+
assumed_by=iam.ServicePrincipal("ecs-tasks.amazonaws.com"),
|
| 94 |
+
)
|
| 95 |
+
|
| 96 |
+
pi_service, pi_sg, _ = create_pi_agent_ecs_resources(
|
| 97 |
+
stack,
|
| 98 |
+
"Pi",
|
| 99 |
+
vpc=vpc,
|
| 100 |
+
cluster=cluster,
|
| 101 |
+
private_subnets=vpc.private_subnets,
|
| 102 |
+
pi_ecr_image_uri="123456789012.dkr.ecr.eu-west-2.amazonaws.com/pi-agent",
|
| 103 |
+
container_name="pi-agent",
|
| 104 |
+
task_role=task_role,
|
| 105 |
+
execution_role=execution_role,
|
| 106 |
+
config_bucket=config_bucket,
|
| 107 |
+
pi_agent_env_s3_key="",
|
| 108 |
+
service_name="test-pi-service",
|
| 109 |
+
task_family="test-pi-task",
|
| 110 |
+
security_group_name="test-pi-sg",
|
| 111 |
+
log_group_name="/ecs/test-pi-logs",
|
| 112 |
+
cpu=1024,
|
| 113 |
+
memory_mib=2048,
|
| 114 |
+
pi_gradio_port=7862,
|
| 115 |
+
service_connect_namespace="test-ns",
|
| 116 |
+
service_connect_discovery_name="summarisation",
|
| 117 |
+
main_app_port=7860,
|
| 118 |
+
use_fargate_spot="FARGATE",
|
| 119 |
+
)
|
| 120 |
+
|
| 121 |
+
http_listener = alb.add_listener("Http", port=80, open=True)
|
| 122 |
+
http_listener.add_action(
|
| 123 |
+
"DefaultDeny",
|
| 124 |
+
action=elbv2.ListenerAction.fixed_response(
|
| 125 |
+
status_code=403,
|
| 126 |
+
content_type="text/plain",
|
| 127 |
+
message_body="Access denied",
|
| 128 |
+
),
|
| 129 |
+
)
|
| 130 |
+
attach_pi_agent_to_shared_alb(
|
| 131 |
+
stack,
|
| 132 |
+
"PiAlb",
|
| 133 |
+
vpc=vpc,
|
| 134 |
+
alb_security_group=alb_sg,
|
| 135 |
+
pi_security_group=pi_sg,
|
| 136 |
+
pi_service=pi_service,
|
| 137 |
+
pi_port=7862,
|
| 138 |
+
routing_mode="host",
|
| 139 |
+
path_prefix="/pi",
|
| 140 |
+
pi_host_header="pi.example.com",
|
| 141 |
+
listener_rule_priority=3,
|
| 142 |
+
target_group_name="test-pi-tg",
|
| 143 |
+
stickiness_cookie_duration=Duration.hours(8),
|
| 144 |
+
https_listener=None,
|
| 145 |
+
http_listener=http_listener,
|
| 146 |
+
acm_certificate_arn="",
|
| 147 |
+
enable_cognito_auth=False,
|
| 148 |
+
cognito_user_pool=None,
|
| 149 |
+
cognito_user_pool_client=None,
|
| 150 |
+
cognito_user_pool_domain=None,
|
| 151 |
+
)
|
| 152 |
+
|
| 153 |
+
template = app.synth().get_stack_by_name("PiAgentAlbTest").template
|
| 154 |
+
resources = template["Resources"]
|
| 155 |
+
lb_count = sum(
|
| 156 |
+
1
|
| 157 |
+
for r in resources.values()
|
| 158 |
+
if r["Type"] == "AWS::ElasticLoadBalancingV2::LoadBalancer"
|
| 159 |
+
)
|
| 160 |
+
tg_count = sum(
|
| 161 |
+
1
|
| 162 |
+
for r in resources.values()
|
| 163 |
+
if r["Type"] == "AWS::ElasticLoadBalancingV2::TargetGroup"
|
| 164 |
+
)
|
| 165 |
+
assert lb_count == 1
|
| 166 |
+
assert tg_count == 1
|
| 167 |
+
ecs_services = [r for r in resources.values() if r["Type"] == "AWS::ECS::Service"]
|
| 168 |
+
assert len(ecs_services) == 1
|
| 169 |
+
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Tests for Pi ALB path/host routing helpers."""
|
| 2 |
+
|
| 3 |
+
import sys
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
|
| 6 |
+
import pytest
|
| 7 |
+
|
| 8 |
+
CDK_DIR = Path(__file__).resolve().parents[1]
|
| 9 |
+
sys.path.insert(0, str(CDK_DIR))
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
@pytest.fixture(autouse=True)
|
| 13 |
+
def _minimal_cdk_config_env(monkeypatch):
|
| 14 |
+
monkeypatch.setenv("USE_ECS_EXPRESS_MODE", "False")
|
| 15 |
+
monkeypatch.setenv("ACM_SSL_CERTIFICATE_ARN", "")
|
| 16 |
+
monkeypatch.setenv("ENABLE_S3_BATCH_ECS_TRIGGER", "False")
|
| 17 |
+
monkeypatch.setenv("ENABLE_PI_AGENT_ECS_SERVICE", "False")
|
| 18 |
+
monkeypatch.setenv("ENABLE_PI_AGENT_EXPRESS_SERVICE", "False")
|
| 19 |
+
monkeypatch.setenv("ENABLE_ECS_SERVICE_CONNECT", "False")
|
| 20 |
+
for mod_name in list(sys.modules):
|
| 21 |
+
if mod_name in ("cdk_config", "cdk_functions") or mod_name.startswith("cdk_"):
|
| 22 |
+
del sys.modules[mod_name]
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def test_normalize_pi_alb_path_prefix():
|
| 26 |
+
from cdk_functions import normalize_pi_alb_path_prefix
|
| 27 |
+
|
| 28 |
+
assert normalize_pi_alb_path_prefix("/pi") == "/pi"
|
| 29 |
+
assert normalize_pi_alb_path_prefix("pi") == "/pi"
|
| 30 |
+
assert normalize_pi_alb_path_prefix("") == "/pi"
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def test_pi_alb_path_patterns():
|
| 34 |
+
from cdk_functions import pi_alb_path_patterns
|
| 35 |
+
|
| 36 |
+
assert pi_alb_path_patterns("/pi") == ["/pi", "/pi/*"]
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def test_format_pi_public_urls_path_on_cloudfront():
|
| 40 |
+
from cdk_functions import format_pi_public_urls
|
| 41 |
+
|
| 42 |
+
urls = format_pi_public_urls(
|
| 43 |
+
routing_mode="path",
|
| 44 |
+
path_prefix="/pi",
|
| 45 |
+
host_header="",
|
| 46 |
+
cloudfront_domain="d123.cloudfront.net",
|
| 47 |
+
use_https=True,
|
| 48 |
+
)
|
| 49 |
+
assert urls == ["https://d123.cloudfront.net/pi/"]
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def test_pi_listener_rule_count():
|
| 53 |
+
from cdk_functions import pi_listener_rule_count
|
| 54 |
+
|
| 55 |
+
assert pi_listener_rule_count("path") == 1
|
| 56 |
+
assert pi_listener_rule_count("host") == 1
|
| 57 |
+
assert pi_listener_rule_count("both") == 2
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def test_attach_pi_path_rule_synth():
|
| 61 |
+
from aws_cdk import App, Duration, Environment, Stack, assertions
|
| 62 |
+
from aws_cdk import aws_ec2 as ec2
|
| 63 |
+
from aws_cdk import aws_ecs as ecs
|
| 64 |
+
from aws_cdk import aws_elasticloadbalancingv2 as elbv2
|
| 65 |
+
from aws_cdk import aws_iam as iam
|
| 66 |
+
from aws_cdk import aws_s3 as s3
|
| 67 |
+
from cdk_functions import (
|
| 68 |
+
attach_pi_agent_to_shared_alb,
|
| 69 |
+
create_pi_agent_ecs_resources,
|
| 70 |
+
)
|
| 71 |
+
|
| 72 |
+
app = App()
|
| 73 |
+
stack = Stack(
|
| 74 |
+
app,
|
| 75 |
+
"PiPathAlbTest",
|
| 76 |
+
env=Environment(account="123456789012", region="eu-west-2"),
|
| 77 |
+
)
|
| 78 |
+
vpc = ec2.Vpc(stack, "Vpc", max_azs=2)
|
| 79 |
+
alb_sg = ec2.SecurityGroup(stack, "AlbSg", vpc=vpc)
|
| 80 |
+
alb = elbv2.ApplicationLoadBalancer(
|
| 81 |
+
stack,
|
| 82 |
+
"Alb",
|
| 83 |
+
vpc=vpc,
|
| 84 |
+
internet_facing=True,
|
| 85 |
+
security_group=alb_sg,
|
| 86 |
+
)
|
| 87 |
+
cluster = ecs.Cluster(stack, "Cluster", vpc=vpc)
|
| 88 |
+
config_bucket = s3.Bucket(stack, "ConfigBucket")
|
| 89 |
+
task_role = iam.Role(
|
| 90 |
+
stack,
|
| 91 |
+
"TaskRole",
|
| 92 |
+
assumed_by=iam.ServicePrincipal("ecs-tasks.amazonaws.com"),
|
| 93 |
+
)
|
| 94 |
+
execution_role = iam.Role(
|
| 95 |
+
stack,
|
| 96 |
+
"ExecRole",
|
| 97 |
+
assumed_by=iam.ServicePrincipal("ecs-tasks.amazonaws.com"),
|
| 98 |
+
)
|
| 99 |
+
|
| 100 |
+
pi_service, pi_sg, _ = create_pi_agent_ecs_resources(
|
| 101 |
+
stack,
|
| 102 |
+
"Pi",
|
| 103 |
+
vpc=vpc,
|
| 104 |
+
cluster=cluster,
|
| 105 |
+
private_subnets=vpc.private_subnets,
|
| 106 |
+
pi_ecr_image_uri="123456789012.dkr.ecr.eu-west-2.amazonaws.com/pi-agent",
|
| 107 |
+
container_name="pi-agent",
|
| 108 |
+
task_role=task_role,
|
| 109 |
+
execution_role=execution_role,
|
| 110 |
+
config_bucket=config_bucket,
|
| 111 |
+
pi_agent_env_s3_key="",
|
| 112 |
+
service_name="test-pi-service",
|
| 113 |
+
task_family="test-pi-task",
|
| 114 |
+
security_group_name="test-pi-sg",
|
| 115 |
+
log_group_name="/ecs/test-pi-logs",
|
| 116 |
+
cpu=1024,
|
| 117 |
+
memory_mib=2048,
|
| 118 |
+
pi_gradio_port=7862,
|
| 119 |
+
service_connect_namespace="test-ns",
|
| 120 |
+
service_connect_discovery_name="summarisation",
|
| 121 |
+
main_app_port=7860,
|
| 122 |
+
pi_root_path="/pi",
|
| 123 |
+
use_fargate_spot="FARGATE",
|
| 124 |
+
)
|
| 125 |
+
|
| 126 |
+
http_listener = alb.add_listener("Http", port=80, open=True)
|
| 127 |
+
http_listener.add_action(
|
| 128 |
+
"DefaultDeny",
|
| 129 |
+
action=elbv2.ListenerAction.fixed_response(
|
| 130 |
+
status_code=403,
|
| 131 |
+
content_type="text/plain",
|
| 132 |
+
message_body="Access denied",
|
| 133 |
+
),
|
| 134 |
+
)
|
| 135 |
+
attach_pi_agent_to_shared_alb(
|
| 136 |
+
stack,
|
| 137 |
+
"PiAlb",
|
| 138 |
+
vpc=vpc,
|
| 139 |
+
alb_security_group=alb_sg,
|
| 140 |
+
pi_security_group=pi_sg,
|
| 141 |
+
pi_service=pi_service,
|
| 142 |
+
pi_port=7862,
|
| 143 |
+
routing_mode="path",
|
| 144 |
+
path_prefix="/pi",
|
| 145 |
+
pi_host_header="",
|
| 146 |
+
listener_rule_priority=3,
|
| 147 |
+
target_group_name="test-pi-tg",
|
| 148 |
+
stickiness_cookie_duration=Duration.hours(8),
|
| 149 |
+
https_listener=None,
|
| 150 |
+
http_listener=http_listener,
|
| 151 |
+
acm_certificate_arn="",
|
| 152 |
+
enable_cognito_auth=False,
|
| 153 |
+
cognito_user_pool=None,
|
| 154 |
+
cognito_user_pool_client=None,
|
| 155 |
+
cognito_user_pool_domain=None,
|
| 156 |
+
)
|
| 157 |
+
|
| 158 |
+
template = assertions.Template.from_stack(stack)
|
| 159 |
+
template.has_resource_properties(
|
| 160 |
+
"AWS::ElasticLoadBalancingV2::TargetGroup",
|
| 161 |
+
{
|
| 162 |
+
"HealthCheckPath": "/pi/",
|
| 163 |
+
},
|
| 164 |
+
)
|
cdk/test/test_public_subnet_igw.py
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Tests for public subnet Internet Gateway audit and CDK wiring helpers."""
|
| 2 |
+
|
| 3 |
+
import sys
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
from unittest.mock import MagicMock, patch
|
| 6 |
+
|
| 7 |
+
import pytest
|
| 8 |
+
|
| 9 |
+
CDK_DIR = Path(__file__).resolve().parents[1]
|
| 10 |
+
sys.path.insert(0, str(CDK_DIR))
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
@pytest.fixture(autouse=True)
|
| 14 |
+
def _minimal_cdk_config_env(monkeypatch):
|
| 15 |
+
"""Avoid loading the developer cdk_config.env validation errors during import."""
|
| 16 |
+
monkeypatch.setenv("USE_ECS_EXPRESS_MODE", "False")
|
| 17 |
+
monkeypatch.setenv("ACM_SSL_CERTIFICATE_ARN", "")
|
| 18 |
+
monkeypatch.setenv("ENABLE_S3_BATCH_ECS_TRIGGER", "False")
|
| 19 |
+
monkeypatch.setenv("ENABLE_PI_AGENT_ECS_SERVICE", "False")
|
| 20 |
+
monkeypatch.setenv("ENABLE_PI_AGENT_EXPRESS_SERVICE", "False")
|
| 21 |
+
monkeypatch.setenv("ENABLE_ECS_SERVICE_CONNECT", "False")
|
| 22 |
+
for mod_name in list(sys.modules):
|
| 23 |
+
if mod_name in ("cdk_config", "cdk_functions") or mod_name.startswith("cdk_"):
|
| 24 |
+
del sys.modules[mod_name]
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def test_route_table_default_internet_gateway_parses_igw():
|
| 28 |
+
from cdk_functions import route_table_default_internet_gateway
|
| 29 |
+
|
| 30 |
+
mock_client = MagicMock()
|
| 31 |
+
mock_client.describe_route_tables.return_value = {
|
| 32 |
+
"RouteTables": [
|
| 33 |
+
{
|
| 34 |
+
"Routes": [
|
| 35 |
+
{
|
| 36 |
+
"DestinationCidrBlock": "0.0.0.0/0",
|
| 37 |
+
"GatewayId": "igw-abc123",
|
| 38 |
+
}
|
| 39 |
+
]
|
| 40 |
+
}
|
| 41 |
+
]
|
| 42 |
+
}
|
| 43 |
+
with patch("cdk_functions.boto3.client", return_value=mock_client):
|
| 44 |
+
assert route_table_default_internet_gateway("rtb-1") == "igw-abc123"
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def test_audit_needs_attachment_when_igw_detached():
|
| 48 |
+
from cdk_functions import audit_public_subnet_internet_connectivity
|
| 49 |
+
|
| 50 |
+
mock_ec2 = MagicMock()
|
| 51 |
+
mock_ec2.describe_internet_gateways.return_value = {
|
| 52 |
+
"InternetGateways": [{"Attachments": []}]
|
| 53 |
+
}
|
| 54 |
+
with (
|
| 55 |
+
patch("cdk_functions.get_internet_gateways_attached_to_vpc", return_value=[]),
|
| 56 |
+
patch("cdk_functions.internet_gateway_exists", return_value=True),
|
| 57 |
+
patch("cdk_functions.boto3.client", return_value=mock_ec2),
|
| 58 |
+
patch("cdk_functions.route_table_default_internet_gateway", return_value=None),
|
| 59 |
+
patch(
|
| 60 |
+
"cdk_functions.route_table_has_non_igw_default_route", return_value=False
|
| 61 |
+
),
|
| 62 |
+
):
|
| 63 |
+
result = audit_public_subnet_internet_connectivity(
|
| 64 |
+
"vpc-111",
|
| 65 |
+
"igw-configured",
|
| 66 |
+
[
|
| 67 |
+
{
|
| 68 |
+
"name": "PublicSubnet1",
|
| 69 |
+
"subnet_id": "subnet-1",
|
| 70 |
+
"route_table_id": "rtb-1",
|
| 71 |
+
}
|
| 72 |
+
],
|
| 73 |
+
)
|
| 74 |
+
assert result["internet_gateway_id"] == "igw-configured"
|
| 75 |
+
assert result["internet_gateway_needs_vpc_attachment"] is True
|
| 76 |
+
assert len(result["public_subnets_needing_igw_route"]) == 1
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def test_audit_raises_when_default_route_conflicts():
|
| 80 |
+
from cdk_functions import audit_public_subnet_internet_connectivity
|
| 81 |
+
|
| 82 |
+
with (
|
| 83 |
+
patch(
|
| 84 |
+
"cdk_functions.get_internet_gateways_attached_to_vpc",
|
| 85 |
+
return_value=["igw-attached"],
|
| 86 |
+
),
|
| 87 |
+
patch("cdk_functions.internet_gateway_exists", return_value=True),
|
| 88 |
+
patch(
|
| 89 |
+
"cdk_functions.route_table_default_internet_gateway",
|
| 90 |
+
return_value="igw-other",
|
| 91 |
+
),
|
| 92 |
+
):
|
| 93 |
+
with pytest.raises(ValueError, match="0.0.0.0/0"):
|
| 94 |
+
audit_public_subnet_internet_connectivity(
|
| 95 |
+
"vpc-111",
|
| 96 |
+
"igw-attached",
|
| 97 |
+
[
|
| 98 |
+
{
|
| 99 |
+
"name": "PublicSubnet1",
|
| 100 |
+
"subnet_id": "subnet-1",
|
| 101 |
+
"route_table_id": "rtb-1",
|
| 102 |
+
}
|
| 103 |
+
],
|
| 104 |
+
)
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def test_wire_public_subnet_internet_access_synth():
|
| 108 |
+
from aws_cdk import App, Environment, Stack, assertions
|
| 109 |
+
from cdk_functions import wire_public_subnet_internet_access
|
| 110 |
+
|
| 111 |
+
app = App()
|
| 112 |
+
stack = Stack(
|
| 113 |
+
app,
|
| 114 |
+
"IgwWireTest",
|
| 115 |
+
env=Environment(account="123456789012", region="eu-west-2"),
|
| 116 |
+
)
|
| 117 |
+
wire_public_subnet_internet_access(
|
| 118 |
+
stack,
|
| 119 |
+
"Test",
|
| 120 |
+
vpc_id="vpc-111",
|
| 121 |
+
internet_gateway_id="igw-abc123",
|
| 122 |
+
needs_igw_vpc_attachment=True,
|
| 123 |
+
subnets_needing_route=[
|
| 124 |
+
{
|
| 125 |
+
"name": "PublicSubnet1",
|
| 126 |
+
"subnet_id": "subnet-1",
|
| 127 |
+
"route_table_id": "rtb-aaa",
|
| 128 |
+
}
|
| 129 |
+
],
|
| 130 |
+
)
|
| 131 |
+
template = assertions.Template.from_stack(stack)
|
| 132 |
+
template.resource_count_is("AWS::EC2::VPCGatewayAttachment", 1)
|
| 133 |
+
template.resource_count_is("AWS::EC2::Route", 1)
|
| 134 |
+
template.has_resource_properties(
|
| 135 |
+
"AWS::EC2::Route",
|
| 136 |
+
{
|
| 137 |
+
"RouteTableId": "rtb-aaa",
|
| 138 |
+
"DestinationCidrBlock": "0.0.0.0/0",
|
| 139 |
+
"GatewayId": "igw-abc123",
|
| 140 |
+
},
|
| 141 |
+
)
|