Spaces:
Running on Zero
Running on Zero
Commit ·
f935095
0
Parent(s):
Sync: Merge pull request #107 from seanpedrick-case/dev
Browse filesAdded option to skip all summarisation. AWS Guardrails now only apply on initial topic extraction (when receiving input responses)
This view is limited to 50 files because it contains too many changes. See raw diff
- .dockerignore +63 -0
- .gitattributes +2 -0
- .github/workflows/ci.yml +215 -0
- .github/workflows/simple-test.yml +53 -0
- .github/workflows/sync_to_hf.yml +53 -0
- .gitignore +62 -0
- Dockerfile +171 -0
- LICENSE +21 -0
- README.md +189 -0
- app.py +0 -0
- cdk/__init__.py +0 -0
- cdk/app.py +140 -0
- cdk/cdk.json.example +7 -0
- cdk/cdk_application_tags.py +95 -0
- cdk/cdk_appregistry.py +79 -0
- cdk/cdk_cloudfront_headers.py +172 -0
- cdk/cdk_config.py +916 -0
- cdk/cdk_functions.py +0 -0
- cdk/cdk_install.py +0 -0
- cdk/cdk_post_deploy.py +1492 -0
- cdk/cdk_stack.py +0 -0
- cdk/check_resources.py +583 -0
- cdk/config/app_config.env.example +31 -0
- cdk/config/headless_s3_seed/general-config/app_defaults.env +52 -0
- cdk/config/headless_s3_seed/input/config/example_headless_env_file.env +15 -0
- cdk/config/lambda/lambda_function.py +192 -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 +201 -0
- cdk/requirements.txt +8 -0
- cdk/test/test_application_tags_and_resource_group.py +79 -0
- cdk/test/test_bedrock_model_invocation_logging.py +106 -0
- cdk/test/test_cdk_install.py +1116 -0
- cdk/test/test_cdk_post_deploy.py +411 -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 +39 -0
- cdk/test/test_headless_output_notifications.py +81 -0
.dockerignore
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
evals/*
|
| 16 |
+
logs/*
|
| 17 |
+
usage/*
|
| 18 |
+
docs/*
|
| 19 |
+
guide/*
|
| 20 |
+
feedback/*
|
| 21 |
+
test_code/*
|
| 22 |
+
test/tmp/*
|
| 23 |
+
unsloth_compiled_cache/*
|
| 24 |
+
.vscode/*
|
| 25 |
+
llm_topic_modelling.egg-info/*
|
| 26 |
+
input/
|
| 27 |
+
output/
|
| 28 |
+
logs/
|
| 29 |
+
usage/
|
| 30 |
+
feedback/
|
| 31 |
+
config/
|
| 32 |
+
tmp/
|
| 33 |
+
index.qmd
|
| 34 |
+
_quarto.yml
|
| 35 |
+
!config/pi_agent.env.example
|
| 36 |
+
!config/docker_app_config.env.example
|
| 37 |
+
!config/app_config.env.example
|
| 38 |
+
workspace/*
|
| 39 |
+
user_guide/*
|
| 40 |
+
_extensions/*
|
| 41 |
+
cdk/config/*
|
| 42 |
+
cdk/node_modules/*
|
| 43 |
+
!cdk/config/app_config.env.example
|
| 44 |
+
!cdk/config/lambda/
|
| 45 |
+
cdk/config/lambda/*
|
| 46 |
+
!cdk/config/lambda/lambda_function.py
|
| 47 |
+
!cdk/config/headless_s3_seed/
|
| 48 |
+
cdk/config/headless_s3_seed/*
|
| 49 |
+
!cdk/config/headless_s3_seed/input/
|
| 50 |
+
cdk/config/headless_s3_seed/input/*
|
| 51 |
+
!cdk/config/headless_s3_seed/input/config/
|
| 52 |
+
cdk/config/headless_s3_seed/input/config/*
|
| 53 |
+
!cdk/config/headless_s3_seed/input/config/example_headless_env_file.env
|
| 54 |
+
!cdk/config/headless_s3_seed/general-config/
|
| 55 |
+
cdk/config/headless_s3_seed/general-config/*
|
| 56 |
+
!cdk/config/headless_s3_seed/general-config/app_defaults.env
|
| 57 |
+
cdk/cdk.out/*
|
| 58 |
+
cdk/archive/*
|
| 59 |
+
cdk/cdk.json
|
| 60 |
+
cdk/cdk.context.json
|
| 61 |
+
cdk/precheck.context.json
|
| 62 |
+
cdk/package.json
|
| 63 |
+
cdk/package-lock.json
|
.gitattributes
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
*.xlsx filter=lfs diff=lfs merge=lfs -text
|
| 2 |
+
*.csv filter=lfs diff=lfs merge=lfs -text
|
.github/workflows/ci.yml
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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
name: CI/CD Pipeline
|
| 2 |
+
|
| 3 |
+
on:
|
| 4 |
+
push:
|
| 5 |
+
branches: [ main ]
|
| 6 |
+
pull_request:
|
| 7 |
+
branches: [ main ]
|
| 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 |
+
with:
|
| 27 |
+
lfs: true
|
| 28 |
+
|
| 29 |
+
- name: Set up Python
|
| 30 |
+
uses: actions/setup-python@v4
|
| 31 |
+
with:
|
| 32 |
+
python-version: ${{ env.PYTHON_VERSION }}
|
| 33 |
+
|
| 34 |
+
- name: Install dependencies
|
| 35 |
+
run: |
|
| 36 |
+
python -m pip install --upgrade pip
|
| 37 |
+
pip install ruff black
|
| 38 |
+
|
| 39 |
+
- name: Run Ruff linter
|
| 40 |
+
run: ruff check .
|
| 41 |
+
|
| 42 |
+
- name: Run Black formatter check
|
| 43 |
+
run: black --check .
|
| 44 |
+
|
| 45 |
+
test-unit:
|
| 46 |
+
runs-on: ubuntu-latest
|
| 47 |
+
strategy:
|
| 48 |
+
matrix:
|
| 49 |
+
python-version: [3.11, 3.12, 3.13]
|
| 50 |
+
|
| 51 |
+
steps:
|
| 52 |
+
- uses: actions/checkout@v4
|
| 53 |
+
with:
|
| 54 |
+
lfs: true
|
| 55 |
+
|
| 56 |
+
- name: Set up Python ${{ matrix.python-version }}
|
| 57 |
+
uses: actions/setup-python@v4
|
| 58 |
+
with:
|
| 59 |
+
python-version: ${{ matrix.python-version }}
|
| 60 |
+
|
| 61 |
+
- name: Cache pip dependencies
|
| 62 |
+
uses: actions/cache@v4
|
| 63 |
+
with:
|
| 64 |
+
path: ~/.cache/pip
|
| 65 |
+
key: ${{ runner.os }}-pip-${{ hashFiles('**/requirements*.txt', '**/pyproject.toml') }}
|
| 66 |
+
restore-keys: |
|
| 67 |
+
${{ runner.os }}-pip-
|
| 68 |
+
|
| 69 |
+
- name: Install Python dependencies
|
| 70 |
+
run: |
|
| 71 |
+
python -m pip install --upgrade pip
|
| 72 |
+
pip install -r requirements_lightweight.txt
|
| 73 |
+
pip install pytest pytest-cov pytest-html pytest-xdist
|
| 74 |
+
|
| 75 |
+
- name: Verify example data files
|
| 76 |
+
run: |
|
| 77 |
+
echo "Checking if example data directory exists:"
|
| 78 |
+
ls -la example_data/ || echo "example_data directory not found"
|
| 79 |
+
echo "Checking for specific CSV files:"
|
| 80 |
+
ls -la example_data/*.csv || echo "No CSV files found"
|
| 81 |
+
# Fail early if Git LFS pointers were not materialized
|
| 82 |
+
if head -n 1 example_data/combined_case_notes.csv | grep -q 'git-lfs.github.com'; then
|
| 83 |
+
echo "ERROR: example_data CSVs are still Git LFS pointers. Ensure checkout uses lfs: true."
|
| 84 |
+
exit 1
|
| 85 |
+
fi
|
| 86 |
+
|
| 87 |
+
- name: Run CLI and GUI tests
|
| 88 |
+
run: |
|
| 89 |
+
cd test
|
| 90 |
+
python run_tests.py
|
| 91 |
+
|
| 92 |
+
- name: Run tests with pytest
|
| 93 |
+
run: |
|
| 94 |
+
pytest test/test.py test/test_gui_only.py -v --tb=short --junitxml=test-results.xml
|
| 95 |
+
|
| 96 |
+
- name: Run tests with coverage
|
| 97 |
+
run: |
|
| 98 |
+
pytest test/test.py test/test_gui_only.py --cov=. --cov-report=xml --cov-report=html --cov-report=term
|
| 99 |
+
|
| 100 |
+
- name: Upload test results
|
| 101 |
+
uses: actions/upload-artifact@v4
|
| 102 |
+
if: always()
|
| 103 |
+
with:
|
| 104 |
+
name: test-results-python-${{ matrix.python-version }}
|
| 105 |
+
path: |
|
| 106 |
+
test-results.xml
|
| 107 |
+
htmlcov/
|
| 108 |
+
coverage.xml
|
| 109 |
+
|
| 110 |
+
test-integration:
|
| 111 |
+
runs-on: ubuntu-latest
|
| 112 |
+
needs: [lint, test-unit]
|
| 113 |
+
|
| 114 |
+
steps:
|
| 115 |
+
- uses: actions/checkout@v4
|
| 116 |
+
with:
|
| 117 |
+
lfs: true
|
| 118 |
+
|
| 119 |
+
- name: Set up Python
|
| 120 |
+
uses: actions/setup-python@v4
|
| 121 |
+
with:
|
| 122 |
+
python-version: ${{ env.PYTHON_VERSION }}
|
| 123 |
+
|
| 124 |
+
- name: Install dependencies
|
| 125 |
+
run: |
|
| 126 |
+
python -m pip install --upgrade pip
|
| 127 |
+
pip install -r requirements_lightweight.txt
|
| 128 |
+
pip install pytest pytest-cov
|
| 129 |
+
|
| 130 |
+
- name: Verify example data files
|
| 131 |
+
run: |
|
| 132 |
+
echo "Checking if example data directory exists:"
|
| 133 |
+
ls -la example_data/
|
| 134 |
+
echo "Checking for specific CSV files:"
|
| 135 |
+
ls -la example_data/*.csv || echo "No CSV files found"
|
| 136 |
+
if head -n 1 example_data/combined_case_notes.csv | grep -q 'git-lfs.github.com'; then
|
| 137 |
+
echo "ERROR: example_data CSVs are still Git LFS pointers. Ensure checkout uses lfs: true."
|
| 138 |
+
exit 1
|
| 139 |
+
fi
|
| 140 |
+
|
| 141 |
+
- name: Run integration tests (CLI and GUI)
|
| 142 |
+
run: |
|
| 143 |
+
cd test
|
| 144 |
+
python run_tests.py
|
| 145 |
+
|
| 146 |
+
- name: Test CLI help
|
| 147 |
+
run: |
|
| 148 |
+
python cli_topics.py --help
|
| 149 |
+
|
| 150 |
+
- name: Test CLI version
|
| 151 |
+
run: |
|
| 152 |
+
python -c "import sys; print(f'Python {sys.version}')"
|
| 153 |
+
|
| 154 |
+
security:
|
| 155 |
+
runs-on: ubuntu-latest
|
| 156 |
+
steps:
|
| 157 |
+
- uses: actions/checkout@v4
|
| 158 |
+
with:
|
| 159 |
+
lfs: true
|
| 160 |
+
|
| 161 |
+
- name: Set up Python
|
| 162 |
+
uses: actions/setup-python@v4
|
| 163 |
+
with:
|
| 164 |
+
python-version: ${{ env.PYTHON_VERSION }}
|
| 165 |
+
|
| 166 |
+
- name: Install dependencies
|
| 167 |
+
run: |
|
| 168 |
+
python -m pip install --upgrade pip
|
| 169 |
+
pip install bandit
|
| 170 |
+
|
| 171 |
+
- name: Run bandit security check
|
| 172 |
+
run: |
|
| 173 |
+
bandit -r . -f json -o bandit-report.json || true
|
| 174 |
+
|
| 175 |
+
- name: Upload security report
|
| 176 |
+
uses: actions/upload-artifact@v4
|
| 177 |
+
if: always()
|
| 178 |
+
with:
|
| 179 |
+
name: security-report
|
| 180 |
+
path: bandit-report.json
|
| 181 |
+
|
| 182 |
+
build:
|
| 183 |
+
runs-on: ubuntu-latest
|
| 184 |
+
needs: [lint, test-unit]
|
| 185 |
+
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
|
| 186 |
+
|
| 187 |
+
steps:
|
| 188 |
+
- uses: actions/checkout@v4
|
| 189 |
+
with:
|
| 190 |
+
lfs: true
|
| 191 |
+
|
| 192 |
+
- name: Set up Python
|
| 193 |
+
uses: actions/setup-python@v4
|
| 194 |
+
with:
|
| 195 |
+
python-version: ${{ env.PYTHON_VERSION }}
|
| 196 |
+
|
| 197 |
+
- name: Install build dependencies
|
| 198 |
+
run: |
|
| 199 |
+
python -m pip install --upgrade pip
|
| 200 |
+
pip install build twine
|
| 201 |
+
|
| 202 |
+
- name: Build package
|
| 203 |
+
run: |
|
| 204 |
+
python -m build
|
| 205 |
+
|
| 206 |
+
- name: Check package
|
| 207 |
+
run: |
|
| 208 |
+
twine check dist/*
|
| 209 |
+
|
| 210 |
+
- name: Upload build artifacts
|
| 211 |
+
uses: actions/upload-artifact@v4
|
| 212 |
+
with:
|
| 213 |
+
name: dist
|
| 214 |
+
path: dist/
|
| 215 |
+
|
.github/workflows/simple-test.yml
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
with:
|
| 20 |
+
lfs: true
|
| 21 |
+
|
| 22 |
+
- name: Set up Python 3.11
|
| 23 |
+
uses: actions/setup-python@v4
|
| 24 |
+
with:
|
| 25 |
+
python-version: "3.11"
|
| 26 |
+
|
| 27 |
+
- name: Install Python dependencies
|
| 28 |
+
run: |
|
| 29 |
+
python -m pip install --upgrade pip
|
| 30 |
+
pip install -r requirements_lightweight.txt
|
| 31 |
+
pip install pytest pytest-cov
|
| 32 |
+
|
| 33 |
+
- name: Verify example data files
|
| 34 |
+
run: |
|
| 35 |
+
echo "Checking if example data directory exists:"
|
| 36 |
+
ls -la example_data/ || echo "example_data directory not found"
|
| 37 |
+
echo "Checking for specific CSV files:"
|
| 38 |
+
ls -la example_data/*.csv || echo "No CSV files found"
|
| 39 |
+
# Fail early if Git LFS pointers were not materialized
|
| 40 |
+
if head -n 1 example_data/combined_case_notes.csv | grep -q 'git-lfs.github.com'; then
|
| 41 |
+
echo "ERROR: example_data CSVs are still Git LFS pointers. Ensure checkout uses lfs: true."
|
| 42 |
+
exit 1
|
| 43 |
+
fi
|
| 44 |
+
|
| 45 |
+
- name: Run CLI and GUI tests
|
| 46 |
+
run: |
|
| 47 |
+
cd test
|
| 48 |
+
python run_tests.py
|
| 49 |
+
|
| 50 |
+
- name: Run tests with pytest
|
| 51 |
+
run: |
|
| 52 |
+
pytest test/test.py test/test_gui_only.py -v --tb=short
|
| 53 |
+
|
.github/workflows/sync_to_hf.yml
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
name: Sync to Hugging Face hub
|
| 2 |
+
on:
|
| 3 |
+
push:
|
| 4 |
+
branches: [main]
|
| 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,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
evals/*
|
| 18 |
+
usage/*
|
| 19 |
+
feedback/*
|
| 20 |
+
test_code/*
|
| 21 |
+
config/*
|
| 22 |
+
tmp/*
|
| 23 |
+
test/tmp/*
|
| 24 |
+
unsloth_compiled_cache/*
|
| 25 |
+
.vscode/*
|
| 26 |
+
llm_topic_modelling.egg-info/*
|
| 27 |
+
index.qmd
|
| 28 |
+
_quarto.yml
|
| 29 |
+
/.quarto/
|
| 30 |
+
**/*.quarto_ipynb
|
| 31 |
+
config/*
|
| 32 |
+
!config/pi_agent.env.example
|
| 33 |
+
!config/docker_app_config.env.example
|
| 34 |
+
!config/app_config.env.example
|
| 35 |
+
workspace/*
|
| 36 |
+
user_guide/*
|
| 37 |
+
_extensions/*
|
| 38 |
+
cdk/config/*
|
| 39 |
+
cdk/node_modules/*
|
| 40 |
+
!cdk/config/app_config.env.example
|
| 41 |
+
!cdk/config/lambda/
|
| 42 |
+
cdk/config/lambda/*
|
| 43 |
+
!cdk/config/lambda/lambda_function.py
|
| 44 |
+
!cdk/config/headless_s3_seed/
|
| 45 |
+
cdk/config/headless_s3_seed/*
|
| 46 |
+
!cdk/config/headless_s3_seed/input/
|
| 47 |
+
cdk/config/headless_s3_seed/input/*
|
| 48 |
+
!cdk/config/headless_s3_seed/input/config/
|
| 49 |
+
cdk/config/headless_s3_seed/input/config/*
|
| 50 |
+
!cdk/config/headless_s3_seed/input/config/example_headless_env_file.env
|
| 51 |
+
!cdk/config/headless_s3_seed/general-config/
|
| 52 |
+
cdk/config/headless_s3_seed/general-config/*
|
| 53 |
+
!cdk/config/headless_s3_seed/general-config/app_defaults.env
|
| 54 |
+
cdk/cdk.out/*
|
| 55 |
+
cdk/archive/*
|
| 56 |
+
cdk/cdk.out/*
|
| 57 |
+
cdk/cdk.json
|
| 58 |
+
cdk/cdk.context.json
|
| 59 |
+
cdk/precheck.context.json
|
| 60 |
+
cdk/package.json
|
| 61 |
+
cdk/package-lock.json
|
| 62 |
+
|
Dockerfile
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Stage 1: Build dependencies and download models
|
| 2 |
+
FROM public.ecr.aws/docker/library/python:3.13.16-slim-trixie AS builder
|
| 3 |
+
|
| 4 |
+
# Install system dependencies.
|
| 5 |
+
RUN apt-get update && apt-get install -y \
|
| 6 |
+
build-essential \
|
| 7 |
+
gcc \
|
| 8 |
+
g++ \
|
| 9 |
+
cmake \
|
| 10 |
+
#libopenblas-dev \
|
| 11 |
+
pkg-config \
|
| 12 |
+
python3-dev \
|
| 13 |
+
libffi-dev \
|
| 14 |
+
&& apt-get clean \
|
| 15 |
+
&& rm -rf /var/lib/apt/lists/*
|
| 16 |
+
|
| 17 |
+
WORKDIR /src
|
| 18 |
+
|
| 19 |
+
COPY requirements_lightweight.txt .
|
| 20 |
+
|
| 21 |
+
ARG INSTALL_TORCH=False
|
| 22 |
+
ENV INSTALL_TORCH=${INSTALL_TORCH}
|
| 23 |
+
|
| 24 |
+
# Local torch install requires CUDA 13.0
|
| 25 |
+
RUN if [ "$INSTALL_TORCH" = "True" ]; then \
|
| 26 |
+
pip install --no-cache-dir --target=/install torch==2.14.1 --extra-index-url https://download.pytorch.org/whl/cu130; \
|
| 27 |
+
fi
|
| 28 |
+
|
| 29 |
+
ARG INSTALL_LLAMA_CPP_PYTHON=False
|
| 30 |
+
ENV INSTALL_LLAMA_CPP_PYTHON=${INSTALL_LLAMA_CPP_PYTHON}
|
| 31 |
+
|
| 32 |
+
# Llama CPP Python install requires CUDA 13.0
|
| 33 |
+
RUN if [ "$INSTALL_LLAMA_CPP_PYTHON" = "True" ]; then \
|
| 34 |
+
pip install --no-cache-dir --target=/install https://github.com/abetlen/llama-cpp-python/releases/download/v0.3.35-cu130/llama_cpp_python-0.3.36-py3-none-manylinux_2_35_x86_64.whl; \
|
| 35 |
+
fi
|
| 36 |
+
|
| 37 |
+
RUN pip install --no-cache-dir --target=/install -r requirements_lightweight.txt
|
| 38 |
+
|
| 39 |
+
RUN rm requirements_lightweight.txt
|
| 40 |
+
|
| 41 |
+
# ===================================================================
|
| 42 |
+
# Stage 2: A common 'base' for both Lambda and Gradio
|
| 43 |
+
# ===================================================================
|
| 44 |
+
FROM public.ecr.aws/docker/library/python:3.13.16-slim-trixie AS base
|
| 45 |
+
|
| 46 |
+
# Set build-time and runtime environment variable for whether to run in Gradio mode or Lambda mode
|
| 47 |
+
ARG APP_MODE=gradio
|
| 48 |
+
ENV APP_MODE=${APP_MODE}
|
| 49 |
+
|
| 50 |
+
# Install runtime system dependencies
|
| 51 |
+
RUN apt-get update && apt-get install -y --no-install-recommends \
|
| 52 |
+
libopenblas0 \
|
| 53 |
+
openssl \
|
| 54 |
+
libpcre2-8-0 \
|
| 55 |
+
&& apt-get upgrade -y openssl libpcre2-8-0 \
|
| 56 |
+
&& apt-get clean && rm -rf /var/lib/apt/lists/*
|
| 57 |
+
|
| 58 |
+
ENV APP_HOME=/home/user
|
| 59 |
+
|
| 60 |
+
# Set env variables for Gradio & other apps
|
| 61 |
+
# TLDEXTRACT_CACHE: Presidio email validation (read-only ECS root FS cannot use ~/.cache)
|
| 62 |
+
ENV GRADIO_TEMP_DIR=/tmp/gradio_tmp/ \
|
| 63 |
+
MPLCONFIGDIR=/tmp/matplotlib_cache/ \
|
| 64 |
+
TLDEXTRACT_CACHE=/tmp/tldextract_cache/ \
|
| 65 |
+
GRADIO_OUTPUT_FOLDER=$APP_HOME/app/output/ \
|
| 66 |
+
GRADIO_INPUT_FOLDER=$APP_HOME/app/input/ \
|
| 67 |
+
FEEDBACK_LOGS_FOLDER=$APP_HOME/app/feedback/ \
|
| 68 |
+
ACCESS_LOGS_FOLDER=$APP_HOME/app/logs/ \
|
| 69 |
+
USAGE_LOGS_FOLDER=$APP_HOME/app/usage/ \
|
| 70 |
+
CONFIG_FOLDER=$APP_HOME/app/config/ \
|
| 71 |
+
GRADIO_SERVER_NAME=0.0.0.0 \
|
| 72 |
+
GRADIO_SERVER_PORT=7860 \
|
| 73 |
+
PATH=$APP_HOME/.local/bin:$PATH \
|
| 74 |
+
PYTHONPATH=$APP_HOME/app \
|
| 75 |
+
PYTHONUNBUFFERED=1 \
|
| 76 |
+
PYTHONDONTWRITEBYTECODE=1 \
|
| 77 |
+
GRADIO_ALLOW_FLAGGING=never \
|
| 78 |
+
GRADIO_NUM_PORTS=1 \
|
| 79 |
+
GRADIO_THEME=huggingface \
|
| 80 |
+
SYSTEM=spaces
|
| 81 |
+
|
| 82 |
+
# Copy Python packages from the builder stage
|
| 83 |
+
COPY --from=builder /install /usr/local/lib/python3.13/site-packages/
|
| 84 |
+
COPY --from=builder /install/bin /usr/local/bin/
|
| 85 |
+
|
| 86 |
+
# Small English model for optional Presidio/spaCy PII redaction (emails/phones/numbers)
|
| 87 |
+
RUN python -m spacy download en_core_web_sm
|
| 88 |
+
|
| 89 |
+
# Copy your application code and entrypoint
|
| 90 |
+
COPY . ${APP_HOME}/app
|
| 91 |
+
COPY entrypoint.sh ${APP_HOME}/app/entrypoint.sh
|
| 92 |
+
# Fix line endings and set execute permissions
|
| 93 |
+
RUN sed -i 's/\r$//' ${APP_HOME}/app/entrypoint.sh \
|
| 94 |
+
&& chmod +x ${APP_HOME}/app/entrypoint.sh
|
| 95 |
+
|
| 96 |
+
WORKDIR ${APP_HOME}/app
|
| 97 |
+
|
| 98 |
+
# ===================================================================
|
| 99 |
+
# FINAL Stage 3: The Lambda Image (runs as root for simplicity)
|
| 100 |
+
# ===================================================================
|
| 101 |
+
FROM base AS lambda
|
| 102 |
+
# Set runtime ENV for Lambda mode
|
| 103 |
+
ENV APP_MODE=lambda
|
| 104 |
+
ENTRYPOINT ["/home/user/app/entrypoint.sh"]
|
| 105 |
+
CMD ["lambda_entrypoint.lambda_handler"]
|
| 106 |
+
|
| 107 |
+
# ===================================================================
|
| 108 |
+
# FINAL Stage 4: The Gradio Image (runs as a secure, non-root user)
|
| 109 |
+
# ===================================================================
|
| 110 |
+
FROM base AS gradio
|
| 111 |
+
# Set runtime ENV for Gradio mode
|
| 112 |
+
ENV APP_MODE=gradio
|
| 113 |
+
|
| 114 |
+
# Create non-root user
|
| 115 |
+
RUN useradd -m -u 1000 user
|
| 116 |
+
|
| 117 |
+
# Create the base application directory and set its ownership
|
| 118 |
+
RUN mkdir -p ${APP_HOME}/app && chown user:user ${APP_HOME}/app
|
| 119 |
+
|
| 120 |
+
# Create required sub-folders within the app directory and set their permissions
|
| 121 |
+
RUN mkdir -p \
|
| 122 |
+
${APP_HOME}/app/output \
|
| 123 |
+
${APP_HOME}/app/input \
|
| 124 |
+
${APP_HOME}/app/logs \
|
| 125 |
+
${APP_HOME}/app/usage \
|
| 126 |
+
${APP_HOME}/app/feedback \
|
| 127 |
+
${APP_HOME}/app/config \
|
| 128 |
+
&& chown user:user \
|
| 129 |
+
${APP_HOME}/app/output \
|
| 130 |
+
${APP_HOME}/app/input \
|
| 131 |
+
${APP_HOME}/app/logs \
|
| 132 |
+
${APP_HOME}/app/usage \
|
| 133 |
+
${APP_HOME}/app/feedback \
|
| 134 |
+
${APP_HOME}/app/config \
|
| 135 |
+
&& chmod 755 \
|
| 136 |
+
${APP_HOME}/app/output \
|
| 137 |
+
${APP_HOME}/app/input \
|
| 138 |
+
${APP_HOME}/app/logs \
|
| 139 |
+
${APP_HOME}/app/usage \
|
| 140 |
+
${APP_HOME}/app/feedback \
|
| 141 |
+
${APP_HOME}/app/config
|
| 142 |
+
|
| 143 |
+
# Now handle the /tmp directories
|
| 144 |
+
RUN mkdir -p /tmp/gradio_tmp /tmp/matplotlib_cache /tmp/tldextract_cache /tmp /var/tmp \
|
| 145 |
+
&& chown user:user /tmp /var/tmp /tmp/gradio_tmp /tmp/matplotlib_cache /tmp/tldextract_cache \
|
| 146 |
+
&& chmod 1777 /tmp /var/tmp /tmp/gradio_tmp /tmp/matplotlib_cache /tmp/tldextract_cache
|
| 147 |
+
|
| 148 |
+
# Fix apply user ownership to all files in the home directory
|
| 149 |
+
RUN chown -R user:user /home/user
|
| 150 |
+
|
| 151 |
+
# Set permissions for Python executable
|
| 152 |
+
RUN chmod 755 /usr/local/bin/python
|
| 153 |
+
|
| 154 |
+
# Declare volumes
|
| 155 |
+
VOLUME ["/tmp/matplotlib_cache"]
|
| 156 |
+
VOLUME ["/tmp/gradio_tmp"]
|
| 157 |
+
VOLUME ["/home/user/app/output"]
|
| 158 |
+
VOLUME ["/home/user/app/input"]
|
| 159 |
+
VOLUME ["/home/user/app/logs"]
|
| 160 |
+
VOLUME ["/home/user/app/usage"]
|
| 161 |
+
VOLUME ["/home/user/app/feedback"]
|
| 162 |
+
VOLUME ["/home/user/app/config"]
|
| 163 |
+
VOLUME ["/tmp"]
|
| 164 |
+
VOLUME ["/var/tmp"]
|
| 165 |
+
|
| 166 |
+
USER user
|
| 167 |
+
|
| 168 |
+
EXPOSE $GRADIO_SERVER_PORT
|
| 169 |
+
|
| 170 |
+
ENTRYPOINT ["/home/user/app/entrypoint.sh"]
|
| 171 |
+
CMD ["python", "app.py"]
|
LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
MIT License
|
| 2 |
+
|
| 3 |
+
Copyright (c) 2026 London Borough of Lambeth
|
| 4 |
+
|
| 5 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 6 |
+
of this software and associated documentation files (the "Software"), to deal
|
| 7 |
+
in the Software without restriction, including without limitation the rights
|
| 8 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 9 |
+
copies of the Software, and to permit persons to whom the Software is
|
| 10 |
+
furnished to do so, subject to the following conditions:
|
| 11 |
+
|
| 12 |
+
The above copyright notice and this permission notice shall be included in all
|
| 13 |
+
copies or substantial portions of the Software.
|
| 14 |
+
|
| 15 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 16 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 17 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 18 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 19 |
+
LIAB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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
title: Large language model topic modelling
|
| 3 |
+
emoji: 📚
|
| 4 |
+
colorFrom: purple
|
| 5 |
+
colorTo: yellow
|
| 6 |
+
sdk: gradio
|
| 7 |
+
sdk_version: 6.30.0
|
| 8 |
+
app_file: app.py
|
| 9 |
+
pinned: true
|
| 10 |
+
license: mit
|
| 11 |
+
short_description: Extract topics from open text data with LLMs
|
| 12 |
+
---
|
| 13 |
+
|
| 14 |
+
# Large language model topic modelling
|
| 15 |
+
|
| 16 |
+
Extract topics and summarise outputs using Large Language Models (LLMs), either local or cloud based (AWS, Azure, Gemini). 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 cloud services can be entered on the settings page.
|
| 17 |
+
|
| 18 |
+
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.
|
| 19 |
+
|
| 20 |
+
Basic use:
|
| 21 |
+
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.
|
| 22 |
+
1. Upload a csv/xlsx/parquet file containing at least one open text column.
|
| 23 |
+
2. Select the relevant open text column from the dropdown.
|
| 24 |
+
3. If you have your own suggested (zero shot) topics, upload this (see examples folder for an example file)
|
| 25 |
+
4. Write a one sentence description of the consultation/context of the open text.
|
| 26 |
+
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.
|
| 27 |
+
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.
|
| 28 |
+
|
| 29 |
+
### Optional: Amazon Bedrock Guardrails (AWS models)
|
| 30 |
+
|
| 31 |
+
When `RUN_AWS_BEDROCK_MODELS=1`, you can attach an existing Bedrock guardrail to every `Converse` call by setting variables in `config/app_config.env` (see `tools/config.py`):
|
| 32 |
+
|
| 33 |
+
- `ENABLE_BEDROCK_GUARDRAILS=True`
|
| 34 |
+
- `BEDROCK_GUARDRAIL_IDENTIFIER` — guardrail ID or ARN from the AWS console / CloudFormation output
|
| 35 |
+
- `BEDROCK_GUARDRAIL_VERSION` — published version number (not `DRAFT` in production)
|
| 36 |
+
- `BEDROCK_GUARDRAIL_TRACE` — `disabled`, `enabled`, or `enabled_full`. Defaults to **`enabled`** when `ENABLE_BEDROCK_GUARDRAILS` is true (so the **Guardrails interventions** sheet can list policy categories). Use `disabled` only if you do not want trace data returned from Bedrock.
|
| 37 |
+
|
| 38 |
+
The guardrail must be created in the **same AWS Region** as Bedrock model invocation (`AWS_REGION`). Content filters, denied topics, and PII actions are defined on that guardrail version in AWS; the app only passes ID and version. For topic modelling, avoid chatbot-style topic denies on citizen open text; prefer PII and harmful-content policies. Optional Presidio redaction (`ENABLE_INPUT_REDACTION`, `REDACTION_ENTITIES`) runs before prompts are built and can be kept aligned with the guardrail’s PII policy when you publish new guardrail versions.
|
| 39 |
+
|
| 40 |
+
**IAM:** The runtime role needs `bedrock:InvokeModel` (or inference-profile access) plus `bedrock:ApplyGuardrail` on the guardrail ARN. The ECS task role’s `AmazonBedrockLimitedAccess` managed policy may not include `ApplyGuardrail`; add a scoped inline policy via `POLICY_FILE_LOCATIONS` in CDK if Converse returns access denied.
|
| 41 |
+
|
| 42 |
+
Guardrails apply to **topic extraction and validation** Converse calls (raw response text). They are **not** attached for LLM topic deduplication, per-topic summarisation, or overall summary, which use aggregated topic tables rather than citizen verbatim text.
|
| 43 |
+
|
| 44 |
+
When a batch is blocked (`stopReason: guardrail_intervened`), topic extraction **continues** with other batches: affected responses get no assignments (they may appear under **Missing responses** in the workbook). If any batch was guardrail-blocked, the combined xlsx includes a **Guardrails interventions** sheet listing batch number, row range, task type, and intervention categories when guardrail tracing is enabled (`BEDROCK_GUARDRAIL_TRACE`).
|
| 45 |
+
|
| 46 |
+
# Installation guide
|
| 47 |
+
|
| 48 |
+
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.
|
| 49 |
+
|
| 50 |
+
-----
|
| 51 |
+
|
| 52 |
+
### Step 1: Clone the Git Repository
|
| 53 |
+
|
| 54 |
+
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.
|
| 55 |
+
|
| 56 |
+
1. **Clone the repo:**
|
| 57 |
+
|
| 58 |
+
```bash
|
| 59 |
+
git clone https://github.com/seanpedrick-case/llm_topic_modelling.git
|
| 60 |
+
```
|
| 61 |
+
|
| 62 |
+
2. **Navigate into the new project folder:**
|
| 63 |
+
|
| 64 |
+
```bash
|
| 65 |
+
cd llm_topic_modelling
|
| 66 |
+
```
|
| 67 |
+
-----
|
| 68 |
+
|
| 69 |
+
### Step 2: Create and Activate a Virtual Environment
|
| 70 |
+
|
| 71 |
+
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.
|
| 72 |
+
|
| 73 |
+
NOTE: Alternatively you could also create and activate a Conda environment instead of using venv below.
|
| 74 |
+
|
| 75 |
+
1. **Create the virtual environment:** We'll use Python's built-in `venv` module. It's common practice to name the environment folder `.venv`.
|
| 76 |
+
|
| 77 |
+
```bash
|
| 78 |
+
python -m venv .venv
|
| 79 |
+
```
|
| 80 |
+
|
| 81 |
+
*This command tells Python to create a new virtual environment in a folder named `.venv`.*
|
| 82 |
+
|
| 83 |
+
2. **Activate the environment:** You must "activate" the environment to start using it. The command differs based on your operating system and shell.
|
| 84 |
+
|
| 85 |
+
* **On macOS / Linux (bash/zsh):**
|
| 86 |
+
|
| 87 |
+
```bash
|
| 88 |
+
source .venv/bin/activate
|
| 89 |
+
```
|
| 90 |
+
|
| 91 |
+
* **On Windows (Command Prompt):**
|
| 92 |
+
|
| 93 |
+
```bash
|
| 94 |
+
.\.venv\Scripts\activate
|
| 95 |
+
```
|
| 96 |
+
|
| 97 |
+
* **On Windows (PowerShell):**
|
| 98 |
+
|
| 99 |
+
```powershell
|
| 100 |
+
.\.venv\Scripts\Activate.ps1
|
| 101 |
+
```
|
| 102 |
+
|
| 103 |
+
You'll know it's active because your command prompt will be prefixed with `(.venv)`.
|
| 104 |
+
|
| 105 |
+
-----
|
| 106 |
+
|
| 107 |
+
### Step 3: Install Dependencies
|
| 108 |
+
|
| 109 |
+
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.
|
| 110 |
+
|
| 111 |
+
1. **Install from pyproject.toml (recommended)**
|
| 112 |
+
|
| 113 |
+
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:
|
| 114 |
+
|
| 115 |
+
```bash
|
| 116 |
+
pip install .
|
| 117 |
+
```
|
| 118 |
+
|
| 119 |
+
#### Install torch (optional)
|
| 120 |
+
|
| 121 |
+
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:
|
| 122 |
+
|
| 123 |
+
```bash
|
| 124 |
+
pip install .[torch]
|
| 125 |
+
```
|
| 126 |
+
|
| 127 |
+
#### Install llama-cpp-python (optional)
|
| 128 |
+
|
| 129 |
+
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).
|
| 130 |
+
|
| 131 |
+
If you do want to install llama-cpp-python in app, first try the following command:
|
| 132 |
+
|
| 133 |
+
```bash
|
| 134 |
+
pip install .[llamacpp]
|
| 135 |
+
```
|
| 136 |
+
|
| 137 |
+
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
|
| 138 |
+
|
| 139 |
+
#### Install mcp version of gradio
|
| 140 |
+
|
| 141 |
+
You can install an mcp-compatible version of gradio for this app with the following command:
|
| 142 |
+
|
| 143 |
+
```bash
|
| 144 |
+
pip install .[mcp]
|
| 145 |
+
```
|
| 146 |
+
|
| 147 |
+
2. **Install from a requirements file (not recommended)**
|
| 148 |
+
|
| 149 |
+
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.
|
| 150 |
+
|
| 151 |
+
If you want to run models locally 'in app', then you have two further requirements files to choose from:
|
| 152 |
+
|
| 153 |
+
- **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!
|
| 154 |
+
- **requirements_gpu.txt**: Used for Python 3.11 GPU-enabled environments. Uncomment the requirements under 'Windows' for Windows compatibility (CUDA 12.4).
|
| 155 |
+
|
| 156 |
+
Example The below instructions will guide you in how to install the GPU-enabled version of the app for local inference.
|
| 157 |
+
|
| 158 |
+
**Install packages for local model 'in-app' inference from the requirements file:**
|
| 159 |
+
```bash
|
| 160 |
+
pip install -r requirements_gpu.txt
|
| 161 |
+
```
|
| 162 |
+
*This command reads every package name listed in the file and installs it into your `.venv` environment.*
|
| 163 |
+
|
| 164 |
+
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.
|
| 165 |
+
|
| 166 |
+
### Step 4: Verify CUDA compatibility (if using a GPU environment)
|
| 167 |
+
|
| 168 |
+
Install the relevant toolkit for CUDA from here: https://developer.nvidia.com/
|
| 169 |
+
|
| 170 |
+
Restart your computer
|
| 171 |
+
|
| 172 |
+
Ensure you have the latest drivers for your NVIDIA GPU. Check your current version and memory availability by running nvidia-smi
|
| 173 |
+
|
| 174 |
+
In command line, CUDA compatibility can be checked by running nvcc --version
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
### Step 5: Ensure you have compatible NVIDIA drivers
|
| 178 |
+
|
| 179 |
+
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
|
| 180 |
+
|
| 181 |
+
Current drivers can be found by running nvidia-smi in command line
|
| 182 |
+
|
| 183 |
+
### Step 6: Run the app
|
| 184 |
+
|
| 185 |
+
Go to the app project directory. Run python app.py
|
| 186 |
+
|
| 187 |
+
### Step 7: (optional) change default configuration
|
| 188 |
+
|
| 189 |
+
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,140 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
|
| 3 |
+
from aws_cdk import App, Environment
|
| 4 |
+
from cdk_application_tags import apply_application_tags_to_app
|
| 5 |
+
from cdk_appregistry import register_llm_topic_application
|
| 6 |
+
from cdk_config import (
|
| 7 |
+
ALB_NAME,
|
| 8 |
+
APPLICATION_NAME,
|
| 9 |
+
APPLICATION_REPOSITORY_URL,
|
| 10 |
+
APPLICATION_TAG_KEY,
|
| 11 |
+
APPREGISTRY_APPLICATION_NAME,
|
| 12 |
+
APPREGISTRY_ATTRIBUTE_GROUP_NAME,
|
| 13 |
+
APPREGISTRY_DESCRIPTION,
|
| 14 |
+
APPREGISTRY_REPOSITORY_URL,
|
| 15 |
+
APPREGISTRY_STACK_NAME,
|
| 16 |
+
AWS_ACCOUNT_ID,
|
| 17 |
+
AWS_REGION,
|
| 18 |
+
CDK_CONTEXT_FILE,
|
| 19 |
+
CDK_PREFIX,
|
| 20 |
+
ENABLE_APPREGISTRY,
|
| 21 |
+
RUN_USEAST_STACK,
|
| 22 |
+
USE_CLOUDFRONT,
|
| 23 |
+
)
|
| 24 |
+
from cdk_functions import (
|
| 25 |
+
create_basic_config_env,
|
| 26 |
+
is_resource_delete_protection_enabled,
|
| 27 |
+
load_context_from_file,
|
| 28 |
+
log_aws_credential_context,
|
| 29 |
+
purge_cdk_lookup_context,
|
| 30 |
+
)
|
| 31 |
+
from cdk_stack import CdkStack, CdkStackCloudfront # , CdkStackMain
|
| 32 |
+
from check_resources import CONTEXT_FILE, check_and_set_context
|
| 33 |
+
|
| 34 |
+
# Initialize the CDK app
|
| 35 |
+
app = App()
|
| 36 |
+
|
| 37 |
+
# Shared application tags on every CDK-managed resource (regional + CloudFront).
|
| 38 |
+
# Preferred over AppRegistry/myApplications for monitoring (AppRegistry new-customer
|
| 39 |
+
# cut-off 30 Jul 2026). Imported resources are not retagged.
|
| 40 |
+
apply_application_tags_to_app(
|
| 41 |
+
app,
|
| 42 |
+
tag_key=APPLICATION_TAG_KEY,
|
| 43 |
+
application_name=APPLICATION_NAME,
|
| 44 |
+
repository_url=APPLICATION_REPOSITORY_URL,
|
| 45 |
+
)
|
| 46 |
+
|
| 47 |
+
log_aws_credential_context(
|
| 48 |
+
expected_account_id=AWS_ACCOUNT_ID,
|
| 49 |
+
expected_region=AWS_REGION,
|
| 50 |
+
)
|
| 51 |
+
|
| 52 |
+
# Drop stale CDK lookup cache entries (require bootstrap lookup role in target account).
|
| 53 |
+
purge_cdk_lookup_context(CDK_CONTEXT_FILE)
|
| 54 |
+
|
| 55 |
+
# --- Pre-check context (boto3) — written to precheck.context.json, NOT cdk.context.json ---
|
| 56 |
+
print(f"Pre-check context file: {CONTEXT_FILE}")
|
| 57 |
+
print(f"CDK lookup cache file: {CDK_CONTEXT_FILE}")
|
| 58 |
+
if os.path.basename(CONTEXT_FILE.replace("\\", "/")) == os.path.basename(
|
| 59 |
+
CDK_CONTEXT_FILE.replace("\\", "/")
|
| 60 |
+
):
|
| 61 |
+
raise RuntimeError(
|
| 62 |
+
f"CONTEXT_FILE and CDK_CONTEXT_FILE must differ (got '{CONTEXT_FILE}' for both). "
|
| 63 |
+
"Set CONTEXT_FILE=precheck.context.json in config/cdk_config.env."
|
| 64 |
+
)
|
| 65 |
+
|
| 66 |
+
print("Running pre-check script to generate application context...")
|
| 67 |
+
try:
|
| 68 |
+
check_and_set_context()
|
| 69 |
+
if not os.path.exists(CONTEXT_FILE):
|
| 70 |
+
raise RuntimeError(
|
| 71 |
+
f"check_and_set_context() finished, but {CONTEXT_FILE} was not created."
|
| 72 |
+
)
|
| 73 |
+
print(f"Context generated successfully at {CONTEXT_FILE}.")
|
| 74 |
+
except Exception as e:
|
| 75 |
+
raise RuntimeError(f"Failed to generate context via check_and_set_context(): {e}")
|
| 76 |
+
|
| 77 |
+
# Pre-check must not repopulate CDK lookup keys; purge again if paths were ever shared.
|
| 78 |
+
purge_cdk_lookup_context(CDK_CONTEXT_FILE)
|
| 79 |
+
|
| 80 |
+
if os.path.exists(CONTEXT_FILE):
|
| 81 |
+
load_context_from_file(app, CONTEXT_FILE)
|
| 82 |
+
else:
|
| 83 |
+
raise RuntimeError(f"Could not find {CONTEXT_FILE}.")
|
| 84 |
+
|
| 85 |
+
create_basic_config_env("config")
|
| 86 |
+
|
| 87 |
+
aws_env_regional = Environment(account=AWS_ACCOUNT_ID, region=AWS_REGION)
|
| 88 |
+
|
| 89 |
+
_stack_delete_protection = is_resource_delete_protection_enabled()
|
| 90 |
+
|
| 91 |
+
regional_stack = CdkStack(
|
| 92 |
+
app, "SummarisationStack", env=aws_env_regional, cross_region_references=True
|
| 93 |
+
)
|
| 94 |
+
regional_stack.termination_protection = _stack_delete_protection
|
| 95 |
+
|
| 96 |
+
if ENABLE_APPREGISTRY == "True":
|
| 97 |
+
# Legacy Service Catalog AppRegistry / myApplications (opt-in).
|
| 98 |
+
# New AppRegistry customers cannot sign up after 30 Jul 2026; prefer
|
| 99 |
+
# APPLICATION_* tags + Resource Groups. Keep this path for existing users.
|
| 100 |
+
# Use pre-check context only — not regional_stack.params (avoids AppRegistry
|
| 101 |
+
# -> SummarisationStack dependency cycle during synth).
|
| 102 |
+
_alb_dns_context = app.node.try_get_context(f"dns:{ALB_NAME}")
|
| 103 |
+
_alb_dns_name = (
|
| 104 |
+
_alb_dns_context.strip()
|
| 105 |
+
if isinstance(_alb_dns_context, str) and _alb_dns_context.strip()
|
| 106 |
+
else None
|
| 107 |
+
)
|
| 108 |
+
appregistry_stack = register_llm_topic_application(
|
| 109 |
+
app,
|
| 110 |
+
aws_account_id=AWS_ACCOUNT_ID,
|
| 111 |
+
aws_region=AWS_REGION,
|
| 112 |
+
application_name=APPREGISTRY_APPLICATION_NAME,
|
| 113 |
+
application_description=APPREGISTRY_DESCRIPTION,
|
| 114 |
+
appregistry_stack_name=APPREGISTRY_STACK_NAME,
|
| 115 |
+
attribute_group_name=APPREGISTRY_ATTRIBUTE_GROUP_NAME,
|
| 116 |
+
repository_url=APPREGISTRY_REPOSITORY_URL,
|
| 117 |
+
cdk_prefix=CDK_PREFIX,
|
| 118 |
+
use_cloudfront=USE_CLOUDFRONT,
|
| 119 |
+
alb_dns_name=_alb_dns_name,
|
| 120 |
+
)
|
| 121 |
+
appregistry_stack.termination_protection = _stack_delete_protection
|
| 122 |
+
|
| 123 |
+
if USE_CLOUDFRONT == "True" and RUN_USEAST_STACK == "True":
|
| 124 |
+
aws_env_us_east_1 = Environment(account=AWS_ACCOUNT_ID, region="us-east-1")
|
| 125 |
+
|
| 126 |
+
cloudfront_stack = CdkStackCloudfront(
|
| 127 |
+
app,
|
| 128 |
+
"SummarisationStackCloudfront",
|
| 129 |
+
env=aws_env_us_east_1,
|
| 130 |
+
alb_arn=regional_stack.params["alb_arn_output"],
|
| 131 |
+
alb_sec_group_id=regional_stack.params["alb_security_group_id"],
|
| 132 |
+
alb_dns_name=regional_stack.params["alb_dns_name"],
|
| 133 |
+
cross_region_references=True,
|
| 134 |
+
)
|
| 135 |
+
cloudfront_stack.termination_protection = _stack_delete_protection
|
| 136 |
+
|
| 137 |
+
# CDK CLI invokes this script and expects a cloud assembly in cdk.out.
|
| 138 |
+
# Without app.synth(), Python defines constructs but never writes manifest.json
|
| 139 |
+
# (ENOENT on deploy). See: https://github.com/aws/aws-cdk/issues/11023
|
| 140 |
+
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_application_tags.py
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Application tagging helpers and tag-based AWS Resource Groups."""
|
| 2 |
+
|
| 3 |
+
from typing import Optional
|
| 4 |
+
|
| 5 |
+
from aws_cdk import CfnOutput, CfnTag, Tags
|
| 6 |
+
from aws_cdk import aws_resourcegroups as resourcegroups
|
| 7 |
+
from constructs import Construct
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def apply_application_tags_to_app(
|
| 11 |
+
app: Construct,
|
| 12 |
+
*,
|
| 13 |
+
tag_key: str,
|
| 14 |
+
application_name: str,
|
| 15 |
+
repository_url: str,
|
| 16 |
+
) -> None:
|
| 17 |
+
"""
|
| 18 |
+
Tag all CDK-managed resources under ``app`` with a shared application identity.
|
| 19 |
+
|
| 20 |
+
Imported / looked-up resources (existing VPC, buckets, etc.) are not retagged
|
| 21 |
+
in AWS; only resources created by this CDK app receive the tags.
|
| 22 |
+
"""
|
| 23 |
+
key = (tag_key or "Application").strip() or "Application"
|
| 24 |
+
name = (application_name or "").strip()
|
| 25 |
+
if not name:
|
| 26 |
+
raise ValueError("application_name is required for application tags.")
|
| 27 |
+
Tags.of(app).add(key, name)
|
| 28 |
+
Tags.of(app).add("ManagedBy", "cdk")
|
| 29 |
+
repo = (repository_url or "").strip()
|
| 30 |
+
if repo:
|
| 31 |
+
Tags.of(app).add("Repository", repo)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def create_application_resource_group(
|
| 35 |
+
scope: Construct,
|
| 36 |
+
logical_id: str,
|
| 37 |
+
*,
|
| 38 |
+
group_name: str,
|
| 39 |
+
tag_key: str,
|
| 40 |
+
application_name: str,
|
| 41 |
+
description: Optional[str] = None,
|
| 42 |
+
) -> resourcegroups.CfnGroup:
|
| 43 |
+
"""
|
| 44 |
+
Create a tag-based Resource Group for inventory/monitoring without AppRegistry.
|
| 45 |
+
|
| 46 |
+
Members are all resources in the account/region that carry ``tag_key=application_name``.
|
| 47 |
+
"""
|
| 48 |
+
key = (tag_key or "Application").strip() or "Application"
|
| 49 |
+
name = (application_name or "").strip()
|
| 50 |
+
group = (group_name or "").strip()
|
| 51 |
+
if not name:
|
| 52 |
+
raise ValueError("application_name is required for the Resource Group.")
|
| 53 |
+
if not group:
|
| 54 |
+
raise ValueError("group_name is required for the Resource Group.")
|
| 55 |
+
|
| 56 |
+
cfn_group = resourcegroups.CfnGroup(
|
| 57 |
+
scope,
|
| 58 |
+
logical_id,
|
| 59 |
+
name=group,
|
| 60 |
+
description=description
|
| 61 |
+
or (
|
| 62 |
+
f"Tag-based group for {name} "
|
| 63 |
+
f"filter {key} {name}. Prefer over AppRegistry after Jul 2026."
|
| 64 |
+
),
|
| 65 |
+
resource_query=resourcegroups.CfnGroup.ResourceQueryProperty(
|
| 66 |
+
type="TAG_FILTERS_1_0",
|
| 67 |
+
query=resourcegroups.CfnGroup.QueryProperty(
|
| 68 |
+
resource_type_filters=["AWS::AllSupported"],
|
| 69 |
+
tag_filters=[
|
| 70 |
+
resourcegroups.CfnGroup.TagFilterProperty(
|
| 71 |
+
key=key,
|
| 72 |
+
values=[name],
|
| 73 |
+
)
|
| 74 |
+
],
|
| 75 |
+
),
|
| 76 |
+
),
|
| 77 |
+
tags=[
|
| 78 |
+
CfnTag(key=key, value=name),
|
| 79 |
+
CfnTag(key="ManagedBy", value="cdk"),
|
| 80 |
+
],
|
| 81 |
+
)
|
| 82 |
+
|
| 83 |
+
CfnOutput(
|
| 84 |
+
scope,
|
| 85 |
+
f"{logical_id}Name",
|
| 86 |
+
value=cfn_group.name,
|
| 87 |
+
description="AWS Resource Groups name for this application's tagged resources",
|
| 88 |
+
)
|
| 89 |
+
CfnOutput(
|
| 90 |
+
scope,
|
| 91 |
+
f"{logical_id}Arn",
|
| 92 |
+
value=cfn_group.attr_arn,
|
| 93 |
+
description="AWS Resource Groups ARN for this application's tagged resources",
|
| 94 |
+
)
|
| 95 |
+
return cfn_group
|
cdk/cdk_appregistry.py
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Legacy AWS Console myApplications (Service Catalog AppRegistry) integration.
|
| 2 |
+
|
| 3 |
+
Opt-in only (ENABLE_APPREGISTRY=True). Preferred monitoring uses application tags
|
| 4 |
+
and AWS Resource Groups (see cdk_application_tags.py). AppRegistry closes to new
|
| 5 |
+
customers after 30 July 2026.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from aws_cdk import App, Environment
|
| 9 |
+
from aws_cdk.aws_servicecatalogappregistry_alpha import (
|
| 10 |
+
ApplicationAssociator,
|
| 11 |
+
TargetApplication,
|
| 12 |
+
)
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def register_llm_topic_application(
|
| 16 |
+
app: App,
|
| 17 |
+
*,
|
| 18 |
+
aws_account_id: str,
|
| 19 |
+
aws_region: str,
|
| 20 |
+
application_name: str,
|
| 21 |
+
application_description: str,
|
| 22 |
+
appregistry_stack_name: str,
|
| 23 |
+
attribute_group_name: str,
|
| 24 |
+
repository_url: str,
|
| 25 |
+
cdk_prefix: str,
|
| 26 |
+
use_cloudfront: str,
|
| 27 |
+
alb_dns_name: str | None = None,
|
| 28 |
+
) -> ApplicationAssociator:
|
| 29 |
+
"""
|
| 30 |
+
Register regional CDK stacks with AWS Console myApplications.
|
| 31 |
+
|
| 32 |
+
Only stacks in ``aws_region`` are associated (phase 1). Cross-region stacks
|
| 33 |
+
such as SummarisationStackCloudfront (us-east-1) are not included.
|
| 34 |
+
|
| 35 |
+
``alb_dns_name`` must be a plain string (e.g. from pre-check context). Do not
|
| 36 |
+
pass a CloudFormation token from SummarisationStack or synth will fail with a
|
| 37 |
+
dependency cycle against the associator stack.
|
| 38 |
+
"""
|
| 39 |
+
associator = ApplicationAssociator(
|
| 40 |
+
app,
|
| 41 |
+
"SummarisationAppRegistry",
|
| 42 |
+
applications=[
|
| 43 |
+
TargetApplication.create_application_stack(
|
| 44 |
+
application_name=application_name,
|
| 45 |
+
application_description=application_description,
|
| 46 |
+
stack_name=appregistry_stack_name,
|
| 47 |
+
env=Environment(account=aws_account_id, region=aws_region),
|
| 48 |
+
)
|
| 49 |
+
],
|
| 50 |
+
)
|
| 51 |
+
|
| 52 |
+
attributes = {
|
| 53 |
+
"repository": repository_url,
|
| 54 |
+
"cdkPrefix": cdk_prefix,
|
| 55 |
+
"awsRegion": aws_region,
|
| 56 |
+
"useCloudFront": use_cloudfront,
|
| 57 |
+
"cloudFrontInAppRegistry": "false",
|
| 58 |
+
"cloudFrontNote": (
|
| 59 |
+
"CloudFront/WAF (SummarisationStackCloudfront) is in us-east-1 and is "
|
| 60 |
+
"not linked to this myApplications entry in phase 1. View it in "
|
| 61 |
+
"CloudFormation (us-east-1) or the CloudFront console."
|
| 62 |
+
),
|
| 63 |
+
}
|
| 64 |
+
if alb_dns_name:
|
| 65 |
+
attributes["albDnsName"] = alb_dns_name
|
| 66 |
+
|
| 67 |
+
associator.app_registry_application.add_attribute_group(
|
| 68 |
+
"SummarisationAttributeGroup",
|
| 69 |
+
attribute_group_name=attribute_group_name,
|
| 70 |
+
description="llm_topic_modeller deployment metadata",
|
| 71 |
+
attributes=attributes,
|
| 72 |
+
)
|
| 73 |
+
|
| 74 |
+
return associator
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def register_doc_summarisation_application(*args, **kwargs):
|
| 78 |
+
"""Deprecated alias for register_llm_topic_application."""
|
| 79 |
+
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,916 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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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 |
+
# Application tagging + Resource Groups (preferred monitoring model).
|
| 126 |
+
# AppRegistry / myApplications closes to new customers after 30 Jul 2026;
|
| 127 |
+
# use these tags and a tag-based Resource Group instead.
|
| 128 |
+
APPLICATION_TAG_KEY = get_or_create_env_var("APPLICATION_TAG_KEY", "Application")
|
| 129 |
+
APPLICATION_NAME = get_or_create_env_var(
|
| 130 |
+
"APPLICATION_NAME", f"{CDK_PREFIX}llm-topic-modeller"
|
| 131 |
+
)
|
| 132 |
+
APPLICATION_REPOSITORY_URL = get_or_create_env_var(
|
| 133 |
+
"APPLICATION_REPOSITORY_URL",
|
| 134 |
+
"https://github.com/seanpedrick-case/llm_topic_modelling.git",
|
| 135 |
+
)
|
| 136 |
+
ENABLE_APPLICATION_RESOURCE_GROUP = get_or_create_env_var(
|
| 137 |
+
"ENABLE_APPLICATION_RESOURCE_GROUP", "True"
|
| 138 |
+
)
|
| 139 |
+
APPLICATION_RESOURCE_GROUP_NAME = get_or_create_env_var(
|
| 140 |
+
"APPLICATION_RESOURCE_GROUP_NAME", f"{APPLICATION_NAME}-resources"
|
| 141 |
+
)
|
| 142 |
+
|
| 143 |
+
# Legacy AWS Console myApplications (Service Catalog AppRegistry) — opt-in only.
|
| 144 |
+
# New AppRegistry customers cannot sign up after 30 Jul 2026; existing customers
|
| 145 |
+
# may keep using it. Prefer APPLICATION_* tags + Resource Groups above.
|
| 146 |
+
ENABLE_APPREGISTRY = get_or_create_env_var("ENABLE_APPREGISTRY", "False")
|
| 147 |
+
APPREGISTRY_APPLICATION_NAME = get_or_create_env_var(
|
| 148 |
+
"APPREGISTRY_APPLICATION_NAME", APPLICATION_NAME
|
| 149 |
+
)
|
| 150 |
+
APPREGISTRY_DESCRIPTION = get_or_create_env_var(
|
| 151 |
+
"APPREGISTRY_DESCRIPTION",
|
| 152 |
+
"LLM topic modelling app (ALB, ECS Fargate, Cognito, S3)",
|
| 153 |
+
)
|
| 154 |
+
APPREGISTRY_STACK_NAME = get_or_create_env_var(
|
| 155 |
+
"APPREGISTRY_STACK_NAME", f"{CDK_PREFIX}AppRegistryStack"
|
| 156 |
+
)
|
| 157 |
+
APPREGISTRY_ATTRIBUTE_GROUP_NAME = get_or_create_env_var(
|
| 158 |
+
"APPREGISTRY_ATTRIBUTE_GROUP_NAME",
|
| 159 |
+
f"{APPREGISTRY_APPLICATION_NAME}-metadata",
|
| 160 |
+
)
|
| 161 |
+
APPREGISTRY_REPOSITORY_URL = get_or_create_env_var(
|
| 162 |
+
"APPREGISTRY_REPOSITORY_URL",
|
| 163 |
+
APPLICATION_REPOSITORY_URL,
|
| 164 |
+
)
|
| 165 |
+
|
| 166 |
+
_precheck_context_file = get_or_create_env_var("CONTEXT_FILE", "precheck.context.json")
|
| 167 |
+
# Never write boto3 pre-check output into CDK's lookup cache file (causes stale
|
| 168 |
+
# vpc-provider / load-balancer entries and wrong-account lookup validation errors).
|
| 169 |
+
if os.path.basename(_precheck_context_file.replace("\\", "/")) == "cdk.context.json":
|
| 170 |
+
print(
|
| 171 |
+
"WARNING: CONTEXT_FILE must not be 'cdk.context.json' (that file is CDK's "
|
| 172 |
+
"lookup cache). Using 'precheck.context.json' instead. Update "
|
| 173 |
+
"config/cdk_config.env and remove CONTEXT_FILE=cdk.context.json if set."
|
| 174 |
+
)
|
| 175 |
+
_precheck_context_file = "precheck.context.json"
|
| 176 |
+
CONTEXT_FILE = _precheck_context_file
|
| 177 |
+
CDK_CONTEXT_FILE = get_or_create_env_var("CDK_CONTEXT_FILE", "cdk.context.json")
|
| 178 |
+
CDK_FOLDER = get_or_create_env_var(
|
| 179 |
+
"CDK_FOLDER", ""
|
| 180 |
+
) # FULL_PATH_TO_CDK_FOLDER_HERE (with forward slash)
|
| 181 |
+
|
| 182 |
+
# App runtime config (uploaded to S3 for legacy Fargate; inlined for ECS Express Mode)
|
| 183 |
+
APP_CONFIG_ENV_BASENAME = "app_config.env"
|
| 184 |
+
_app_config_rel = os.path.join(CONFIG_FOLDER, APP_CONFIG_ENV_BASENAME).replace(
|
| 185 |
+
"\\", "/"
|
| 186 |
+
)
|
| 187 |
+
APP_CONFIG_ENV_FILE = get_or_create_env_var(
|
| 188 |
+
"APP_CONFIG_ENV_FILE",
|
| 189 |
+
(
|
| 190 |
+
os.path.normpath(os.path.join(CDK_FOLDER, _app_config_rel))
|
| 191 |
+
if CDK_FOLDER
|
| 192 |
+
else os.path.normpath(_app_config_rel)
|
| 193 |
+
),
|
| 194 |
+
)
|
| 195 |
+
RUN_USEAST_STACK = get_or_create_env_var("RUN_USEAST_STACK", "False")
|
| 196 |
+
|
| 197 |
+
### VPC and connections
|
| 198 |
+
VPC_NAME = get_or_create_env_var("VPC_NAME", "")
|
| 199 |
+
NEW_VPC_DEFAULT_NAME = get_or_create_env_var("NEW_VPC_DEFAULT_NAME", f"{CDK_PREFIX}vpc")
|
| 200 |
+
NEW_VPC_CIDR = get_or_create_env_var("NEW_VPC_CIDR", "") # "10.0.0.0/24"
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
# Internet Gateway for legacy VPC public subnets (attach + 0.0.0.0/0 routes via CDK when missing).
|
| 204 |
+
EXISTING_IGW_ID = get_or_create_env_var("EXISTING_IGW_ID", "")
|
| 205 |
+
SINGLE_NAT_GATEWAY_ID = get_or_create_env_var("SINGLE_NAT_GATEWAY_ID", "")
|
| 206 |
+
|
| 207 |
+
### SUBNETS / ROUTE TABLES / NAT GATEWAY
|
| 208 |
+
PUBLIC_SUBNETS_TO_USE = get_or_create_env_var(
|
| 209 |
+
"PUBLIC_SUBNETS_TO_USE", ""
|
| 210 |
+
) # e.g. ['PublicSubnet1', 'PublicSubnet2']
|
| 211 |
+
PUBLIC_SUBNET_CIDR_BLOCKS = get_or_create_env_var(
|
| 212 |
+
"PUBLIC_SUBNET_CIDR_BLOCKS", ""
|
| 213 |
+
) # e.g. ["10.0.1.0/24", "10.0.2.0/24"]
|
| 214 |
+
PUBLIC_SUBNET_AVAILABILITY_ZONES = get_or_create_env_var(
|
| 215 |
+
"PUBLIC_SUBNET_AVAILABILITY_ZONES", ""
|
| 216 |
+
) # e.g. ["eu-east-1b", "eu-east1b"]
|
| 217 |
+
|
| 218 |
+
PRIVATE_SUBNETS_TO_USE = get_or_create_env_var(
|
| 219 |
+
"PRIVATE_SUBNETS_TO_USE", ""
|
| 220 |
+
) # e.g. ['PrivateSubnet1', 'PrivateSubnet2']
|
| 221 |
+
PRIVATE_SUBNET_CIDR_BLOCKS = get_or_create_env_var(
|
| 222 |
+
"PRIVATE_SUBNET_CIDR_BLOCKS", ""
|
| 223 |
+
) # e.g. ["10.0.1.0/24", "10.0.2.0/24"]
|
| 224 |
+
PRIVATE_SUBNET_AVAILABILITY_ZONES = get_or_create_env_var(
|
| 225 |
+
"PRIVATE_SUBNET_AVAILABILITY_ZONES", ""
|
| 226 |
+
) # e.g. ["eu-east-1b", "eu-east1b"]
|
| 227 |
+
|
| 228 |
+
ROUTE_TABLE_BASE_NAME = get_or_create_env_var(
|
| 229 |
+
"ROUTE_TABLE_BASE_NAME", f"{CDK_PREFIX}PrivateRouteTable"
|
| 230 |
+
)
|
| 231 |
+
NAT_GATEWAY_EIP_NAME = get_or_create_env_var(
|
| 232 |
+
"NAT_GATEWAY_EIP_NAME", f"{CDK_PREFIX}NatGatewayEip"
|
| 233 |
+
)
|
| 234 |
+
NAT_GATEWAY_NAME = get_or_create_env_var("NAT_GATEWAY_NAME", f"{CDK_PREFIX}NatGateway")
|
| 235 |
+
|
| 236 |
+
# IAM roles — managed policy *names* (AWS managed) and JSON policy *files* (inline statements)
|
| 237 |
+
# Bedrock Guardrails (ENABLE_BEDROCK_GUARDRAILS in app config): task role may need
|
| 238 |
+
# bedrock:ApplyGuardrail on the guardrail ARN in the same Region as Converse; add via
|
| 239 |
+
# POLICY_FILE_LOCATIONS if AmazonBedrockLimitedAccess is insufficient.
|
| 240 |
+
AWS_MANAGED_TASK_ROLES_LIST = get_or_create_env_var(
|
| 241 |
+
"AWS_MANAGED_TASK_ROLES_LIST",
|
| 242 |
+
'["AmazonCognitoReadOnly", "service-role/AmazonECSTaskExecutionRolePolicy", "AmazonDynamoDBFullAccess", "service-role/AWSAppSyncPushToCloudWatchLogs", "AmazonBedrockLimitedAccess"]',
|
| 243 |
+
)
|
| 244 |
+
ECS_EXECUTION_ROLE_MANAGED_POLICIES = get_or_create_env_var(
|
| 245 |
+
"ECS_EXECUTION_ROLE_MANAGED_POLICIES",
|
| 246 |
+
'["service-role/AmazonECSTaskExecutionRolePolicy"]',
|
| 247 |
+
)
|
| 248 |
+
# JSON IAM policy document paths (relative to CDK_FOLDER or absolute). Task role = app runtime.
|
| 249 |
+
POLICY_FILE_LOCATIONS = get_or_create_env_var(
|
| 250 |
+
"POLICY_FILE_LOCATIONS",
|
| 251 |
+
"[]",
|
| 252 |
+
)
|
| 253 |
+
# Optional extra JSON policies for the ECS task *execution* role (image pull / logs / secrets).
|
| 254 |
+
ECS_EXECUTION_ROLE_POLICY_FILES = get_or_create_env_var(
|
| 255 |
+
"ECS_EXECUTION_ROLE_POLICY_FILES",
|
| 256 |
+
"",
|
| 257 |
+
)
|
| 258 |
+
# Customer-managed policy ARNs (full ARN per entry), attached in addition to the lists above.
|
| 259 |
+
POLICY_FILE_ARNS = get_or_create_env_var("POLICY_FILE_ARNS", "")
|
| 260 |
+
ECS_EXECUTION_ROLE_POLICY_ARNS = get_or_create_env_var(
|
| 261 |
+
"ECS_EXECUTION_ROLE_POLICY_ARNS", ""
|
| 262 |
+
)
|
| 263 |
+
|
| 264 |
+
AWS_MANAGED_TASK_ROLES_LIST = parse_comma_separated_list(AWS_MANAGED_TASK_ROLES_LIST)
|
| 265 |
+
ECS_EXECUTION_ROLE_MANAGED_POLICIES = parse_comma_separated_list(
|
| 266 |
+
ECS_EXECUTION_ROLE_MANAGED_POLICIES
|
| 267 |
+
)
|
| 268 |
+
POLICY_FILE_LOCATIONS = parse_comma_separated_list(POLICY_FILE_LOCATIONS)
|
| 269 |
+
ECS_EXECUTION_ROLE_POLICY_FILES = parse_comma_separated_list(
|
| 270 |
+
ECS_EXECUTION_ROLE_POLICY_FILES
|
| 271 |
+
)
|
| 272 |
+
POLICY_FILE_ARNS = parse_comma_separated_list(POLICY_FILE_ARNS)
|
| 273 |
+
ECS_EXECUTION_ROLE_POLICY_ARNS = parse_comma_separated_list(
|
| 274 |
+
ECS_EXECUTION_ROLE_POLICY_ARNS
|
| 275 |
+
)
|
| 276 |
+
|
| 277 |
+
# GITHUB REPO
|
| 278 |
+
GITHUB_REPO_USERNAME = get_or_create_env_var("GITHUB_REPO_USERNAME", "seanpedrick-case")
|
| 279 |
+
GITHUB_REPO_NAME = get_or_create_env_var("GITHUB_REPO_NAME", "llm_topic_modeller")
|
| 280 |
+
GITHUB_REPO_BRANCH = get_or_create_env_var("GITHUB_REPO_BRANCH", "main")
|
| 281 |
+
|
| 282 |
+
### CODEBUILD
|
| 283 |
+
CODEBUILD_ROLE_NAME = get_or_create_env_var(
|
| 284 |
+
"CODEBUILD_ROLE_NAME", f"{CDK_PREFIX}CodeBuildRole"
|
| 285 |
+
)
|
| 286 |
+
CODEBUILD_PROJECT_NAME = get_or_create_env_var(
|
| 287 |
+
"CODEBUILD_PROJECT_NAME", f"{CDK_PREFIX}CodeBuildProject"
|
| 288 |
+
)
|
| 289 |
+
|
| 290 |
+
### ECR
|
| 291 |
+
ECR_REPO_NAME = get_or_create_env_var(
|
| 292 |
+
"ECR_REPO_NAME", "llm-topic-modeller"
|
| 293 |
+
) # Beware - cannot have underscores and must be lower case
|
| 294 |
+
ECR_CDK_REPO_NAME = get_or_create_env_var(
|
| 295 |
+
"ECR_CDK_REPO_NAME", f"{CDK_PREFIX}{ECR_REPO_NAME}".lower()
|
| 296 |
+
)
|
| 297 |
+
|
| 298 |
+
|
| 299 |
+
### S3
|
| 300 |
+
def _resolve_s3_bucket_name(env_key: str, suffix: str) -> str:
|
| 301 |
+
"""
|
| 302 |
+
Bucket name default is ``{CDK_PREFIX}{suffix}`` (lowercase).
|
| 303 |
+
|
| 304 |
+
If an earlier import cached a bare ``suffix`` in ``os.environ`` before
|
| 305 |
+
``CDK_PREFIX`` was loaded from dotenv, upgrade it to the prefixed name.
|
| 306 |
+
"""
|
| 307 |
+
prefix = (os.environ.get("CDK_PREFIX") or "").lower()
|
| 308 |
+
default = f"{prefix}{suffix}"
|
| 309 |
+
value = get_or_create_env_var(env_key, default)
|
| 310 |
+
if prefix and value == suffix:
|
| 311 |
+
os.environ[env_key] = default
|
| 312 |
+
return default
|
| 313 |
+
return value
|
| 314 |
+
|
| 315 |
+
|
| 316 |
+
S3_LOG_CONFIG_BUCKET_NAME = _resolve_s3_bucket_name(
|
| 317 |
+
"S3_LOG_CONFIG_BUCKET_NAME", "s3-logs"
|
| 318 |
+
) # S3 bucket names need to be lower case
|
| 319 |
+
S3_OUTPUT_BUCKET_NAME = _resolve_s3_bucket_name("S3_OUTPUT_BUCKET_NAME", "s3-output")
|
| 320 |
+
|
| 321 |
+
### VPC endpoints for ECS tasks in private subnets (ECR image pull, logs, secrets)
|
| 322 |
+
ENABLE_ECS_VPC_INTERFACE_ENDPOINTS = get_or_create_env_var(
|
| 323 |
+
"ENABLE_ECS_VPC_INTERFACE_ENDPOINTS", "True"
|
| 324 |
+
)
|
| 325 |
+
|
| 326 |
+
### KMS KEYS FOR S3 AND SECRETS MANAGER
|
| 327 |
+
USE_CUSTOM_KMS_KEY = get_or_create_env_var("USE_CUSTOM_KMS_KEY", "1")
|
| 328 |
+
CUSTOM_KMS_KEY_NAME = get_or_create_env_var(
|
| 329 |
+
"CUSTOM_KMS_KEY_NAME", f"alias/{CDK_PREFIX}kms-key".lower()
|
| 330 |
+
)
|
| 331 |
+
|
| 332 |
+
### ECS
|
| 333 |
+
FARGATE_TASK_DEFINITION_NAME = get_or_create_env_var(
|
| 334 |
+
"FARGATE_TASK_DEFINITION_NAME", f"{CDK_PREFIX}FargateTaskDefinition"
|
| 335 |
+
)
|
| 336 |
+
TASK_DEFINITION_FILE_LOCATION = get_or_create_env_var(
|
| 337 |
+
"TASK_DEFINITION_FILE_LOCATION", CDK_FOLDER + CONFIG_FOLDER + "task_definition.json"
|
| 338 |
+
)
|
| 339 |
+
|
| 340 |
+
CLUSTER_NAME = get_or_create_env_var("CLUSTER_NAME", f"{CDK_PREFIX}Cluster")
|
| 341 |
+
ECS_SERVICE_NAME = get_or_create_env_var("ECS_SERVICE_NAME", f"{CDK_PREFIX}ECSService")
|
| 342 |
+
# Second Fargate service when ENABLE_PI_AGENT_ECS_SERVICE=True (legacy path only).
|
| 343 |
+
ECS_PI_SERVICE_NAME = get_or_create_env_var(
|
| 344 |
+
"ECS_PI_SERVICE_NAME", f"{CDK_PREFIX}PiAgentService"
|
| 345 |
+
)
|
| 346 |
+
ECS_TASK_ROLE_NAME = get_or_create_env_var(
|
| 347 |
+
"ECS_TASK_ROLE_NAME", f"{CDK_PREFIX}TaskRole"
|
| 348 |
+
)
|
| 349 |
+
ECS_TASK_EXECUTION_ROLE_NAME = get_or_create_env_var(
|
| 350 |
+
"ECS_TASK_EXECUTION_ROLE_NAME", f"{CDK_PREFIX}ExecutionRole"
|
| 351 |
+
)
|
| 352 |
+
ECS_SECURITY_GROUP_NAME = get_or_create_env_var(
|
| 353 |
+
"ECS_SECURITY_GROUP_NAME", f"{CDK_PREFIX}SecurityGroupECS"
|
| 354 |
+
)
|
| 355 |
+
ECS_LOG_GROUP_NAME = get_or_create_env_var(
|
| 356 |
+
"ECS_LOG_GROUP_NAME", f"/ecs/{ECS_SERVICE_NAME}-logs".lower()
|
| 357 |
+
)
|
| 358 |
+
|
| 359 |
+
ECS_TASK_CPU_SIZE = get_or_create_env_var("ECS_TASK_CPU_SIZE", "1024")
|
| 360 |
+
ECS_TASK_MEMORY_SIZE = get_or_create_env_var("ECS_TASK_MEMORY_SIZE", "4096")
|
| 361 |
+
ECS_USE_FARGATE_SPOT = get_or_create_env_var("USE_FARGATE_SPOT", "False")
|
| 362 |
+
ECS_READ_ONLY_FILE_SYSTEM = get_or_create_env_var("ECS_READ_ONLY_FILE_SYSTEM", "True")
|
| 363 |
+
# ECS service AZ rebalancing (AWS defaults new services to ENABLED if omitted).
|
| 364 |
+
ECS_AVAILABILITY_ZONE_REBALANCING = get_or_create_env_var(
|
| 365 |
+
"ECS_AVAILABILITY_ZONE_REBALANCING", "DISABLED"
|
| 366 |
+
)
|
| 367 |
+
if ECS_AVAILABILITY_ZONE_REBALANCING not in ("ENABLED", "DISABLED"):
|
| 368 |
+
raise ValueError(
|
| 369 |
+
"ECS_AVAILABILITY_ZONE_REBALANCING must be ENABLED or DISABLED "
|
| 370 |
+
f"(got {ECS_AVAILABILITY_ZONE_REBALANCING!r})."
|
| 371 |
+
)
|
| 372 |
+
|
| 373 |
+
### Cognito
|
| 374 |
+
COGNITO_USER_POOL_NAME = get_or_create_env_var(
|
| 375 |
+
"COGNITO_USER_POOL_NAME", f"{CDK_PREFIX}UserPool"
|
| 376 |
+
)
|
| 377 |
+
COGNITO_USER_POOL_CLIENT_NAME = get_or_create_env_var(
|
| 378 |
+
"COGNITO_USER_POOL_CLIENT_NAME", f"{CDK_PREFIX}UserPoolClient"
|
| 379 |
+
)
|
| 380 |
+
COGNITO_USER_POOL_CLIENT_SECRET_NAME = get_or_create_env_var(
|
| 381 |
+
"COGNITO_USER_POOL_CLIENT_SECRET_NAME", f"{CDK_PREFIX}ParamCognitoSecret"
|
| 382 |
+
)
|
| 383 |
+
COGNITO_USER_POOL_DOMAIN_PREFIX = get_or_create_env_var(
|
| 384 |
+
"COGNITO_USER_POOL_DOMAIN_PREFIX", "llm-topic-app-domain"
|
| 385 |
+
) # Should change this to something unique or you'll probably hit an error
|
| 386 |
+
|
| 387 |
+
COGNITO_REFRESH_TOKEN_VALIDITY = int(
|
| 388 |
+
get_or_create_env_var("COGNITO_REFRESH_TOKEN_VALIDITY", "480")
|
| 389 |
+
) # Minutes
|
| 390 |
+
COGNITO_ID_TOKEN_VALIDITY = int(
|
| 391 |
+
get_or_create_env_var("COGNITO_ID_TOKEN_VALIDITY", "60")
|
| 392 |
+
) # Minutes
|
| 393 |
+
COGNITO_ACCESS_TOKEN_VALIDITY = int(
|
| 394 |
+
get_or_create_env_var("COGNITO_ACCESS_TOKEN_VALIDITY", "60")
|
| 395 |
+
) # Minutes
|
| 396 |
+
|
| 397 |
+
# Application load balancer
|
| 398 |
+
ALB_NAME = get_or_create_env_var(
|
| 399 |
+
"ALB_NAME", f"{CDK_PREFIX}Alb"[-32:]
|
| 400 |
+
) # Application load balancer name can be max 32 characters, so taking the last 32 characters of the suggested name
|
| 401 |
+
ALB_NAME_SECURITY_GROUP_NAME = get_or_create_env_var(
|
| 402 |
+
"ALB_SECURITY_GROUP_NAME", f"{CDK_PREFIX}SecurityGroupALB"
|
| 403 |
+
)
|
| 404 |
+
ALB_TARGET_GROUP_NAME = get_or_create_env_var(
|
| 405 |
+
"ALB_TARGET_GROUP_NAME", f"{CDK_PREFIX}-tg"[-32:]
|
| 406 |
+
) # Max 32 characters
|
| 407 |
+
EXISTING_LOAD_BALANCER_ARN = get_or_create_env_var("EXISTING_LOAD_BALANCER_ARN", "")
|
| 408 |
+
EXISTING_LOAD_BALANCER_DNS = get_or_create_env_var(
|
| 409 |
+
"EXISTING_LOAD_BALANCER_DNS", "placeholder_load_balancer_dns.net"
|
| 410 |
+
)
|
| 411 |
+
|
| 412 |
+
## CLOUDFRONT
|
| 413 |
+
USE_CLOUDFRONT = get_or_create_env_var("USE_CLOUDFRONT", "True")
|
| 414 |
+
CLOUDFRONT_PREFIX_LIST_ID = get_or_create_env_var(
|
| 415 |
+
"CLOUDFRONT_PREFIX_LIST_ID", "pl-93a247fa"
|
| 416 |
+
)
|
| 417 |
+
CLOUDFRONT_GEO_RESTRICTION = get_or_create_env_var(
|
| 418 |
+
"CLOUDFRONT_GEO_RESTRICTION", ""
|
| 419 |
+
) # A country that Cloudfront restricts access to. See here: https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/georestrictions.html
|
| 420 |
+
CLOUDFRONT_DISTRIBUTION_NAME = get_or_create_env_var(
|
| 421 |
+
"CLOUDFRONT_DISTRIBUTION_NAME", f"{CDK_PREFIX}CfDist"
|
| 422 |
+
)
|
| 423 |
+
CLOUDFRONT_DOMAIN = get_or_create_env_var(
|
| 424 |
+
"CLOUDFRONT_DOMAIN", "cloudfront_placeholder.net"
|
| 425 |
+
)
|
| 426 |
+
# Attach CSP / security response headers to the CDK CloudFront distribution (us-east-1 stack).
|
| 427 |
+
CLOUDFRONT_ENABLE_SECURE_RESPONSE_HEADERS = get_or_create_env_var(
|
| 428 |
+
"CLOUDFRONT_ENABLE_SECURE_RESPONSE_HEADERS", "True"
|
| 429 |
+
)
|
| 430 |
+
# Optional override for manifest-src (Cognito hosted UI). Default: https://{COGNITO_USER_POOL_DOMAIN_PREFIX}.auth.{AWS_REGION}.amazoncognito.com
|
| 431 |
+
COGNITO_USER_POOL_LOGIN_URL = get_or_create_env_var("COGNITO_USER_POOL_LOGIN_URL", "")
|
| 432 |
+
|
| 433 |
+
|
| 434 |
+
# Certificate for Application load balancer (optional, for HTTPS and logins through the ALB)
|
| 435 |
+
ACM_SSL_CERTIFICATE_ARN = get_or_create_env_var("ACM_SSL_CERTIFICATE_ARN", "")
|
| 436 |
+
SSL_CERTIFICATE_DOMAIN = get_or_create_env_var(
|
| 437 |
+
"SSL_CERTIFICATE_DOMAIN", ""
|
| 438 |
+
) # e.g. example.com or www.example.com
|
| 439 |
+
|
| 440 |
+
# ECS Express Mode (opt-in HTTPS ingress without supplying ACM_SSL_CERTIFICATE_ARN).
|
| 441 |
+
# Pilot/dev: Express PrimaryContainer does not support S3 environmentFiles or Fargate mount points.
|
| 442 |
+
USE_ECS_EXPRESS_MODE = get_or_create_env_var("USE_ECS_EXPRESS_MODE", "False")
|
| 443 |
+
ECS_EXPRESS_SERVICE_NAME = get_or_create_env_var(
|
| 444 |
+
"ECS_EXPRESS_SERVICE_NAME", ECS_SERVICE_NAME
|
| 445 |
+
)
|
| 446 |
+
ECS_EXPRESS_HEALTH_CHECK_PATH = get_or_create_env_var(
|
| 447 |
+
"ECS_EXPRESS_HEALTH_CHECK_PATH", "/"
|
| 448 |
+
)
|
| 449 |
+
ECS_EXPRESS_INFRASTRUCTURE_ROLE_NAME = get_or_create_env_var(
|
| 450 |
+
"ECS_EXPRESS_INFRASTRUCTURE_ROLE_NAME", f"{CDK_PREFIX}ExpressInfraRole"
|
| 451 |
+
)
|
| 452 |
+
# After first deploy, set to ExpressServiceEndpoint output (https://...) if not using CloudFront.
|
| 453 |
+
# The installer updates Cognito callback URLs via API (no second CDK deploy).
|
| 454 |
+
ECS_EXPRESS_COGNITO_REDIRECT_BASE = get_or_create_env_var(
|
| 455 |
+
"ECS_EXPRESS_COGNITO_REDIRECT_BASE", ""
|
| 456 |
+
)
|
| 457 |
+
# Express networkConfiguration.subnets drives both tasks and the managed ALB.
|
| 458 |
+
# Public subnets (IGW route) → internet-facing ALB; private → internal ALB only.
|
| 459 |
+
ECS_EXPRESS_USE_PUBLIC_SUBNETS = get_or_create_env_var(
|
| 460 |
+
"ECS_EXPRESS_USE_PUBLIC_SUBNETS", "True"
|
| 461 |
+
)
|
| 462 |
+
|
| 463 |
+
if USE_ECS_EXPRESS_MODE == "True" and ACM_SSL_CERTIFICATE_ARN:
|
| 464 |
+
raise ValueError(
|
| 465 |
+
"USE_ECS_EXPRESS_MODE=True cannot be used with ACM_SSL_CERTIFICATE_ARN set. "
|
| 466 |
+
"Clear ACM_SSL_CERTIFICATE_ARN or set USE_ECS_EXPRESS_MODE=False."
|
| 467 |
+
)
|
| 468 |
+
|
| 469 |
+
# ECS Service Connect (legacy Fargate only): VPC service-to-service HTTP to Gradio/FastAPI.
|
| 470 |
+
ENABLE_ECS_SERVICE_CONNECT = get_or_create_env_var(
|
| 471 |
+
"ENABLE_ECS_SERVICE_CONNECT", "False"
|
| 472 |
+
)
|
| 473 |
+
ECS_SERVICE_CONNECT_NAMESPACE = get_or_create_env_var(
|
| 474 |
+
"ECS_SERVICE_CONNECT_NAMESPACE",
|
| 475 |
+
(f"{CDK_PREFIX}local".lower().replace("_", "-").strip("-") or "llm-topic-local"),
|
| 476 |
+
)
|
| 477 |
+
ECS_SERVICE_CONNECT_DISCOVERY_NAME = get_or_create_env_var(
|
| 478 |
+
"ECS_SERVICE_CONNECT_DISCOVERY_NAME", "llm-topic"
|
| 479 |
+
)
|
| 480 |
+
# Optional friendly DNS label; defaults to discovery name when empty.
|
| 481 |
+
ECS_SERVICE_CONNECT_DNS_NAME = get_or_create_env_var("ECS_SERVICE_CONNECT_DNS_NAME", "")
|
| 482 |
+
# Client task security groups (at least one of IDs, names, or CDK prefixes required when SC on).
|
| 483 |
+
ECS_SERVICE_CONNECT_CLIENT_SECURITY_GROUP_IDS = get_or_create_env_var(
|
| 484 |
+
"ECS_SERVICE_CONNECT_CLIENT_SECURITY_GROUP_IDS", ""
|
| 485 |
+
)
|
| 486 |
+
ECS_SERVICE_CONNECT_CLIENT_SECURITY_GROUP_IDS_LIST = parse_comma_separated_list(
|
| 487 |
+
ECS_SERVICE_CONNECT_CLIENT_SECURITY_GROUP_IDS
|
| 488 |
+
)
|
| 489 |
+
ECS_SERVICE_CONNECT_CLIENT_SECURITY_GROUP_NAMES = get_or_create_env_var(
|
| 490 |
+
"ECS_SERVICE_CONNECT_CLIENT_SECURITY_GROUP_NAMES", ""
|
| 491 |
+
)
|
| 492 |
+
ECS_SERVICE_CONNECT_CLIENT_CDK_PREFIXES = get_or_create_env_var(
|
| 493 |
+
"ECS_SERVICE_CONNECT_CLIENT_CDK_PREFIXES", ""
|
| 494 |
+
)
|
| 495 |
+
|
| 496 |
+
|
| 497 |
+
def normalize_https_redirect_url(url: str) -> str:
|
| 498 |
+
"""Ensure Cognito/OAuth redirect bases use an explicit https:// scheme."""
|
| 499 |
+
raw = (url or "").strip()
|
| 500 |
+
if not raw:
|
| 501 |
+
return ""
|
| 502 |
+
if raw.startswith("https://"):
|
| 503 |
+
return raw.rstrip("/")
|
| 504 |
+
if raw.startswith("http://"):
|
| 505 |
+
return ("https://" + raw[len("http://") :]).rstrip("/")
|
| 506 |
+
return ("https://" + raw.lstrip("/")).rstrip("/")
|
| 507 |
+
|
| 508 |
+
|
| 509 |
+
# This should be the CloudFront domain, the domain linked to your ACM certificate, or the DNS of your application load balancer in console afterwards
|
| 510 |
+
if USE_CLOUDFRONT == "True":
|
| 511 |
+
COGNITO_REDIRECTION_URL = get_or_create_env_var(
|
| 512 |
+
"COGNITO_REDIRECTION_URL", "https://" + CLOUDFRONT_DOMAIN
|
| 513 |
+
)
|
| 514 |
+
elif SSL_CERTIFICATE_DOMAIN:
|
| 515 |
+
COGNITO_REDIRECTION_URL = get_or_create_env_var(
|
| 516 |
+
"COGNITO_REDIRECTION_URL", "https://" + SSL_CERTIFICATE_DOMAIN
|
| 517 |
+
)
|
| 518 |
+
elif USE_ECS_EXPRESS_MODE == "True":
|
| 519 |
+
_express_redirect_default = ECS_EXPRESS_COGNITO_REDIRECT_BASE or (
|
| 520 |
+
"https://" + EXISTING_LOAD_BALANCER_DNS
|
| 521 |
+
)
|
| 522 |
+
COGNITO_REDIRECTION_URL = get_or_create_env_var(
|
| 523 |
+
"COGNITO_REDIRECTION_URL", _express_redirect_default
|
| 524 |
+
)
|
| 525 |
+
else:
|
| 526 |
+
COGNITO_REDIRECTION_URL = get_or_create_env_var(
|
| 527 |
+
"COGNITO_REDIRECTION_URL", "https://" + EXISTING_LOAD_BALANCER_DNS
|
| 528 |
+
)
|
| 529 |
+
|
| 530 |
+
COGNITO_REDIRECTION_URL = normalize_https_redirect_url(COGNITO_REDIRECTION_URL)
|
| 531 |
+
if ECS_EXPRESS_COGNITO_REDIRECT_BASE:
|
| 532 |
+
ECS_EXPRESS_COGNITO_REDIRECT_BASE = normalize_https_redirect_url(
|
| 533 |
+
ECS_EXPRESS_COGNITO_REDIRECT_BASE
|
| 534 |
+
)
|
| 535 |
+
|
| 536 |
+
# Custom headers e.g. if routing traffic through Cloudfront
|
| 537 |
+
CUSTOM_HEADER = get_or_create_env_var(
|
| 538 |
+
"CUSTOM_HEADER", ""
|
| 539 |
+
) # Retrieving or setting CUSTOM_HEADER
|
| 540 |
+
CUSTOM_HEADER_VALUE = get_or_create_env_var(
|
| 541 |
+
"CUSTOM_HEADER_VALUE", ""
|
| 542 |
+
) # Retrieving or setting CUSTOM_HEADER_VALUE
|
| 543 |
+
|
| 544 |
+
# Firewall on top of load balancer
|
| 545 |
+
LOAD_BALANCER_WEB_ACL_NAME = get_or_create_env_var(
|
| 546 |
+
"LOAD_BALANCER_WEB_ACL_NAME", f"{CDK_PREFIX}alb-web-acl"
|
| 547 |
+
)
|
| 548 |
+
|
| 549 |
+
# Firewall on top of CloudFront
|
| 550 |
+
WEB_ACL_NAME = get_or_create_env_var("WEB_ACL_NAME", f"{CDK_PREFIX}cloudfront-web-acl")
|
| 551 |
+
|
| 552 |
+
###
|
| 553 |
+
# File I/O options
|
| 554 |
+
###
|
| 555 |
+
|
| 556 |
+
OUTPUT_FOLDER = get_or_create_env_var("GRADIO_OUTPUT_FOLDER", "output/") # 'output/'
|
| 557 |
+
INPUT_FOLDER = get_or_create_env_var("GRADIO_INPUT_FOLDER", "input/") # 'input/'
|
| 558 |
+
|
| 559 |
+
# Allow for files to be saved in a temporary folder for increased security in some instances
|
| 560 |
+
if OUTPUT_FOLDER == "TEMP" or INPUT_FOLDER == "TEMP":
|
| 561 |
+
# Create a temporary directory
|
| 562 |
+
with tempfile.TemporaryDirectory() as temp_dir:
|
| 563 |
+
print(f"Temporary directory created at: {temp_dir}")
|
| 564 |
+
|
| 565 |
+
if OUTPUT_FOLDER == "TEMP":
|
| 566 |
+
OUTPUT_FOLDER = temp_dir + "/"
|
| 567 |
+
if INPUT_FOLDER == "TEMP":
|
| 568 |
+
INPUT_FOLDER = temp_dir + "/"
|
| 569 |
+
|
| 570 |
+
###
|
| 571 |
+
# LOGGING OPTIONS
|
| 572 |
+
###
|
| 573 |
+
|
| 574 |
+
SAVE_LOGS_TO_CSV = get_or_create_env_var("SAVE_LOGS_TO_CSV", "True")
|
| 575 |
+
|
| 576 |
+
### DYNAMODB logs. Whether to save to DynamoDB, and the headers of the table
|
| 577 |
+
SAVE_LOGS_TO_DYNAMODB = get_or_create_env_var("SAVE_LOGS_TO_DYNAMODB", "True")
|
| 578 |
+
ACCESS_LOG_DYNAMODB_TABLE_NAME = get_or_create_env_var(
|
| 579 |
+
"ACCESS_LOG_DYNAMODB_TABLE_NAME", f"{CDK_PREFIX}dynamodb-access-logs".lower()
|
| 580 |
+
)
|
| 581 |
+
FEEDBACK_LOG_DYNAMODB_TABLE_NAME = get_or_create_env_var(
|
| 582 |
+
"FEEDBACK_LOG_DYNAMODB_TABLE_NAME", f"{CDK_PREFIX}dynamodb-feedback-logs".lower()
|
| 583 |
+
)
|
| 584 |
+
USAGE_LOG_DYNAMODB_TABLE_NAME = get_or_create_env_var(
|
| 585 |
+
"USAGE_LOG_DYNAMODB_TABLE_NAME", f"{CDK_PREFIX}dynamodb-usage-logs".lower()
|
| 586 |
+
)
|
| 587 |
+
|
| 588 |
+
# Optional scheduled export of usage-log DynamoDB table to CSV in S3 (EventBridge -> Lambda).
|
| 589 |
+
ENABLE_DYNAMODB_USAGE_LOG_EXPORT = get_or_create_env_var(
|
| 590 |
+
"ENABLE_DYNAMODB_USAGE_LOG_EXPORT", "False"
|
| 591 |
+
)
|
| 592 |
+
DYNAMODB_USAGE_LOG_EXPORT_LAMBDA_NAME = get_or_create_env_var(
|
| 593 |
+
"DYNAMODB_USAGE_LOG_EXPORT_LAMBDA_NAME",
|
| 594 |
+
f"{CDK_PREFIX}DynamoUsageLogExport".lower().replace("_", "-"),
|
| 595 |
+
)
|
| 596 |
+
DYNAMODB_USAGE_LOG_EXPORT_SCHEDULE = get_or_create_env_var(
|
| 597 |
+
"DYNAMODB_USAGE_LOG_EXPORT_SCHEDULE", "cron(0 6 ? * * *)"
|
| 598 |
+
)
|
| 599 |
+
DYNAMODB_USAGE_LOG_EXPORT_S3_KEY = get_or_create_env_var(
|
| 600 |
+
"DYNAMODB_USAGE_LOG_EXPORT_S3_KEY",
|
| 601 |
+
"reports/dynamodb-usage/dynamodb_logs_export.csv",
|
| 602 |
+
)
|
| 603 |
+
DYNAMODB_USAGE_LOG_EXPORT_DATE_ATTRIBUTE = get_or_create_env_var(
|
| 604 |
+
"DYNAMODB_USAGE_LOG_EXPORT_DATE_ATTRIBUTE", "timestamp"
|
| 605 |
+
)
|
| 606 |
+
DYNAMODB_USAGE_LOG_EXPORT_OUTPUT_FILENAME = get_or_create_env_var(
|
| 607 |
+
"DYNAMODB_USAGE_LOG_EXPORT_OUTPUT_FILENAME", "dynamodb_logs_export.csv"
|
| 608 |
+
)
|
| 609 |
+
|
| 610 |
+
if ENABLE_DYNAMODB_USAGE_LOG_EXPORT == "True":
|
| 611 |
+
if SAVE_LOGS_TO_DYNAMODB != "True":
|
| 612 |
+
raise ValueError(
|
| 613 |
+
"ENABLE_DYNAMODB_USAGE_LOG_EXPORT=True requires SAVE_LOGS_TO_DYNAMODB=True."
|
| 614 |
+
)
|
| 615 |
+
schedule = (DYNAMODB_USAGE_LOG_EXPORT_SCHEDULE or "").strip()
|
| 616 |
+
if not schedule.startswith("cron(") and not schedule.startswith("rate("):
|
| 617 |
+
raise ValueError(
|
| 618 |
+
"DYNAMODB_USAGE_LOG_EXPORT_SCHEDULE must be an EventBridge cron(...) or "
|
| 619 |
+
f"rate(...) expression; got {schedule!r}."
|
| 620 |
+
)
|
| 621 |
+
if not (DYNAMODB_USAGE_LOG_EXPORT_S3_KEY or "").strip():
|
| 622 |
+
raise ValueError(
|
| 623 |
+
"DYNAMODB_USAGE_LOG_EXPORT_S3_KEY is required when "
|
| 624 |
+
"ENABLE_DYNAMODB_USAGE_LOG_EXPORT=True."
|
| 625 |
+
)
|
| 626 |
+
|
| 627 |
+
###
|
| 628 |
+
# APP OPTIONS
|
| 629 |
+
###
|
| 630 |
+
|
| 631 |
+
# Get some environment variables and Launch the Gradio app
|
| 632 |
+
COGNITO_AUTH = get_or_create_env_var("COGNITO_AUTH", "False")
|
| 633 |
+
|
| 634 |
+
GRADIO_SERVER_PORT = int(get_or_create_env_var("GRADIO_SERVER_PORT", "7860"))
|
| 635 |
+
|
| 636 |
+
# Must match the named port mapping on the Fargate container (see cdk_stack.py).
|
| 637 |
+
ECS_SERVICE_CONNECT_PORT_MAPPING_NAME = get_or_create_env_var(
|
| 638 |
+
"ECS_SERVICE_CONNECT_PORT_MAPPING_NAME", f"port-{GRADIO_SERVER_PORT}"
|
| 639 |
+
)
|
| 640 |
+
|
| 641 |
+
# Suffix used with ECS_SERVICE_CONNECT_CLIENT_CDK_PREFIXES (matches this stack's ECS SG name).
|
| 642 |
+
if ECS_SECURITY_GROUP_NAME.startswith(CDK_PREFIX):
|
| 643 |
+
_default_sc_client_sg_suffix = ECS_SECURITY_GROUP_NAME[len(CDK_PREFIX) :]
|
| 644 |
+
else:
|
| 645 |
+
_default_sc_client_sg_suffix = "SecurityGroupECS"
|
| 646 |
+
ECS_SERVICE_CONNECT_CLIENT_SG_NAME_SUFFIX = get_or_create_env_var(
|
| 647 |
+
"ECS_SERVICE_CONNECT_CLIENT_SG_NAME_SUFFIX", _default_sc_client_sg_suffix
|
| 648 |
+
)
|
| 649 |
+
|
| 650 |
+
ECS_SERVICE_CONNECT_CLIENT_SECURITY_GROUP_NAMES_LIST = parse_comma_separated_list(
|
| 651 |
+
ECS_SERVICE_CONNECT_CLIENT_SECURITY_GROUP_NAMES
|
| 652 |
+
)
|
| 653 |
+
ECS_SERVICE_CONNECT_CLIENT_CDK_PREFIXES_LIST = parse_comma_separated_list(
|
| 654 |
+
ECS_SERVICE_CONNECT_CLIENT_CDK_PREFIXES
|
| 655 |
+
)
|
| 656 |
+
|
| 657 |
+
|
| 658 |
+
def build_service_connect_client_security_group_names() -> List[str]:
|
| 659 |
+
"""Explicit SG names plus {prefix}{suffix} for each client CDK_PREFIX."""
|
| 660 |
+
names: List[str] = list(ECS_SERVICE_CONNECT_CLIENT_SECURITY_GROUP_NAMES_LIST)
|
| 661 |
+
for prefix in ECS_SERVICE_CONNECT_CLIENT_CDK_PREFIXES_LIST:
|
| 662 |
+
names.append(f"{prefix}{ECS_SERVICE_CONNECT_CLIENT_SG_NAME_SUFFIX}")
|
| 663 |
+
deduped: List[str] = []
|
| 664 |
+
seen = set()
|
| 665 |
+
for name in names:
|
| 666 |
+
if name and name not in seen:
|
| 667 |
+
seen.add(name)
|
| 668 |
+
deduped.append(name)
|
| 669 |
+
return deduped
|
| 670 |
+
|
| 671 |
+
|
| 672 |
+
ECS_SERVICE_CONNECT_CLIENT_SECURITY_GROUP_NAMES_TO_LOOKUP = (
|
| 673 |
+
build_service_connect_client_security_group_names()
|
| 674 |
+
)
|
| 675 |
+
|
| 676 |
+
if ENABLE_ECS_SERVICE_CONNECT == "True" and USE_ECS_EXPRESS_MODE == "True":
|
| 677 |
+
raise ValueError(
|
| 678 |
+
"ENABLE_ECS_SERVICE_CONNECT=True is only supported on the legacy Fargate "
|
| 679 |
+
"service path. Set USE_ECS_EXPRESS_MODE=False or disable Service Connect."
|
| 680 |
+
)
|
| 681 |
+
|
| 682 |
+
# Headless deployment: S3 job .env -> Lambda -> one-shot ECS Fargate (RUN_DIRECT_MODE).
|
| 683 |
+
# No ALB, CloudFront, or always-on ECS service.
|
| 684 |
+
ENABLE_HEADLESS_DEPLOYMENT = get_or_create_env_var(
|
| 685 |
+
"ENABLE_HEADLESS_DEPLOYMENT", "False"
|
| 686 |
+
)
|
| 687 |
+
|
| 688 |
+
# S3-uploaded job .env files trigger one-shot ECS Fargate tasks (direct mode / cli_redact).
|
| 689 |
+
ENABLE_S3_BATCH_ECS_TRIGGER = get_or_create_env_var(
|
| 690 |
+
"ENABLE_S3_BATCH_ECS_TRIGGER", "False"
|
| 691 |
+
)
|
| 692 |
+
S3_BATCH_ENV_PREFIX = get_or_create_env_var("S3_BATCH_ENV_PREFIX", "input/config/")
|
| 693 |
+
S3_BATCH_ENV_SUFFIX = get_or_create_env_var("S3_BATCH_ENV_SUFFIX", ".env")
|
| 694 |
+
S3_BATCH_INPUT_PREFIX = get_or_create_env_var("S3_BATCH_INPUT_PREFIX", "input/")
|
| 695 |
+
S3_BATCH_CONFIG_PREFIX = get_or_create_env_var("S3_BATCH_CONFIG_PREFIX", "")
|
| 696 |
+
# Durable batch defaults live on the log/config bucket (S3_LOG_CONFIG_BUCKET_NAME),
|
| 697 |
+
# not the output bucket, which has an object-expiration lifecycle rule.
|
| 698 |
+
S3_BATCH_GENERAL_ENV_PREFIX = get_or_create_env_var(
|
| 699 |
+
"S3_BATCH_GENERAL_ENV_PREFIX", "general-config/"
|
| 700 |
+
)
|
| 701 |
+
S3_BATCH_DEFAULT_PARAMS_KEY = get_or_create_env_var(
|
| 702 |
+
"S3_BATCH_DEFAULT_PARAMS_KEY", "general-config/app_defaults.env"
|
| 703 |
+
)
|
| 704 |
+
S3_BATCH_LAMBDA_FUNCTION_NAME = get_or_create_env_var(
|
| 705 |
+
"S3_BATCH_LAMBDA_FUNCTION_NAME", f"{CDK_PREFIX}S3BatchEcsTrigger"
|
| 706 |
+
)
|
| 707 |
+
|
| 708 |
+
if ENABLE_S3_BATCH_ECS_TRIGGER == "True" and USE_ECS_EXPRESS_MODE == "True":
|
| 709 |
+
raise ValueError(
|
| 710 |
+
"ENABLE_S3_BATCH_ECS_TRIGGER=True requires the legacy Fargate task definition "
|
| 711 |
+
"for ecs.run_task. Set USE_ECS_EXPRESS_MODE=False or disable the batch trigger."
|
| 712 |
+
)
|
| 713 |
+
|
| 714 |
+
if ENABLE_HEADLESS_DEPLOYMENT == "True":
|
| 715 |
+
if ENABLE_S3_BATCH_ECS_TRIGGER != "True":
|
| 716 |
+
raise ValueError(
|
| 717 |
+
"ENABLE_HEADLESS_DEPLOYMENT=True requires ENABLE_S3_BATCH_ECS_TRIGGER=True."
|
| 718 |
+
)
|
| 719 |
+
if USE_ECS_EXPRESS_MODE == "True":
|
| 720 |
+
raise ValueError(
|
| 721 |
+
"ENABLE_HEADLESS_DEPLOYMENT=True requires USE_ECS_EXPRESS_MODE=False."
|
| 722 |
+
)
|
| 723 |
+
if USE_CLOUDFRONT == "True":
|
| 724 |
+
raise ValueError(
|
| 725 |
+
"ENABLE_HEADLESS_DEPLOYMENT=True is incompatible with USE_CLOUDFRONT=True."
|
| 726 |
+
)
|
| 727 |
+
|
| 728 |
+
# Account-level Bedrock model invocation logging (S3 + CloudWatch) for this Region.
|
| 729 |
+
# Uses a CDK custom resource (no CloudFormation L1 for PutModelInvocationLoggingConfiguration).
|
| 730 |
+
ENABLE_BEDROCK_MODEL_INVOCATION_LOGGING = get_or_create_env_var(
|
| 731 |
+
"ENABLE_BEDROCK_MODEL_INVOCATION_LOGGING", "False"
|
| 732 |
+
)
|
| 733 |
+
BEDROCK_MODEL_INVOCATION_S3_PREFIX = get_or_create_env_var(
|
| 734 |
+
"BEDROCK_MODEL_INVOCATION_S3_PREFIX", "bedrock-logs"
|
| 735 |
+
)
|
| 736 |
+
BEDROCK_MODEL_INVOCATION_LOG_GROUP_NAME = get_or_create_env_var(
|
| 737 |
+
"BEDROCK_MODEL_INVOCATION_LOG_GROUP_NAME",
|
| 738 |
+
f"/aws/bedrock/{CDK_PREFIX}model-invocations".rstrip("/"),
|
| 739 |
+
)
|
| 740 |
+
BEDROCK_MODEL_INVOCATION_LOG_RETENTION_DAYS = get_or_create_env_var(
|
| 741 |
+
"BEDROCK_MODEL_INVOCATION_LOG_RETENTION_DAYS", "90"
|
| 742 |
+
)
|
| 743 |
+
BEDROCK_MODEL_INVOCATION_TEXT_ENABLED = get_or_create_env_var(
|
| 744 |
+
"BEDROCK_MODEL_INVOCATION_TEXT_ENABLED", "True"
|
| 745 |
+
)
|
| 746 |
+
BEDROCK_MODEL_INVOCATION_IMAGE_ENABLED = get_or_create_env_var(
|
| 747 |
+
"BEDROCK_MODEL_INVOCATION_IMAGE_ENABLED", "True"
|
| 748 |
+
)
|
| 749 |
+
BEDROCK_MODEL_INVOCATION_EMBEDDING_ENABLED = get_or_create_env_var(
|
| 750 |
+
"BEDROCK_MODEL_INVOCATION_EMBEDDING_ENABLED", "True"
|
| 751 |
+
)
|
| 752 |
+
BEDROCK_MODEL_INVOCATION_VIDEO_ENABLED = get_or_create_env_var(
|
| 753 |
+
"BEDROCK_MODEL_INVOCATION_VIDEO_ENABLED", "True"
|
| 754 |
+
)
|
| 755 |
+
|
| 756 |
+
# Optional Bedrock Guardrails on Converse (app + headless batch defaults; set via cdk_install).
|
| 757 |
+
ENABLE_BEDROCK_GUARDRAILS = get_or_create_env_var("ENABLE_BEDROCK_GUARDRAILS", "False")
|
| 758 |
+
BEDROCK_GUARDRAIL_IDENTIFIER = get_or_create_env_var(
|
| 759 |
+
"BEDROCK_GUARDRAIL_IDENTIFIER", ""
|
| 760 |
+
).strip()
|
| 761 |
+
BEDROCK_GUARDRAIL_VERSION = get_or_create_env_var(
|
| 762 |
+
"BEDROCK_GUARDRAIL_VERSION", ""
|
| 763 |
+
).strip()
|
| 764 |
+
BEDROCK_GUARDRAIL_TRACE = (
|
| 765 |
+
get_or_create_env_var("BEDROCK_GUARDRAIL_TRACE", "disabled").strip().lower()
|
| 766 |
+
)
|
| 767 |
+
|
| 768 |
+
# Optional headless follow-on: S3 output PutRequests alarm -> SNS email + IAM user for downloads.
|
| 769 |
+
ENABLE_HEADLESS_OUTPUT_NOTIFICATIONS = get_or_create_env_var(
|
| 770 |
+
"ENABLE_HEADLESS_OUTPUT_NOTIFICATIONS", "False"
|
| 771 |
+
)
|
| 772 |
+
HEADLESS_OUTPUT_NOTIFY_EMAIL = get_or_create_env_var("HEADLESS_OUTPUT_NOTIFY_EMAIL", "")
|
| 773 |
+
HEADLESS_OUTPUT_IAM_USER_NAME = get_or_create_env_var(
|
| 774 |
+
"HEADLESS_OUTPUT_IAM_USER_NAME", f"{CDK_PREFIX}s3-output-reader"
|
| 775 |
+
)
|
| 776 |
+
HEADLESS_OUTPUT_S3_METRIC_FILTER_ID = get_or_create_env_var(
|
| 777 |
+
"HEADLESS_OUTPUT_S3_METRIC_FILTER_ID",
|
| 778 |
+
f"{CDK_PREFIX}s3-output-put".lower().replace("_", "-"),
|
| 779 |
+
)
|
| 780 |
+
HEADLESS_OUTPUT_SNS_TOPIC_NAME = get_or_create_env_var(
|
| 781 |
+
"HEADLESS_OUTPUT_SNS_TOPIC_NAME",
|
| 782 |
+
f"{CDK_PREFIX}llm-topic-s3-save-sns".lower().replace("_", "-"),
|
| 783 |
+
)
|
| 784 |
+
HEADLESS_OUTPUT_ALARM_NAME = get_or_create_env_var(
|
| 785 |
+
"HEADLESS_OUTPUT_ALARM_NAME",
|
| 786 |
+
f"{CDK_PREFIX}cloudwatch-alarm-new-output-s3".lower().replace("_", "-"),
|
| 787 |
+
)
|
| 788 |
+
HEADLESS_OUTPUT_S3_PREFIX = get_or_create_env_var(
|
| 789 |
+
"HEADLESS_OUTPUT_S3_PREFIX", "output/"
|
| 790 |
+
)
|
| 791 |
+
HEADLESS_OUTPUT_IAM_SECRET_NAME = get_or_create_env_var(
|
| 792 |
+
"HEADLESS_OUTPUT_IAM_SECRET_NAME",
|
| 793 |
+
f"{CDK_PREFIX}headless-output-reader-key",
|
| 794 |
+
)
|
| 795 |
+
|
| 796 |
+
if ENABLE_HEADLESS_OUTPUT_NOTIFICATIONS == "True":
|
| 797 |
+
if ENABLE_HEADLESS_DEPLOYMENT != "True":
|
| 798 |
+
raise ValueError(
|
| 799 |
+
"ENABLE_HEADLESS_OUTPUT_NOTIFICATIONS=True requires "
|
| 800 |
+
"ENABLE_HEADLESS_DEPLOYMENT=True."
|
| 801 |
+
)
|
| 802 |
+
if not (HEADLESS_OUTPUT_NOTIFY_EMAIL or "").strip():
|
| 803 |
+
raise ValueError(
|
| 804 |
+
"HEADLESS_OUTPUT_NOTIFY_EMAIL is required when "
|
| 805 |
+
"ENABLE_HEADLESS_OUTPUT_NOTIFICATIONS=True."
|
| 806 |
+
)
|
| 807 |
+
|
| 808 |
+
# Pi agent Gradio UI (second Fargate service; shared legacy ALB + Service Connect to main app).
|
| 809 |
+
ENABLE_PI_AGENT_ECS_SERVICE = get_or_create_env_var(
|
| 810 |
+
"ENABLE_PI_AGENT_ECS_SERVICE", "False"
|
| 811 |
+
)
|
| 812 |
+
ECR_PI_REPO_NAME = get_or_create_env_var(
|
| 813 |
+
"ECR_PI_REPO_NAME", f"{CDK_PREFIX}pi-agent".lower()
|
| 814 |
+
)
|
| 815 |
+
CODEBUILD_PI_PROJECT_NAME = get_or_create_env_var(
|
| 816 |
+
"CODEBUILD_PI_PROJECT_NAME", f"{CDK_PREFIX}CodeBuildPiAgent"
|
| 817 |
+
)
|
| 818 |
+
ECS_PI_TASK_DEFINITION_NAME = get_or_create_env_var(
|
| 819 |
+
"ECS_PI_TASK_DEFINITION_NAME", f"{CDK_PREFIX}PiAgentTaskDefinition"
|
| 820 |
+
)
|
| 821 |
+
ECS_PI_SECURITY_GROUP_NAME = get_or_create_env_var(
|
| 822 |
+
"ECS_PI_SECURITY_GROUP_NAME", f"{CDK_PREFIX}SecurityGroupPiAgent"
|
| 823 |
+
)
|
| 824 |
+
ECS_PI_LOG_GROUP_NAME = get_or_create_env_var(
|
| 825 |
+
"ECS_PI_LOG_GROUP_NAME", f"/ecs/{ECS_PI_SERVICE_NAME}-logs".lower()
|
| 826 |
+
)
|
| 827 |
+
ECS_PI_TASK_CPU_SIZE = get_or_create_env_var("ECS_PI_TASK_CPU_SIZE", "1024")
|
| 828 |
+
ECS_PI_TASK_MEMORY_SIZE = get_or_create_env_var("ECS_PI_TASK_MEMORY_SIZE", "2048")
|
| 829 |
+
PI_GRADIO_PORT = get_or_create_env_var("PI_GRADIO_PORT", "7862")
|
| 830 |
+
# Pi ALB routing: path (default /pi on shared host e.g. CloudFront), host, or both.
|
| 831 |
+
PI_ALB_ROUTING = get_or_create_env_var("PI_ALB_ROUTING", "path").strip().lower()
|
| 832 |
+
PI_ALB_PATH_PREFIX = get_or_create_env_var("PI_ALB_PATH_PREFIX", "/pi")
|
| 833 |
+
PI_ALB_HOST_HEADER = get_or_create_env_var("PI_ALB_HOST_HEADER", "")
|
| 834 |
+
PI_ALB_TARGET_GROUP_NAME = get_or_create_env_var(
|
| 835 |
+
"PI_ALB_TARGET_GROUP_NAME", f"{CDK_PREFIX}PiAgentTG"[-32:]
|
| 836 |
+
)
|
| 837 |
+
PI_ALB_LISTENER_RULE_PRIORITY = int(
|
| 838 |
+
get_or_create_env_var("PI_ALB_LISTENER_RULE_PRIORITY", "3")
|
| 839 |
+
)
|
| 840 |
+
PI_AGENT_ENV_S3_KEY = get_or_create_env_var("PI_AGENT_ENV_S3_KEY", "pi_agent.env")
|
| 841 |
+
|
| 842 |
+
|
| 843 |
+
def _normalize_pi_alb_path_prefix(raw: str) -> str:
|
| 844 |
+
segment = (raw or "pi").strip().strip("/")
|
| 845 |
+
return f"/{segment}" if segment else "/pi"
|
| 846 |
+
|
| 847 |
+
|
| 848 |
+
PI_ALB_PATH_PREFIX_NORMALIZED = _normalize_pi_alb_path_prefix(PI_ALB_PATH_PREFIX)
|
| 849 |
+
_PI_ALB_ROUTING_MODES = frozenset({"path", "host", "both"})
|
| 850 |
+
|
| 851 |
+
|
| 852 |
+
def _validate_pi_alb_routing_for_enabled_pi() -> None:
|
| 853 |
+
if PI_ALB_ROUTING not in _PI_ALB_ROUTING_MODES:
|
| 854 |
+
raise ValueError(
|
| 855 |
+
f"PI_ALB_ROUTING must be one of {sorted(_PI_ALB_ROUTING_MODES)}; got '{PI_ALB_ROUTING}'."
|
| 856 |
+
)
|
| 857 |
+
if PI_ALB_ROUTING in ("host", "both") and not PI_ALB_HOST_HEADER.strip():
|
| 858 |
+
raise ValueError(
|
| 859 |
+
"PI_ALB_HOST_HEADER is required when PI_ALB_ROUTING is 'host' or 'both' "
|
| 860 |
+
"(dedicated hostname on the shared ALB)."
|
| 861 |
+
)
|
| 862 |
+
if PI_ALB_ROUTING in ("path", "both") and not PI_ALB_PATH_PREFIX_NORMALIZED:
|
| 863 |
+
raise ValueError("PI_ALB_PATH_PREFIX must resolve to a non-empty path segment.")
|
| 864 |
+
|
| 865 |
+
|
| 866 |
+
# Pi on ECS Express Mode (second Express service on shared ALB; SC via ecs:UpdateService).
|
| 867 |
+
ENABLE_PI_AGENT_EXPRESS_SERVICE = get_or_create_env_var(
|
| 868 |
+
"ENABLE_PI_AGENT_EXPRESS_SERVICE", "False"
|
| 869 |
+
)
|
| 870 |
+
ECS_PI_EXPRESS_SERVICE_NAME = get_or_create_env_var(
|
| 871 |
+
"ECS_PI_EXPRESS_SERVICE_NAME", f"{CDK_PREFIX}PiExpressService"
|
| 872 |
+
)
|
| 873 |
+
ECS_PI_EXPRESS_HEALTH_CHECK_PATH = get_or_create_env_var(
|
| 874 |
+
"ECS_PI_EXPRESS_HEALTH_CHECK_PATH", "/health"
|
| 875 |
+
)
|
| 876 |
+
ECS_PI_EXPRESS_SECURITY_GROUP_NAME = get_or_create_env_var(
|
| 877 |
+
"ECS_PI_EXPRESS_SECURITY_GROUP_NAME", f"{CDK_PREFIX}SecurityGroupPiExpress"
|
| 878 |
+
)
|
| 879 |
+
# Service Connect port names for Express services (applied in post_cdk_build_quickstart.py).
|
| 880 |
+
ECS_EXPRESS_SC_PORT_NAME = get_or_create_env_var(
|
| 881 |
+
"ECS_EXPRESS_SC_PORT_NAME", ECS_SERVICE_CONNECT_PORT_MAPPING_NAME
|
| 882 |
+
)
|
| 883 |
+
ECS_PI_EXPRESS_SC_PORT_NAME = get_or_create_env_var(
|
| 884 |
+
"ECS_PI_EXPRESS_SC_PORT_NAME", f"port-{PI_GRADIO_PORT}"
|
| 885 |
+
)
|
| 886 |
+
|
| 887 |
+
if ENABLE_PI_AGENT_ECS_SERVICE == "True" and ENABLE_PI_AGENT_EXPRESS_SERVICE == "True":
|
| 888 |
+
raise ValueError(
|
| 889 |
+
"Enable at most one Pi deployment mode: ENABLE_PI_AGENT_ECS_SERVICE (legacy Fargate) "
|
| 890 |
+
"or ENABLE_PI_AGENT_EXPRESS_SERVICE (Express), not both."
|
| 891 |
+
)
|
| 892 |
+
if ENABLE_PI_AGENT_EXPRESS_SERVICE == "True" and USE_ECS_EXPRESS_MODE != "True":
|
| 893 |
+
raise ValueError(
|
| 894 |
+
"ENABLE_PI_AGENT_EXPRESS_SERVICE=True requires USE_ECS_EXPRESS_MODE=True "
|
| 895 |
+
"(no ACM_SSL_CERTIFICATE_ARN)."
|
| 896 |
+
)
|
| 897 |
+
if ENABLE_PI_AGENT_ECS_SERVICE == "True" and USE_ECS_EXPRESS_MODE == "True":
|
| 898 |
+
raise ValueError(
|
| 899 |
+
"ENABLE_PI_AGENT_ECS_SERVICE=True requires legacy Fargate (USE_ECS_EXPRESS_MODE=False). "
|
| 900 |
+
"For Pi on Express, use ENABLE_PI_AGENT_EXPRESS_SERVICE=True instead."
|
| 901 |
+
)
|
| 902 |
+
if ENABLE_PI_AGENT_ECS_SERVICE == "True" and ENABLE_ECS_SERVICE_CONNECT != "True":
|
| 903 |
+
raise ValueError(
|
| 904 |
+
"ENABLE_PI_AGENT_ECS_SERVICE=True requires ENABLE_ECS_SERVICE_CONNECT=True "
|
| 905 |
+
"so the Pi task can reach the main app at http://<discovery>:7860."
|
| 906 |
+
)
|
| 907 |
+
if ENABLE_PI_AGENT_ECS_SERVICE == "True":
|
| 908 |
+
_validate_pi_alb_routing_for_enabled_pi()
|
| 909 |
+
|
| 910 |
+
###
|
| 911 |
+
# WHOLE DOCUMENT API OPTIONS
|
| 912 |
+
###
|
| 913 |
+
|
| 914 |
+
DAYS_TO_DISPLAY_WHOLE_DOCUMENT_JOBS = get_or_create_env_var(
|
| 915 |
+
"DAYS_TO_DISPLAY_WHOLE_DOCUMENT_JOBS", "7"
|
| 916 |
+
) # 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,1492 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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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 |
+
log_bucket: str = "",
|
| 1211 |
+
default_params_key: str = "general-config/app_defaults.env",
|
| 1212 |
+
app_defaults_local_path: str = "",
|
| 1213 |
+
s3_outputs_bucket_name: str = "",
|
| 1214 |
+
env_overrides: Optional[Dict[str, str]] = None,
|
| 1215 |
+
) -> None:
|
| 1216 |
+
"""
|
| 1217 |
+
Ensure headless batch prefixes and example job .env exist on the output bucket.
|
| 1218 |
+
|
| 1219 |
+
When ``log_bucket`` is set, also ensure durable ``app_defaults.env`` exists on
|
| 1220 |
+
the log/config bucket (so it is not deleted by output-bucket lifecycle rules).
|
| 1221 |
+
|
| 1222 |
+
Idempotent: existing keys are left unchanged (safe to run from quickstart).
|
| 1223 |
+
"""
|
| 1224 |
+
if not output_bucket:
|
| 1225 |
+
print("Skipping headless S3 layout seed: output bucket name is empty.")
|
| 1226 |
+
return
|
| 1227 |
+
|
| 1228 |
+
input_prefix_norm = (
|
| 1229 |
+
input_prefix if input_prefix.endswith("/") else f"{input_prefix}/"
|
| 1230 |
+
)
|
| 1231 |
+
env_prefix_norm = env_prefix if env_prefix.endswith("/") else f"{env_prefix}/"
|
| 1232 |
+
if not env_prefix_norm.startswith(input_prefix_norm):
|
| 1233 |
+
env_prefix_norm = f"{input_prefix_norm}{env_prefix_norm.lstrip('/')}"
|
| 1234 |
+
if not env_prefix_norm.endswith("/"):
|
| 1235 |
+
env_prefix_norm += "/"
|
| 1236 |
+
|
| 1237 |
+
s3_client = boto3.client("s3", region_name=aws_region)
|
| 1238 |
+
markers = (
|
| 1239 |
+
input_prefix_norm,
|
| 1240 |
+
env_prefix_norm,
|
| 1241 |
+
)
|
| 1242 |
+
for key in markers:
|
| 1243 |
+
if _s3_object_exists(s3_client, output_bucket, key):
|
| 1244 |
+
print(f"S3 prefix marker already present: s3://{output_bucket}/{key}")
|
| 1245 |
+
continue
|
| 1246 |
+
s3_client.put_object(Bucket=output_bucket, Key=key, Body=b"")
|
| 1247 |
+
print(f"Created S3 prefix marker: s3://{output_bucket}/{key}")
|
| 1248 |
+
|
| 1249 |
+
example_key = f"{env_prefix_norm}{example_env_basename}"
|
| 1250 |
+
if _s3_object_exists(s3_client, output_bucket, example_key):
|
| 1251 |
+
print(f"Example job .env already present: s3://{output_bucket}/{example_key}")
|
| 1252 |
+
elif not os.path.isfile(example_env_local_path):
|
| 1253 |
+
print(f"Skipping example job .env upload: {example_env_local_path} not found.")
|
| 1254 |
+
else:
|
| 1255 |
+
with open(example_env_local_path, "rb") as handle:
|
| 1256 |
+
s3_client.put_object(
|
| 1257 |
+
Bucket=output_bucket, Key=example_key, Body=handle.read()
|
| 1258 |
+
)
|
| 1259 |
+
print(f"Uploaded example job .env to s3://{output_bucket}/{example_key}")
|
| 1260 |
+
|
| 1261 |
+
if not log_bucket:
|
| 1262 |
+
return
|
| 1263 |
+
|
| 1264 |
+
defaults_key = (default_params_key or "general-config/app_defaults.env").lstrip("/")
|
| 1265 |
+
if _s3_object_exists(s3_client, log_bucket, defaults_key):
|
| 1266 |
+
print(f"app_defaults.env already present: s3://{log_bucket}/{defaults_key}")
|
| 1267 |
+
return
|
| 1268 |
+
|
| 1269 |
+
defaults_path = app_defaults_local_path
|
| 1270 |
+
if not defaults_path:
|
| 1271 |
+
defaults_path = os.path.join(
|
| 1272 |
+
os.path.dirname(__file__),
|
| 1273 |
+
"config",
|
| 1274 |
+
"headless_s3_seed",
|
| 1275 |
+
"general-config",
|
| 1276 |
+
"app_defaults.env",
|
| 1277 |
+
)
|
| 1278 |
+
|
| 1279 |
+
# Prefer rendered content (fills S3_OUTPUTS_BUCKET) when seed helpers are available.
|
| 1280 |
+
body: Optional[bytes] = None
|
| 1281 |
+
try:
|
| 1282 |
+
from cdk_functions import build_headless_app_defaults_env_content
|
| 1283 |
+
|
| 1284 |
+
seed_dir = os.path.join(os.path.dirname(__file__), "config", "headless_s3_seed")
|
| 1285 |
+
if env_overrides is None:
|
| 1286 |
+
try:
|
| 1287 |
+
from cdk_config import (
|
| 1288 |
+
BEDROCK_GUARDRAIL_IDENTIFIER,
|
| 1289 |
+
BEDROCK_GUARDRAIL_TRACE,
|
| 1290 |
+
BEDROCK_GUARDRAIL_VERSION,
|
| 1291 |
+
ENABLE_BEDROCK_GUARDRAILS,
|
| 1292 |
+
)
|
| 1293 |
+
from cdk_functions import bedrock_guardrail_env_overrides_for_defaults
|
| 1294 |
+
|
| 1295 |
+
env_overrides = bedrock_guardrail_env_overrides_for_defaults(
|
| 1296 |
+
ENABLE_BEDROCK_GUARDRAILS,
|
| 1297 |
+
BEDROCK_GUARDRAIL_IDENTIFIER,
|
| 1298 |
+
BEDROCK_GUARDRAIL_VERSION,
|
| 1299 |
+
BEDROCK_GUARDRAIL_TRACE,
|
| 1300 |
+
)
|
| 1301 |
+
except Exception:
|
| 1302 |
+
env_overrides = {}
|
| 1303 |
+
|
| 1304 |
+
rendered = build_headless_app_defaults_env_content(
|
| 1305 |
+
seed_dir,
|
| 1306 |
+
s3_outputs_bucket_name=s3_outputs_bucket_name or output_bucket,
|
| 1307 |
+
env_overrides=env_overrides or None,
|
| 1308 |
+
)
|
| 1309 |
+
body = rendered.encode("utf-8")
|
| 1310 |
+
except Exception as exc:
|
| 1311 |
+
print(f"Warning: could not render app_defaults.env ({exc}); using local file.")
|
| 1312 |
+
|
| 1313 |
+
if body is None:
|
| 1314 |
+
if not os.path.isfile(defaults_path):
|
| 1315 |
+
print(f"Skipping app_defaults.env upload: {defaults_path} not found.")
|
| 1316 |
+
return
|
| 1317 |
+
with open(defaults_path, "rb") as handle:
|
| 1318 |
+
body = handle.read()
|
| 1319 |
+
|
| 1320 |
+
s3_client.put_object(Bucket=log_bucket, Key=defaults_key, Body=body)
|
| 1321 |
+
print(f"Uploaded app_defaults.env to s3://{log_bucket}/{defaults_key}")
|
| 1322 |
+
|
| 1323 |
+
|
| 1324 |
+
def print_headless_deployment_next_steps(
|
| 1325 |
+
values: Dict[str, str],
|
| 1326 |
+
*,
|
| 1327 |
+
stack_name: str = "SummarisationStack",
|
| 1328 |
+
region: Optional[str] = None,
|
| 1329 |
+
) -> None:
|
| 1330 |
+
"""Print user-facing next steps after headless deploy + quickstart."""
|
| 1331 |
+
aws_region = region or values.get("AWS_REGION") or AWS_REGION
|
| 1332 |
+
output_bucket = (values.get("S3_OUTPUT_BUCKET_NAME") or "").strip()
|
| 1333 |
+
log_bucket = (values.get("S3_LOG_CONFIG_BUCKET_NAME") or "").strip()
|
| 1334 |
+
input_prefix = (values.get("S3_BATCH_INPUT_PREFIX") or "input/").strip("/")
|
| 1335 |
+
config_prefix = (values.get("S3_BATCH_ENV_PREFIX") or "input/config/").strip("/")
|
| 1336 |
+
defaults_key = (
|
| 1337 |
+
(values.get("S3_BATCH_DEFAULT_PARAMS_KEY") or "general-config/app_defaults.env")
|
| 1338 |
+
.strip()
|
| 1339 |
+
.lstrip("/")
|
| 1340 |
+
)
|
| 1341 |
+
|
| 1342 |
+
lambda_name = (values.get("S3_BATCH_LAMBDA_FUNCTION_NAME") or "").strip()
|
| 1343 |
+
if not lambda_name:
|
| 1344 |
+
lambda_name = (
|
| 1345 |
+
get_stack_output(stack_name, "BatchEcsTriggerLambdaName", aws_region) or ""
|
| 1346 |
+
).strip()
|
| 1347 |
+
if not lambda_name:
|
| 1348 |
+
prefix = (values.get("CDK_PREFIX") or "").strip()
|
| 1349 |
+
lambda_name = f"{prefix}S3BatchEcsTrigger" if prefix else "S3BatchEcsTrigger"
|
| 1350 |
+
|
| 1351 |
+
input_uri = (
|
| 1352 |
+
f"s3://{output_bucket}/{input_prefix}/"
|
| 1353 |
+
if output_bucket
|
| 1354 |
+
else f"<output-bucket>/{input_prefix}/"
|
| 1355 |
+
)
|
| 1356 |
+
config_uri = (
|
| 1357 |
+
f"s3://{output_bucket}/{config_prefix}/"
|
| 1358 |
+
if output_bucket
|
| 1359 |
+
else f"<output-bucket>/{config_prefix}/"
|
| 1360 |
+
)
|
| 1361 |
+
output_uri = (
|
| 1362 |
+
f"s3://{output_bucket}/output/<session-folder>/"
|
| 1363 |
+
if output_bucket
|
| 1364 |
+
else "<output-bucket>/output/<session-folder>/"
|
| 1365 |
+
)
|
| 1366 |
+
defaults_uri = (
|
| 1367 |
+
f"s3://{log_bucket}/{defaults_key}"
|
| 1368 |
+
if log_bucket
|
| 1369 |
+
else f"<log-bucket>/{defaults_key}"
|
| 1370 |
+
)
|
| 1371 |
+
example_name = "example_headless_env_file.env"
|
| 1372 |
+
|
| 1373 |
+
print("\nDone. Next steps:")
|
| 1374 |
+
print(
|
| 1375 |
+
f" - Upload a consultation spreadsheet (.xlsx) to {input_uri}. "
|
| 1376 |
+
"You can use dummy_consultation_response.xlsx as a placeholder filename "
|
| 1377 |
+
"in the example job .env below."
|
| 1378 |
+
)
|
| 1379 |
+
print(
|
| 1380 |
+
f" - Create a job .env file for submitting a task to {config_uri}. "
|
| 1381 |
+
f"You can copy the example at cdk/config/headless_s3_seed/input/config/{example_name} "
|
| 1382 |
+
f"(also seeded at {config_uri}{example_name}) and adjust DIRECT_MODE_INPUT_FILE "
|
| 1383 |
+
"and DIRECT_MODE_TEXT_COLUMN. Further DIRECT_MODE_* variables are documented in "
|
| 1384 |
+
"tools/config.py and cli_topics.py."
|
| 1385 |
+
)
|
| 1386 |
+
print(f" - Upload your job .env file to {config_uri}")
|
| 1387 |
+
print(
|
| 1388 |
+
f" - Durable batch defaults (app_defaults.env) live at {defaults_uri} "
|
| 1389 |
+
"on the log/config bucket (not deleted by the output bucket lifecycle rule)."
|
| 1390 |
+
)
|
| 1391 |
+
print(
|
| 1392 |
+
f" - AWS Lambda function {lambda_name} will start an ECS task to run "
|
| 1393 |
+
"topic modelling according to your job .env (RUN_DIRECT_MODE=1)."
|
| 1394 |
+
)
|
| 1395 |
+
print(
|
| 1396 |
+
f" - Outputs are written to {output_uri} when SAVE_OUTPUTS_TO_S3=True "
|
| 1397 |
+
"in your job .env (see the example file)."
|
| 1398 |
+
)
|
| 1399 |
+
log_group = (values.get("ECS_LOG_GROUP_NAME") or "").strip()
|
| 1400 |
+
if log_group:
|
| 1401 |
+
print(
|
| 1402 |
+
f" - Batch task logs: CloudWatch log group {log_group} "
|
| 1403 |
+
"(streams appear once the container starts)."
|
| 1404 |
+
)
|
| 1405 |
+
|
| 1406 |
+
|
| 1407 |
+
def print_headless_output_notification_steps(values: Dict[str, str]) -> None:
|
| 1408 |
+
"""Print follow-on steps for S3 output alarms, SNS, and IAM reader user."""
|
| 1409 |
+
email = (values.get("HEADLESS_OUTPUT_NOTIFY_EMAIL") or "").strip()
|
| 1410 |
+
iam_user = (values.get("HEADLESS_OUTPUT_IAM_USER_NAME") or "").strip()
|
| 1411 |
+
output_bucket = (values.get("S3_OUTPUT_BUCKET_NAME") or "").strip()
|
| 1412 |
+
output_prefix = (values.get("HEADLESS_OUTPUT_S3_PREFIX") or "output/").strip()
|
| 1413 |
+
alarm_name = (values.get("HEADLESS_OUTPUT_ALARM_NAME") or "").strip()
|
| 1414 |
+
secret_name = (values.get("HEADLESS_OUTPUT_IAM_SECRET_NAME") or "").strip()
|
| 1415 |
+
|
| 1416 |
+
print("\nHeadless output notifications:")
|
| 1417 |
+
if email:
|
| 1418 |
+
print(
|
| 1419 |
+
f" - Confirm the SNS email subscription sent to {email} "
|
| 1420 |
+
"(check spam; status shows Pending until confirmed)."
|
| 1421 |
+
)
|
| 1422 |
+
if output_bucket:
|
| 1423 |
+
print(
|
| 1424 |
+
f" - CloudWatch alarm fires when objects are uploaded under "
|
| 1425 |
+
f"s3://{output_bucket}/{output_prefix.rstrip('/')}/"
|
| 1426 |
+
)
|
| 1427 |
+
if alarm_name:
|
| 1428 |
+
print(f" - Alarm name: {alarm_name}")
|
| 1429 |
+
if iam_user:
|
| 1430 |
+
print(
|
| 1431 |
+
f" - IAM user {iam_user} can list/get/put/delete objects in the "
|
| 1432 |
+
f"output bucket for programmatic result download."
|
| 1433 |
+
)
|
| 1434 |
+
if secret_name:
|
| 1435 |
+
print(
|
| 1436 |
+
" - If an access key was created, credentials are stored in "
|
| 1437 |
+
"the relevantSecrets Manager secret."
|
| 1438 |
+
)
|
| 1439 |
+
|
| 1440 |
+
|
| 1441 |
+
def provision_headless_output_reader_access_key(
|
| 1442 |
+
values: Dict[str, str],
|
| 1443 |
+
*,
|
| 1444 |
+
region: Optional[str] = None,
|
| 1445 |
+
) -> Optional[str]:
|
| 1446 |
+
"""
|
| 1447 |
+
Create an IAM access key for the headless output reader user.
|
| 1448 |
+
|
| 1449 |
+
Stores JSON credentials in Secrets Manager when HEADLESS_OUTPUT_IAM_SECRET_NAME
|
| 1450 |
+
is set in cdk_config.env.
|
| 1451 |
+
"""
|
| 1452 |
+
from botocore.exceptions import ClientError
|
| 1453 |
+
|
| 1454 |
+
iam_user = (values.get("HEADLESS_OUTPUT_IAM_USER_NAME") or "").strip()
|
| 1455 |
+
if not iam_user:
|
| 1456 |
+
print("Warning: HEADLESS_OUTPUT_IAM_USER_NAME not set; skipping access key.")
|
| 1457 |
+
return None
|
| 1458 |
+
|
| 1459 |
+
aws_region = region or values.get("AWS_REGION") or AWS_REGION
|
| 1460 |
+
iam_client = boto3.client("iam", region_name=aws_region)
|
| 1461 |
+
secret_name = (values.get("HEADLESS_OUTPUT_IAM_SECRET_NAME") or "").strip()
|
| 1462 |
+
|
| 1463 |
+
try:
|
| 1464 |
+
response = iam_client.create_access_key(UserName=iam_user)
|
| 1465 |
+
except ClientError as exc:
|
| 1466 |
+
print(f"Could not create IAM access key for {iam_user}: {exc}")
|
| 1467 |
+
return None
|
| 1468 |
+
|
| 1469 |
+
access_key = response["AccessKey"]
|
| 1470 |
+
payload = json.dumps(
|
| 1471 |
+
{
|
| 1472 |
+
"aws_access_key_id": access_key["AccessKeyId"],
|
| 1473 |
+
"aws_secret_access_key": access_key["SecretAccessKey"],
|
| 1474 |
+
}
|
| 1475 |
+
)
|
| 1476 |
+
|
| 1477 |
+
if secret_name:
|
| 1478 |
+
sm_client = boto3.client("secretsmanager", region_name=aws_region)
|
| 1479 |
+
try:
|
| 1480 |
+
sm_client.create_secret(Name=secret_name, SecretString=payload)
|
| 1481 |
+
print("Stored output-reader credentials in Secrets Manager secret")
|
| 1482 |
+
except ClientError as exc:
|
| 1483 |
+
if exc.response["Error"]["Code"] == "ResourceExistsException":
|
| 1484 |
+
sm_client.put_secret_value(SecretId=secret_name, SecretString=payload)
|
| 1485 |
+
print("Updated output-reader credentials in Secrets Manager secret")
|
| 1486 |
+
else:
|
| 1487 |
+
print(f"Warning: could not store credentials in Secrets Manager: {exc}")
|
| 1488 |
+
print("IAM access key created (view in IAM console if needed):")
|
| 1489 |
+
else:
|
| 1490 |
+
print("IAM access key created (view in IAM console if needed):")
|
| 1491 |
+
|
| 1492 |
+
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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+
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,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
# Optional Bedrock Guardrails on Converse (same Region as the guardrail resource)
|
| 25 |
+
# ENABLE_BEDROCK_GUARDRAILS=False
|
| 26 |
+
# BEDROCK_GUARDRAIL_IDENTIFIER=
|
| 27 |
+
# BEDROCK_GUARDRAIL_VERSION=1
|
| 28 |
+
# BEDROCK_GUARDRAIL_TRACE=enabled
|
| 29 |
+
LOG_FILE_NAME=log.csv
|
| 30 |
+
USAGE_LOG_FILE_NAME=usage_log.csv
|
| 31 |
+
FEEDBACK_LOG_FILE_NAME=feedback_log.csv
|
cdk/config/headless_s3_seed/general-config/app_defaults.env
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
RUN_DIRECT_MODE=1
|
| 2 |
+
RUN_AWS_FUNCTIONS=1
|
| 3 |
+
RUN_AWS_BEDROCK_MODELS=1
|
| 4 |
+
RUN_LOCAL_MODEL=0
|
| 5 |
+
RUN_INFERENCE_SERVER=0
|
| 6 |
+
RUN_GEMINI_MODELS=0
|
| 7 |
+
RUN_AZURE_MODELS=0
|
| 8 |
+
DIRECT_MODE_TASK=extract
|
| 9 |
+
DIRECT_MODE_OUTPUT_DIR=output/
|
| 10 |
+
SAVE_OUTPUTS_TO_S3=True
|
| 11 |
+
S3_OUTPUTS_BUCKET=
|
| 12 |
+
S3_OUTPUTS_FOLDER=output
|
| 13 |
+
DIRECT_MODE_MAX_TOKENS=8192
|
| 14 |
+
DIRECT_MODE_TEMPERATURE=1.0
|
| 15 |
+
BEDROCK_READ_TIMEOUT_SECONDS=300
|
| 16 |
+
BEDROCK_CONNECT_TIMEOUT_SECONDS=60
|
| 17 |
+
# ENABLE_BEDROCK_GUARDRAILS=False
|
| 18 |
+
# BEDROCK_GUARDRAIL_IDENTIFIER=
|
| 19 |
+
# BEDROCK_GUARDRAIL_VERSION=1
|
| 20 |
+
# BEDROCK_GUARDRAIL_TRACE=enabled
|
| 21 |
+
DIRECT_MODE_BATCH_SIZE=10
|
| 22 |
+
DIRECT_MODE_MODEL_CHOICE=google.gemma-3-27b-it
|
| 23 |
+
DIRECT_MODE_RANDOM_SEED=42
|
| 24 |
+
DIRECT_MODE_TASK=all_in_one
|
| 25 |
+
SESSION_OUTPUT_FOLDER=True
|
| 26 |
+
LLM_CONTEXT_LENGTH=65536
|
| 27 |
+
LLM_RESET=False
|
| 28 |
+
LLM_TOP_K=64
|
| 29 |
+
LLM_TOP_P=0.95
|
| 30 |
+
MAX_COMMENT_CHARS=100000
|
| 31 |
+
OUTPUT_DEBUG_FILES=False
|
| 32 |
+
DEFAULT_COST_CODE=D13922
|
| 33 |
+
SAVE_LOGS_TO_DYNAMODB=True
|
| 34 |
+
SAVE_LOGS_TO_CSV=True
|
| 35 |
+
USAGE_LOG_FILE_NAME=usage_log.csv
|
| 36 |
+
FEEDBACK_LOG_FILE_NAME=feedback_log.csv
|
| 37 |
+
ENABLE_VALIDATION=False
|
| 38 |
+
INCLUDE_TOPIC_CONFIDENCE=False
|
| 39 |
+
DIRECT_MODE_INCLUDE_TOPIC_CONFIDENCE=No
|
| 40 |
+
INCLUDE_RESPONSE_LEVEL_SUMMARY=False
|
| 41 |
+
INCLUDE_GENERAL_TOPIC_PIVOT_TABLE=False
|
| 42 |
+
PRIORITISE_SSO_OVER_AWS_ENV_ACCESS_KEYS=1
|
| 43 |
+
DIRECT_MODE_S3_UPLOAD_ONLY_XLSX=True
|
| 44 |
+
UPLOAD_USAGE_LOG_TO_S3_OUTPUTS=True
|
| 45 |
+
ALL_IN_ONE_USE_LLM_DEDUP=True
|
| 46 |
+
UPLOAD_PROMPT_RESPONSE_LOG_TO_S3_OUTPUTS=True
|
| 47 |
+
ENABLE_INPUT_REDACTION=False
|
| 48 |
+
ENABLE_ORIGINAL_DATA_REDACTION=False
|
| 49 |
+
REDACTION_ENTITIES=['EMAIL_ADDRESS', 'PHONE_NUMBER', 'CREDIT_CARD', 'IBAN_CODE', 'UK_NHS', 'UKPOSTCODE', 'IP_ADDRESS', 'STREETNAME']
|
| 50 |
+
REDACTION_STRATEGY=entity_type
|
| 51 |
+
SPACY_MODEL=en_core_web_sm
|
| 52 |
+
SPACY_MODEL_PATH=
|
cdk/config/headless_s3_seed/input/config/example_headless_env_file.env
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
# Durable defaults (app_defaults.env) live on the log/config bucket under
|
| 6 |
+
# general-config/ — not the output bucket, which expires objects after N days.
|
| 7 |
+
#
|
| 8 |
+
# More DIRECT_MODE_* variables: tools/config.py and cli_topics.py in this repo.
|
| 9 |
+
|
| 10 |
+
RUN_DIRECT_MODE=1
|
| 11 |
+
DIRECT_MODE_TASK=extract
|
| 12 |
+
DIRECT_MODE_INPUT_FILE=dummy_consultation_response.xlsx
|
| 13 |
+
DIRECT_MODE_TEXT_COLUMN="Response Text"
|
| 14 |
+
SAVE_OUTPUTS_TO_S3=True
|
| 15 |
+
S3_OUTPUTS_FOLDER=output/
|
cdk/config/lambda/lambda_function.py
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
|
|
|
|
|
|
|
|
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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 |
+
# Durable config (app_defaults.env) lives on the log/config bucket so it is not
|
| 12 |
+
# deleted by the output bucket object-expiration lifecycle rule.
|
| 13 |
+
LOG_BUCKET = os.environ.get("LOG_BUCKET") or BUCKET
|
| 14 |
+
INPUT_PREFIX = os.environ.get("INPUT_PREFIX", "input/")
|
| 15 |
+
ENV_PREFIX = os.environ.get("ENV_PREFIX", f"{INPUT_PREFIX}config/")
|
| 16 |
+
GENERAL_ENV_PREFIX = os.environ.get("GENERAL_ENV_PREFIX", "general-config/")
|
| 17 |
+
ENV_SUFFIX = os.environ.get("ENV_SUFFIX", ".env")
|
| 18 |
+
DEFAULT_PARAMS_KEY = os.environ.get(
|
| 19 |
+
"DEFAULT_PARAMS_KEY", f"{GENERAL_ENV_PREFIX}app_defaults{ENV_SUFFIX}"
|
| 20 |
+
)
|
| 21 |
+
CLUSTER = os.environ.get("ECS_CLUSTER", "analytics_fargate_cluster")
|
| 22 |
+
TASK_DEF = os.environ.get("ECS_TASK_DEF", "llm_topic_modelling_fargate_def:5")
|
| 23 |
+
SUBNETS = os.environ.get(
|
| 24 |
+
"SUBNETS", "subnet-083650a35f93a0ee5,subnet-0a41ba70470cabab8"
|
| 25 |
+
).split(",")
|
| 26 |
+
SECURITY_GROUPS = os.environ.get("SECURITY_GROUPS", "sg-051effb4c5e752df1").split(",")
|
| 27 |
+
ECS_ASSIGN_PUBLIC_IP = os.environ.get("ECS_ASSIGN_PUBLIC_IP", "DISABLED").upper()
|
| 28 |
+
DEFAULT_INPUT_S3_URI = os.environ.get(
|
| 29 |
+
"DEFAULT_INPUT_S3_URI",
|
| 30 |
+
f"s3://{BUCKET}/{INPUT_PREFIX}dummy_consultation_response.xlsx",
|
| 31 |
+
)
|
| 32 |
+
DEFAULT_TASK_TYPE = os.environ.get("DEFAULT_TASK_TYPE", "extract")
|
| 33 |
+
CONTAINER_NAME = os.environ.get("CONTAINER_NAME", "llm_topic_modelling_container")
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def _key_matches(key: str) -> bool:
|
| 37 |
+
return key.startswith(ENV_PREFIX) and key.endswith(ENV_SUFFIX)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def _derive_runtime_params_from_key(key: str) -> dict:
|
| 41 |
+
"""Optional convention: decide task type from file name."""
|
| 42 |
+
basename = key.split("/")[-1].lower()
|
| 43 |
+
if "train" in basename:
|
| 44 |
+
task_type = "train"
|
| 45 |
+
elif "infer" in basename or "staging" in basename:
|
| 46 |
+
task_type = "infer"
|
| 47 |
+
else:
|
| 48 |
+
task_type = DEFAULT_TASK_TYPE
|
| 49 |
+
|
| 50 |
+
return {
|
| 51 |
+
"DIRECT_MODE_TASK": task_type,
|
| 52 |
+
"DIRECT_MODE_INPUT_FILE": DEFAULT_INPUT_S3_URI,
|
| 53 |
+
}
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def _parse_dotenv(dotenv_bytes: bytes, bucket: str, input_prefix: str) -> dict:
|
| 57 |
+
"""
|
| 58 |
+
Parse a basic .env and prepend S3 paths to specific keys if they have values.
|
| 59 |
+
"""
|
| 60 |
+
env = {}
|
| 61 |
+
text = dotenv_bytes.decode("utf-8", errors="replace")
|
| 62 |
+
|
| 63 |
+
# 1. Parse the file (Existing Logic)
|
| 64 |
+
for raw_line in text.splitlines():
|
| 65 |
+
line = raw_line.strip()
|
| 66 |
+
if not line or line.startswith("#"):
|
| 67 |
+
continue
|
| 68 |
+
if line.startswith("export "):
|
| 69 |
+
line = line[len("export ") :].strip()
|
| 70 |
+
if "=" not in line:
|
| 71 |
+
continue
|
| 72 |
+
key, value = line.split("=", 1)
|
| 73 |
+
key = key.strip()
|
| 74 |
+
value = value.strip()
|
| 75 |
+
if (value.startswith('"') and value.endswith('"')) or (
|
| 76 |
+
value.startswith("'") and value.endswith("'")
|
| 77 |
+
):
|
| 78 |
+
value = value[1:-1]
|
| 79 |
+
env[key] = value
|
| 80 |
+
|
| 81 |
+
# 2. Apply S3 Prefix Logic (New Logic)
|
| 82 |
+
# We define the base S3 path string using the provided arguments
|
| 83 |
+
s3_base = f"s3://{bucket}/{input_prefix}"
|
| 84 |
+
|
| 85 |
+
# List of keys that need modification
|
| 86 |
+
keys_to_modify = ["DIRECT_MODE_INPUT_FILE", "DIRECT_MODE_CANDIDATE_TOPICS"]
|
| 87 |
+
|
| 88 |
+
for key in keys_to_modify:
|
| 89 |
+
# env.get(key) returns the value.
|
| 90 |
+
# The 'if' check ensures the key exists AND is not an empty string.
|
| 91 |
+
if env.get(key):
|
| 92 |
+
env[key] = s3_base + env[key]
|
| 93 |
+
|
| 94 |
+
return env
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def _build_environment_array(*env_dicts):
|
| 98 |
+
"""Merge dictionaries left→right and produce ECS environment array format."""
|
| 99 |
+
merged = {}
|
| 100 |
+
for d in env_dicts:
|
| 101 |
+
merged.update(d or {})
|
| 102 |
+
# ECS override format: [{"name": "...","value":"..."}]
|
| 103 |
+
return [{"name": k, "value": v} for k, v in merged.items()]
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def lambda_handler(event, context):
|
| 107 |
+
runs = []
|
| 108 |
+
|
| 109 |
+
# Parse default env file with default config.
|
| 110 |
+
# Read from LOG_BUCKET (log/config bucket) so app_defaults.env survives
|
| 111 |
+
# output-bucket lifecycle expiration.
|
| 112 |
+
print(f"Loading default params from s3://{LOG_BUCKET}/{DEFAULT_PARAMS_KEY}")
|
| 113 |
+
default_obj = s3.get_object(Bucket=LOG_BUCKET, Key=DEFAULT_PARAMS_KEY)
|
| 114 |
+
default_dotenv_bytes = default_obj["Body"].read()
|
| 115 |
+
|
| 116 |
+
# Parse .env → dict of env vars (input paths still resolve against output BUCKET)
|
| 117 |
+
default_file_env = _parse_dotenv(default_dotenv_bytes, BUCKET, INPUT_PREFIX)
|
| 118 |
+
|
| 119 |
+
for record in event.get("Records", []):
|
| 120 |
+
|
| 121 |
+
# Parse env file from user
|
| 122 |
+
s3rec = record.get("s3", {})
|
| 123 |
+
bucket = s3rec.get("bucket", {}).get("name")
|
| 124 |
+
raw_key = s3rec.get("object", {}).get("key")
|
| 125 |
+
if not bucket or not raw_key:
|
| 126 |
+
print(f"Object in bucket {bucket} and key {raw_key} not found, exiting.")
|
| 127 |
+
continue
|
| 128 |
+
|
| 129 |
+
key = urllib.parse.unquote_plus(raw_key)
|
| 130 |
+
|
| 131 |
+
# combined_key = ENV_PREFIX + key
|
| 132 |
+
combined_key = key
|
| 133 |
+
|
| 134 |
+
print("combined_key:", combined_key)
|
| 135 |
+
|
| 136 |
+
# Only process the intended prefix/suffix
|
| 137 |
+
if not _key_matches(combined_key):
|
| 138 |
+
print(f"Key does not match: {combined_key}, exiting")
|
| 139 |
+
continue
|
| 140 |
+
|
| 141 |
+
# Fetch the .env file content from S3
|
| 142 |
+
obj = s3.get_object(Bucket=bucket, Key=combined_key)
|
| 143 |
+
dotenv_bytes = obj["Body"].read()
|
| 144 |
+
|
| 145 |
+
# Parse .env → dict of env vars
|
| 146 |
+
file_env = _parse_dotenv(dotenv_bytes, BUCKET, INPUT_PREFIX)
|
| 147 |
+
|
| 148 |
+
# Optionally derive run-time params from naming
|
| 149 |
+
# run_params = _derive_runtime_params_from_key(key)
|
| 150 |
+
|
| 151 |
+
# Merge: file env (dominant), overwrites default values.
|
| 152 |
+
environment = _build_environment_array(file_env, default_file_env)
|
| 153 |
+
|
| 154 |
+
print("Combined environment variables:", environment)
|
| 155 |
+
|
| 156 |
+
# Execute ECS Fargate task with fully dynamic environment overrides
|
| 157 |
+
response = ecs.run_task(
|
| 158 |
+
cluster=CLUSTER,
|
| 159 |
+
launchType="FARGATE",
|
| 160 |
+
taskDefinition=TASK_DEF,
|
| 161 |
+
networkConfiguration={
|
| 162 |
+
"awsvpcConfiguration": {
|
| 163 |
+
"subnets": SUBNETS,
|
| 164 |
+
"securityGroups": SECURITY_GROUPS,
|
| 165 |
+
"assignPublicIp": (
|
| 166 |
+
ECS_ASSIGN_PUBLIC_IP
|
| 167 |
+
if ECS_ASSIGN_PUBLIC_IP in ("ENABLED", "DISABLED")
|
| 168 |
+
else "DISABLED"
|
| 169 |
+
),
|
| 170 |
+
}
|
| 171 |
+
},
|
| 172 |
+
overrides={
|
| 173 |
+
"containerOverrides": [
|
| 174 |
+
{
|
| 175 |
+
"name": CONTAINER_NAME,
|
| 176 |
+
"environment": environment,
|
| 177 |
+
}
|
| 178 |
+
]
|
| 179 |
+
},
|
| 180 |
+
)
|
| 181 |
+
|
| 182 |
+
runs.append(
|
| 183 |
+
{
|
| 184 |
+
"bucket": bucket,
|
| 185 |
+
"key": key,
|
| 186 |
+
"taskArns": [t["taskArn"] for t in response.get("tasks", [])],
|
| 187 |
+
"failures": response.get("failures", []),
|
| 188 |
+
"envCount": len(environment),
|
| 189 |
+
}
|
| 190 |
+
)
|
| 191 |
+
|
| 192 |
+
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_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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
ADDED
|
@@ -0,0 +1,187 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
prior_arn = event.get("PhysicalResourceId", "")
|
| 185 |
+
if prior_arn and prior_arn != rule_arn:
|
| 186 |
+
_delete_rule(prior_arn)
|
| 187 |
+
return {"PhysicalResourceId": rule_arn}
|
cdk/post_cdk_build_quickstart.py
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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E_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_DEFAULT_PARAMS_KEY,
|
| 29 |
+
S3_BATCH_ENV_PREFIX,
|
| 30 |
+
S3_BATCH_INPUT_PREFIX,
|
| 31 |
+
S3_BATCH_LAMBDA_FUNCTION_NAME,
|
| 32 |
+
S3_LOG_CONFIG_BUCKET_NAME,
|
| 33 |
+
S3_OUTPUT_BUCKET_NAME,
|
| 34 |
+
USE_ECS_EXPRESS_MODE,
|
| 35 |
+
)
|
| 36 |
+
from cdk_functions import create_basic_config_env, ensure_codebuild_public_github_source
|
| 37 |
+
|
| 38 |
+
# boto3-only module (does not import aws-cdk / Node.js)
|
| 39 |
+
from cdk_post_deploy import (
|
| 40 |
+
apply_cognito_secret_fixup_from_stack,
|
| 41 |
+
configure_express_pi_service_connect,
|
| 42 |
+
print_headless_deployment_next_steps,
|
| 43 |
+
seed_headless_batch_s3_layout,
|
| 44 |
+
start_codebuild_build,
|
| 45 |
+
start_ecs_task,
|
| 46 |
+
start_express_gateway_service,
|
| 47 |
+
upload_file_to_s3,
|
| 48 |
+
)
|
| 49 |
+
from tqdm import tqdm
|
| 50 |
+
|
| 51 |
+
# Create basic app_config.env file that user can use to run the app later. Input is the folder it is saved into.
|
| 52 |
+
create_basic_config_env(
|
| 53 |
+
"config",
|
| 54 |
+
headless=ENABLE_HEADLESS_DEPLOYMENT == "True",
|
| 55 |
+
pi_express_backend=ENABLE_PI_AGENT_EXPRESS_SERVICE == "True",
|
| 56 |
+
)
|
| 57 |
+
|
| 58 |
+
# Ensure CodeBuild clones the public GitHub repo (not CodeConnections/OAuth).
|
| 59 |
+
ensure_codebuild_public_github_source(
|
| 60 |
+
CODEBUILD_PROJECT_NAME,
|
| 61 |
+
GITHUB_REPO_USERNAME,
|
| 62 |
+
GITHUB_REPO_NAME,
|
| 63 |
+
GITHUB_REPO_BRANCH,
|
| 64 |
+
aws_region=AWS_REGION,
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
# Start CodeBuild for the main app image
|
| 68 |
+
print("Starting main app CodeBuild project.")
|
| 69 |
+
start_codebuild_build(project_name=CODEBUILD_PROJECT_NAME)
|
| 70 |
+
|
| 71 |
+
_enable_pi_image_build = (
|
| 72 |
+
ENABLE_PI_AGENT_ECS_SERVICE == "True" or ENABLE_PI_AGENT_EXPRESS_SERVICE == "True"
|
| 73 |
+
)
|
| 74 |
+
if _enable_pi_image_build:
|
| 75 |
+
ensure_codebuild_public_github_source(
|
| 76 |
+
CODEBUILD_PI_PROJECT_NAME,
|
| 77 |
+
GITHUB_REPO_USERNAME,
|
| 78 |
+
GITHUB_REPO_NAME,
|
| 79 |
+
GITHUB_REPO_BRANCH,
|
| 80 |
+
aws_region=AWS_REGION,
|
| 81 |
+
)
|
| 82 |
+
print("Starting Pi agent CodeBuild project.")
|
| 83 |
+
start_codebuild_build(project_name=CODEBUILD_PI_PROJECT_NAME)
|
| 84 |
+
|
| 85 |
+
# Upload app_config.env file to S3 bucket
|
| 86 |
+
upload_file_to_s3(
|
| 87 |
+
local_file_paths="config/app_config.env",
|
| 88 |
+
s3_key="",
|
| 89 |
+
s3_bucket=S3_LOG_CONFIG_BUCKET_NAME,
|
| 90 |
+
)
|
| 91 |
+
|
| 92 |
+
if _enable_pi_image_build:
|
| 93 |
+
pi_env_local = os.path.join("config", "pi_agent.env")
|
| 94 |
+
if os.path.isfile(pi_env_local):
|
| 95 |
+
print(
|
| 96 |
+
f"Uploading {pi_env_local} to s3://{S3_LOG_CONFIG_BUCKET_NAME}/{PI_AGENT_ENV_S3_KEY}"
|
| 97 |
+
)
|
| 98 |
+
upload_file_to_s3(
|
| 99 |
+
local_file_paths=pi_env_local,
|
| 100 |
+
s3_key="",
|
| 101 |
+
s3_bucket=S3_LOG_CONFIG_BUCKET_NAME,
|
| 102 |
+
)
|
| 103 |
+
else:
|
| 104 |
+
print(
|
| 105 |
+
f"Skipping Pi env upload: {pi_env_local} not found. "
|
| 106 |
+
f"Create it (from config/pi_agent.env.example) and upload to "
|
| 107 |
+
f"s3://{S3_LOG_CONFIG_BUCKET_NAME}/{PI_AGENT_ENV_S3_KEY} before scaling the Pi service."
|
| 108 |
+
)
|
| 109 |
+
|
| 110 |
+
total_seconds = 480 # 8 minutes
|
| 111 |
+
update_interval = 1 # Update every second
|
| 112 |
+
|
| 113 |
+
print("Waiting 8 minutes for CodeBuild container image(s) to build.")
|
| 114 |
+
|
| 115 |
+
# tqdm iterates over a range, and you perform a small sleep in each iteration
|
| 116 |
+
for i in tqdm(range(total_seconds), desc="Building container"):
|
| 117 |
+
time.sleep(update_interval)
|
| 118 |
+
|
| 119 |
+
# Scale main ECS service to one task (skipped for headless batch-only deployments)
|
| 120 |
+
if ENABLE_HEADLESS_DEPLOYMENT != "True":
|
| 121 |
+
if USE_ECS_EXPRESS_MODE == "True":
|
| 122 |
+
print(f"Starting Express ECS service {ECS_EXPRESS_SERVICE_NAME}")
|
| 123 |
+
start_express_gateway_service(
|
| 124 |
+
cluster_name=CLUSTER_NAME, service_name=ECS_EXPRESS_SERVICE_NAME
|
| 125 |
+
)
|
| 126 |
+
if ENABLE_PI_AGENT_EXPRESS_SERVICE == "True":
|
| 127 |
+
print(
|
| 128 |
+
"Configuring Service Connect for main Express (server) and "
|
| 129 |
+
"Pi Express (client)."
|
| 130 |
+
)
|
| 131 |
+
try:
|
| 132 |
+
configure_express_pi_service_connect(
|
| 133 |
+
cluster_name=CLUSTER_NAME,
|
| 134 |
+
main_service_name=ECS_EXPRESS_SERVICE_NAME,
|
| 135 |
+
pi_service_name=ECS_PI_EXPRESS_SERVICE_NAME,
|
| 136 |
+
namespace=ECS_SERVICE_CONNECT_NAMESPACE,
|
| 137 |
+
main_port_name=ECS_EXPRESS_SC_PORT_NAME,
|
| 138 |
+
discovery_name=ECS_SERVICE_CONNECT_DISCOVERY_NAME,
|
| 139 |
+
main_port=int(GRADIO_SERVER_PORT),
|
| 140 |
+
)
|
| 141 |
+
except Exception as exc:
|
| 142 |
+
print("Warning: could not configure Express Service Connect: " f"{exc}")
|
| 143 |
+
print("Syncing Cognito app client secret for in-app authentication.")
|
| 144 |
+
apply_cognito_secret_fixup_from_stack(
|
| 145 |
+
stack_name="SummarisationStack",
|
| 146 |
+
secret_name=COGNITO_USER_POOL_CLIENT_SECRET_NAME,
|
| 147 |
+
cluster_name=CLUSTER_NAME,
|
| 148 |
+
main_service_name=ECS_EXPRESS_SERVICE_NAME,
|
| 149 |
+
recycle_tasks=False,
|
| 150 |
+
)
|
| 151 |
+
else:
|
| 152 |
+
print(f"Starting ECS service {ECS_SERVICE_NAME}")
|
| 153 |
+
start_ecs_task(cluster_name=CLUSTER_NAME, service_name=ECS_SERVICE_NAME)
|
| 154 |
+
else:
|
| 155 |
+
print(
|
| 156 |
+
"Headless deployment: skipping always-on ECS service start "
|
| 157 |
+
"(tasks are started by the S3 batch Lambda)."
|
| 158 |
+
)
|
| 159 |
+
seed_headless_batch_s3_layout(
|
| 160 |
+
S3_OUTPUT_BUCKET_NAME,
|
| 161 |
+
input_prefix=S3_BATCH_INPUT_PREFIX,
|
| 162 |
+
env_prefix=S3_BATCH_ENV_PREFIX,
|
| 163 |
+
example_env_local_path=os.path.join("config", "example_headless_env_file.env"),
|
| 164 |
+
log_bucket=S3_LOG_CONFIG_BUCKET_NAME,
|
| 165 |
+
default_params_key=S3_BATCH_DEFAULT_PARAMS_KEY,
|
| 166 |
+
s3_outputs_bucket_name=S3_OUTPUT_BUCKET_NAME,
|
| 167 |
+
)
|
| 168 |
+
print_headless_deployment_next_steps(
|
| 169 |
+
{
|
| 170 |
+
"AWS_REGION": AWS_REGION,
|
| 171 |
+
"S3_OUTPUT_BUCKET_NAME": S3_OUTPUT_BUCKET_NAME,
|
| 172 |
+
"S3_LOG_CONFIG_BUCKET_NAME": S3_LOG_CONFIG_BUCKET_NAME,
|
| 173 |
+
"S3_BATCH_INPUT_PREFIX": S3_BATCH_INPUT_PREFIX,
|
| 174 |
+
"S3_BATCH_ENV_PREFIX": S3_BATCH_ENV_PREFIX,
|
| 175 |
+
"S3_BATCH_DEFAULT_PARAMS_KEY": S3_BATCH_DEFAULT_PARAMS_KEY,
|
| 176 |
+
"ECS_LOG_GROUP_NAME": ECS_LOG_GROUP_NAME,
|
| 177 |
+
"S3_BATCH_LAMBDA_FUNCTION_NAME": S3_BATCH_LAMBDA_FUNCTION_NAME,
|
| 178 |
+
"CDK_PREFIX": CDK_PREFIX,
|
| 179 |
+
}
|
| 180 |
+
)
|
| 181 |
+
|
| 182 |
+
if ENABLE_PI_AGENT_ECS_SERVICE == "True":
|
| 183 |
+
print(f"Starting Pi agent ECS service {ECS_PI_SERVICE_NAME}")
|
| 184 |
+
start_ecs_task(cluster_name=CLUSTER_NAME, service_name=ECS_PI_SERVICE_NAME)
|
| 185 |
+
|
| 186 |
+
if ENABLE_PI_AGENT_EXPRESS_SERVICE == "True":
|
| 187 |
+
print(f"Starting Pi Express ECS service {ECS_PI_EXPRESS_SERVICE_NAME}")
|
| 188 |
+
start_express_gateway_service(
|
| 189 |
+
cluster_name=CLUSTER_NAME, service_name=ECS_PI_EXPRESS_SERVICE_NAME
|
| 190 |
+
)
|
| 191 |
+
|
| 192 |
+
if USE_ECS_EXPRESS_MODE == "True" and ENABLE_HEADLESS_DEPLOYMENT != "True":
|
| 193 |
+
from cdk_post_deploy import print_express_mode_next_steps
|
| 194 |
+
|
| 195 |
+
print_express_mode_next_steps(
|
| 196 |
+
{
|
| 197 |
+
"AWS_REGION": AWS_REGION,
|
| 198 |
+
"ECS_EXPRESS_COGNITO_REDIRECT_BASE": ECS_EXPRESS_COGNITO_REDIRECT_BASE,
|
| 199 |
+
"ENABLE_PI_AGENT_EXPRESS_SERVICE": ENABLE_PI_AGENT_EXPRESS_SERVICE,
|
| 200 |
+
}
|
| 201 |
+
)
|
cdk/requirements.txt
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
aws-cdk-lib>=2.268.0
|
| 2 |
+
# Optional: only needed when ENABLE_APPREGISTRY=True (legacy myApplications; new-
|
| 3 |
+
# customer cut-off 30 Jul 2026). Can be removed once the AppRegistry path is retired.
|
| 4 |
+
# aws-cdk.aws-servicecatalogappregistry-alpha~=2.257.0a0
|
| 5 |
+
boto3
|
| 6 |
+
pandas
|
| 7 |
+
nodejs
|
| 8 |
+
python-dotenv
|
cdk/test/test_application_tags_and_resource_group.py
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Synth coverage for application tags and tag-based Resource Groups."""
|
| 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_apply_application_tags_to_app():
|
| 11 |
+
from aws_cdk import App, Environment, Stack
|
| 12 |
+
from aws_cdk import aws_s3 as s3
|
| 13 |
+
from cdk_application_tags import apply_application_tags_to_app
|
| 14 |
+
|
| 15 |
+
app = App()
|
| 16 |
+
apply_application_tags_to_app(
|
| 17 |
+
app,
|
| 18 |
+
tag_key="Application",
|
| 19 |
+
application_name="demo-llm-topic-modeller",
|
| 20 |
+
repository_url="https://github.com/example/repo.git",
|
| 21 |
+
)
|
| 22 |
+
stack = Stack(
|
| 23 |
+
app,
|
| 24 |
+
"TagTestStack",
|
| 25 |
+
env=Environment(account="123456789012", region="eu-west-2"),
|
| 26 |
+
)
|
| 27 |
+
s3.Bucket(stack, "TaggedBucket")
|
| 28 |
+
|
| 29 |
+
template = app.synth().get_stack_by_name("TagTestStack").template
|
| 30 |
+
buckets = [
|
| 31 |
+
r for r in template["Resources"].values() if r["Type"] == "AWS::S3::Bucket"
|
| 32 |
+
]
|
| 33 |
+
assert buckets
|
| 34 |
+
tags = buckets[0]["Properties"].get("Tags", [])
|
| 35 |
+
tag_map = {t["Key"]: t["Value"] for t in tags}
|
| 36 |
+
assert tag_map.get("Application") == "demo-llm-topic-modeller"
|
| 37 |
+
assert tag_map.get("ManagedBy") == "cdk"
|
| 38 |
+
assert tag_map.get("Repository") == "https://github.com/example/repo.git"
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def test_create_application_resource_group_synth():
|
| 42 |
+
from aws_cdk import App, Environment, Stack
|
| 43 |
+
from cdk_application_tags import create_application_resource_group
|
| 44 |
+
|
| 45 |
+
app = App()
|
| 46 |
+
stack = Stack(
|
| 47 |
+
app,
|
| 48 |
+
"ResourceGroupTest",
|
| 49 |
+
env=Environment(account="123456789012", region="eu-west-2"),
|
| 50 |
+
)
|
| 51 |
+
create_application_resource_group(
|
| 52 |
+
stack,
|
| 53 |
+
"ApplicationResourceGroup",
|
| 54 |
+
group_name="demo-llm-topic-modeller-resources",
|
| 55 |
+
tag_key="Application",
|
| 56 |
+
application_name="demo-llm-topic-modeller",
|
| 57 |
+
)
|
| 58 |
+
|
| 59 |
+
template = app.synth().get_stack_by_name("ResourceGroupTest").template
|
| 60 |
+
groups = [
|
| 61 |
+
r
|
| 62 |
+
for r in template["Resources"].values()
|
| 63 |
+
if r["Type"] == "AWS::ResourceGroups::Group"
|
| 64 |
+
]
|
| 65 |
+
assert len(groups) == 1
|
| 66 |
+
props = groups[0]["Properties"]
|
| 67 |
+
assert props["Name"] == "demo-llm-topic-modeller-resources"
|
| 68 |
+
assert all(
|
| 69 |
+
character.isalnum() or character in " _.-" for character in props["Description"]
|
| 70 |
+
)
|
| 71 |
+
assert props["ResourceQuery"]["Type"] == "TAG_FILTERS_1_0"
|
| 72 |
+
tag_filters = props["ResourceQuery"]["Query"]["TagFilters"]
|
| 73 |
+
assert any(
|
| 74 |
+
f.get("Key") == "Application"
|
| 75 |
+
and "demo-llm-topic-modeller" in f.get("Values", [])
|
| 76 |
+
for f in tag_filters
|
| 77 |
+
)
|
| 78 |
+
outputs = template.get("Outputs", {})
|
| 79 |
+
assert any("ApplicationResourceGroup" in name for name in outputs)
|
cdk/test/test_bedrock_model_invocation_logging.py
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Synth coverage for Bedrock model invocation logging (S3 + CloudWatch)."""
|
| 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_add_bedrock_s3_policy_documents_prefix_paths():
|
| 11 |
+
from aws_cdk import App, Environment, Stack
|
| 12 |
+
from aws_cdk import aws_s3 as s3
|
| 13 |
+
from cdk_functions import add_bedrock_model_invocation_s3_bucket_policy
|
| 14 |
+
|
| 15 |
+
app = App()
|
| 16 |
+
stack = Stack(
|
| 17 |
+
app,
|
| 18 |
+
"BedrockS3PolicyTest",
|
| 19 |
+
env=Environment(account="063418083240", region="eu-west-2"),
|
| 20 |
+
)
|
| 21 |
+
bucket = s3.Bucket(stack, "LogBucket", bucket_name="test-summarisation-s3-logs")
|
| 22 |
+
add_bedrock_model_invocation_s3_bucket_policy(
|
| 23 |
+
bucket,
|
| 24 |
+
region="eu-west-2",
|
| 25 |
+
account="063418083240",
|
| 26 |
+
key_prefix="bedrock-logs",
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
template = app.synth().get_stack_by_name("BedrockS3PolicyTest").template
|
| 30 |
+
policies = [
|
| 31 |
+
r
|
| 32 |
+
for r in template["Resources"].values()
|
| 33 |
+
if r["Type"] == "AWS::S3::BucketPolicy"
|
| 34 |
+
]
|
| 35 |
+
assert policies
|
| 36 |
+
blob = str(policies)
|
| 37 |
+
assert "bedrock.amazonaws.com" in blob
|
| 38 |
+
assert "BedrockModelInvocationLogs" in blob
|
| 39 |
+
assert "bedrock-logs" in blob
|
| 40 |
+
assert "063418083240" in blob
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def test_create_bedrock_model_invocation_logging_synth():
|
| 44 |
+
from aws_cdk import App, Environment, RemovalPolicy, Stack
|
| 45 |
+
from aws_cdk import aws_kms as kms
|
| 46 |
+
from aws_cdk import aws_s3 as s3
|
| 47 |
+
from cdk_functions import create_bedrock_model_invocation_logging
|
| 48 |
+
|
| 49 |
+
app = App()
|
| 50 |
+
stack = Stack(
|
| 51 |
+
app,
|
| 52 |
+
"BedrockLoggingTest",
|
| 53 |
+
env=Environment(account="123456789012", region="eu-west-2"),
|
| 54 |
+
)
|
| 55 |
+
key = kms.Key(stack, "SharedKey", removal_policy=RemovalPolicy.DESTROY)
|
| 56 |
+
bucket = s3.Bucket(
|
| 57 |
+
stack,
|
| 58 |
+
"LogBucket",
|
| 59 |
+
encryption=s3.BucketEncryption.KMS,
|
| 60 |
+
encryption_key=key,
|
| 61 |
+
removal_policy=RemovalPolicy.DESTROY,
|
| 62 |
+
auto_delete_objects=True,
|
| 63 |
+
)
|
| 64 |
+
create_bedrock_model_invocation_logging(
|
| 65 |
+
stack,
|
| 66 |
+
"BedrockModelInvocationLogging",
|
| 67 |
+
log_bucket=bucket,
|
| 68 |
+
region="eu-west-2",
|
| 69 |
+
account="123456789012",
|
| 70 |
+
key_prefix="bedrock-logs",
|
| 71 |
+
log_group_name="/aws/bedrock/test-model-invocations",
|
| 72 |
+
log_retention_days=90,
|
| 73 |
+
kms_key=key,
|
| 74 |
+
)
|
| 75 |
+
|
| 76 |
+
template = app.synth().get_stack_by_name("BedrockLoggingTest").template
|
| 77 |
+
resources = template["Resources"]
|
| 78 |
+
types = {r["Type"] for r in resources.values()}
|
| 79 |
+
|
| 80 |
+
assert "AWS::Logs::LogGroup" in types
|
| 81 |
+
assert "AWS::IAM::Role" in types
|
| 82 |
+
assert "AWS::S3::BucketPolicy" in types
|
| 83 |
+
assert "Custom::AWS" in types or any(
|
| 84 |
+
"Custom::AWS" in r.get("Type", "") for r in resources.values()
|
| 85 |
+
)
|
| 86 |
+
|
| 87 |
+
log_groups = [r for r in resources.values() if r["Type"] == "AWS::Logs::LogGroup"]
|
| 88 |
+
assert any(
|
| 89 |
+
r["Properties"].get("LogGroupName") == "/aws/bedrock/test-model-invocations"
|
| 90 |
+
for r in log_groups
|
| 91 |
+
)
|
| 92 |
+
|
| 93 |
+
roles = [r for r in resources.values() if r["Type"] == "AWS::IAM::Role"]
|
| 94 |
+
bedrock_roles = [
|
| 95 |
+
r
|
| 96 |
+
for r in roles
|
| 97 |
+
if "bedrock.amazonaws.com"
|
| 98 |
+
in str(r["Properties"].get("AssumeRolePolicyDocument", {}))
|
| 99 |
+
]
|
| 100 |
+
assert bedrock_roles
|
| 101 |
+
|
| 102 |
+
policy_blob = str(
|
| 103 |
+
[r for r in resources.values() if r["Type"] == "AWS::IAM::Policy"]
|
| 104 |
+
+ [r for r in resources.values() if r["Type"] == "AWS::KMS::Key"]
|
| 105 |
+
)
|
| 106 |
+
assert "GenerateDataKey" in policy_blob or "kms:GenerateDataKey" in str(resources)
|
cdk/test/test_cdk_install.py
ADDED
|
@@ -0,0 +1,1116 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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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["ENABLE_APPREGISTRY"] == "False"
|
| 92 |
+
assert values["ENABLE_APPLICATION_RESOURCE_GROUP"] == "True"
|
| 93 |
+
assert values["APPLICATION_TAG_KEY"] == "Application"
|
| 94 |
+
assert values["APPLICATION_NAME"].endswith("llm-topic-modeller")
|
| 95 |
+
assert values["APPLICATION_RESOURCE_GROUP_NAME"].endswith(
|
| 96 |
+
"llm-topic-modeller-resources"
|
| 97 |
+
)
|
| 98 |
+
assert values["VPC_NAME"] == "test-vpc"
|
| 99 |
+
assert values["CONTEXT_FILE"] == "precheck.context.json"
|
| 100 |
+
assert values["CDK_FOLDER"].endswith("/cdk/")
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def test_build_env_values_appregistry_opt_in():
|
| 104 |
+
answers = _demo_answers()
|
| 105 |
+
answers.enable_appregistry = True
|
| 106 |
+
answers.application_name = "demo-llm-topic-modeller"
|
| 107 |
+
values = inst.build_env_values(answers)
|
| 108 |
+
assert values["ENABLE_APPREGISTRY"] == "True"
|
| 109 |
+
assert values["APPREGISTRY_STACK_NAME"].endswith("AppRegistryStack")
|
| 110 |
+
assert values["APPREGISTRY_APPLICATION_NAME"] == "demo-llm-topic-modeller"
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def test_build_env_values_disable_application_resource_group():
|
| 114 |
+
answers = _headless_answers()
|
| 115 |
+
answers.enable_application_resource_group = False
|
| 116 |
+
values = inst.build_env_values(answers)
|
| 117 |
+
assert values["ENABLE_APPLICATION_RESOURCE_GROUP"] == "False"
|
| 118 |
+
assert values["APPLICATION_NAME"]
|
| 119 |
+
assert values["ENABLE_APPREGISTRY"] == "False"
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def test_default_application_name():
|
| 123 |
+
assert (
|
| 124 |
+
inst.default_application_name("Demo-Summarisation-")
|
| 125 |
+
== "Demo-Summarisation-llm-topic-modeller"
|
| 126 |
+
)
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def test_build_env_values_production():
|
| 130 |
+
values = inst.build_env_values(_production_answers())
|
| 131 |
+
assert values["USE_ECS_EXPRESS_MODE"] == "False"
|
| 132 |
+
assert values["USE_CLOUDFRONT"] == "True"
|
| 133 |
+
assert values["RUN_USEAST_STACK"] == "True"
|
| 134 |
+
assert values["ENABLE_RESOURCE_DELETE_PROTECTION"] == "True"
|
| 135 |
+
assert values["ACM_SSL_CERTIFICATE_ARN"].startswith("arn:aws:acm:")
|
| 136 |
+
assert values["SSL_CERTIFICATE_DOMAIN"] == "summarisation.example.com"
|
| 137 |
+
assert values["ENABLE_APPREGISTRY"] == "False"
|
| 138 |
+
assert "APPREGISTRY_STACK_NAME" not in values
|
| 139 |
+
assert values["ENABLE_APPLICATION_RESOURCE_GROUP"] == "True"
|
| 140 |
+
assert values["APPLICATION_NAME"] == "Test-Summarisation-llm-topic-modeller"
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def test_build_env_values_uses_custom_s3_bucket_names():
|
| 144 |
+
answers = _demo_answers()
|
| 145 |
+
answers.s3_log_bucket_name = "063418083240-demo-summarisation-s3-logs"
|
| 146 |
+
answers.s3_output_bucket_name = "063418083240-demo-summarisation-s3-output"
|
| 147 |
+
values = inst.build_env_values(answers)
|
| 148 |
+
assert (
|
| 149 |
+
values["S3_LOG_CONFIG_BUCKET_NAME"] == "063418083240-demo-summarisation-s3-logs"
|
| 150 |
+
)
|
| 151 |
+
assert (
|
| 152 |
+
values["S3_OUTPUT_BUCKET_NAME"] == "063418083240-demo-summarisation-s3-output"
|
| 153 |
+
)
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
def test_normalize_s3_bucket_name_truncates_and_sanitizes():
|
| 157 |
+
long_name = "A" * 80 + "/underscores"
|
| 158 |
+
normalized = inst.normalize_s3_bucket_name(long_name)
|
| 159 |
+
assert normalized == normalized.lower()
|
| 160 |
+
assert len(normalized) <= inst.S3_BUCKET_NAME_MAX_LEN
|
| 161 |
+
assert "_" not in normalized
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
def test_suggest_available_s3_bucket_name_prefers_account_prefix(monkeypatch):
|
| 165 |
+
calls: list[str] = []
|
| 166 |
+
|
| 167 |
+
def fake_resolve(name: str, **kwargs):
|
| 168 |
+
calls.append(name)
|
| 169 |
+
if name.startswith("123456789012-"):
|
| 170 |
+
return ("available", name)
|
| 171 |
+
return ("globally_taken", name)
|
| 172 |
+
|
| 173 |
+
monkeypatch.setattr("cdk_functions.resolve_s3_bucket_availability", fake_resolve)
|
| 174 |
+
suggested = inst.suggest_available_s3_bucket_name(
|
| 175 |
+
"demo-summarisation-s3-logs", "123456789012"
|
| 176 |
+
)
|
| 177 |
+
assert suggested == "123456789012-demo-summarisation-s3-logs"
|
| 178 |
+
assert calls[0] == "demo-summarisation-s3-logs"
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
def test_validate_globally_unique_env_values_flags_taken_bucket(monkeypatch):
|
| 182 |
+
monkeypatch.setattr(
|
| 183 |
+
"cdk_functions.resolve_s3_bucket_availability",
|
| 184 |
+
lambda name, **kwargs: ("globally_taken", name),
|
| 185 |
+
)
|
| 186 |
+
monkeypatch.setattr(
|
| 187 |
+
"cdk_functions.resolve_cognito_domain_prefix_availability",
|
| 188 |
+
lambda prefix, **kwargs: "available",
|
| 189 |
+
)
|
| 190 |
+
values = inst.build_env_values(_demo_answers())
|
| 191 |
+
errors = inst.validate_globally_unique_env_values(values)
|
| 192 |
+
assert any("taken globally" in err for err in errors)
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
def test_prompt_globally_unique_cognito_prefix_suggests_when_taken(monkeypatch):
|
| 196 |
+
monkeypatch.setattr(
|
| 197 |
+
"cdk_functions.resolve_cognito_domain_prefix_availability",
|
| 198 |
+
lambda prefix, **kwargs: (
|
| 199 |
+
"taken" if prefix == "demo-summarisation" else "available"
|
| 200 |
+
),
|
| 201 |
+
)
|
| 202 |
+
monkeypatch.setattr(
|
| 203 |
+
inst,
|
| 204 |
+
"suggest_available_cognito_domain_prefix",
|
| 205 |
+
lambda preferred, account_id, region, **kwargs: "063418083240-demo-summarisation",
|
| 206 |
+
)
|
| 207 |
+
monkeypatch.setattr(inst, "ask_yes_no", lambda *args, **kwargs: True)
|
| 208 |
+
result = inst._prompt_globally_unique_cognito_prefix(
|
| 209 |
+
"demo-summarisation",
|
| 210 |
+
"063418083240",
|
| 211 |
+
"eu-west-2",
|
| 212 |
+
interactive=True,
|
| 213 |
+
assume_yes=False,
|
| 214 |
+
)
|
| 215 |
+
assert result == "063418083240-demo-summarisation"
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
def test_prompt_globally_unique_cognito_prefix_rejects_taken_cli_override(monkeypatch):
|
| 219 |
+
monkeypatch.setattr(
|
| 220 |
+
"cdk_functions.resolve_cognito_domain_prefix_availability",
|
| 221 |
+
lambda prefix, **kwargs: "taken",
|
| 222 |
+
)
|
| 223 |
+
with pytest.raises(SystemExit):
|
| 224 |
+
inst._prompt_globally_unique_cognito_prefix(
|
| 225 |
+
"demo-summarisation",
|
| 226 |
+
"063418083240",
|
| 227 |
+
"eu-west-2",
|
| 228 |
+
interactive=False,
|
| 229 |
+
assume_yes=False,
|
| 230 |
+
cli_override="demo-summarisation",
|
| 231 |
+
)
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
def test_subnet_cidr_prefix_len_for_express_demo():
|
| 235 |
+
answers = _demo_answers()
|
| 236 |
+
assert inst.subnet_cidr_prefix_len_for_tier(answers, "public") == 27
|
| 237 |
+
assert inst.subnet_cidr_prefix_len_for_tier(answers, "private") == 28
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
def test_validate_public_subnet_cidr_for_express_rejects_small_blocks():
|
| 241 |
+
assert inst.validate_public_subnet_cidr_for_express("10.0.0.0/28") is not None
|
| 242 |
+
assert inst.validate_public_subnet_cidr_for_express("10.0.0.0/27") is None
|
| 243 |
+
assert inst.validate_public_subnet_cidr_for_express("10.0.0.0/26") is None
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
def test_validate_env_values_rejects_express_public_subnets_too_small():
|
| 247 |
+
values = inst.build_env_values(_demo_answers())
|
| 248 |
+
values["PUBLIC_SUBNET_CIDR_BLOCKS"] = "['10.0.0.0/28', '10.0.0.16/28']"
|
| 249 |
+
errors = inst.validate_env_values(values)
|
| 250 |
+
assert any("too small for ECS Express" in err for err in errors)
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
def test_build_env_values_headless():
|
| 254 |
+
values = inst.build_env_values(_headless_answers())
|
| 255 |
+
assert values["USE_ECS_EXPRESS_MODE"] == "False"
|
| 256 |
+
assert values["USE_CLOUDFRONT"] == "False"
|
| 257 |
+
assert values["RUN_USEAST_STACK"] == "False"
|
| 258 |
+
assert values["ENABLE_HEADLESS_DEPLOYMENT"] == "True"
|
| 259 |
+
assert values["ENABLE_S3_BATCH_ECS_TRIGGER"] == "True"
|
| 260 |
+
assert values["COGNITO_AUTH"] == "False"
|
| 261 |
+
assert values["ECS_EXPRESS_USE_PUBLIC_SUBNETS"] == "True"
|
| 262 |
+
assert values["PRIVATE_SUBNETS_TO_USE"] == ""
|
| 263 |
+
assert values["S3_LOG_CONFIG_BUCKET_NAME"] == "headless-summarisation-s3-logs"
|
| 264 |
+
assert values["S3_OUTPUT_BUCKET_NAME"] == "headless-summarisation-s3-output"
|
| 265 |
+
assert "ENABLE_BEDROCK_MODEL_INVOCATION_LOGGING" not in values
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
def test_build_env_values_bedrock_model_invocation_logging():
|
| 269 |
+
answers = _headless_answers()
|
| 270 |
+
answers.enable_bedrock_model_invocation_logging = True
|
| 271 |
+
answers.bedrock_invocation_s3_prefix = "bedrock-logs"
|
| 272 |
+
answers.bedrock_invocation_log_group_name = (
|
| 273 |
+
"/aws/bedrock/headless-model-invocations"
|
| 274 |
+
)
|
| 275 |
+
answers.bedrock_invocation_log_retention_days = "30"
|
| 276 |
+
values = inst.build_env_values(answers)
|
| 277 |
+
assert values["ENABLE_BEDROCK_MODEL_INVOCATION_LOGGING"] == "True"
|
| 278 |
+
assert values["BEDROCK_MODEL_INVOCATION_S3_PREFIX"] == "bedrock-logs"
|
| 279 |
+
assert (
|
| 280 |
+
values["BEDROCK_MODEL_INVOCATION_LOG_GROUP_NAME"]
|
| 281 |
+
== "/aws/bedrock/headless-model-invocations"
|
| 282 |
+
)
|
| 283 |
+
assert values["BEDROCK_MODEL_INVOCATION_LOG_RETENTION_DAYS"] == "30"
|
| 284 |
+
|
| 285 |
+
|
| 286 |
+
def test_validate_install_answers_bedrock_logging_requires_prefix():
|
| 287 |
+
answers = _headless_answers()
|
| 288 |
+
answers.enable_bedrock_model_invocation_logging = True
|
| 289 |
+
answers.bedrock_invocation_s3_prefix = ""
|
| 290 |
+
answers.bedrock_invocation_log_group_name = "/aws/bedrock/test"
|
| 291 |
+
errors = inst.validate_install_answers(answers)
|
| 292 |
+
assert any("S3 key prefix" in err for err in errors)
|
| 293 |
+
|
| 294 |
+
|
| 295 |
+
def test_build_env_values_bedrock_guardrails():
|
| 296 |
+
answers = _headless_answers()
|
| 297 |
+
answers.enable_bedrock_guardrails = True
|
| 298 |
+
answers.bedrock_guardrail_identifier = "gr-abc123"
|
| 299 |
+
answers.bedrock_guardrail_version = "2"
|
| 300 |
+
answers.bedrock_guardrail_trace = "enabled"
|
| 301 |
+
values = inst.build_env_values(answers)
|
| 302 |
+
assert values["ENABLE_BEDROCK_GUARDRAILS"] == "True"
|
| 303 |
+
assert values["BEDROCK_GUARDRAIL_IDENTIFIER"] == "gr-abc123"
|
| 304 |
+
assert values["BEDROCK_GUARDRAIL_VERSION"] == "2"
|
| 305 |
+
assert values["BEDROCK_GUARDRAIL_TRACE"] == "enabled"
|
| 306 |
+
|
| 307 |
+
|
| 308 |
+
def test_build_app_config_env_values_includes_bedrock_guardrails():
|
| 309 |
+
answers = _headless_answers()
|
| 310 |
+
answers.enable_bedrock_guardrails = True
|
| 311 |
+
answers.bedrock_guardrail_identifier = "gr-abc123"
|
| 312 |
+
answers.bedrock_guardrail_version = "1"
|
| 313 |
+
answers.bedrock_guardrail_trace = "disabled"
|
| 314 |
+
values = inst.build_env_values(answers)
|
| 315 |
+
updates = inst.build_app_config_env_values(values)
|
| 316 |
+
assert updates["ENABLE_BEDROCK_GUARDRAILS"] == "True"
|
| 317 |
+
assert updates["BEDROCK_GUARDRAIL_IDENTIFIER"] == "gr-abc123"
|
| 318 |
+
|
| 319 |
+
|
| 320 |
+
def test_validate_install_answers_bedrock_guardrails_requires_id_and_version():
|
| 321 |
+
answers = _headless_answers()
|
| 322 |
+
answers.enable_bedrock_guardrails = True
|
| 323 |
+
answers.bedrock_guardrail_identifier = ""
|
| 324 |
+
answers.bedrock_guardrail_version = ""
|
| 325 |
+
errors = inst.validate_install_answers(answers)
|
| 326 |
+
assert any("GUARDRAIL_IDENTIFIER" in err for err in errors)
|
| 327 |
+
assert any("GUARDRAIL_VERSION" in err for err in errors)
|
| 328 |
+
|
| 329 |
+
|
| 330 |
+
def test_default_bedrock_invocation_log_group_name():
|
| 331 |
+
assert (
|
| 332 |
+
inst.default_bedrock_invocation_log_group_name("Headless-Summarisation-")
|
| 333 |
+
== "/aws/bedrock/Headless-Summarisation-model-invocations"
|
| 334 |
+
)
|
| 335 |
+
|
| 336 |
+
|
| 337 |
+
def test_validate_env_values_rejects_bare_s3_bucket_names():
|
| 338 |
+
values = inst.build_env_values(_headless_answers())
|
| 339 |
+
values["S3_LOG_CONFIG_BUCKET_NAME"] = "s3-logs"
|
| 340 |
+
errors = inst.validate_env_values(values)
|
| 341 |
+
assert any("S3_LOG_CONFIG_BUCKET_NAME" in e for e in errors)
|
| 342 |
+
|
| 343 |
+
|
| 344 |
+
def test_headless_profile_uses_public_subnets_only():
|
| 345 |
+
assert inst.answers_use_public_subnets_only(_headless_answers()) is True
|
| 346 |
+
|
| 347 |
+
|
| 348 |
+
def test_build_env_values_production_headless():
|
| 349 |
+
answers = _production_answers()
|
| 350 |
+
answers.enable_headless = True
|
| 351 |
+
values = inst.build_env_values(answers)
|
| 352 |
+
assert values["USE_ECS_EXPRESS_MODE"] == "False"
|
| 353 |
+
assert values["USE_CLOUDFRONT"] == "False"
|
| 354 |
+
assert values["ENABLE_HEADLESS_DEPLOYMENT"] == "True"
|
| 355 |
+
assert values["ENABLE_RESOURCE_DELETE_PROTECTION"] == "True"
|
| 356 |
+
assert values.get("ECS_EXPRESS_USE_PUBLIC_SUBNETS") != "True"
|
| 357 |
+
assert "PRIVATE_SUBNET_CIDR_BLOCKS" in values
|
| 358 |
+
|
| 359 |
+
|
| 360 |
+
def test_validate_install_answers_rejects_demo_headless():
|
| 361 |
+
answers = _demo_answers()
|
| 362 |
+
answers.enable_headless = True
|
| 363 |
+
errors = inst.validate_install_answers(answers)
|
| 364 |
+
assert any("Demonstration" in err for err in errors)
|
| 365 |
+
|
| 366 |
+
|
| 367 |
+
def test_validate_install_answers_rejects_custom_express_headless():
|
| 368 |
+
answers = inst.InstallAnswers(profile="custom", enable_headless=True)
|
| 369 |
+
answers.custom_overrides["USE_ECS_EXPRESS_MODE"] = "True"
|
| 370 |
+
errors = inst.validate_install_answers(answers)
|
| 371 |
+
assert any("USE_ECS_EXPRESS_MODE=False" in err for err in errors)
|
| 372 |
+
|
| 373 |
+
|
| 374 |
+
def test_profile_allows_headless_add_on():
|
| 375 |
+
assert inst.profile_allows_headless_add_on(_demo_answers()) is False
|
| 376 |
+
assert inst.profile_allows_headless_add_on(_production_answers()) is True
|
| 377 |
+
assert inst.profile_allows_headless_add_on(_headless_answers()) is True
|
| 378 |
+
custom = inst.InstallAnswers(profile="custom")
|
| 379 |
+
assert inst.profile_allows_headless_add_on(custom) is True
|
| 380 |
+
custom.custom_overrides["USE_ECS_EXPRESS_MODE"] = "True"
|
| 381 |
+
assert inst.profile_allows_headless_add_on(custom) is False
|
| 382 |
+
|
| 383 |
+
|
| 384 |
+
def test_validate_install_answers_skips_cognito_prefix_for_headless():
|
| 385 |
+
values = inst.build_env_values(_headless_answers())
|
| 386 |
+
values["COGNITO_USER_POOL_DOMAIN_PREFIX"] = ""
|
| 387 |
+
assert inst.validate_env_values(values) == []
|
| 388 |
+
|
| 389 |
+
|
| 390 |
+
def test_validate_headless_rejects_pi():
|
| 391 |
+
values = inst.build_env_values(_headless_answers())
|
| 392 |
+
values["ENABLE_ECS_SERVICE_CONNECT"] = "True"
|
| 393 |
+
errors = inst.validate_env_values(values)
|
| 394 |
+
assert any("HEADLESS" in e for e in errors)
|
| 395 |
+
|
| 396 |
+
|
| 397 |
+
def test_validate_rejects_express_with_acm():
|
| 398 |
+
values = inst.build_env_values(_demo_answers())
|
| 399 |
+
values["ACM_SSL_CERTIFICATE_ARN"] = "arn:aws:acm:eu-west-2:123:certificate/x"
|
| 400 |
+
errors = inst.validate_env_values(values)
|
| 401 |
+
assert any("ACM_SSL_CERTIFICATE_ARN" in e for e in errors)
|
| 402 |
+
|
| 403 |
+
|
| 404 |
+
def test_build_env_values_mixed_subnet_tiers():
|
| 405 |
+
answers = _production_answers()
|
| 406 |
+
answers.public_subnet_mode = "existing"
|
| 407 |
+
answers.private_subnet_mode = "create"
|
| 408 |
+
answers.public_subnet_names = ["existing-public-a", "existing-public-b"]
|
| 409 |
+
answers.public_subnet_cidrs = ["10.244.1.0/28", "10.244.2.0/28"]
|
| 410 |
+
answers.public_subnet_azs = ["eu-west-2a", "eu-west-2b"]
|
| 411 |
+
answers.private_subnet_names = ["Demo-Summarisation-PrivateSubnet1"]
|
| 412 |
+
answers.private_subnet_cidrs = ["10.0.10.0/28"]
|
| 413 |
+
answers.private_subnet_azs = ["eu-west-2a"]
|
| 414 |
+
values = inst.build_env_values(answers)
|
| 415 |
+
assert (
|
| 416 |
+
values["PUBLIC_SUBNETS_TO_USE"] == '["existing-public-a", "existing-public-b"]'
|
| 417 |
+
)
|
| 418 |
+
assert values["PUBLIC_SUBNET_CIDR_BLOCKS"] == "['10.244.1.0/28', '10.244.2.0/28']"
|
| 419 |
+
assert values["PUBLIC_SUBNET_AVAILABILITY_ZONES"] == "['eu-west-2a', 'eu-west-2b']"
|
| 420 |
+
assert values["PRIVATE_SUBNETS_TO_USE"] == '["Demo-Summarisation-PrivateSubnet1"]'
|
| 421 |
+
assert values["PRIVATE_SUBNET_CIDR_BLOCKS"] == "['10.0.10.0/28']"
|
| 422 |
+
assert values["PRIVATE_SUBNET_AVAILABILITY_ZONES"] == "['eu-west-2a']"
|
| 423 |
+
|
| 424 |
+
|
| 425 |
+
def test_enrich_existing_subnet_details_from_aws(monkeypatch):
|
| 426 |
+
answers = _demo_answers()
|
| 427 |
+
answers.vpc_name = "test-vpc"
|
| 428 |
+
answers.public_subnet_mode = "existing"
|
| 429 |
+
answers.public_subnet_names = ["pub-a", "pub-b"]
|
| 430 |
+
answers.private_subnet_mode = "create"
|
| 431 |
+
|
| 432 |
+
monkeypatch.setattr(
|
| 433 |
+
inst,
|
| 434 |
+
"list_vpcs",
|
| 435 |
+
lambda _region: [{"name": "test-vpc", "id": "vpc-123", "cidr": "10.0.0.0/16"}],
|
| 436 |
+
)
|
| 437 |
+
monkeypatch.setattr(
|
| 438 |
+
inst,
|
| 439 |
+
"list_subnets_in_vpc",
|
| 440 |
+
lambda _vpc_id, _region: [
|
| 441 |
+
{"name": "pub-a", "cidr": "10.244.1.0/28", "az": "eu-west-2a"},
|
| 442 |
+
{"name": "pub-b", "cidr": "10.244.2.0/28", "az": "eu-west-2b"},
|
| 443 |
+
],
|
| 444 |
+
)
|
| 445 |
+
|
| 446 |
+
errors = inst.enrich_existing_subnet_details_from_aws(answers)
|
| 447 |
+
assert errors == []
|
| 448 |
+
assert answers.public_subnet_cidrs == ["10.244.1.0/28", "10.244.2.0/28"]
|
| 449 |
+
assert answers.public_subnet_azs == ["eu-west-2a", "eu-west-2b"]
|
| 450 |
+
|
| 451 |
+
|
| 452 |
+
def test_validate_subnet_answers_mixed_requires_public_names():
|
| 453 |
+
answers = _demo_answers()
|
| 454 |
+
answers.public_subnet_mode = "existing"
|
| 455 |
+
answers.private_subnet_mode = "create"
|
| 456 |
+
answers.private_subnet_names = ["new-private"]
|
| 457 |
+
errors = inst.validate_subnet_answers(answers)
|
| 458 |
+
assert any("Public subnets" in err for err in errors)
|
| 459 |
+
|
| 460 |
+
|
| 461 |
+
def test_resolve_subnet_tier_modes_per_tier_override():
|
| 462 |
+
args = argparse.Namespace(
|
| 463 |
+
subnet_mode="auto",
|
| 464 |
+
public_subnet_mode="existing",
|
| 465 |
+
private_subnet_mode="create",
|
| 466 |
+
)
|
| 467 |
+
public, private = inst.resolve_subnet_tier_modes(args)
|
| 468 |
+
assert public == "existing"
|
| 469 |
+
assert private == "create"
|
| 470 |
+
|
| 471 |
+
|
| 472 |
+
def test_suggest_vpc_cidr_block_empty_region():
|
| 473 |
+
assert inst.suggest_vpc_cidr_block([]) == "10.0.0.0/24"
|
| 474 |
+
|
| 475 |
+
|
| 476 |
+
def test_suggest_vpc_cidr_block_skips_overlaps():
|
| 477 |
+
assert inst.suggest_vpc_cidr_block(["10.0.0.0/24"]) == "10.0.1.0/24"
|
| 478 |
+
assert inst.suggest_vpc_cidr_block(["10.0.0.0/16"]) == "10.1.0.0/24"
|
| 479 |
+
|
| 480 |
+
|
| 481 |
+
def test_validate_new_vpc_cidr_rejects_overlap_and_public_space():
|
| 482 |
+
err = inst.validate_new_vpc_cidr("10.0.0.0/24", ["10.0.0.0/16"])
|
| 483 |
+
assert err is not None
|
| 484 |
+
assert "overlaps" in err
|
| 485 |
+
err = inst.validate_new_vpc_cidr("8.8.8.0/24", [])
|
| 486 |
+
assert err is not None
|
| 487 |
+
assert "RFC1918" in err
|
| 488 |
+
|
| 489 |
+
|
| 490 |
+
def test_validate_new_vpc_cidr_accepts_available_block():
|
| 491 |
+
assert inst.validate_new_vpc_cidr("10.2.0.0/24", ["10.0.0.0/16"]) is None
|
| 492 |
+
|
| 493 |
+
|
| 494 |
+
def test_prompt_new_vpc_cidr_validates_cli_override(monkeypatch):
|
| 495 |
+
answers = inst.InstallAnswers(aws_region="eu-west-2", new_vpc_cidr="10.0.0.0/24")
|
| 496 |
+
monkeypatch.setattr(
|
| 497 |
+
inst, "list_vpc_cidr_blocks_in_region", lambda _r: ["10.0.0.0/16"]
|
| 498 |
+
)
|
| 499 |
+
with pytest.raises(SystemExit):
|
| 500 |
+
inst.prompt_new_vpc_cidr(answers, interactive=False)
|
| 501 |
+
|
| 502 |
+
|
| 503 |
+
def test_prompt_new_vpc_cidr_auto_select_noninteractive(monkeypatch):
|
| 504 |
+
answers = inst.InstallAnswers(aws_region="eu-west-2")
|
| 505 |
+
monkeypatch.setattr(inst, "list_vpc_cidr_blocks_in_region", lambda _r: [])
|
| 506 |
+
inst.prompt_new_vpc_cidr(answers, interactive=False)
|
| 507 |
+
assert answers.new_vpc_cidr == "10.0.0.0/24"
|
| 508 |
+
|
| 509 |
+
|
| 510 |
+
def test_suggest_subnet_cidr_blocks_lowest_available():
|
| 511 |
+
blocks = inst.suggest_subnet_cidr_blocks("10.0.0.0/24", ["10.0.0.0/28"], 2)
|
| 512 |
+
assert blocks == ["10.0.0.16/28", "10.0.0.32/28"]
|
| 513 |
+
|
| 514 |
+
|
| 515 |
+
def test_suggest_subnet_cidr_blocks_respects_reserved():
|
| 516 |
+
blocks = inst.suggest_subnet_cidr_blocks(
|
| 517 |
+
"10.0.0.0/24",
|
| 518 |
+
[],
|
| 519 |
+
1,
|
| 520 |
+
reserved_cidrs=["10.0.0.0/28"],
|
| 521 |
+
)
|
| 522 |
+
assert blocks == ["10.0.0.16/28"]
|
| 523 |
+
|
| 524 |
+
|
| 525 |
+
def test_vpc_cidr_blocks_from_describe_includes_associations():
|
| 526 |
+
vpc = {
|
| 527 |
+
"CidrBlock": "10.0.0.0/16",
|
| 528 |
+
"CidrBlockAssociationSet": [{"CidrBlock": "10.1.0.0/16"}],
|
| 529 |
+
}
|
| 530 |
+
assert inst.vpc_cidr_blocks_from_describe(vpc) == [
|
| 531 |
+
"10.0.0.0/16",
|
| 532 |
+
"10.1.0.0/16",
|
| 533 |
+
]
|
| 534 |
+
|
| 535 |
+
|
| 536 |
+
def test_build_app_config_env_values_express_uses_in_app_cognito():
|
| 537 |
+
values = inst.build_env_values(_demo_answers())
|
| 538 |
+
updates = inst.build_app_config_env_values(values)
|
| 539 |
+
assert updates["COGNITO_AUTH"] == "True"
|
| 540 |
+
assert updates["RUN_AWS_FUNCTIONS"] == "True"
|
| 541 |
+
assert updates["S3_LOG_BUCKET"].endswith("s3-logs")
|
| 542 |
+
|
| 543 |
+
|
| 544 |
+
def test_build_app_config_env_values_express_pi_disables_main_cognito():
|
| 545 |
+
values = inst.build_env_values(_demo_answers())
|
| 546 |
+
values["ENABLE_PI_AGENT_EXPRESS_SERVICE"] = "True"
|
| 547 |
+
updates = inst.build_app_config_env_values(values)
|
| 548 |
+
assert updates["COGNITO_AUTH"] == "False"
|
| 549 |
+
|
| 550 |
+
|
| 551 |
+
def test_build_app_config_env_values_headless():
|
| 552 |
+
answers = _headless_answers()
|
| 553 |
+
values = inst.build_env_values(answers)
|
| 554 |
+
updates = inst.build_app_config_env_values(values)
|
| 555 |
+
assert updates["COGNITO_AUTH"] == "False"
|
| 556 |
+
|
| 557 |
+
|
| 558 |
+
def test_write_app_config_env_from_example(tmp_path, monkeypatch):
|
| 559 |
+
example = tmp_path / "app_config.env.example"
|
| 560 |
+
example.write_text(
|
| 561 |
+
"RUN_AWS_FUNCTIONS=True\nS3_LOG_BUCKET=placeholder\n",
|
| 562 |
+
encoding="utf-8",
|
| 563 |
+
)
|
| 564 |
+
target = tmp_path / "app_config.env"
|
| 565 |
+
monkeypatch.setattr(inst, "APP_CONFIG_ENV_EXAMPLE", example)
|
| 566 |
+
monkeypatch.setattr(inst, "APP_CONFIG_ENV_PATH", target)
|
| 567 |
+
|
| 568 |
+
answers = _demo_answers()
|
| 569 |
+
answers.write_app_config_env = True
|
| 570 |
+
values = inst.build_env_values(answers)
|
| 571 |
+
inst.write_app_config_env_file(answers, values)
|
| 572 |
+
|
| 573 |
+
written = inst.read_env_file(target)
|
| 574 |
+
assert written["RUN_AWS_FUNCTIONS"] == "True"
|
| 575 |
+
assert written["S3_LOG_BUCKET"].endswith("s3-logs")
|
| 576 |
+
assert written["COGNITO_AUTH"] == "True"
|
| 577 |
+
|
| 578 |
+
|
| 579 |
+
def test_format_list_env():
|
| 580 |
+
assert inst.format_list_env(["a", "b"]) == '["a", "b"]'
|
| 581 |
+
assert (
|
| 582 |
+
inst.format_list_env(["10.0.0.0/28"], use_single_quotes=True)
|
| 583 |
+
== "['10.0.0.0/28']"
|
| 584 |
+
)
|
| 585 |
+
assert inst.format_list_env([]) == "[]"
|
| 586 |
+
|
| 587 |
+
|
| 588 |
+
def test_write_env_file_backs_up(tmp_path):
|
| 589 |
+
env_path = tmp_path / "cdk_config.env"
|
| 590 |
+
env_path.write_text("OLD=1\n", encoding="utf-8")
|
| 591 |
+
inst.write_env_file(env_path, {"NEW": "2"})
|
| 592 |
+
backups = list(tmp_path.glob("cdk_config.env.bak.*"))
|
| 593 |
+
assert len(backups) == 1
|
| 594 |
+
assert "NEW=2" in env_path.read_text(encoding="utf-8")
|
| 595 |
+
|
| 596 |
+
|
| 597 |
+
def test_write_cdk_json_preserves_context(tmp_path, monkeypatch):
|
| 598 |
+
cdk_json = tmp_path / "cdk.json"
|
| 599 |
+
cdk_json.write_text(
|
| 600 |
+
json.dumps(
|
| 601 |
+
{
|
| 602 |
+
"app": "old-python app.py",
|
| 603 |
+
"context": {"@aws-cdk/custom:flag": True, "keep": 1},
|
| 604 |
+
}
|
| 605 |
+
),
|
| 606 |
+
encoding="utf-8",
|
| 607 |
+
)
|
| 608 |
+
monkeypatch.setattr(inst, "CDK_JSON_PATH", cdk_json)
|
| 609 |
+
monkeypatch.setattr(inst, "CDK_JSON_EXAMPLE", tmp_path / "missing.example")
|
| 610 |
+
|
| 611 |
+
py = Path(sys.executable)
|
| 612 |
+
inst.write_cdk_json(py, force=True)
|
| 613 |
+
|
| 614 |
+
data = json.loads(cdk_json.read_text(encoding="utf-8"))
|
| 615 |
+
assert data["context"]["@aws-cdk/custom:flag"] is True
|
| 616 |
+
assert data["context"]["keep"] == 1
|
| 617 |
+
assert data["app"].endswith("app.py")
|
| 618 |
+
assert "output" in data
|
| 619 |
+
backups = list(tmp_path.glob("cdk.json.bak.*"))
|
| 620 |
+
assert len(backups) == 1
|
| 621 |
+
|
| 622 |
+
|
| 623 |
+
def test_format_cdk_app_command():
|
| 624 |
+
cmd = inst.format_cdk_app_command(Path(sys.executable))
|
| 625 |
+
assert cmd.endswith("app.py")
|
| 626 |
+
assert str(sys.executable).replace("/", "\\") in cmd or sys.executable in cmd
|
| 627 |
+
|
| 628 |
+
|
| 629 |
+
def test_venv_python_paths_includes_sys_executable():
|
| 630 |
+
paths = inst._venv_python_paths()
|
| 631 |
+
assert Path(sys.executable).resolve() == paths[0].resolve()
|
| 632 |
+
|
| 633 |
+
|
| 634 |
+
def test_merge_preset_custom():
|
| 635 |
+
merged = inst.merge_preset("demo", {"ECS_TASK_MEMORY_SIZE": "8192"})
|
| 636 |
+
assert merged["USE_ECS_EXPRESS_MODE"] == "True"
|
| 637 |
+
assert merged["ECS_TASK_MEMORY_SIZE"] == "8192"
|
| 638 |
+
|
| 639 |
+
|
| 640 |
+
def test_build_env_values_pi_express_forced_off():
|
| 641 |
+
answers = _demo_answers()
|
| 642 |
+
answers.enable_pi_express = True
|
| 643 |
+
values = inst.build_env_values(answers)
|
| 644 |
+
assert values["ENABLE_PI_AGENT_EXPRESS_SERVICE"] == "False"
|
| 645 |
+
assert values["ENABLE_PI_AGENT_ECS_SERVICE"] == "False"
|
| 646 |
+
|
| 647 |
+
|
| 648 |
+
def test_build_pi_agent_env_values_express_skips_root_path():
|
| 649 |
+
answers = _demo_answers()
|
| 650 |
+
answers.enable_pi_express = True
|
| 651 |
+
env = inst.build_pi_agent_env_values(answers)
|
| 652 |
+
assert env["RUN_FASTAPI"] == "True"
|
| 653 |
+
assert "PI_ROOT_PATH" not in env
|
| 654 |
+
|
| 655 |
+
|
| 656 |
+
def test_build_env_values_pi_production_host_forced_off():
|
| 657 |
+
answers = _production_answers()
|
| 658 |
+
answers.enable_pi_legacy = True
|
| 659 |
+
answers.enable_service_connect = True
|
| 660 |
+
answers.pi_alb_routing = "host"
|
| 661 |
+
answers.pi_alb_host_header = "agent.example.com"
|
| 662 |
+
values = inst.build_env_values(answers)
|
| 663 |
+
assert values["ENABLE_PI_AGENT_ECS_SERVICE"] == "False"
|
| 664 |
+
assert values["ENABLE_PI_AGENT_EXPRESS_SERVICE"] == "False"
|
| 665 |
+
|
| 666 |
+
|
| 667 |
+
def test_validate_pi_host_requires_header():
|
| 668 |
+
values = inst.build_env_values(_production_answers())
|
| 669 |
+
values["ENABLE_PI_AGENT_ECS_SERVICE"] = "True"
|
| 670 |
+
values["ENABLE_ECS_SERVICE_CONNECT"] = "True"
|
| 671 |
+
values["PI_ALB_ROUTING"] = "host"
|
| 672 |
+
values["PI_ALB_HOST_HEADER"] = ""
|
| 673 |
+
errors = inst.validate_env_values(values)
|
| 674 |
+
assert any("PI_ALB_HOST_HEADER" in e for e in errors)
|
| 675 |
+
|
| 676 |
+
|
| 677 |
+
def test_validate_pi_express_skips_alb_routing():
|
| 678 |
+
values = inst.build_env_values(_demo_answers())
|
| 679 |
+
values["ENABLE_PI_AGENT_EXPRESS_SERVICE"] = "True"
|
| 680 |
+
values["USE_ECS_EXPRESS_MODE"] = "True"
|
| 681 |
+
assert inst.validate_env_values(values) == []
|
| 682 |
+
|
| 683 |
+
|
| 684 |
+
def test_build_pi_agent_env_values():
|
| 685 |
+
answers = _demo_answers()
|
| 686 |
+
answers.enable_pi_express = False
|
| 687 |
+
answers.enable_pi_legacy = True
|
| 688 |
+
answers.pi_alb_routing = "path"
|
| 689 |
+
answers.pi_alb_path_prefix = "/pi"
|
| 690 |
+
values = inst.build_pi_agent_env_values(answers)
|
| 691 |
+
assert values["PI_DEPLOYMENT_PROFILE"] == "aws-ecs"
|
| 692 |
+
assert values["DOC_SUMMARISATION_GRADIO_URL"] == "http://llm-topic:7860"
|
| 693 |
+
assert values["PI_ROOT_PATH"] == "/pi"
|
| 694 |
+
|
| 695 |
+
|
| 696 |
+
def test_apply_pi_cli_flags_enable_pi_demo():
|
| 697 |
+
answers = inst.InstallAnswers(profile="demo")
|
| 698 |
+
args = argparse.Namespace(
|
| 699 |
+
enable_pi=True,
|
| 700 |
+
enable_pi_express=False,
|
| 701 |
+
enable_pi_legacy=False,
|
| 702 |
+
pi_alb_routing=None,
|
| 703 |
+
pi_path_prefix="",
|
| 704 |
+
pi_host_header="",
|
| 705 |
+
pi_listener_priority="",
|
| 706 |
+
pi_gradio_port="",
|
| 707 |
+
sc_discovery_name="",
|
| 708 |
+
pi_provider="",
|
| 709 |
+
skip_pi_agent_env=False,
|
| 710 |
+
)
|
| 711 |
+
inst.apply_pi_cli_flags(args, answers)
|
| 712 |
+
assert answers.enable_pi_express is True
|
| 713 |
+
|
| 714 |
+
|
| 715 |
+
def test_stacks_to_check_includes_appregistry_when_enabled():
|
| 716 |
+
checks = inst.stacks_to_check(
|
| 717 |
+
"eu-west-2",
|
| 718 |
+
{
|
| 719 |
+
"ENABLE_APPREGISTRY": "True",
|
| 720 |
+
"APPREGISTRY_STACK_NAME": "Demo-Summarisation-AppRegistryStack",
|
| 721 |
+
},
|
| 722 |
+
)
|
| 723 |
+
names = [name for name, _ in checks]
|
| 724 |
+
assert names == [
|
| 725 |
+
inst.CLOUDFRONT_STACK,
|
| 726 |
+
"Demo-Summarisation-AppRegistryStack",
|
| 727 |
+
inst.REGIONAL_STACK,
|
| 728 |
+
]
|
| 729 |
+
assert checks[0][1] == inst.CLOUDFRONT_STACK_REGION
|
| 730 |
+
assert checks[-1] == (inst.REGIONAL_STACK, "eu-west-2")
|
| 731 |
+
|
| 732 |
+
|
| 733 |
+
def test_stacks_to_check_without_appregistry():
|
| 734 |
+
checks = inst.stacks_to_check("eu-west-2", {"ENABLE_APPREGISTRY": "False"})
|
| 735 |
+
assert [name for name, _ in checks] == [
|
| 736 |
+
inst.CLOUDFRONT_STACK,
|
| 737 |
+
inst.REGIONAL_STACK,
|
| 738 |
+
]
|
| 739 |
+
|
| 740 |
+
|
| 741 |
+
def test_derived_appregistry_stack_name_from_cdk_prefix():
|
| 742 |
+
name = inst.derived_appregistry_stack_name(
|
| 743 |
+
{"CDK_PREFIX": "Demo-Summarisation-", "ENABLE_APPREGISTRY": "True"}
|
| 744 |
+
)
|
| 745 |
+
assert name == "Demo-Summarisation-AppRegistryStack"
|
| 746 |
+
|
| 747 |
+
|
| 748 |
+
def test_stacks_to_check_derives_appregistry_from_cdk_prefix():
|
| 749 |
+
checks = inst.stacks_to_check(
|
| 750 |
+
"eu-west-2",
|
| 751 |
+
{
|
| 752 |
+
"CDK_PREFIX": "Demo-Summarisation-",
|
| 753 |
+
"ENABLE_APPREGISTRY": "True",
|
| 754 |
+
},
|
| 755 |
+
)
|
| 756 |
+
assert "Demo-Summarisation-AppRegistryStack" in [name for name, _ in checks]
|
| 757 |
+
|
| 758 |
+
|
| 759 |
+
def test_stacks_to_check_skips_cloudfront_when_disabled():
|
| 760 |
+
checks = inst.stacks_to_check(
|
| 761 |
+
"eu-west-2",
|
| 762 |
+
{
|
| 763 |
+
"USE_CLOUDFRONT": "False",
|
| 764 |
+
"RUN_USEAST_STACK": "False",
|
| 765 |
+
"ENABLE_APPREGISTRY": "False",
|
| 766 |
+
},
|
| 767 |
+
)
|
| 768 |
+
assert checks == [(inst.REGIONAL_STACK, "eu-west-2")]
|
| 769 |
+
|
| 770 |
+
|
| 771 |
+
def test_discover_existing_doc_summarisation_stacks_order(monkeypatch):
|
| 772 |
+
monkeypatch.setattr(
|
| 773 |
+
inst, "list_regional_appregistry_stack_names", lambda _region: []
|
| 774 |
+
)
|
| 775 |
+
|
| 776 |
+
def fake_describe(stack_name: str, region: str):
|
| 777 |
+
if stack_name == inst.REGIONAL_STACK and region == "eu-west-2":
|
| 778 |
+
return inst.ExistingStack(
|
| 779 |
+
name=stack_name,
|
| 780 |
+
region=region,
|
| 781 |
+
status="UPDATE_COMPLETE",
|
| 782 |
+
)
|
| 783 |
+
if (
|
| 784 |
+
stack_name == inst.CLOUDFRONT_STACK
|
| 785 |
+
and region == inst.CLOUDFRONT_STACK_REGION
|
| 786 |
+
):
|
| 787 |
+
return inst.ExistingStack(
|
| 788 |
+
name=stack_name,
|
| 789 |
+
region=region,
|
| 790 |
+
status="CREATE_COMPLETE",
|
| 791 |
+
termination_protection=True,
|
| 792 |
+
)
|
| 793 |
+
return None
|
| 794 |
+
|
| 795 |
+
monkeypatch.setattr(inst, "describe_existing_stack", fake_describe)
|
| 796 |
+
found = inst.discover_existing_llm_topic_stacks("eu-west-2")
|
| 797 |
+
assert [s.name for s in found] == [inst.CLOUDFRONT_STACK, inst.REGIONAL_STACK]
|
| 798 |
+
assert found[0].termination_protection is True
|
| 799 |
+
|
| 800 |
+
|
| 801 |
+
def test_discover_existing_stacks_continues_after_access_denied(monkeypatch):
|
| 802 |
+
from botocore.exceptions import ClientError
|
| 803 |
+
|
| 804 |
+
monkeypatch.setattr(
|
| 805 |
+
inst, "list_regional_appregistry_stack_names", lambda _region: []
|
| 806 |
+
)
|
| 807 |
+
|
| 808 |
+
def fake_describe(stack_name: str, region: str):
|
| 809 |
+
if (
|
| 810 |
+
stack_name == inst.CLOUDFRONT_STACK
|
| 811 |
+
and region == inst.CLOUDFRONT_STACK_REGION
|
| 812 |
+
):
|
| 813 |
+
raise ClientError(
|
| 814 |
+
{
|
| 815 |
+
"Error": {
|
| 816 |
+
"Code": "AccessDenied",
|
| 817 |
+
"Message": "explicit deny in SCP",
|
| 818 |
+
}
|
| 819 |
+
},
|
| 820 |
+
"DescribeStacks",
|
| 821 |
+
)
|
| 822 |
+
if stack_name == inst.REGIONAL_STACK and region == "eu-west-2":
|
| 823 |
+
return inst.ExistingStack(
|
| 824 |
+
name=stack_name,
|
| 825 |
+
region=region,
|
| 826 |
+
status="UPDATE_COMPLETE",
|
| 827 |
+
)
|
| 828 |
+
return None
|
| 829 |
+
|
| 830 |
+
monkeypatch.setattr(inst, "describe_existing_stack", fake_describe)
|
| 831 |
+
found = inst.discover_existing_llm_topic_stacks("eu-west-2")
|
| 832 |
+
assert [s.name for s in found] == [inst.REGIONAL_STACK]
|
| 833 |
+
|
| 834 |
+
|
| 835 |
+
def test_discover_includes_orphan_appregistry_when_disabled_in_config(monkeypatch):
|
| 836 |
+
monkeypatch.setattr(
|
| 837 |
+
inst,
|
| 838 |
+
"list_regional_appregistry_stack_names",
|
| 839 |
+
lambda _region: ["Old-Summarisation-AppRegistryStack"],
|
| 840 |
+
)
|
| 841 |
+
|
| 842 |
+
def fake_describe(stack_name: str, region: str):
|
| 843 |
+
if stack_name == "Old-Summarisation-AppRegistryStack":
|
| 844 |
+
return inst.ExistingStack(
|
| 845 |
+
name=stack_name,
|
| 846 |
+
region=region,
|
| 847 |
+
status="CREATE_COMPLETE",
|
| 848 |
+
)
|
| 849 |
+
return None
|
| 850 |
+
|
| 851 |
+
monkeypatch.setattr(inst, "describe_existing_stack", fake_describe)
|
| 852 |
+
found = inst.discover_existing_llm_topic_stacks(
|
| 853 |
+
"eu-west-2",
|
| 854 |
+
{"ENABLE_APPREGISTRY": "False"},
|
| 855 |
+
)
|
| 856 |
+
assert [s.name for s in found] == ["Old-Summarisation-AppRegistryStack"]
|
| 857 |
+
|
| 858 |
+
|
| 859 |
+
def test_handle_existing_stacks_force_delete(monkeypatch):
|
| 860 |
+
stacks = [
|
| 861 |
+
inst.ExistingStack(
|
| 862 |
+
name=inst.CLOUDFRONT_STACK,
|
| 863 |
+
region=inst.CLOUDFRONT_STACK_REGION,
|
| 864 |
+
status="CREATE_COMPLETE",
|
| 865 |
+
)
|
| 866 |
+
]
|
| 867 |
+
deleted: list = []
|
| 868 |
+
|
| 869 |
+
monkeypatch.setattr(
|
| 870 |
+
inst,
|
| 871 |
+
"discover_existing_llm_topic_stacks",
|
| 872 |
+
lambda *_a, **_k: stacks,
|
| 873 |
+
)
|
| 874 |
+
monkeypatch.setattr(
|
| 875 |
+
inst,
|
| 876 |
+
"force_delete_cloudformation_stacks",
|
| 877 |
+
lambda s, **kwargs: deleted.extend(s),
|
| 878 |
+
)
|
| 879 |
+
|
| 880 |
+
args = argparse.Namespace(
|
| 881 |
+
skip_stack_check=False,
|
| 882 |
+
config_only=False,
|
| 883 |
+
synth_only=False,
|
| 884 |
+
force_delete_stacks=True,
|
| 885 |
+
yes=True,
|
| 886 |
+
)
|
| 887 |
+
inst.handle_existing_stacks_at_start(args, "eu-west-2")
|
| 888 |
+
assert deleted == stacks
|
| 889 |
+
|
| 890 |
+
|
| 891 |
+
def test_handle_existing_stacks_yes_without_force_skips_delete(monkeypatch):
|
| 892 |
+
monkeypatch.setattr(
|
| 893 |
+
inst,
|
| 894 |
+
"discover_existing_llm_topic_stacks",
|
| 895 |
+
lambda *_a, **_k: [
|
| 896 |
+
inst.ExistingStack(
|
| 897 |
+
name=inst.REGIONAL_STACK,
|
| 898 |
+
region="eu-west-2",
|
| 899 |
+
status="CREATE_COMPLETE",
|
| 900 |
+
)
|
| 901 |
+
],
|
| 902 |
+
)
|
| 903 |
+
monkeypatch.setattr(
|
| 904 |
+
inst,
|
| 905 |
+
"force_delete_cloudformation_stacks",
|
| 906 |
+
lambda *_a, **_k: (_ for _ in ()).throw(AssertionError("should not delete")),
|
| 907 |
+
)
|
| 908 |
+
|
| 909 |
+
args = argparse.Namespace(
|
| 910 |
+
skip_stack_check=False,
|
| 911 |
+
config_only=False,
|
| 912 |
+
synth_only=False,
|
| 913 |
+
force_delete_stacks=False,
|
| 914 |
+
yes=True,
|
| 915 |
+
)
|
| 916 |
+
inst.handle_existing_stacks_at_start(args, "eu-west-2")
|
| 917 |
+
|
| 918 |
+
|
| 919 |
+
def test_write_pi_agent_env_file_minimal(tmp_path, monkeypatch):
|
| 920 |
+
answers = _demo_answers()
|
| 921 |
+
answers.enable_pi_express = True
|
| 922 |
+
target = tmp_path / "pi_agent.env"
|
| 923 |
+
monkeypatch.setattr(inst, "PI_AGENT_ENV_PATH", target)
|
| 924 |
+
monkeypatch.setattr(inst, "PI_AGENT_ENV_EXAMPLE", tmp_path / "missing.example")
|
| 925 |
+
inst.write_pi_agent_env_file(answers)
|
| 926 |
+
text = target.read_text(encoding="utf-8")
|
| 927 |
+
assert "PI_DEPLOYMENT_PROFILE=aws-ecs" in text
|
| 928 |
+
assert "DOC_SUMMARISATION_GRADIO_URL=http://llm-topic:7860" in text
|
| 929 |
+
|
| 930 |
+
|
| 931 |
+
def test_run_cdk_command_invokes_cdk_cli_not_python(monkeypatch):
|
| 932 |
+
calls: list = []
|
| 933 |
+
|
| 934 |
+
def fake_run(cmd, **kwargs):
|
| 935 |
+
calls.append((cmd, kwargs))
|
| 936 |
+
return subprocess.CompletedProcess(cmd, 0)
|
| 937 |
+
|
| 938 |
+
monkeypatch.setattr(inst, "resolve_cdk_executable", lambda: r"C:\npm\cdk.cmd")
|
| 939 |
+
monkeypatch.setattr(inst.subprocess, "run", fake_run)
|
| 940 |
+
inst.run_cdk_command(["synth"], check=False)
|
| 941 |
+
cmd, kwargs = calls[0]
|
| 942 |
+
assert cmd == [r"C:\npm\cdk.cmd", "synth"]
|
| 943 |
+
assert "executable" not in kwargs
|
| 944 |
+
|
| 945 |
+
|
| 946 |
+
def test_build_cdk_subprocess_env_overrides_stale_defaults(tmp_path, monkeypatch):
|
| 947 |
+
env_path = tmp_path / "config" / "cdk_config.env"
|
| 948 |
+
env_path.parent.mkdir(parents=True)
|
| 949 |
+
env_path.write_text(
|
| 950 |
+
"VPC_NAME=my-vpc\nCDK_PREFIX=MyPrefix-\nAWS_REGION=eu-west-2\n",
|
| 951 |
+
encoding="utf-8",
|
| 952 |
+
)
|
| 953 |
+
monkeypatch.setattr(inst, "ENV_PATH", env_path)
|
| 954 |
+
monkeypatch.setattr(inst, "CDK_DIR", tmp_path)
|
| 955 |
+
monkeypatch.setenv("VPC_NAME", "")
|
| 956 |
+
monkeypatch.setenv("CDK_PREFIX", "")
|
| 957 |
+
|
| 958 |
+
env = inst.build_cdk_subprocess_env()
|
| 959 |
+
assert env["VPC_NAME"] == "my-vpc"
|
| 960 |
+
assert env["CDK_PREFIX"] == "MyPrefix-"
|
| 961 |
+
assert env["CDK_CONFIG_PATH"] == str(env_path)
|
| 962 |
+
|
| 963 |
+
|
| 964 |
+
def test_apply_cdk_runtime_env_sets_paths(tmp_path, monkeypatch):
|
| 965 |
+
env_path = tmp_path / "cdk_config.env"
|
| 966 |
+
monkeypatch.setattr(inst, "ENV_PATH", env_path)
|
| 967 |
+
inst.apply_cdk_runtime_env(
|
| 968 |
+
{"CDK_FOLDER": "C:/example/cdk/", "AWS_REGION": "eu-west-2"}
|
| 969 |
+
)
|
| 970 |
+
assert os.environ["CDK_CONFIG_PATH"] == str(env_path)
|
| 971 |
+
assert os.environ["CDK_FOLDER"] == "C:/example/cdk/"
|
| 972 |
+
|
| 973 |
+
|
| 974 |
+
def test_run_smoke_test_if_needed_skips_config_only(monkeypatch):
|
| 975 |
+
called = []
|
| 976 |
+
|
| 977 |
+
def fake_smoke(_python_exe):
|
| 978 |
+
called.append(True)
|
| 979 |
+
|
| 980 |
+
monkeypatch.setattr(inst, "smoke_test_python_app", fake_smoke)
|
| 981 |
+
args = argparse.Namespace(config_only=True, skip_cdk_json=False)
|
| 982 |
+
inst.run_smoke_test_if_needed(Path(sys.executable), args)
|
| 983 |
+
assert called == []
|
| 984 |
+
|
| 985 |
+
|
| 986 |
+
def test_main_writes_config_before_smoke_test(monkeypatch, tmp_path):
|
| 987 |
+
call_order: list[str] = []
|
| 988 |
+
config_dir = tmp_path / "config"
|
| 989 |
+
config_dir.mkdir()
|
| 990 |
+
env_path = config_dir / "cdk_config.env"
|
| 991 |
+
cdk_json = tmp_path / "cdk.json"
|
| 992 |
+
|
| 993 |
+
monkeypatch.setattr(inst, "CONFIG_DIR", config_dir)
|
| 994 |
+
monkeypatch.setattr(inst, "ENV_PATH", env_path)
|
| 995 |
+
monkeypatch.setattr(inst, "CDK_JSON_PATH", cdk_json)
|
| 996 |
+
monkeypatch.setattr(inst, "CDK_DIR", tmp_path)
|
| 997 |
+
monkeypatch.setattr(inst, "check_cdk_cli", lambda: "2.0.0")
|
| 998 |
+
monkeypatch.setattr(
|
| 999 |
+
inst,
|
| 1000 |
+
"handle_existing_stacks_at_start",
|
| 1001 |
+
lambda *_a, **_k: None,
|
| 1002 |
+
)
|
| 1003 |
+
monkeypatch.setattr(
|
| 1004 |
+
inst,
|
| 1005 |
+
"resolve_python_executable",
|
| 1006 |
+
lambda **_kw: Path(sys.executable),
|
| 1007 |
+
)
|
| 1008 |
+
monkeypatch.setattr(inst, "write_cdk_json", lambda *_a, **_k: cdk_json)
|
| 1009 |
+
|
| 1010 |
+
def fake_wizard(_args):
|
| 1011 |
+
call_order.append("wizard")
|
| 1012 |
+
return _demo_answers()
|
| 1013 |
+
|
| 1014 |
+
def fake_write_env_file(path, values):
|
| 1015 |
+
call_order.append("write_config")
|
| 1016 |
+
path.write_text("VPC_NAME=test-vpc\n", encoding="utf-8")
|
| 1017 |
+
return values
|
| 1018 |
+
|
| 1019 |
+
def fake_smoke(_python_exe):
|
| 1020 |
+
call_order.append("smoke")
|
| 1021 |
+
|
| 1022 |
+
monkeypatch.setattr(inst, "run_wizard", fake_wizard)
|
| 1023 |
+
monkeypatch.setattr(inst, "write_env_file", fake_write_env_file)
|
| 1024 |
+
monkeypatch.setattr(inst, "smoke_test_python_app", fake_smoke)
|
| 1025 |
+
monkeypatch.setattr(inst, "print_summary", lambda *_a, **_k: None)
|
| 1026 |
+
monkeypatch.setattr(inst, "ask_yes_no", lambda *_a, **_k: True)
|
| 1027 |
+
monkeypatch.setattr(inst, "cdk_bootstrap_needed", lambda *_a, **_k: False)
|
| 1028 |
+
monkeypatch.setattr(inst, "run_cdk_command", lambda *_a, **_k: None)
|
| 1029 |
+
|
| 1030 |
+
inst.main(
|
| 1031 |
+
[
|
| 1032 |
+
"--yes",
|
| 1033 |
+
"--profile",
|
| 1034 |
+
"demo",
|
| 1035 |
+
"--vpc-name",
|
| 1036 |
+
"test-vpc",
|
| 1037 |
+
"--synth-only",
|
| 1038 |
+
]
|
| 1039 |
+
)
|
| 1040 |
+
|
| 1041 |
+
assert call_order.index("wizard") < call_order.index("write_config")
|
| 1042 |
+
assert call_order.index("write_config") < call_order.index("smoke")
|
| 1043 |
+
|
| 1044 |
+
|
| 1045 |
+
def test_resolve_fixup_env_values_derives_service_from_prefix():
|
| 1046 |
+
values = {"CDK_PREFIX": "Demo-Summarisation-", "USE_ECS_EXPRESS_MODE": "True"}
|
| 1047 |
+
resolved = inst.resolve_fixup_env_values(values)
|
| 1048 |
+
assert resolved["ECS_EXPRESS_SERVICE_NAME"] == "Demo-Summarisation-ECSService"
|
| 1049 |
+
assert resolved["CLUSTER_NAME"] == "Demo-Summarisation-Cluster"
|
| 1050 |
+
assert (
|
| 1051 |
+
resolved["ECS_PI_EXPRESS_SERVICE_NAME"] == "Demo-Summarisation-PiExpressService"
|
| 1052 |
+
)
|
| 1053 |
+
|
| 1054 |
+
|
| 1055 |
+
def test_apply_post_deploy_fixup_express_syncs_cognito_secret_not_alb(monkeypatch):
|
| 1056 |
+
import cdk_post_deploy as post
|
| 1057 |
+
|
| 1058 |
+
values = {
|
| 1059 |
+
"USE_ECS_EXPRESS_MODE": "True",
|
| 1060 |
+
"USE_CLOUDFRONT": "False",
|
| 1061 |
+
"AWS_REGION": "eu-west-2",
|
| 1062 |
+
"CDK_PREFIX": "Demo-Summarisation-",
|
| 1063 |
+
"ECS_EXPRESS_COGNITO_REDIRECT_BASE": "",
|
| 1064 |
+
}
|
| 1065 |
+
outputs = {
|
| 1066 |
+
"ExpressServiceEndpoint": "https://express.example.com",
|
| 1067 |
+
"CognitoPoolId": "pool-1",
|
| 1068 |
+
"CognitoAppClientId": "client-1",
|
| 1069 |
+
}
|
| 1070 |
+
monkeypatch.setattr(
|
| 1071 |
+
inst,
|
| 1072 |
+
"fetch_stack_output",
|
| 1073 |
+
lambda _stack, key, _region: outputs.get(key),
|
| 1074 |
+
)
|
| 1075 |
+
monkeypatch.setattr(inst, "patch_env_file", lambda *_a, **_k: None)
|
| 1076 |
+
monkeypatch.setattr(inst, "ask_yes_no", lambda *_a, **_k: True)
|
| 1077 |
+
redeploy_calls: list = []
|
| 1078 |
+
monkeypatch.setattr(
|
| 1079 |
+
inst,
|
| 1080 |
+
"run_cdk_command",
|
| 1081 |
+
lambda *args, **_k: redeploy_calls.append(args),
|
| 1082 |
+
)
|
| 1083 |
+
monkeypatch.setattr(
|
| 1084 |
+
post,
|
| 1085 |
+
"cognito_alb_callbacks_need_update",
|
| 1086 |
+
lambda *_a, **_k: True,
|
| 1087 |
+
)
|
| 1088 |
+
monkeypatch.setattr(
|
| 1089 |
+
post,
|
| 1090 |
+
"apply_cognito_alb_callback_fixup",
|
| 1091 |
+
lambda *_a, **_k: True,
|
| 1092 |
+
)
|
| 1093 |
+
secret_fixup_calls: list = []
|
| 1094 |
+
monkeypatch.setattr(
|
| 1095 |
+
post,
|
| 1096 |
+
"apply_cognito_secret_fixup_from_stack",
|
| 1097 |
+
lambda **_k: secret_fixup_calls.append(_k) or True,
|
| 1098 |
+
)
|
| 1099 |
+
|
| 1100 |
+
assert inst.apply_post_deploy_fixup(values, assume_yes=False) is True
|
| 1101 |
+
assert redeploy_calls == []
|
| 1102 |
+
assert secret_fixup_calls
|
| 1103 |
+
assert secret_fixup_calls[0]["main_service_name"] == "Demo-Summarisation-ECSService"
|
| 1104 |
+
assert secret_fixup_calls[0]["cluster_name"] == "Demo-Summarisation-Cluster"
|
| 1105 |
+
|
| 1106 |
+
|
| 1107 |
+
def test_jsii_import_failure_hint_detects_json_decode_error():
|
| 1108 |
+
hint = inst._jsii_import_failure_hint(
|
| 1109 |
+
"json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)"
|
| 1110 |
+
)
|
| 1111 |
+
assert "JSII Node.js helper" in hint
|
| 1112 |
+
assert "node --version" in hint
|
| 1113 |
+
|
| 1114 |
+
|
| 1115 |
+
def test_jsii_import_failure_hint_empty_for_other_errors():
|
| 1116 |
+
assert inst._jsii_import_failure_hint("ModuleNotFoundError: aws_cdk") == ""
|
cdk/test/test_cdk_post_deploy.py
ADDED
|
@@ -0,0 +1,411 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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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_LOG_CONFIG_BUCKET_NAME": "my-log-bucket",
|
| 360 |
+
"S3_BATCH_INPUT_PREFIX": "input/",
|
| 361 |
+
"S3_BATCH_ENV_PREFIX": "input/config/",
|
| 362 |
+
"S3_BATCH_DEFAULT_PARAMS_KEY": "general-config/app_defaults.env",
|
| 363 |
+
"S3_BATCH_LAMBDA_FUNCTION_NAME": "Headless-Summarisation-S3BatchEcsTrigger",
|
| 364 |
+
"ECS_LOG_GROUP_NAME": "/ecs/headless-summarisation-ecsservice-logs",
|
| 365 |
+
}
|
| 366 |
+
)
|
| 367 |
+
out = capsys.readouterr().out
|
| 368 |
+
assert (
|
| 369 |
+
"Upload a consultation spreadsheet (.xlsx) to s3://my-output-bucket/input/"
|
| 370 |
+
in out
|
| 371 |
+
)
|
| 372 |
+
assert "example_headless_env_file.env" in out
|
| 373 |
+
assert "s3://my-output-bucket/input/config/" in out
|
| 374 |
+
assert "Headless-Summarisation-S3BatchEcsTrigger" in out
|
| 375 |
+
assert "s3://my-output-bucket/output/<session-folder>/" in out
|
| 376 |
+
assert "s3://my-log-bucket/general-config/app_defaults.env" in out
|
| 377 |
+
assert "tools/config.py" in out
|
| 378 |
+
|
| 379 |
+
|
| 380 |
+
def test_seed_headless_batch_s3_layout_creates_prefixes(tmp_path):
|
| 381 |
+
from botocore.exceptions import ClientError
|
| 382 |
+
|
| 383 |
+
example = tmp_path / "example_headless_env_file.env"
|
| 384 |
+
example.write_text("DIRECT_MODE_TASK=redact\n", encoding="utf-8")
|
| 385 |
+
defaults = tmp_path / "app_defaults.env"
|
| 386 |
+
defaults.write_text("RUN_DIRECT_MODE=1\nS3_OUTPUTS_BUCKET=\n", encoding="utf-8")
|
| 387 |
+
|
| 388 |
+
missing = ClientError(
|
| 389 |
+
{"Error": {"Code": "404", "Message": "Not Found"}},
|
| 390 |
+
"HeadObject",
|
| 391 |
+
)
|
| 392 |
+
s3 = MagicMock()
|
| 393 |
+
s3.head_object.side_effect = missing
|
| 394 |
+
|
| 395 |
+
with patch("cdk_post_deploy.boto3.client", return_value=s3):
|
| 396 |
+
post.seed_headless_batch_s3_layout(
|
| 397 |
+
"my-bucket",
|
| 398 |
+
example_env_local_path=str(example),
|
| 399 |
+
log_bucket="my-log-bucket",
|
| 400 |
+
app_defaults_local_path=str(defaults),
|
| 401 |
+
s3_outputs_bucket_name="my-bucket",
|
| 402 |
+
aws_region="eu-west-2",
|
| 403 |
+
)
|
| 404 |
+
|
| 405 |
+
put_calls = s3.put_object.call_args_list
|
| 406 |
+
assert len(put_calls) == 4
|
| 407 |
+
keys_by_bucket = [(call.kwargs["Bucket"], call.kwargs["Key"]) for call in put_calls]
|
| 408 |
+
assert ("my-bucket", "input/") in keys_by_bucket
|
| 409 |
+
assert ("my-bucket", "input/config/") in keys_by_bucket
|
| 410 |
+
assert ("my-bucket", "input/config/example_headless_env_file.env") in keys_by_bucket
|
| 411 |
+
assert ("my-log-bucket", "general-config/app_defaults.env") in keys_by_bucket
|
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_modelling.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 |
+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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_modelling.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_modelling.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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|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Tests for Pi on ECS Express Mode helpers and config rules."""
|
| 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_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,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def test_build_headless_app_defaults_env_merges_bedrock_guardrails():
|
| 26 |
+
seed_dir = str(CDK_DIR / "config" / "headless_s3_seed")
|
| 27 |
+
content = build_headless_app_defaults_env_content(
|
| 28 |
+
seed_dir,
|
| 29 |
+
s3_outputs_bucket_name="test-output-bucket",
|
| 30 |
+
env_overrides={
|
| 31 |
+
"ENABLE_BEDROCK_GUARDRAILS": "True",
|
| 32 |
+
"BEDROCK_GUARDRAIL_IDENTIFIER": "gr-test",
|
| 33 |
+
"BEDROCK_GUARDRAIL_VERSION": "1",
|
| 34 |
+
"BEDROCK_GUARDRAIL_TRACE": "disabled",
|
| 35 |
+
},
|
| 36 |
+
)
|
| 37 |
+
assert "ENABLE_BEDROCK_GUARDRAILS=True" in content
|
| 38 |
+
assert "BEDROCK_GUARDRAIL_IDENTIFIER=gr-test" in content
|
| 39 |
+
assert "# ENABLE_BEDROCK_GUARDRAILS" not in content
|
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 |
+
)
|