diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml new file mode 100644 index 0000000..1152d19 --- /dev/null +++ b/.github/workflows/deploy.yml @@ -0,0 +1,138 @@ +name: Deploy + +# Runs only after the "CI" workflow (lint, typecheck, tests, cdk synth) +# finishes successfully on main — never deploys code that hasn't passed +# validation. Triggered on push to main only; no manual dispatch. +on: + workflow_run: + workflows: ["CI"] + types: [completed] + branches: [main] + +permissions: + contents: read + +concurrency: + group: deploy-${{ vars.STAGE || 'dev' }} + cancel-in-progress: false + +env: + AWS_REGION: ${{ vars.AWS_REGION || 'eu-west-1' }} + STAGE: ${{ vars.STAGE || 'dev' }} + +jobs: + deploy-infrastructure: + name: deploy-infrastructure + if: github.event.workflow_run.conclusion == 'success' + runs-on: ubuntu-latest + outputs: + api_url: ${{ steps.outputs.outputs.api_url }} + bucket_name: ${{ steps.outputs.outputs.bucket_name }} + distribution_id: ${{ steps.outputs.outputs.distribution_id }} + site_url: ${{ steps.outputs.outputs.site_url }} + steps: + - name: Checkout (commit CI validated) + uses: actions/checkout@v4 + with: + ref: ${{ github.event.workflow_run.head_sha }} + + - name: Set up pnpm + uses: pnpm/action-setup@v4 + with: + version: 10.7.1 + + - name: Set up Node.js + uses: actions/setup-node@v4 + with: + node-version: 20 + cache: pnpm + + - name: Install dependencies + run: pnpm install --frozen-lockfile + + - name: Configure AWS credentials + uses: aws-actions/configure-aws-credentials@v4 + with: + aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }} + aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }} + aws-region: ${{ env.AWS_REGION }} + + - name: CDK bootstrap (idempotent, one-time per account/region) + working-directory: infrastructure + run: npx cdk bootstrap + + - name: CDK deploy (Database, Auth, Notifications, Api, Monitoring, Budget, Frontend) + working-directory: infrastructure + run: | + npx cdk deploy --all --require-approval never \ + -c stage="${{ env.STAGE }}" \ + -c alertEmail="${{ vars.ALERT_EMAIL || 'ezeamartey777@gmail.com' }}" \ + -c monthlyBudgetUsd="${{ vars.MONTHLY_BUDGET_USD || '10' }}" \ + --outputs-file cdk-outputs.json + + - name: Extract stack outputs + id: outputs + working-directory: infrastructure + run: | + api_url=$(jq -r ".\"EventTicketing-${STAGE}-Api\".ApiUrl" cdk-outputs.json) + bucket_name=$(jq -r ".\"EventTicketing-${STAGE}-Frontend\".BucketName" cdk-outputs.json) + distribution_id=$(jq -r ".\"EventTicketing-${STAGE}-Frontend\".DistributionId" cdk-outputs.json) + site_url=$(jq -r ".\"EventTicketing-${STAGE}-Frontend\".SiteUrl" cdk-outputs.json) + echo "api_url=$api_url" >> "$GITHUB_OUTPUT" + echo "bucket_name=$bucket_name" >> "$GITHUB_OUTPUT" + echo "distribution_id=$distribution_id" >> "$GITHUB_OUTPUT" + echo "site_url=$site_url" >> "$GITHUB_OUTPUT" + + deploy-frontend: + name: deploy-frontend + needs: deploy-infrastructure + runs-on: ubuntu-latest + steps: + - name: Checkout (commit CI validated) + uses: actions/checkout@v4 + with: + ref: ${{ github.event.workflow_run.head_sha }} + + - name: Set up pnpm + uses: pnpm/action-setup@v4 + with: + version: 10.7.1 + + - name: Set up Node.js + uses: actions/setup-node@v4 + with: + node-version: 20 + cache: pnpm + + - name: Install dependencies + run: pnpm install --frozen-lockfile + + - name: Build frontend + working-directory: frontend + env: + VITE_API_BASE_URL: ${{ needs.deploy-infrastructure.outputs.api_url }} + run: pnpm run build + + - name: Configure AWS credentials + uses: aws-actions/configure-aws-credentials@v4 + with: + aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }} + aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }} + aws-region: ${{ env.AWS_REGION }} + + - name: Sync build to S3 + run: aws s3 sync frontend/dist "s3://${{ needs.deploy-infrastructure.outputs.bucket_name }}" --delete + + - name: Invalidate CloudFront cache + run: | + aws cloudfront create-invalidation \ + --distribution-id "${{ needs.deploy-infrastructure.outputs.distribution_id }}" \ + --paths "/*" + + - name: Deployment summary + run: | + { + echo "### Deployed to AWS (${{ env.AWS_REGION }}, stage ${{ env.STAGE }})" + echo "- Site: ${{ needs.deploy-infrastructure.outputs.site_url }}" + echo "- API: ${{ needs.deploy-infrastructure.outputs.api_url }}" + } >> "$GITHUB_STEP_SUMMARY" diff --git a/README.md b/README.md index c6ab485..d3d5f6d 100644 --- a/README.md +++ b/README.md @@ -22,7 +22,7 @@ major choice was made. . ├── backend/ Lambda source (TypeScript) — handlers, services, repositories ├── infrastructure/ AWS CDK app (TypeScript) — one stack per concern -├── frontend/ placeholder — design/build pending further instructions +├── frontend/ Vite + React SPA, deployed to S3/CloudFront ├── docs/ architecture, data model, API reference, ADRs ├── scripts/ seed-admin.ts — creates the first Admin account └── .github/workflows/ CI — lint, typecheck, unit tests, cdk synth on every push/PR @@ -66,12 +66,43 @@ without touching real AWS resources. Every push and every PR into `main` runs [`.github/workflows/ci.yml`](.github/workflows/ci.yml): lint → typecheck (backend + infrastructure) → unit tests with coverage → `cdk synth` -(validates all six stacks build without needing AWS credentials). See +(validates all seven stacks build without needing AWS credentials). See [docs/branching-strategy.md](docs/branching-strategy.md) for how this gates merges to `main`. Check the [Actions tab](https://github.com/ForkYeahMan/Azubi_Final_Capstone/actions) for build history and logs. +## Continuous deployment + +[`.github/workflows/deploy.yml`](.github/workflows/deploy.yml) deploys +automatically once CI finishes successfully on `main` (`workflow_run`, +so a broken build never deploys). It runs against the AWS account behind +the repo's `AWS_ACCESS_KEY_ID` / `AWS_SECRET_ACCESS_KEY` secrets, region +`eu-west-1` (Ireland) by default: + +1. **`deploy-infrastructure`** — `cdk bootstrap` (idempotent) then + `cdk deploy --all`, provisioning/updating all seven stacks, and + captures the `Api`/`Frontend` stack outputs. +2. **`deploy-frontend`** — builds the Vite app with `VITE_API_BASE_URL` + set to the just-deployed API URL, syncs `frontend/dist` to the + `Frontend` stack's S3 bucket, and invalidates its CloudFront + distribution. + +Repo-level config (Settings → Secrets and variables → Actions): + +| Name | Kind | Purpose | +|---|---|---| +| `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY` | secret | credentials for the deploying IAM user | +| `AWS_REGION` | variable | deploy region (`eu-west-1`) | +| `STAGE` | variable | CDK stage/context (`dev`) | +| `ALERT_EMAIL` | variable | Budget/CloudWatch/SES alert recipient | +| `MONTHLY_BUDGET_USD` | variable | `Budget` stack threshold | + +This is a demo/capstone deployment: stage `dev` uses long-lived IAM user +keys rather than an OIDC role, and `dev`-stage resources are destroyed +(not retained) on stack deletion — see `RemovalPolicy` usage across +`infrastructure/lib/stacks/`. + ## Infrastructure — deploy ```bash @@ -136,8 +167,10 @@ safety net against accidental data loss. ## Frontend -Not started yet — design and implementation are pending further -instructions. `frontend/` currently holds a placeholder only. +A Vite + React SPA in `frontend/` (see [frontend/README.md](frontend/README.md) +for local dev). It's hosted on the `Frontend` CDK stack (S3 + CloudFront) +and deployed by [`deploy.yml`](#continuous-deployment) — see that section +for how a push to `main` gets it live. ## Cost & monitoring diff --git a/infrastructure/README.md b/infrastructure/README.md index b0af650..288255b 100644 --- a/infrastructure/README.md +++ b/infrastructure/README.md @@ -1,6 +1,6 @@ # Infrastructure -AWS CDK (TypeScript) app that provisions the entire system. Six stacks, +AWS CDK (TypeScript) app that provisions the entire system. Seven stacks, deployed together, each owning one concern: | Stack | Provisions | @@ -11,10 +11,11 @@ deployed together, each owning one concern: | `Api` | HTTP API (v2), Cognito JWT authorizer, one Lambda per route (18 handlers) | | `Monitoring` | CloudWatch alarms (Lambda errors, API 5xx, DynamoDB throttles) + dashboard, ops SNS topic with email subscription | | `Budget` | AWS Budgets monthly cost alert (80% actual / 100% forecasted) | +| `Frontend` | Private S3 bucket + CloudFront (OAC, SPA routing) that hosts the built `frontend/` SPA — CDK provisions the bucket/distribution only, the `deploy.yml` GitHub Actions workflow builds and syncs the actual site | Stack dependency order: `Database` → `Auth` → `Notifications` → `Api` → -`Monitoring`; `Budget` is independent. `bin/app.ts` wires these together -and is the only place that constructs them. +`Monitoring`; `Budget` and `Frontend` are independent. `bin/app.ts` wires +these together and is the only place that constructs them. ## Commands diff --git a/infrastructure/bin/app.ts b/infrastructure/bin/app.ts index 0cdec56..63b1d6f 100644 --- a/infrastructure/bin/app.ts +++ b/infrastructure/bin/app.ts @@ -8,6 +8,7 @@ import { NotificationsStack } from '../lib/stacks/notifications-stack'; import { ApiStack } from '../lib/stacks/api-stack'; import { MonitoringStack } from '../lib/stacks/monitoring-stack'; import { BudgetStack } from '../lib/stacks/budget-stack'; +import { FrontendStack } from '../lib/stacks/frontend-stack'; const app = new App(); const config = getStageConfig(app); @@ -52,6 +53,8 @@ new MonitoringStack(app, `${prefix}-Monitoring`, { new BudgetStack(app, `${prefix}-Budget`, { env, config }); +new FrontendStack(app, `${prefix}-Frontend`, { env, config }); + // Cost-allocation tag every stack shares — BudgetStack's cost filter // matches on this so the monthly budget only tracks this project's spend. Tags.of(app).add('Project', 'event-ticketing'); diff --git a/infrastructure/lib/stacks/frontend-stack.ts b/infrastructure/lib/stacks/frontend-stack.ts new file mode 100644 index 0000000..2bf6d87 --- /dev/null +++ b/infrastructure/lib/stacks/frontend-stack.ts @@ -0,0 +1,63 @@ +import { CfnOutput, Duration, RemovalPolicy, Stack, StackProps } from 'aws-cdk-lib'; +import { BlockPublicAccess, Bucket } from 'aws-cdk-lib/aws-s3'; +import { + AllowedMethods, + CachePolicy, + Distribution, + ViewerProtocolPolicy, +} from 'aws-cdk-lib/aws-cloudfront'; +import { S3BucketOrigin } from 'aws-cdk-lib/aws-cloudfront-origins'; +import { Construct } from 'constructs'; +import { StageConfig } from '../config/environment'; + +export interface FrontendStackProps extends StackProps { + config: StageConfig; +} + +/** + * Static hosting for the Vite/React SPA: a private S3 bucket (no public + * website hosting, no public bucket policy) behind CloudFront with Origin + * Access Control, so the bucket is only ever reachable through the CDN. + * The bucket holds *built* assets only — the GitHub Actions deploy + * workflow runs `vite build` and syncs `dist/` here; CDK never packages + * frontend source. + */ +export class FrontendStack extends Stack { + public readonly bucket: Bucket; + public readonly distribution: Distribution; + + constructor(scope: Construct, id: string, props: FrontendStackProps) { + super(scope, id, props); + + const removalPolicy = props.config.stageName === 'prod' ? RemovalPolicy.RETAIN : RemovalPolicy.DESTROY; + + this.bucket = new Bucket(this, 'SiteBucket', { + bucketName: `event-ticketing-${props.config.stageName}-frontend-${this.account}`, + blockPublicAccess: BlockPublicAccess.BLOCK_ALL, + enforceSSL: true, + removalPolicy, + autoDeleteObjects: removalPolicy === RemovalPolicy.DESTROY, + }); + + this.distribution = new Distribution(this, 'SiteDistribution', { + defaultBehavior: { + origin: S3BucketOrigin.withOriginAccessControl(this.bucket), + viewerProtocolPolicy: ViewerProtocolPolicy.REDIRECT_TO_HTTPS, + cachePolicy: CachePolicy.CACHING_OPTIMIZED, + allowedMethods: AllowedMethods.ALLOW_GET_HEAD_OPTIONS, + }, + defaultRootObject: 'index.html', + // react-router client-side routes (e.g. /events/abc) don't exist as + // S3 keys, so the origin 403s (private bucket) / 404s on them — + // rewrite both to index.html and let the SPA's router take over. + errorResponses: [ + { httpStatus: 403, responseHttpStatus: 200, responsePagePath: '/index.html', ttl: Duration.seconds(0) }, + { httpStatus: 404, responseHttpStatus: 200, responsePagePath: '/index.html', ttl: Duration.seconds(0) }, + ], + }); + + new CfnOutput(this, 'BucketName', { value: this.bucket.bucketName }); + new CfnOutput(this, 'DistributionId', { value: this.distribution.distributionId }); + new CfnOutput(this, 'SiteUrl', { value: `https://${this.distribution.distributionDomainName}` }); + } +}