From 4891fd7f695a84cafbf4aa8067398d1bef194e77 Mon Sep 17 00:00:00 2001 From: Will Date: Wed, 21 Oct 2026 14:14:19 -0400 Subject: [PATCH 01/12] Bring stranded Lab 48 planning drafts onto docs/lab48-pack Carried over file by file (git checkout -- ), no branch merges: - docs/06-event-contract-adr: docs/adrs/001-event-contract.md - docs/07-c4-docs: docs/architecture/context.md, docs/architecture/container.md - docs/08-postgres-adr-nfrs: docs/adrs/002-postgresql.md, docs/nfrs.md - docs/09-risk-register: docs/risk-register.md - docs/11-actions-plan: docs/adrs/003-github-actions-self-hosted-runner.md - docs/14-backlog: docs/backlog.md (replaces the will_work stub) - docs/15-team-roles: docs/team-roles.md Content is unchanged from those branches; accuracy edits follow in later commits. architecture.md, github-actions-plan.md and terraform-ansible-plan.md were not taken from the branches because will_work has newer versions. --- docs/adrs/001-event-contract.md | 60 +++++++++++++ docs/adrs/002-postgresql.md | 22 +++++ .../003-github-actions-self-hosted-runner.md | 24 +++++ docs/architecture/container.md | 33 +++++++ docs/architecture/context.md | 37 ++++++++ docs/backlog.md | 88 +++++++++++++++---- docs/nfrs.md | 41 +++++++++ docs/risk-register.md | 15 ++++ docs/team-roles.md | 24 +++++ 9 files changed, 327 insertions(+), 17 deletions(-) create mode 100644 docs/adrs/001-event-contract.md create mode 100644 docs/adrs/002-postgresql.md create mode 100644 docs/adrs/003-github-actions-self-hosted-runner.md create mode 100644 docs/architecture/container.md create mode 100644 docs/architecture/context.md create mode 100644 docs/nfrs.md create mode 100644 docs/risk-register.md create mode 100644 docs/team-roles.md diff --git a/docs/adrs/001-event-contract.md b/docs/adrs/001-event-contract.md new file mode 100644 index 0000000..4c2a53a --- /dev/null +++ b/docs/adrs/001-event-contract.md @@ -0,0 +1,60 @@ +# ADR 001: Event contract for recorded interactions + +**Status:** Proposed. **FILL IN:** confirm the frozen field list with the instructor, or note that the team froze it without an answer. + +## Context + +When an agent records an interaction, the API saves it and then announces it on Kafka. We need one event shape before anyone writes publish code, and the sources disagree. Lab 49 Step 2 has `eventId`, `actor`, and an integer `eventVersion`. The starter record in `backend/.../messaging/CustomerInteractionRecordedV1.java` has no `eventId` or `actor` and stores the version as the string `"1"`. We go with the course shape. + +## Decision + +- **Topic:** `crm.customer.interactions.v1` +- **Message key:** the customer id string (`CUS-1001`), so one customer's events stay on one partition and in order. +- **Value:** JSON `CustomerInteractionRecordedV1`. + +| Field | JSON type | Notes | +| --- | --- | --- | +| `eventId` | string (UUID) | New for every event. Consumers dedupe on it | +| `eventType` | string | Always `CustomerInteractionRecorded` | +| `eventVersion` | number | `1` | +| `occurredAt` | string (ISO-8601, UTC) | When the row was committed | +| `correlationId` | string | From the request; defaults to `lab-request-001` | +| `actor` | string | Who recorded it. **FILL IN:** value to use until real JWT lands (suggest the demo user's subject) | +| `customerId` | string | Public id like `CUS-1001`. Never the database key or a UUID | +| `interactionId` | string (UUID) | Same as `interaction_id` in PostgreSQL | +| `interactionType` | string | `CALL`, `EMAIL`, `NOTE`, or `MEETING` | + +```json +{ + "eventId": "6f1c2a9e-3b4d-4c8e-9a51-2d7f0b8e4c13", + "eventType": "CustomerInteractionRecorded", + "eventVersion": 1, + "occurredAt": "2026-10-20T14:05:00Z", + "correlationId": "lab-request-001", + "actor": "demo-agent", + "customerId": "CUS-1001", + "interactionId": "0b7e8f44-1d2c-4a6b-8e3f-5c9a7d1e2f60", + "interactionType": "CALL" +} +``` + +**Publish after commit.** The service saves the interaction, commits, then publishes. A validation failure or an unknown customer (`CUS-9999`, 404) publishes nothing. No outbox for the capstone. + +**When Kafka is down.** The row is already committed, so the API still returns `201`. The failed publish is logged at ERROR with the interaction id and correlation id so we can find it. **FILL IN:** confirm the team accepts this gap (the instructor question on after-commit vs outbox covers it too). + +**Versioning.** Adding an optional field stays V1. Renaming or removing a field, or changing a type, means a new `CustomerInteractionRecordedV2` on `crm.customer.interactions.v2`, with both running until consumers move. + +**Consumer.** **FILL IN:** what the consumer does with a good event, or whether a log-line consumer is an accepted substitute (instructor). Whatever it does, it has to be idempotent on `eventId`, because Kafka can deliver twice. + +## Consequences + +- The starter record changes before Lab 49 publish work: add `eventId` and `actor`, make `eventVersion` an `int`. `customerId` stays a `String`. +- PostgreSQL stays the system of record. A lost event never means a wrong row. +- Events can go missing while Kafka is down. An outbox is the upgrade if that turns out to matter. +- Ordering only holds per customer, which is all CAP-12 needs. + +## Rejected + +- **Outbox table.** Safer, but it adds a table, a poller, and tests we can't fit into the week. +- **Publish before or inside the transaction.** Can announce a row that then rolls back. +- **Keep the starter shape.** Without `eventId`, consumers can't dedupe. diff --git a/docs/adrs/002-postgresql.md b/docs/adrs/002-postgresql.md new file mode 100644 index 0000000..d1507be --- /dev/null +++ b/docs/adrs/002-postgresql.md @@ -0,0 +1,22 @@ +# ADR 002: PostgreSQL as the system of record + +**Status:** Accepted. The stack is frozen in [docs/architecture.md](../architecture.md). + +## Context + +Interactions have to survive restarts, and they're the truth if Kafka and the database ever disagree. The course stack names PostgreSQL, the starter already ships Flyway `V1__crm_schema.sql`, and local dev runs `postgres:16` in Compose. + +## Decision + +PostgreSQL 16 through Spring Data JPA, with Flyway owning the schema. Hibernate runs `ddl-auto: validate`, so it checks the schema but never changes it. Migrations use PostgreSQL types (`UUID`, `TIMESTAMPTZ`, `BIGSERIAL`, `VARCHAR`) and CHECK constraints for customer status and interaction type. + +## Rejected + +- **Oracle.** Not the taught path, licensed, and its types (`VARCHAR2`, `NUMBER`, `SYSDATE`) would leak into migrations and AI-drafted SQL. +- **Kafka as the store.** Events are notifications. We need 404 lookups and newest-first lists, which a topic can't answer. + +## Consequences + +- Every schema change is a new `V__*.sql`. A merged migration is never edited. +- Integration tests and the CI backend job need a real Postgres 16. +- Where Postgres runs on the shared cluster is still open. **FILL IN:** shared cluster service or our own (instructor). That also decides backups (see recoverability in [docs/nfrs.md](../nfrs.md)). diff --git a/docs/adrs/003-github-actions-self-hosted-runner.md b/docs/adrs/003-github-actions-self-hosted-runner.md new file mode 100644 index 0000000..9cbc6c8 --- /dev/null +++ b/docs/adrs/003-github-actions-self-hosted-runner.md @@ -0,0 +1,24 @@ +# ADR 003: GitHub Actions on a self-hosted runner, deploying digests to k3s + +**Status:** Accepted (team policy). + +## Context + +CI/CD has to test and build Angular and Spring Boot, scan, build images, and deploy to the shared k3s cluster. The course uses GitHub Actions, and its Lab 51 starter runs on `ubuntu-latest`. Our Actions minutes on this account are used up, so hosted runners aren't an option right now. + +## Decision + +GitHub Actions for all CI/CD, on our own self-hosted runner. Deploys promote an image digest built once on `main` to k3s with `kubectl`. This is a team rule. If the instructor wants hosted runners, switching back is a `runs-on` change per job. + +## Rejected + +- **GitHub-hosted `ubuntu-latest`.** What the course uses. Out because of billing, kept as the fallback. +- **Bitbucket Pipelines or other CI.** Not the taught path. +- **Deploying by hand from a laptop.** No approval record and no digest trail. + +## Consequences + +- We maintain the runner: Docker, JDK 21, Node, headless Chrome for `ng test`, and `kubectl`. Owner is Security / deploy. **FILL IN:** where the runner is hosted. +- The runner holds secrets during deploy jobs, so it serves only this private repo, never fork PRs, and cleans its workspace after each job. +- If the runner is down, CI stops. The fallback is `ubuntu-latest` for that run, if minutes allow. +- A hello-world workflow on the runner gets proven before Lab 51 CI work starts. diff --git a/docs/architecture/container.md b/docs/architecture/container.md new file mode 100644 index 0000000..cb6b190 --- /dev/null +++ b/docs/architecture/container.md @@ -0,0 +1,33 @@ +# Containers (C4 level 2) + +The deployable units, and how requests and events move between them. This matches [docs/architecture.md](../architecture.md) and the [context view](context.md). + +```mermaid +flowchart LR + B([Browser]) --> I[Traefik Ingress] + I -->|/| SPA[Angular SPA] + I -->|/api| API[Spring Boot API] + API -->|JPA| PG[(PostgreSQL 16)] + API -->|after commit| K[[Kafka: crm.customer.interactions.v1]] +``` + +## Deployable units + +| Container | Tech | Runs where | +| --- | --- | --- | +| Angular SPA | Angular 19, built once with `ng build` | **FILL IN:** its own image or served by the API (suggest its own image) | +| CRM API | Spring Boot 3.3, Java 21, one image pinned by digest | k3s Deployment in each env namespace | +| PostgreSQL 16 | Flyway-managed schema, system of record | **FILL IN:** shared cluster service or our own (instructor) | +| Kafka | Topic `crm.customer.interactions.v1` | **FILL IN:** shared cluster service or our own (instructor) | +| Traefik Ingress | Built into k3s | Cluster. **FILL IN:** hostnames and Ingress class (instructor). Path split `/` and `/api` is a suggestion | + +Locally, Compose runs PostgreSQL and Kafka, and the API and SPA run from the IDE. + +## Flows + +| Flow | Path | +| --- | --- | +| Record interaction | SPA sends `POST /api/v1/interactions` with Bearer token and `X-Correlation-Id`. API validates, saves, commits, publishes, returns `201` | +| List interactions | SPA sends `GET /api/v1/interactions?customerId=CUS-1001`. API reads newest first from PostgreSQL. No Kafka | +| Unknown customer | `CUS-9999` returns `404`. No row, no event | +| Release | Actions builds each image once, records the digest, and deploys that digest to each namespace. Only ConfigMaps, Secrets, and replicas differ per env | diff --git a/docs/architecture/context.md b/docs/architecture/context.md new file mode 100644 index 0000000..1f0749d --- /dev/null +++ b/docs/architecture/context.md @@ -0,0 +1,37 @@ +# Context (C4 level 1) + +Who uses Northstar CRM, what it depends on, and where the trust lines are. This matches [docs/architecture.md](../architecture.md). + +```mermaid +flowchart LR + Agent([Service agent]) -->|HTTPS| CRM[Northstar CRM] + CRM -->|checks tokens from| IdP[JWT issuer] + CRM -->|interaction events| Consumers[Event consumers] + Team([Delivery team]) -->|PRs| GH[GitHub and Actions] + GH -->|digest deploy| CRM +``` + +## People + +| Who | What they do | +| --- | --- | +| Service agent | Signs in, opens a customer (`CUS-1001`), records and reviews interactions | +| Second role | **FILL IN:** name and permissions of the second role (brief says AGENT / ADMIN; instructor to confirm) | +| Delivery team | Merges through reviewed PRs and releases through Actions | + +## External systems + +| System | Why we depend on it | +| --- | --- | +| JWT issuer | Signs the tokens the API checks. **FILL IN:** who issues them and how we get a demo token (instructor). Until Lab 51 the API accepts the demo bearer token | +| GitHub and Actions | Source, reviews, CI/CD on our self-hosted runner (team policy) | +| Image registry | Holds images by digest. **FILL IN:** which registry (instructor) | +| Shared k3s cluster | Runs our namespaces behind Traefik Ingress | +| Event consumers | Read `crm.customer.interactions.v1`. **FILL IN:** consumer scope (instructor) | + +## Trust boundaries + +1. **Browser to Ingress.** The browser is untrusted. Angular keeps the JWT in memory and adds it to calls, but that's convenience, not security. +2. **Ingress to API.** Spring Security is the gate: no or bad token is `401`, wrong role is `403`. The API accepts `X-Correlation-Id` or defaults to `lab-request-001`. +3. **API to PostgreSQL and Kafka.** Inside the cluster only, never exposed through Ingress. Credentials come from k8s Secrets. +4. **GitHub to cluster.** Only the deploy job, behind a GitHub Environment approval, holds cluster credentials. diff --git a/docs/backlog.md b/docs/backlog.md index 3920774..2f51995 100644 --- a/docs/backlog.md +++ b/docs/backlog.md @@ -1,17 +1,71 @@ -# Capstone backlog — TODO (Lab 48) - -## CAP-12 — Record customer interaction -**As** an agent **I want** to POST an interaction for `CUS-1001` -**So that** the note persists in PostgreSQL and emits a versioned Kafka event. - -**Acceptance** -1. `201` with correlation `lab-request-001` -2. Row visible in PostgreSQL -3. Event `CustomerInteractionRecordedV1` (or equivalent) published -4. `CUS-9999` → `404` - -## Additional seeds -- CAP-?? Angular list/detail for interactions — TODO -- CAP-?? JWT login shell — TODO -- CAP-?? Actions PR gate (Angular + Maven) — TODO -- CAP-?? OpenShift smoke via Route — TODO +# Capstone backlog (Lab 48) + +Stories in priority order. Each one fits a session and has checks we can demo. Owners are workstreams. **FILL IN:** team confirms the order. + +## CAP-12: Record customer interaction + +**As** an agent **I want** to record an interaction for `CUS-1001` **so that** it persists in PostgreSQL and emits `CustomerInteractionRecordedV1` on Kafka. +Owner: Backend / Kafka. Lab 49. + +1. `POST /api/v1/interactions` for `CUS-1001` with correlation `lab-request-001` returns `201` and the new interaction id. +2. One row in `customer_interaction` with that id and correlation id. +3. One `CustomerInteractionRecordedV1` on `crm.customer.interactions.v1`, keyed `CUS-1001`, carrying `lab-request-001`, published after commit. Fields per [ADR 001](adrs/001-event-contract.md). +4. `CUS-9999` returns `404`, with no row and no event. + +## CAP-13: Interaction list and detail in Angular + +**As** an agent **I want** to see a customer's interactions and open one **so that** I can pick up where the last contact left off. +Owner: Frontend. Lab 50. + +1. Signed in, opening `CUS-1001` lists its interactions newest first from `GET /api/v1/interactions?customerId=CUS-1001`. +2. Selecting one shows type, summary, correlation id, and created time. +3. Loading, empty, and error states each show a message. `CUS-9999` shows not found. +4. `ng test` and `ng build` pass. + +## CAP-14: JWT login shell + +**As** an agent **I want** to sign in once **so that** every API call carries my token. +Owner: Security / deploy. Labs 50–51. + +1. Visiting `/interactions` without signing in redirects to `/login`. +2. After sign-in the token is held in memory only, and the interceptor adds `Authorization: Bearer …` to API calls. +3. A `401` from the API sends the user back to login. +4. The API rejects a missing or bad token with `401`. The server is the gate, not Angular. **FILL IN:** token issuer and role names (instructor). + +## CAP-15: Flyway interaction table + +**As** the team **we want** the interaction schema managed by Flyway **so that** any environment can rebuild it from empty. +Owner: Database. Lab 50. + +1. `V1__crm_schema.sql` applies clean on an empty Postgres 16 (`docker compose up postgres`, then start the API). +2. Hibernate `ddl-auto: validate` passes against it. +3. PostgreSQL types only. CHECK constraints reject an unknown customer status or interaction type. +4. Seeds only the synthetic `CUS-1001` and `CUS-1002`. + +## CAP-16: Actions PR gate + +**As** the team **we want** every PR tested on both halves **so that** a broken UI or API can't merge. +Owner: Security / deploy. Lab 51. + +1. Every PR runs `frontend` (`npm ci`, `ng test`, `ng build`) and `backend` (`mvn -B clean verify`) on the self-hosted runner. +2. A failing Angular or Maven test turns the run red. +3. The SAST and dependency scan runs, and its result shows in the run. +4. **FILL IN:** whether these can be required checks to merge (instructor). + +## CAP-17: k3s smoke through Ingress + +**As** the team **we want** a smoke check after every deploy **so that** a bad release rolls back before anyone relies on it. +Owner: Security / deploy. Lab 51. + +1. After deploy, the rollout completes and readiness is green. +2. Smoke lists interactions for `CUS-1001` through the Traefik Ingress host with `lab-request-001` and gets `200`. +3. `CUS-9999` through the Ingress gets `404`. +4. If smoke fails, the job rolls back to the previous digest and the run shows it. + +## Scope decisions + +| Topic | Where we stand | +| --- | --- | +| Interaction update and delete | Not part of CAP-12. Lab 50 asks for update and delete, or a designed soft delete. **FILL IN:** hard or soft delete (Database workstream), confirmed with the instructor | +| Customer search and profile | CAP-12 and CAP-13 take a customer id; there's no customer API yet. **FILL IN:** whether search, profile, or customer create/update is in scope (instructor) | +| Kafka consumer | CAP-12 is producer only. **FILL IN:** what the consumer does with a good event, or whether a log-line consumer is accepted (instructor) | diff --git a/docs/nfrs.md b/docs/nfrs.md new file mode 100644 index 0000000..525de05 --- /dev/null +++ b/docs/nfrs.md @@ -0,0 +1,41 @@ +# Non-functional requirements + +Every target has a number and a way to check it. Where the team or instructor still owes us the number, the line says **FILL IN** with a suggestion. Evidence gets linked from `defense/evidence-index.md` as it lands. + +## Security + +| Target | How we check | Lab | +| --- | --- | --- | +| 100% of `/api/**` calls without a valid JWT get `401`; wrong role gets `403` | Auth tests for no token, bad token, wrong role; repeated in smoke | 51 | +| 0 secrets, tokens, kubeconfigs, `.env`, or `*.tfstate` in git | `.gitignore`, diff review per the AI usage plan, secret scan in CI | 48–51 | +| 0 open findings at or above the scan threshold. **FILL IN:** threshold (suggest High) | Dependency and image scan in Actions | 51 | + +## Traceability + +| Target | How we check | Lab | +| --- | --- | --- | +| 100% of interaction creates store the request's correlation id (default `lab-request-001`) in the row, the event, and the log line | Integration test, then console consumer and log grep in the demo | 49 | +| 100% of deployed pods run an image pinned by digest, and each digest maps to one Actions run | `kubectl get pods -o jsonpath` against the run summary | 51 | + +## Recoverability + +| Target | How we check | Lab | +| --- | --- | --- | +| Roll back to the previous digest in **FILL IN** minutes (suggest 10) | Timed rollback rehearsal before the stage-to-prod-like gate | 51 | +| Schema rebuilds from an empty Postgres 16 with 0 manual SQL steps | Fresh `docker compose up postgres`, start the API, Flyway applies | 50 | +| 0 committed interactions lost while Kafka is down | Stop Kafka, POST for `CUS-1001`, row is still there | 49 | +| Data loss window **FILL IN** (depends on where Postgres runs) | Restore drill, once hosting is known | 51 | + +## Performance + +| Target | How we check | Lab | +| --- | --- | --- | +| p95 under **FILL IN** ms (suggest 500) for `POST` and `GET /api/v1/interactions` at **FILL IN** concurrent users (suggest 10) on synthetic data | Short scripted load run against stage, results in `reports/` | 51 | + +## Operability + +| Target | How we check | Lab | +| --- | --- | --- | +| `/actuator/health` readiness reports UP within **FILL IN** seconds of pod start (suggest 60) | Readiness probe and `kubectl rollout status` | 51 | +| Post-deploy smoke finishes in under **FILL IN** minutes (suggest 2), and any non-2xx for `CUS-1001` fails the deploy | Smoke job in the CD run | 51 | +| 100% of API request log lines carry the correlation id | Grep logs for `lab-request-001` after the demo calls | 49 | diff --git a/docs/risk-register.md b/docs/risk-register.md new file mode 100644 index 0000000..6a9d0d6 --- /dev/null +++ b/docs/risk-register.md @@ -0,0 +1,15 @@ +# Risk register + +Living list. Add a row whenever we cut scope or learn a new blocker. Owners are workstreams until names are assigned in `docs/team-roles.md`. + +| ID | Risk | Likelihood / impact | Mitigation | Owner | Date | +| --- | --- | --- | --- | --- | --- | +| R-01 | No JWT issuer / signing details defined yet | Med / High | Keep demo bearer until Lab 51; record instructor answer in the security ADR; do not hard-code a fake issuer | Security / deploy | 2026-10-19 | +| R-02 | Kafka consumer side effect undefined (what happens on consume) | Med / Med | Ship producer-only for CAP-12 unless instructor says otherwise; document the cut in the event ADR and backlog | Backend / Kafka | 2026-10-19 | +| R-03 | Shared k3s access / namespace names unknown | Med / High | Environment strategy rows stay "pending instructor"; ask in one batch; fallback is local Compose + recorded evidence if cluster access slips | Security / deploy | 2026-10-19 | +| R-04 | Self-hosted Actions runner not proven yet | Med / High | Prove a hello-world workflow on the runner before Lab 51 CI; course sample is `ubuntu-latest` — self-hosted is team policy | Security / deploy | 2026-10-19 | +| R-05 | Graded vs practice unclear for some Lab 48 notes / exercises | Low / Med | Treat `docs/` planning pack as the graded path; keep pre-lab `notes/` out of the Lab 48 merge PR; confirm with instructor if unsure | Shared (instructor contact) | 2026-10-19 | + +## Scope cuts + +When we drop or defer work, add a row here (what we cut, why, who decided, date). Start empty beyond the seeds above. diff --git a/docs/team-roles.md b/docs/team-roles.md new file mode 100644 index 0000000..45add83 --- /dev/null +++ b/docs/team-roles.md @@ -0,0 +1,24 @@ +# Team roles and working agreements + +Four workstreams. Everyone should still be able to walk through every major part at the defense. + +| Workstream | Owner | Backup | +| --- | --- | --- | +| Frontend (Angular) | TBD | TBD | +| Backend / Kafka | TBD | TBD | +| Database (PostgreSQL / Flyway) | TBD | TBD | +| Security / deploy (JWT, Actions, k3s) | TBD | TBD | + +Shared Lab 48 docs and Lab 52 defense work are everyone's, with the owner of the closest workstream driving the draft. + +## Side duties + +| Duty | Who | What | +| --- | --- | --- | +| Merge keeper | TBD | Keep PRs moving, require one non-author approval, keep `main` green | +| Evidence lead | TBD | Own `defense/evidence-index.md` so proof lands during the week, not Thursday night | +| Instructor contact | TBD | Batch questions to the instructor and record answers in ADRs or the risk register | + +## Branch and review rule + +Every change goes through a pull request into `main` with **one non-author approval**. Reviewers rotate so the same person is not always rubber-stamping. No direct pushes to `main`. From aaa4e92fe73826dae99b202471d2966dcfa45e76 Mon Sep 17 00:00:00 2001 From: Will Date: Wed, 21 Oct 2026 14:18:22 -0400 Subject: [PATCH 02/12] Lab 48: align architecture, C4 views and ADRs with the built system - architecture.md: real stack versions, three required diagrams (CAP-12 app flow, Kafka topics/consumers/DLT, JWT login and API security) plus delivery, trust boundaries, ADR table with working links, open questions. OpenShift is recorded as an instructor question, not silently changed. - C4 context/container: AGENT and ADMIN roles, GHCR, real containers and flows; unknowns marked Team to confirm. - ADR 001 (from docs/06-event-contract-adr): accepted contract as coded, lifecycle event, idempotent consumers, DLT, Kafka-down gap. - ADR 002 (from docs/08-postgres-adr-nfrs): Flyway V1-V3 and real key types. - ADR 003 (from docs/11-actions-plan, renamed): hosted runners and digest promotion; records why the self-hosted runner draft was dropped. - ADR 004 k3s + Traefik + Kustomize, ADR 005 REST contract, ADR 006 JWT roles: new; 005/006 started from the 48-grok samples and were rewritten to match the code (AGENT/ADMIN, /api/v1 paths). --- docs/adrs/001-event-contract.md | 69 +++++--- docs/adrs/002-postgresql.md | 25 ++- .../003-github-actions-digest-promotion.md | 36 +++++ .../003-github-actions-self-hosted-runner.md | 24 --- docs/adrs/004-k3s-traefik-ingress.md | 32 ++++ docs/adrs/005-rest-api-contract.md | 39 +++++ docs/adrs/006-jwt-roles.md | 37 +++++ docs/architecture.md | 153 +++++++++++++----- docs/architecture/container.md | 32 ++-- docs/architecture/context.md | 42 ++--- 10 files changed, 362 insertions(+), 127 deletions(-) create mode 100644 docs/adrs/003-github-actions-digest-promotion.md delete mode 100644 docs/adrs/003-github-actions-self-hosted-runner.md create mode 100644 docs/adrs/004-k3s-traefik-ingress.md create mode 100644 docs/adrs/005-rest-api-contract.md create mode 100644 docs/adrs/006-jwt-roles.md diff --git a/docs/adrs/001-event-contract.md b/docs/adrs/001-event-contract.md index 4c2a53a..e435998 100644 --- a/docs/adrs/001-event-contract.md +++ b/docs/adrs/001-event-contract.md @@ -1,28 +1,37 @@ -# ADR 001: Event contract for recorded interactions +# ADR 001: Kafka event contracts and publish-after-commit -**Status:** Proposed. **FILL IN:** confirm the frozen field list with the instructor, or note that the team froze it without an answer. +**Status:** Accepted (built in Lab 49, extended with the lifecycle event in the customer-management work). +**Owner:** Backend (Keifer leads; see [team roles](../team-roles.md)). ## Context -When an agent records an interaction, the API saves it and then announces it on Kafka. We need one event shape before anyone writes publish code, and the sources disagree. Lab 49 Step 2 has `eventId`, `actor`, and an integer `eventVersion`. The starter record in `backend/.../messaging/CustomerInteractionRecordedV1.java` has no `eventId` or `actor` and stores the version as the string `"1"`. We go with the course shape. +When an agent records an interaction, the API saves it and then announces it on Kafka. We needed one event shape before anyone wrote publish code, and the sources disagreed. Lab 49 Step 2 has `eventId`, `actor`, and an integer `eventVersion`; the original starter record had no `eventId` or `actor` and stored the version as the string `"1"`. We went with the course shape, because without `eventId` a consumer can't spot a duplicate delivery. + +Later, customer status changes (Ravi `PROSPECT -> ACTIVE`, any status `-> CLOSED`) also needed an audit trail, so a second event was added with the same rules. ## Decision -- **Topic:** `crm.customer.interactions.v1` -- **Message key:** the customer id string (`CUS-1001`), so one customer's events stay on one partition and in order. -- **Value:** JSON `CustomerInteractionRecordedV1`. +### Event 1: interaction recorded + +- **Topic:** `crm.customer.interactions.v1` (setting `crm.kafka.topic`) +- **Key:** the customer's public id (`CUS-1001`), so one customer's events stay on one partition and in order. +- **Value:** JSON `CustomerInteractionRecordedV1` (`backend/.../messaging/CustomerInteractionRecordedV1.java`). -| Field | JSON type | Notes | +| Field | Type in Java | Notes | | --- | --- | --- | -| `eventId` | string (UUID) | New for every event. Consumers dedupe on it | -| `eventType` | string | Always `CustomerInteractionRecorded` | -| `eventVersion` | number | `1` | -| `occurredAt` | string (ISO-8601, UTC) | When the row was committed | -| `correlationId` | string | From the request; defaults to `lab-request-001` | -| `actor` | string | Who recorded it. **FILL IN:** value to use until real JWT lands (suggest the demo user's subject) | -| `customerId` | string | Public id like `CUS-1001`. Never the database key or a UUID | -| `interactionId` | string (UUID) | Same as `interaction_id` in PostgreSQL | -| `interactionType` | string | `CALL`, `EMAIL`, `NOTE`, or `MEETING` | +| `eventId` | `UUID` | New for every event. The consumer dedupes on it | +| `eventType` | `String` | Always `CustomerInteractionRecorded` | +| `eventVersion` | `int` | `1` | +| `occurredAt` | `Instant` (UTC) | Set when the event is built, on the request thread, just before the commit | +| `correlationId` | `String` | Same value stored on the row: `X-Correlation-Id` header, else the body's `correlationId`, else `lab-request-001` | +| `actor` | `String` | The JWT subject of the caller (`agent` or `admin`) | +| `customerId` | `String` | Public id like `CUS-1001`. Never the internal database key | +| `interactionId` | `String` | The interaction UUID, written as text so non-Java consumers don't need a UUID type | +| `interactionType` | `String` | `CALL`, `EMAIL`, `NOTE`, or `MEETING` | + +The summary (the note text) is **not** in the event, and the publisher never logs it. Events carry identifiers only. + +Example (values are synthetic): ```json { @@ -31,30 +40,40 @@ When an agent records an interaction, the API saves it and then announces it on "eventVersion": 1, "occurredAt": "2026-10-20T14:05:00Z", "correlationId": "lab-request-001", - "actor": "demo-agent", + "actor": "agent", "customerId": "CUS-1001", "interactionId": "0b7e8f44-1d2c-4a6b-8e3f-5c9a7d1e2f60", "interactionType": "CALL" } ``` -**Publish after commit.** The service saves the interaction, commits, then publishes. A validation failure or an unknown customer (`CUS-9999`, 404) publishes nothing. No outbox for the capstone. +Team to confirm: the exact JSON form of `occurredAt` (ISO text or a number) depends on the serializer settings. Check it once with the Kafka console consumer and update this example. + +### Event 2: customer status changed + +- **Topic:** `crm.customer.lifecycle.v1` (setting `crm.kafka.lifecycle-topic`), keyed by customer public id. +- **Value:** `CustomerStatusChangedV1`: `eventId`, `eventType` (`CustomerStatusChanged`), `eventVersion` (`1`), `occurredAt`, `correlationId`, `actor`, `customerId`, `fromStatus`, `toStatus`. +- Published only when the status really changes, from `PUT /api/v1/customers/{id}` or `DELETE /api/v1/customers/{id}` (which closes the customer). No names or other personal data. + +### Rules for both events + +**Publish after commit.** The service saves the row inside a `@Transactional` method. The publisher registers an after-commit hook (`TransactionSynchronization.afterCommit`), so Kafka only hears about rows that actually committed. A validation error (`400`) or an unknown customer (`CUS-9999`, `404`) publishes nothing. Tests: `InteractionEventPublisherTest.publish_insideTransaction_waitsForAfterCommit`, `CustomerLifecycleEventPublisherTest.rolledBackTransaction_neverPublishes`, `InteractionServiceTest.create_unknownCustomer_neverPersistsOrPublishes`. -**When Kafka is down.** The row is already committed, so the API still returns `201`. The failed publish is logged at ERROR with the interaction id and correlation id so we can find it. **FILL IN:** confirm the team accepts this gap (the instructor question on after-commit vs outbox covers it too). +**Consumers are idempotent.** `InteractionEventConsumer` (group `crm-interactions-audit`) and `CustomerLifecycleEventConsumer` (group `crm-customer-lifecycle-audit`) write one row per `eventId` into `processed_event` (Flyway V2). A redelivered event finds its row and is skipped. Test: `InteractionEventConsumerIT.duplicateDelivery_appliesOnlyOnce`. -**Versioning.** Adding an optional field stays V1. Renaming or removing a field, or changing a type, means a new `CustomerInteractionRecordedV2` on `crm.customer.interactions.v2`, with both running until consumers move. +**Bounded retries, then a dead-letter topic.** A failing record is retried twice, 500 ms apart, then copied to `.DLT` (`crm.customer.interactions.v1.DLT`, `crm.customer.lifecycle.v1.DLT`). An unknown `eventVersion` can never succeed, so it goes straight to the DLT. Test: `InteractionEventConsumerIT.unsupportedVersion_goesToDeadLetterTopic_andIsNotApplied`. -**Consumer.** **FILL IN:** what the consumer does with a good event, or whether a log-line consumer is an accepted substitute (instructor). Whatever it does, it has to be idempotent on `eventId`, because Kafka can deliver twice. +**Versioning.** Adding an optional field stays V1. Renaming or removing a field, or changing a type, means a new `...V2` event on a new `.v2` topic, with both running until consumers move. ## Consequences -- The starter record changes before Lab 49 publish work: add `eventId` and `actor`, make `eventVersion` an `int`. `customerId` stays a `String`. - PostgreSQL stays the system of record. A lost event never means a wrong row. -- Events can go missing while Kafka is down. An outbox is the upgrade if that turns out to matter. +- **Gap we accept:** if Kafka is down right after the commit, the row exists but its event can be lost. The send is fire-and-forget and there is no outbox yet. See risk R-06 in the [risk register](../risk-register.md). Team to confirm the team accepts this for the capstone. - Ordering only holds per customer, which is all CAP-12 needs. +- The consumers record an audit row only. They don't trigger any other side effect yet. ## Rejected -- **Outbox table.** Safer, but it adds a table, a poller, and tests we can't fit into the week. -- **Publish before or inside the transaction.** Can announce a row that then rolls back. +- **Outbox table.** Safer (the event is saved in the same transaction and relayed later), but it adds a table, a poller, and tests we couldn't fit into the week. It's the upgrade path. +- **Publish before or inside the transaction.** Could announce a row that then rolls back. - **Keep the starter shape.** Without `eventId`, consumers can't dedupe. diff --git a/docs/adrs/002-postgresql.md b/docs/adrs/002-postgresql.md index d1507be..d604828 100644 --- a/docs/adrs/002-postgresql.md +++ b/docs/adrs/002-postgresql.md @@ -1,22 +1,35 @@ # ADR 002: PostgreSQL as the system of record -**Status:** Accepted. The stack is frozen in [docs/architecture.md](../architecture.md). +**Status:** Accepted (built in Labs 49–50). +**Owner:** Backend (Keifer leads; see [team roles](../team-roles.md)). ## Context -Interactions have to survive restarts, and they're the truth if Kafka and the database ever disagree. The course stack names PostgreSQL, the starter already ships Flyway `V1__crm_schema.sql`, and local dev runs `postgres:16` in Compose. +Customers and interactions have to survive restarts, and they're the truth if Kafka and the database ever disagree. The course stack names PostgreSQL, and local dev runs `postgres:16` in `compose.yaml`. ## Decision -PostgreSQL 16 through Spring Data JPA, with Flyway owning the schema. Hibernate runs `ddl-auto: validate`, so it checks the schema but never changes it. Migrations use PostgreSQL types (`UUID`, `TIMESTAMPTZ`, `BIGSERIAL`, `VARCHAR`) and CHECK constraints for customer status and interaction type. +PostgreSQL 16 through Spring Data JPA, with **Flyway owning the schema**. Hibernate runs `ddl-auto: validate`, so it checks the schema at startup but never changes it. + +| Migration | What it does | +| --- | --- | +| `V1__crm_schema.sql` | `customer` (internal `BIGSERIAL` key plus unique `public_id` like `CUS-1001`, `status` CHECK `PROSPECT/ACTIVE/CLOSED`) and `customer_interaction` (`UUID` key, `interaction_type` CHECK `CALL/EMAIL/NOTE/MEETING`, `summary` up to 1024 characters, `correlation_id`, `TIMESTAMPTZ` times). Index on `(customer_id, created_at DESC)` for the newest-first timeline. Seeds only the synthetic `CUS-1001` Amina Khan (ACTIVE) and `CUS-1002` Ravi Singh (PROSPECT) | +| `V2__processed_event.sql` | `processed_event`, one row per consumed `eventId`, so redelivered Kafka events are skipped | +| `V3__interaction_soft_delete.sql` | Adds `deleted_at` so deleting an interaction hides it but keeps the audit row | + +Customers are never hard-deleted either: `DELETE /api/v1/customers/{id}` sets `status = CLOSED`, so interactions never point at a missing customer. + +The API only ever shows the public id (`CUS-1001`). The internal numeric key stays inside the database. ## Rejected - **Oracle.** Not the taught path, licensed, and its types (`VARCHAR2`, `NUMBER`, `SYSDATE`) would leak into migrations and AI-drafted SQL. -- **Kafka as the store.** Events are notifications. We need 404 lookups and newest-first lists, which a topic can't answer. +- **Kafka as the store.** Events are notifications. We need `404` lookups, search, and newest-first lists, which a topic can't answer. +- **H2 for tests.** Tests would pass against a database we don't run. Integration tests use Testcontainers `postgres:16`, and the CI backend job uses a `postgres:16` service. ## Consequences - Every schema change is a new `V__*.sql`. A merged migration is never edited. -- Integration tests and the CI backend job need a real Postgres 16. -- Where Postgres runs on the shared cluster is still open. **FILL IN:** shared cluster service or our own (instructor). That also decides backups (see recoverability in [docs/nfrs.md](../nfrs.md)). +- `mvn clean verify` needs Docker for Testcontainers. +- Where PostgreSQL runs on the shared cluster is not decided by us. The deploy reads `CRM_DATABASE_URL` from the GitHub Environment. **Team to confirm** with the instructor: a shared database service, or our own. That also decides backups (see the recoverability rows in [docs/nfrs.md](../nfrs.md)). +- `V1` still starts with a leftover starter `TODO` comment about types. It's harmless, and per the rule above we don't edit a merged migration. diff --git a/docs/adrs/003-github-actions-digest-promotion.md b/docs/adrs/003-github-actions-digest-promotion.md new file mode 100644 index 0000000..df46319 --- /dev/null +++ b/docs/adrs/003-github-actions-digest-promotion.md @@ -0,0 +1,36 @@ +# ADR 003: GitHub Actions builds once and promotes image digests + +**Status:** Accepted (built in Lab 51). This replaces the first Lab 48 draft, which proposed a self-hosted runner. See "What changed" below. +**Owner:** Deployment (Will leads; see [team roles](../team-roles.md)). + +## Context + +CI/CD has to test and build both Angular and Spring Boot, scan the code and images, build images, and deploy to the shared k3s cluster. The course uses GitHub Actions. A deploy that rebuilds code can ship something nobody tested, so the image that passed the checks has to be the one that ships. + +## Decision + +- **GitHub Actions** for all CI/CD, in three workflows: + - `capstone-ci.yml`: runs on every PR, on pushes to `main`, and on `v*` tags. Its jobs are `frontend` (`npm ci`, `ng test`, `ng build`), `backend` (`mvn -B clean verify`), `security-scan` (Trivy on the repo) and `container-images` (build and scan both images, then push to GHCR on `main` or a tag), plus `package-once` (the JAR's SHA-256) on pushes. + - `codeql.yml`: CodeQL for Java and TypeScript. + - `capstone-deploy.yml`: manual only, one GitHub Environment per k3s environment. +- **GitHub-hosted runners** (`ubuntu-latest`), the same as the Lab 51 starter. +- **Package once.** The image builds copy in the JAR and Angular bundle that the test jobs already checked. They don't run Maven or `ng build` again. Pushes to `main` publish images to GHCR and record their `sha256:` digests as the `image-digests-` artifact. +- **Promote digests, not tags.** `capstone-deploy.yml` only accepts `sha256:<64 hex>` digests as input, pins them into the Kustomize overlay, and never builds anything. + +## What changed from the first draft + +The `docs/11-actions-plan` draft chose a self-hosted runner because the team expected to run out of hosted Actions minutes. When Lab 51 was built, the workflows ended up on `ubuntu-latest`, and they run green there (Capstone CI took about 3–4 minutes per run on 2026-10-21). We never set up a self-hosted runner. **Team to confirm:** whether the minutes concern still applies. If it does, switching back is a `runs-on` change per job. + +## Rejected + +- **Self-hosted runner.** We'd have to maintain it, and it would hold deploy secrets. Hosted runners work, so we don't need it right now. +- **Bitbucket Pipelines or other CI.** Not the taught path. +- **Rebuilding inside the deploy job.** That breaks package-once, and the deployed image would no longer be the one that was scanned. +- **Deploying by hand from a laptop.** No approval record and no digest trail. + +## Consequences + +- A deploy can only happen after a green `main` run that produced digests. Today `main` doesn't have these workflows yet; they arrive when PR #22 merges. +- Trivy findings are reported but don't block yet (`exit-code: "0"`). The reason and the exit condition are in `docs/capstone-cicd-runbook.md`. +- CodeQL fails at the upload step on this private repo, because code scanning isn't available for it. The team's plan is in risk R-03 in the [risk register](../risk-register.md). +- The CI Node version is 20, but the brief says Node 22. **Team to confirm** which one to use (risk R-13). diff --git a/docs/adrs/003-github-actions-self-hosted-runner.md b/docs/adrs/003-github-actions-self-hosted-runner.md deleted file mode 100644 index 9cbc6c8..0000000 --- a/docs/adrs/003-github-actions-self-hosted-runner.md +++ /dev/null @@ -1,24 +0,0 @@ -# ADR 003: GitHub Actions on a self-hosted runner, deploying digests to k3s - -**Status:** Accepted (team policy). - -## Context - -CI/CD has to test and build Angular and Spring Boot, scan, build images, and deploy to the shared k3s cluster. The course uses GitHub Actions, and its Lab 51 starter runs on `ubuntu-latest`. Our Actions minutes on this account are used up, so hosted runners aren't an option right now. - -## Decision - -GitHub Actions for all CI/CD, on our own self-hosted runner. Deploys promote an image digest built once on `main` to k3s with `kubectl`. This is a team rule. If the instructor wants hosted runners, switching back is a `runs-on` change per job. - -## Rejected - -- **GitHub-hosted `ubuntu-latest`.** What the course uses. Out because of billing, kept as the fallback. -- **Bitbucket Pipelines or other CI.** Not the taught path. -- **Deploying by hand from a laptop.** No approval record and no digest trail. - -## Consequences - -- We maintain the runner: Docker, JDK 21, Node, headless Chrome for `ng test`, and `kubectl`. Owner is Security / deploy. **FILL IN:** where the runner is hosted. -- The runner holds secrets during deploy jobs, so it serves only this private repo, never fork PRs, and cleans its workspace after each job. -- If the runner is down, CI stops. The fallback is `ubuntu-latest` for that run, if minutes allow. -- A hello-world workflow on the runner gets proven before Lab 51 CI work starts. diff --git a/docs/adrs/004-k3s-traefik-ingress.md b/docs/adrs/004-k3s-traefik-ingress.md new file mode 100644 index 0000000..c8e07a6 --- /dev/null +++ b/docs/adrs/004-k3s-traefik-ingress.md @@ -0,0 +1,32 @@ +# ADR 004: Run on shared k3s behind Traefik Ingress, with Kustomize overlays + +**Status:** Accepted for the build. **Open question for the instructor:** the platform (see below). +**Owner:** Deployment (Will leads). + +## Context + +The capstone brief (`CAPSTONE-BRIEF-AND-RUBRIC.md`) and the Lab 48–51 guides say to deploy to the **shared k3s cluster** and list OpenShift as not the taught path. The scored rubric (`Java_Angular_Fullstack_Capstone_Rubric.docx`) says the opposite: it names **OpenShift** (Routes, `oc` rollback) and treats k3s as "not the taught path". We have to pick one to build against, and we can't change the course documents. + +## Decision + +- Build for **k3s** because the labs teach it: Deployments and Services, plus one **Traefik** `Ingress` (`ingressClassName: traefik`) that sends `/api` and `/actuator/health` to `crm-backend` and `/` to `crm-frontend`. The browser sees one origin, so production needs no CORS entry. +- Manifests live in `deploy/k3s/base`, with one **Kustomize overlay** per environment (`dev`, `test`, `stage`, `prod-like`). Overlays only change the namespace, the Ingress host, and replicas (1 in dev and test, 2 in stage and prod-like). +- Pods are hardened: they run as non-root with a read-only root filesystem, drop all Linux capabilities, and don't mount a service account token. The backend has startup, readiness and liveness probes on Actuator. +- Settings come from the `crm-config` ConfigMap and secrets from the `crm-secrets` Secret. The deploy workflow creates the Secret from GitHub Environment secrets. + +## Open question (Will to ask the instructor) + +> "The brief and labs say to deploy to shared k3s. The rubric docx scores OpenShift Routes and `oc` rollback, and marks k3s down. Which one is graded? If it's OpenShift, can you give us a Project and access?" + +We haven't switched anything to OpenShift without an answer. If OpenShift is required, the change is limited to swapping the `Ingress` for a `Route` and `kubectl` for `oc`, and checking the security context. The images, digests and workflows stay the same. + +## Rejected + +- **OpenShift Routes (for now).** We have no Project or access, and the brief says not to use it. We'll revisit this once the instructor answers. +- **Laptop k3s as the release target.** It wouldn't prove anything about the shared cluster. Local runs use Docker Compose for Postgres and Kafka only. +- **NodePort or LoadBalancer per service.** That exposes more ports, and the UI and API would end up on different origins. + +## Consequences + +- The namespaces (`northstar-crm-`) and hosts (`crm-.example.invalid`) in the overlays are placeholders. The deploy overrides them from the GitHub Environment variables `CRM_NAMESPACE` and `CRM_INGRESS_HOST`. **Team to confirm** the real values with the instructor. +- The backend container asks for `runAsNonRoot`, but `backend/Dockerfile` names its user (`USER spring`) rather than giving a numeric UID. Kubernetes can't prove a named user isn't root, so the first deploy will probably fail. The fix is one line (risk R-07). diff --git a/docs/adrs/005-rest-api-contract.md b/docs/adrs/005-rest-api-contract.md new file mode 100644 index 0000000..264e873 --- /dev/null +++ b/docs/adrs/005-rest-api-contract.md @@ -0,0 +1,39 @@ +# ADR 005: REST API contract shape + +**Status:** Accepted (built in Labs 49–50 and the customer-management work). +**Owner:** Backend (Keifer leads) with Frontend (Jason leads), because both sides depend on it. + +## Context + +Angular and the API have to agree on paths, fields and error shapes, or both sides break. The Lab 49/50 starters use `POST /api/v1/interactions` with the customer id in the body. Some course slides show nested paths like `/api/customers/{id}/interactions`. An earlier assistant-drafted sample (branch `48-grok`) proposed the nested style. We kept the starter style because the starter tests and labs already used it. + +## Decision + +All paths sit under `/api/v1`. They use JSON DTOs, and JPA entities never leave the API. + +| Method and path | Who | Success | Errors | +| --- | --- | --- | --- | +| `POST /api/v1/auth/login` | anyone | `200` with `accessToken`, `tokenType`, `expiresIn`, `username`, `roles` | `400`, `401` | +| `GET /api/v1/customers?q=` | AGENT | `200` list, by name (search matches id or name) | `401` | +| `POST /api/v1/customers` | AGENT | `201` with `Location: /api/v1/customers/CUS-####` | `400`, `401` | +| `GET /api/v1/customers/{customerId}` | AGENT | `200` | `401`, `404` (`CUS-9999`) | +| `PUT /api/v1/customers/{customerId}` | AGENT; closing or reopening needs ADMIN | `200` | `400`, `401`, `403`, `404` | +| `DELETE /api/v1/customers/{customerId}` | ADMIN | `204` (sets status `CLOSED`, row kept) | `401`, `403`, `404` | +| `GET /api/v1/interactions?customerId=` | AGENT | `200` newest first | `401`, `404` | +| `POST /api/v1/interactions` | AGENT | `201` with the new interaction | `400`, `401`, `404` | +| `GET` / `PUT` / `DELETE /api/v1/interactions/{id}` | AGENT | `200` / `200` / `204` (soft delete) | `400`, `401`, `404` | + +- `{customerId}` is always the public id (`CUS-1001`). The server generates it when a customer is created. +- Errors are **Problem Details** (RFC 9457) with `type`, `title`, `status`, `detail` and `instance`, and no stack traces. That covers `401` and `403` too (`ProblemDetailAuthHandlers`). +- Requests can send `X-Correlation-Id`. The API echoes it back on the response, or generates one if it's missing or unsafe. + +## Rejected + +- **Nested paths** (`/api/customers/{id}/interactions`). Cleaner on paper, but we'd have had to rewrite the starter's controller, tests and Angular service mid-week. +- **SOAP / XML.** Not the taught path. + +## Consequences + +- There's **no OpenAPI document yet**. The table above and the DTO records are the contract. The rubric names "REST / OpenAPI", so adding one is a backlog item (CAP-21). **Team to confirm** whether it's needed for the defense. +- `POST /api/v1/interactions` returns `201` without a `Location` header (customers do send one). It's a small inconsistency, recorded here so nobody is surprised. +- A breaking change means `/api/v2`, not editing v1. diff --git a/docs/adrs/006-jwt-roles.md b/docs/adrs/006-jwt-roles.md new file mode 100644 index 0000000..3cfa344 --- /dev/null +++ b/docs/adrs/006-jwt-roles.md @@ -0,0 +1,37 @@ +# ADR 006: JWT authentication with AGENT and ADMIN roles + +**Status:** Accepted (built in the Lab 51 security work). +**Owner:** Will (deployment/security). **Team to confirm** whether someone else should own security. + +## Context + +The brief asks for JWT login and role-based access with AGENT and ADMIN. It also says Angular is not the security boundary. No external identity provider was given to us, so we needed something we could run on a laptop and in CI. + +## Decision + +- **The API issues its own token.** `POST /api/v1/auth/login` checks one of two synthetic accounts, `agent` (AGENT) or `admin` (AGENT + ADMIN). Passwords are stored as BCrypt hashes, and an account with no configured password is disabled. On success it returns an **HS256-signed JWT** that lasts **15 minutes** (`crm.security.jwt.ttl`), with issuer `northstar-crm`, a subject, an id and a `roles` claim. +- **Spring Security checks every request.** It runs as a stateless OAuth2 resource server and checks the signature, the expiry and the issuer. Rules, in order: + - `OPTIONS`, `POST /api/v1/auth/login`, `/actuator/health/**` and `/error` are public. + - The rest of `/actuator/**` needs ADMIN. + - `DELETE /api/v1/customers/**` needs ADMIN. + - The rest of `/api/**` needs AGENT. + - Everything else is denied. +- **A business rule in the service layer.** `CustomerService.update` refuses a status change into or out of `CLOSED` unless the caller has ADMIN, so an agent can't use `PUT` to get around the `DELETE` rule. +- **No built-in secret.** The app refuses to start without `CRM_JWT_SECRET` (at least 32 bytes). Only the `local` and `test` profiles carry labeled throwaway values. Deployed environments get it from the `crm-secrets` Secret. +- **Angular** keeps the token in memory only (a signal, never `localStorage`). An interceptor adds `Authorization: Bearer` to first-party API calls only. A `401` sends the user to `/login`. Roles only hide buttons, and the server checks again on every call. +- CSRF protection is off, because nothing authenticates with cookies. + +## Rejected + +- **Server sessions with cookies.** They'd need CSRF protection and sticky state across pods. +- **An external identity provider (e.g. Keycloak).** It's the right long-term answer, but there was nothing provided and no time to run one. `DemoUserDirectory` is the only piece we'd swap out. Controllers only ever see a JWT. +- **Checking roles only in Angular.** The browser is untrusted. +- **Keeping the token in `localStorage`.** Any injected script could read it. +- **AGENT/MANAGER naming** (from an early sample). The brief says ADMIN. + +## Consequences + +- Proven by `SecurityIT`, which covers no token, a bad or expired token, wrong-role `403`s, admin-only close, and CORS. `CustomerServiceTest` covers the agent close/reopen denial. +- **Accepted gaps** (risk R-09): no refresh token, so users log in again after 15 minutes or after a page refresh. No revocation: logout only clears the browser copy, so a stolen token works until it expires. No login rate limit or lockout. +- Rotating `CRM_JWT_SECRET` logs everyone out, which is fine for a demo. +- An agent can still rename a `CLOSED` customer, as long as the status stays `CLOSED`. That's recorded as a known gap (R-17). diff --git a/docs/architecture.md b/docs/architecture.md index 433becf..163adc5 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -1,72 +1,145 @@ # Northstar CRM Architecture -Agents search a customer, open the profile, and record an interaction (call, email, note, meeting). The Angular app talks to a Spring Boot REST API. The API checks the JWT, saves the note in PostgreSQL, then publishes a versioned Kafka event. GitHub Actions builds and scans the change and deploys a digest-pinned image to the shared k3s cluster behind Traefik Ingress. +Agents sign in, search for a customer, open the profile, and record interactions (call, email, note, meeting). Admins can also close or reopen a customer. The Angular app talks to a Spring Boot REST API. The API checks the JWT and the role, saves to PostgreSQL, and then publishes a versioned Kafka event. GitHub Actions tests, scans and builds each change once and publishes images by digest. A manual, approval-gated workflow deploys those digests to the shared k3s cluster behind Traefik Ingress. + +More detail: [C4 context](architecture/context.md) · [C4 containers](architecture/container.md) · [NFRs](nfrs.md) · [Lab 48 index](lab48/README.md) ## Stack -| Layer | Choice | +| Layer | Choice (version in the repo) | | --- | --- | -| Frontend | Angular | -| API | REST / OpenAPI | -| Backend | Spring Boot | -| Database | PostgreSQL | -| Messaging | Kafka | -| Containers | Docker | -| Runtime | k3s (Traefik Ingress) | -| CI/CD | GitHub Actions | -| IaC | Terraform / Ansible | +| Frontend | Angular 19 (standalone components, signals, HttpClient interceptors), TypeScript 5.7 | +| API | REST / JSON under `/api/v1`, Problem Details errors (no OpenAPI file yet, see [ADR 005](adrs/005-rest-api-contract.md)) | +| Backend | Spring Boot 3.3, Java 21, Maven | +| Security | Spring Security resource server, HS256 JWT (15 minutes), roles AGENT and ADMIN | +| Database | PostgreSQL 16, Spring Data JPA, Flyway V1–V3 | +| Messaging | Apache Kafka: `crm.customer.interactions.v1`, `crm.customer.lifecycle.v1`, each with a `.DLT` | +| Observability | Spring Boot Actuator (health probes, metrics), `X-Correlation-Id` in every log line | +| Containers | Docker. Backend on `eclipse-temurin:21-jre-alpine`, frontend on `nginx-unprivileged` | +| Runtime | k3s, Traefik Ingress, Kustomize overlays (dev, test, stage, prod-like) | +| CI/CD | GitHub Actions (`capstone-ci`, `codeql`, `capstone-deploy`), Trivy, GHCR | +| IaC | Terraform and Ansible, validate and plan only (see the [Terraform / Ansible plan](terraform-ansible-plan.md)) | +| Tests | JUnit 5, Mockito, Testcontainers (PostgreSQL 16, Kafka 3.8), Karma, Selenium | ## Non-goals -Not the taught path: **React**, **SOAP**, **Oracle**, **Bitbucket Pipelines**, and **OpenShift** (`oc`, Routes). We deploy to the **shared k3s cluster**. +Not the taught path, and not used: **React**, **SOAP**, **Oracle**, and **Bitbucket Pipelines**. + +**OpenShift:** the brief and the labs say to deploy to shared k3s, so that's what we built. The rubric docx still names OpenShift, so the platform is an **open question for the instructor** ([ADR 004](adrs/004-k3s-traefik-ingress.md)). We haven't switched anything. + +Also out of scope: real customer data (synthetic fixtures only), an external identity provider, and an outbox table. ## Runtime path -Angular SPA → REST (JWT) → Spring Boot → PostgreSQL. +Angular SPA → REST (JWT) → Spring Boot → PostgreSQL. Spring Boot ↔ Kafka. -Spring Boot also talks to Kafka for versioned events, but **PostgreSQL is the system of record**. The API saves the interaction first, commits, then publishes. Kafka never replaces the database. If the customer is missing (`CUS-9999`), the API returns 404 and writes nothing and publishes nothing. +**PostgreSQL is the system of record.** The service saves inside a transaction and publishes to Kafka only **after the commit**. Kafka never replaces the database. An unknown customer (`CUS-9999`) returns `404`, with no row and no event. -Fixtures: `CUS-1001` Amina Khan (ACTIVE), `CUS-1002` Ravi Singh (PROSPECT), `CUS-9999` not found. Default correlation id `lab-request-001`. +Fixtures: `CUS-1001` Amina Khan (ACTIVE), `CUS-1002` Ravi Singh (PROSPECT, used for the PROSPECT → ACTIVE journey), `CUS-9999` (not found). Demo correlation id: `lab-request-001`. -## Delivery path +## Diagram 1: application flow (CAP-12, record an interaction) -GitHub → Actions (test, scan, build) → image digest → shared k3s. The delivery Mermaid lives with the Actions plan (#11). The Kafka Mermaid and event field freeze live with the event ADR (#6). +```mermaid +flowchart LR + Agent["Agent in browser"] --> UI["Angular SPA"] + UI -->|"POST /api/v1/interactions
Bearer JWT + X-Correlation-Id"| SEC["Spring Security
(JWT + role check)"] + SEC --> CTRL["InteractionController
(@Valid DTO)"] + CTRL --> SVC["InteractionService
(@Transactional)"] + SVC -->|"find CUS-1001"| PG[("PostgreSQL 16
customer, customer_interaction")] + SVC -->|"insert row"| PG + SVC -->|"after commit"| K[["Kafka
crm.customer.interactions.v1"]] + CTRL -->|"201 + InteractionResponse"| UI +``` -## Application path +Unhappy paths: no or bad token → `401`. Bad `interactionType` or empty summary → `400`. `CUS-9999` → `404`. None of these save a row or publish an event (`InteractionApiIT`). -Left to right: browser app calls the API; the API saves to the database, then may publish an event. +## Diagram 2: Kafka topics and consumers ```mermaid flowchart LR - A[Angular] -->|REST with JWT| B[Spring Boot] - B --> C[(PostgreSQL)] - B -->|after save| D[Kafka] + IS["InteractionService
create()"] -->|"after commit
key = customerId"| T1[["crm.customer.interactions.v1
CustomerInteractionRecordedV1"]] + CS["CustomerService
update() / delete()"] -->|"after commit, status changed only
key = customerId"| T2[["crm.customer.lifecycle.v1
CustomerStatusChangedV1"]] + T1 --> C1["InteractionEventConsumer
group crm-interactions-audit"] + T2 --> C2["CustomerLifecycleEventConsumer
group crm-customer-lifecycle-audit"] + C1 --> D{"eventId already in
processed_event?"} + C2 --> D + D -->|"yes"| SKIP["skip (duplicate)"] + D -->|"no"| SAVE[("insert processed_event")] + C1 -.->|"fails 3 times, or unknown version"| DLT1[["crm.customer.interactions.v1.DLT"]] + C2 -.->|"fails 3 times, or unknown version"| DLT2[["crm.customer.lifecycle.v1.DLT"]] +``` + +"Fails 3 times" means the first try plus two retries, 500 ms apart. Field lists are in [ADR 001](adrs/001-event-contract.md). + +## Diagram 3: JWT login and API security + +```mermaid +sequenceDiagram + participant A as Agent + participant UI as Angular + participant API as Spring Boot API + A->>UI: username + password + UI->>API: POST /api/v1/auth/login + API->>API: BCrypt check (DemoUserDirectory) + API-->>UI: 200 accessToken (HS256, 15 min, roles) + UI->>UI: keep token in memory (signal) + A->>UI: open CUS-1001 + UI->>API: GET /api/v1/customers/CUS-1001
Authorization: Bearer ... (authInterceptor) + alt missing, expired, forged token + API-->>UI: 401 Problem Details + UI->>UI: unauthorizedInterceptor clears session, go to /login + else AGENT tries an ADMIN action (DELETE customer, close/reopen via PUT, /actuator/metrics) + API-->>UI: 403 Problem Details (session kept) + else allowed + API-->>UI: 200 / 201 / 204 + end ``` -## JWT interceptor and customer fixtures +The Angular route guard and the hidden "Close" button only make the UI nicer to use. **The API is the security boundary.** Every request is checked again on the server. Full write-up: [ADR 006](adrs/006-jwt-roles.md) and [Lab 51 security notes](lab51/security-and-observability.md). -After sign-in, Angular keeps the JWT in memory and an HTTP interceptor sticks `Authorization: Bearer …` (plus a correlation id) on each API call. Spring Security on the server is the real gate (bad token → 401, wrong role → 403). The interceptor is only for convenience. +## Delivery path -Same call path for every customer id. Known customers succeed; the missing one does not. +GitHub → Actions (test, scan, build once) → GHCR image digest → approved deploy to k3s → smoke → roll back by digest. ```mermaid -flowchart TD - A[Agent uses Angular] --> B[Interceptor adds JWT] - B --> C[Spring Boot API] - C --> D{Customer id?} - D -->|CUS-1001 Amina or CUS-1002 Ravi| E[Save in PostgreSQL then optional Kafka] - E --> F[200 or 201] - D -->|CUS-9999| G[404 — no row, no event] +flowchart LR + PR["Pull request"] --> CI["capstone-ci: frontend (ng test, ng build)
backend (mvn clean verify)
security-scan (Trivy)
container-images (build + scan)"] + PR --> CQ["codeql: Java + TypeScript"] + CI -->|"merge to main"| MAIN["push to main: same jobs, then push images
to GHCR, record sha256 digests, JAR SHA-256"] + MAIN --> DISP["capstone-deploy (manual)
pick environment + digests"] + DISP --> APPR{"GitHub Environment
approval"} + APPR --> APPLY["Terraform validate/plan, Ansible preflight,
kustomize build, kubectl apply, rollout status"] + APPLY --> SMOKE["scripts/smoke-crm.sh
CUS-1001, lab-request-001"] + SMOKE -->|"fail"| RB["re-run deploy with the
previous digests"] ``` -## Architecture decisions +Jobs, gates and evidence: [GitHub Actions plan](github-actions-plan.md). Environments: [environment strategy](environment-strategy.md). Step-by-step: [CI/CD runbook](capstone-cicd-runbook.md). -Short ADRs (written under issues #6, #8, and #11): +## Trust boundaries -| Decision | ADR (lands with) | -| --- | --- | -| Event contract (`CustomerInteractionRecordedV1`, topic, publish-after-commit) | [docs/adrs/001-event-contract.md](adrs/001-event-contract.md) (#6) | -| PostgreSQL as system of record (not Oracle) | [docs/adrs/002-postgresql.md](adrs/002-postgresql.md) (#8) | -| GitHub Actions on a self-hosted runner → digest deploy to k3s | [docs/adrs/003-github-actions-self-hosted-runner.md](adrs/003-github-actions-self-hosted-runner.md) (#11) | +1. **Browser → Ingress/API:** everything from the browser is untrusted. The API validates the JWT, the role and every DTO field. +2. **API → PostgreSQL and Kafka:** reachable only from inside the cluster. The Ingress only exposes `/api`, `/actuator/health` and `/`. Database credentials come from `crm-secrets`. +3. **Kafka → consumers:** consumers check `eventVersion` and dedupe on `eventId`. Anything they can't handle goes to the DLT. +4. **GitHub → cluster:** only `capstone-deploy`, after Environment approval, gets the kubeconfig and runtime secrets (as Environment secrets). + +## Architecture decisions -Those files are created by their issues. This overview links them so the Lab 48 pack stays one story. +| # | Decision | File | +| --- | --- | --- | +| 001 | Versioned Kafka events, publish after commit, idempotent consumers, DLT | [adrs/001-event-contract.md](adrs/001-event-contract.md) | +| 002 | PostgreSQL 16 + Flyway as the system of record (not Oracle) | [adrs/002-postgresql.md](adrs/002-postgresql.md) | +| 003 | GitHub Actions builds once and promotes image digests | [adrs/003-github-actions-digest-promotion.md](adrs/003-github-actions-digest-promotion.md) | +| 004 | Shared k3s with Traefik Ingress and Kustomize overlays (OpenShift is an open question) | [adrs/004-k3s-traefik-ingress.md](adrs/004-k3s-traefik-ingress.md) | +| 005 | REST contract under `/api/v1`, public ids, Problem Details | [adrs/005-rest-api-contract.md](adrs/005-rest-api-contract.md) | +| 006 | Self-issued HS256 JWT with AGENT and ADMIN, deny by default | [adrs/006-jwt-roles.md](adrs/006-jwt-roles.md) | + +## Open questions + +| # | Question | What we do until it's answered | Ask | +| --- | --- | --- | --- | +| 1 | Is OpenShift or k3s graded? | Build for k3s | Instructor | +| 2 | Shared cluster access, namespaces, Ingress hosts | Placeholders `northstar-crm-` and `crm-.example.invalid` | Instructor | +| 3 | Where do PostgreSQL and Kafka run on the cluster? | Read from `CRM_DATABASE_URL` and `CRM_KAFKA_BOOTSTRAP_SERVERS` | Instructor | +| 4 | Is CodeQL code scanning required, given the private repo? | Plan for a short public window ([risk R-03](risk-register.md)) | Instructor + team | +| 5 | Node 20 (CI today) or 22 (brief)? | Node 20 | Team | +| 6 | Is an OpenAPI document required? | Contract table in ADR 005 | Instructor | diff --git a/docs/architecture/container.md b/docs/architecture/container.md index cb6b190..d0bd7d0 100644 --- a/docs/architecture/container.md +++ b/docs/architecture/container.md @@ -4,30 +4,34 @@ The deployable units, and how requests and events move between them. This matche ```mermaid flowchart LR - B([Browser]) --> I[Traefik Ingress] - I -->|/| SPA[Angular SPA] - I -->|/api| API[Spring Boot API] - API -->|JPA| PG[(PostgreSQL 16)] - API -->|after commit| K[[Kafka: crm.customer.interactions.v1]] + B(["Browser"]) --> I["Traefik Ingress
one host per environment"] + I -->|"/"| SPA["crm-frontend
Angular 19 bundle on nginx-unprivileged :8080"] + I -->|"/api, /actuator/health"| API["crm-backend
Spring Boot 3.3 / Java 21 :8080"] + API -->|"JPA + Flyway"| PG[("PostgreSQL 16")] + API -->|"after commit"| K[["Kafka
interactions.v1, lifecycle.v1 (+ .DLT)"]] + K -->|"audit consumers"| API ``` ## Deployable units | Container | Tech | Runs where | | --- | --- | --- | -| Angular SPA | Angular 19, built once with `ng build` | **FILL IN:** its own image or served by the API (suggest its own image) | -| CRM API | Spring Boot 3.3, Java 21, one image pinned by digest | k3s Deployment in each env namespace | -| PostgreSQL 16 | Flyway-managed schema, system of record | **FILL IN:** shared cluster service or our own (instructor) | -| Kafka | Topic `crm.customer.interactions.v1` | **FILL IN:** shared cluster service or our own (instructor) | -| Traefik Ingress | Built into k3s | Cluster. **FILL IN:** hostnames and Ingress class (instructor). Path split `/` and `/api` is a suggestion | +| `crm-frontend` | Angular 19 production bundle, built once in CI and copied into `nginxinc/nginx-unprivileged:1.27-alpine`. Uses same-origin `/api` calls | k3s Deployment and Service in each environment namespace (1 replica in dev and test, 2 in stage and prod-like) | +| `crm-backend` | Spring Boot 3.3 on `eclipse-temurin:21-jre-alpine`, running the CI-verified JAR, pinned by digest | k3s Deployment and Service. Startup, readiness (includes the DB) and liveness probes on Actuator | +| PostgreSQL 16 | Flyway V1–V3 schema, system of record | Local: `compose.yaml`. Cluster: **Team to confirm** (URL comes from `CRM_DATABASE_URL`) | +| Kafka | Topics `crm.customer.interactions.v1` and `crm.customer.lifecycle.v1`, plus `.DLT` | Local: `compose.yaml`. Cluster: **Team to confirm** (`CRM_KAFKA_BOOTSTRAP_SERVERS`) | +| Traefik Ingress | Built into k3s, `ingressClassName: traefik` | Cluster. Hosts are placeholders until the instructor assigns them | -Locally, Compose runs PostgreSQL and Kafka, and the API and SPA run from the IDE. +Locally, `docker compose up -d` starts PostgreSQL and Kafka only. The API runs with `mvn spring-boot:run` on port 8081 and the SPA with `ng serve` on 4200 (see the README). ## Flows | Flow | Path | | --- | --- | -| Record interaction | SPA sends `POST /api/v1/interactions` with Bearer token and `X-Correlation-Id`. API validates, saves, commits, publishes, returns `201` | -| List interactions | SPA sends `GET /api/v1/interactions?customerId=CUS-1001`. API reads newest first from PostgreSQL. No Kafka | +| Sign in | SPA sends `POST /api/v1/auth/login`. The API returns a 15-minute JWT, which the SPA keeps in memory | +| Find a customer | SPA sends `GET /api/v1/customers?q=amina`. The API reads from PostgreSQL. No Kafka | +| Record an interaction | SPA sends `POST /api/v1/interactions` with a Bearer token and `X-Correlation-Id`. The API validates, saves, commits, publishes `CustomerInteractionRecordedV1`, and returns `201` | +| List interactions | SPA sends `GET /api/v1/interactions?customerId=CUS-1001`. The API reads newest first, hiding soft-deleted rows | +| Change status | `PUT /api/v1/customers/CUS-1002` with `ACTIVE`. The API saves and publishes `CustomerStatusChangedV1`. Closing or reopening needs ADMIN | | Unknown customer | `CUS-9999` returns `404`. No row, no event | -| Release | Actions builds each image once, records the digest, and deploys that digest to each namespace. Only ConfigMaps, Secrets, and replicas differ per env | +| Release | CI builds each image once and records the digest. `capstone-deploy` pins that digest into the overlay for each namespace. Only ConfigMap values, Secrets, hosts and replicas differ per environment | diff --git a/docs/architecture/context.md b/docs/architecture/context.md index 1f0749d..e76e623 100644 --- a/docs/architecture/context.md +++ b/docs/architecture/context.md @@ -1,37 +1,43 @@ # Context (C4 level 1) -Who uses Northstar CRM, what it depends on, and where the trust lines are. This matches [docs/architecture.md](../architecture.md). +Who uses Northstar CRM, what it depends on, and where the trust lines are. This matches [docs/architecture.md](../architecture.md). The next level down is the [container view](container.md). ```mermaid flowchart LR - Agent([Service agent]) -->|HTTPS| CRM[Northstar CRM] - CRM -->|checks tokens from| IdP[JWT issuer] - CRM -->|interaction events| Consumers[Event consumers] - Team([Delivery team]) -->|PRs| GH[GitHub and Actions] - GH -->|digest deploy| CRM + Agent(["Service agent
(role AGENT)"]) -->|"HTTPS, browser"| CRM["Northstar CRM
Angular SPA + Spring Boot API"] + Admin(["Admin
(roles AGENT + ADMIN)"]) -->|"HTTPS, browser"| CRM + CRM -->|"reads/writes"| PG[("PostgreSQL 16")] + CRM -->|"publishes + consumes
versioned events"| K[["Kafka"]] + Team(["Delivery team"]) -->|"PRs, reviews"| GH["GitHub + Actions"] + GH -->|"images by digest"| GHCR["GHCR registry"] + GH -->|"approved deploy"| K3S["Shared k3s cluster"] + K3S -->|"pulls digest"| GHCR + K3S -->|"runs"| CRM ``` ## People | Who | What they do | | --- | --- | -| Service agent | Signs in, opens a customer (`CUS-1001`), records and reviews interactions | -| Second role | **FILL IN:** name and permissions of the second role (brief says AGENT / ADMIN; instructor to confirm) | +| Service agent (`agent`, role AGENT) | Signs in, searches customers, opens `CUS-1001`, records, edits and soft-deletes interactions, creates customers and moves Ravi `PROSPECT → ACTIVE` | +| Admin (`admin`, roles AGENT + ADMIN) | Everything an agent can do, plus close or reopen a customer and read `/actuator/metrics` | | Delivery team | Merges through reviewed PRs and releases through Actions | +Both accounts are synthetic demo users. The API signs in-house tokens, so there's no outside login service. + ## External systems -| System | Why we depend on it | -| --- | --- | -| JWT issuer | Signs the tokens the API checks. **FILL IN:** who issues them and how we get a demo token (instructor). Until Lab 51 the API accepts the demo bearer token | -| GitHub and Actions | Source, reviews, CI/CD on our self-hosted runner (team policy) | -| Image registry | Holds images by digest. **FILL IN:** which registry (instructor) | -| Shared k3s cluster | Runs our namespaces behind Traefik Ingress | -| Event consumers | Read `crm.customer.interactions.v1`. **FILL IN:** consumer scope (instructor) | +| System | Why we depend on it | Status | +| --- | --- | --- | +| PostgreSQL 16 | System of record | Local: Compose. Cluster: **Team to confirm** (instructor-provided or ours) | +| Kafka | Interaction and lifecycle events | Local: Compose (`apache/kafka:3.8.0`). Cluster: **Team to confirm** | +| GitHub and Actions | Source, reviews, CI/CD on hosted `ubuntu-latest` runners | In use. CI runs on PR #22 | +| GHCR | Holds images, which are deployed by `sha256` digest | Pushes happen only on `main` and tags, so nothing has been published yet | +| Shared k3s cluster | Runs our namespaces behind Traefik Ingress | **Team to confirm** access, namespaces and hosts | ## Trust boundaries 1. **Browser to Ingress.** The browser is untrusted. Angular keeps the JWT in memory and adds it to calls, but that's convenience, not security. -2. **Ingress to API.** Spring Security is the gate: no or bad token is `401`, wrong role is `403`. The API accepts `X-Correlation-Id` or defaults to `lab-request-001`. -3. **API to PostgreSQL and Kafka.** Inside the cluster only, never exposed through Ingress. Credentials come from k8s Secrets. -4. **GitHub to cluster.** Only the deploy job, behind a GitHub Environment approval, holds cluster credentials. +2. **Ingress to API.** Spring Security is the gate. No token or a bad one gets `401`, and the wrong role gets `403`. The API accepts `X-Correlation-Id` if it's safe (64 characters at most, letters, digits and `._:-`), otherwise it generates one, and it echoes the value back. +3. **API to PostgreSQL and Kafka.** Inside the cluster only, never exposed through Ingress. Credentials come from the `crm-secrets` Kubernetes Secret. +4. **GitHub to cluster.** Only the `capstone-deploy` job, behind a GitHub Environment approval, holds cluster credentials. From 9b3764d23eb9de270f2b6ae4b4c1f89fa8c25ede Mon Sep 17 00:00:00 2001 From: Will Date: Wed, 21 Oct 2026 14:20:25 -0400 Subject: [PATCH 03/12] Lab 48: measurable NFRs, risk register, finished backlog and team roles - nfrs.md (from docs/08-postgres-adr-nfrs): every FILL IN replaced with a number, a check tied to a real test/config, a proving lab and a status; unmeasured items say so. - risk-register.md (from docs/09-risk-register, gaps filled from 48-grok): 20 open risks with proposed owners and dates, retired draft risks, scope cuts. - backlog.md (from docs/14-backlog): CAP-12..CAP-22 in priority order with status and evidence; drops the stub that named OpenShift as fact and the self-hosted runner. - team-roles.md (from docs/15-team-roles, agreements adapted from 48-grok): Will planning/deployment, Keifer backend, Jason frontend, Brandon's piece Team to confirm; blank sign-off lines, nothing pre-signed. --- docs/backlog.md | 141 +++++++++++++++++++++++++++++++----------- docs/nfrs.md | 71 ++++++++++++++------- docs/risk-register.md | 49 ++++++++++++--- docs/team-roles.md | 50 ++++++++++----- 4 files changed, 228 insertions(+), 83 deletions(-) diff --git a/docs/backlog.md b/docs/backlog.md index 2f51995..b1a822c 100644 --- a/docs/backlog.md +++ b/docs/backlog.md @@ -1,71 +1,138 @@ # Capstone backlog (Lab 48) -Stories in priority order. Each one fits a session and has checks we can demo. Owners are workstreams. **FILL IN:** team confirms the order. +Stories in priority order. Each one is a thin vertical slice with acceptance checks we can demo. "Workstream" points to the lead in [team roles](team-roles.md). Status as of 2026-10-21 on `will_work`. **Team to confirm** the order of the not-started stories. + +| ID | Story | Workstream | Lab | Status | +| --- | --- | --- | --- | --- | +| CAP-12 | Record customer interaction | Backend | 49 | Done | +| CAP-13 | Interaction list and detail in Angular | Frontend | 50 | Done | +| CAP-14 | JWT login shell | Deployment/security + Frontend | 50–51 | Done | +| CAP-15 | Flyway interaction schema | Backend | 49–50 | Done | +| CAP-16 | Actions PR gate (Angular + Maven + scans) | Deployment | 51 | Done, except CodeQL (R-03) | +| CAP-17 | k3s deploy and smoke through Ingress | Deployment | 51 | Not started. Blocked on cluster access (R-01) | +| CAP-18 | Customer search, profile, create, update | Backend + Frontend | 50 | Done | +| CAP-19 | Admin-only close and reopen | Backend | 51 | Done | +| CAP-20 | Customer lifecycle event | Backend | 49–51 | Done | +| CAP-21 | OpenAPI document for the REST API | Backend | 51 | Not started. Team to confirm if needed (R-11) | +| CAP-22 | Unique correlation id per UI request | Frontend | 51 | Not started (R-10) | + +--- ## CAP-12: Record customer interaction **As** an agent **I want** to record an interaction for `CUS-1001` **so that** it persists in PostgreSQL and emits `CustomerInteractionRecordedV1` on Kafka. -Owner: Backend / Kafka. Lab 49. -1. `POST /api/v1/interactions` for `CUS-1001` with correlation `lab-request-001` returns `201` and the new interaction id. -2. One row in `customer_interaction` with that id and correlation id. -3. One `CustomerInteractionRecordedV1` on `crm.customer.interactions.v1`, keyed `CUS-1001`, carrying `lab-request-001`, published after commit. Fields per [ADR 001](adrs/001-event-contract.md). -4. `CUS-9999` returns `404`, with no row and no event. +1. `POST /api/v1/interactions` for `CUS-1001`, with header `X-Correlation-Id: lab-request-001` and a valid AGENT token, returns `201` and the new interaction id. +2. One row in `customer_interaction` with that id and `correlation_id = lab-request-001`. +3. One `CustomerInteractionRecordedV1` on `crm.customer.interactions.v1`, keyed `CUS-1001`, carrying `lab-request-001`, published after commit. Fields are in [ADR 001](adrs/001-event-contract.md). +4. `CUS-9999` returns `404`, with no row and no event. An invalid `interactionType` returns `400`, with no row and no event. + +Evidence: `InteractionApiIT`, `InteractionServiceTest`, `InteractionEventPublisherTest`, [Lab 49 demo](lab49/backend-demo.md). ## CAP-13: Interaction list and detail in Angular **As** an agent **I want** to see a customer's interactions and open one **so that** I can pick up where the last contact left off. -Owner: Frontend. Lab 50. -1. Signed in, opening `CUS-1001` lists its interactions newest first from `GET /api/v1/interactions?customerId=CUS-1001`. -2. Selecting one shows type, summary, correlation id, and created time. -3. Loading, empty, and error states each show a message. `CUS-9999` shows not found. -4. `ng test` and `ng build` pass. +1. Signed in, picking `CUS-1001` lists its interactions newest first from `GET /api/v1/interactions?customerId=CUS-1001`. Soft-deleted ones don't show. +2. Opening one (`/interactions/:id`) shows its type, summary, correlation id and created time, and lets the agent edit or delete it. +3. Loading, empty and error states each show a message. `CUS-9999` shows "not found". +4. `ng test` and `ng build` pass in CI. + +Evidence: `interaction-pages.spec.ts`, `interaction-list-page.component.spec.ts`, the Selenium happy path (`frontend/e2e`), [Lab 50 demo](lab50/frontend-persistence-demo.md). ## CAP-14: JWT login shell **As** an agent **I want** to sign in once **so that** every API call carries my token. -Owner: Security / deploy. Labs 50–51. -1. Visiting `/interactions` without signing in redirects to `/login`. -2. After sign-in the token is held in memory only, and the interceptor adds `Authorization: Bearer …` to API calls. -3. A `401` from the API sends the user back to login. -4. The API rejects a missing or bad token with `401`. The server is the gate, not Angular. **FILL IN:** token issuer and role names (instructor). +1. Opening any guarded page (e.g. `/customers`) without signing in redirects to `/login`. +2. After sign-in, the token is kept in memory only (never `localStorage`), and the interceptor adds `Authorization: Bearer …` to API calls only. +3. A `401` from the API clears the session and goes back to `/login`. A `403` keeps the session and shows the Problem Details message. +4. The API rejects a missing, expired or forged token with `401`. **The server is the gate, not Angular.** Roles are AGENT and ADMIN. + +Evidence: `SecurityIT`, `auth-session.spec.ts`, `auth.interceptor.spec.ts`, `login-page.spec.ts`, [ADR 006](adrs/006-jwt-roles.md). -## CAP-15: Flyway interaction table +## CAP-15: Flyway interaction schema -**As** the team **we want** the interaction schema managed by Flyway **so that** any environment can rebuild it from empty. -Owner: Database. Lab 50. +**As** the team **we want** the schema managed by Flyway **so that** any environment can rebuild it from empty. -1. `V1__crm_schema.sql` applies clean on an empty Postgres 16 (`docker compose up postgres`, then start the API). -2. Hibernate `ddl-auto: validate` passes against it. +1. V1–V3 apply cleanly on an empty PostgreSQL 16 (every Testcontainers run does this). +2. Hibernate `ddl-auto: validate` passes against the result. 3. PostgreSQL types only. CHECK constraints reject an unknown customer status or interaction type. 4. Seeds only the synthetic `CUS-1001` and `CUS-1002`. +Evidence: `InteractionPersistenceIT`, [ADR 002](adrs/002-postgresql.md). + ## CAP-16: Actions PR gate **As** the team **we want** every PR tested on both halves **so that** a broken UI or API can't merge. -Owner: Security / deploy. Lab 51. -1. Every PR runs `frontend` (`npm ci`, `ng test`, `ng build`) and `backend` (`mvn -B clean verify`) on the self-hosted runner. -2. A failing Angular or Maven test turns the run red. -3. The SAST and dependency scan runs, and its result shows in the run. -4. **FILL IN:** whether these can be required checks to merge (instructor). +1. Every PR runs `frontend` (`npm ci`, `ng test`, `ng build`) and `backend` (`mvn -B clean verify`) on hosted `ubuntu-latest` runners. +2. A failing Angular or Maven test turns the run red, and the image jobs don't run. +3. Trivy (repository and images) and CodeQL (Java + TypeScript) run, and their reports are attached to the run. +4. Branch protection on `main` requires a non-author approval. **Team to confirm** which check names are set as required in GitHub settings (the list is in the CI/CD runbook). + +Evidence: Capstone CI runs on PR #22. CodeQL currently fails at upload (R-03). + +## CAP-17: k3s deploy and smoke through Ingress + +**As** the team **we want** an approved deploy with a smoke check **so that** a bad release is caught and rolled back before anyone relies on it. + +1. Capstone Deploy takes the two `sha256` digests from a green `main` run, waits for Environment approval, applies the overlay, and both rollouts finish within 300 s. +2. `scripts/smoke-crm.sh` through the Ingress host checks readiness and the frontend, logs in as `agent`, and creates, reads and soft-deletes one `CUS-1001` interaction with `lab-request-001`. +3. A failed smoke fails the job and prints the pod and event diagnostics. +4. A rollback is rehearsed by running Capstone Deploy again with the previous digest pair, timed against NFR-R1 (10 minutes or less). + +## CAP-18: Customer search, profile, create, update + +**As** an agent **I want** to find and maintain customers **so that** I can onboard Ravi and keep records current. + +1. `GET /api/v1/customers?q=amina` finds `CUS-1001`. An empty query lists everyone by name. +2. `POST /api/v1/customers` returns `201` with a server-generated `CUS-####` and a `Location` header. +3. `PUT /api/v1/customers/CUS-1002` with `ACTIVE` moves Ravi from PROSPECT to ACTIVE in the database. +4. `CUS-9999` returns `404`. An invalid status returns `400` and nothing is saved. + +Evidence: `CustomerApiIT`, `CustomerServiceTest`, `customer-pages.spec.ts`, [customer management notes](customer-management.md). + +## CAP-19: Admin-only close and reopen + +**As** an admin **I want** only admins to close or reopen customers **so that** agents can't remove a customer from service by mistake. + +1. `DELETE /api/v1/customers/{id}` as ADMIN sets `CLOSED` and keeps the row. As AGENT it returns `403` and changes nothing. +2. `PUT` to or from `CLOSED` as AGENT returns `403`. Renaming with the same status is allowed. +3. Angular hides the close option from agents, but the API enforces the rule regardless. + +Evidence: `SecurityIT` admin/agent close tests, `CustomerServiceTest`. + +## CAP-20: Customer lifecycle event + +**As** the audit team **we want** each status change announced **so that** there is a trail of who changed what. + +1. A real status change publishes one `CustomerStatusChangedV1` on `crm.customer.lifecycle.v1` after commit, with `fromStatus`, `toStatus`, `actor` and `correlationId`. +2. A name-only update, or closing a customer that's already closed, publishes nothing. +3. The consumer writes one audit row per `eventId`. Duplicates and unknown versions are handled (unknown versions go to `.DLT`). + +Evidence: `CustomerLifecycleEventPublisherTest`, `CustomerLifecycleEventConsumerIT`, `CustomerServiceTest`. + +## CAP-21: OpenAPI document (not started) + +**As** a reviewer **I want** a machine-readable API contract **so that** Angular and the API can't drift. + +1. An OpenAPI 3 document is served or committed, and it matches the table in [ADR 005](adrs/005-rest-api-contract.md). +2. It shows the Bearer auth scheme and the Problem Details error responses. -## CAP-17: k3s smoke through Ingress +## CAP-22: Unique correlation id per UI request (not started) -**As** the team **we want** a smoke check after every deploy **so that** a bad release rolls back before anyone relies on it. -Owner: Security / deploy. Lab 51. +**As** an operator **I want** each UI request to have its own correlation id **so that** I can follow one click through the logs. -1. After deploy, the rollout completes and readiness is green. -2. Smoke lists interactions for `CUS-1001` through the Traefik Ingress host with `lab-request-001` and gets `200`. -3. `CUS-9999` through the Ingress gets `404`. -4. If smoke fails, the job rolls back to the previous digest and the run shows it. +1. The Angular interceptor sends a new id for each request, unless a page sets one on purpose (the demo can still send `lab-request-001`). +2. The id appears in the response header, the log lines, and (for creates) the row and the event. ## Scope decisions -| Topic | Where we stand | +| Topic | Decision | | --- | --- | -| Interaction update and delete | Not part of CAP-12. Lab 50 asks for update and delete, or a designed soft delete. **FILL IN:** hard or soft delete (Database workstream), confirmed with the instructor | -| Customer search and profile | CAP-12 and CAP-13 take a customer id; there's no customer API yet. **FILL IN:** whether search, profile, or customer create/update is in scope (instructor) | -| Kafka consumer | CAP-12 is producer only. **FILL IN:** what the consumer does with a good event, or whether a log-line consumer is accepted (instructor) | +| Interaction delete | **Soft delete** (`deleted_at`, Flyway V3). The row stays for audit | +| Customer delete | **Close** (`status = CLOSED`), ADMIN only. The row stays | +| Customer search and profile | In scope and built (CAP-18) | +| Kafka consumer | Audit consumer: dedupe on `eventId`, bounded retries, DLT | +| Outbox | Out of scope for the capstone (R-06) | diff --git a/docs/nfrs.md b/docs/nfrs.md index 525de05..f7ebfa3 100644 --- a/docs/nfrs.md +++ b/docs/nfrs.md @@ -1,41 +1,64 @@ # Non-functional requirements -Every target has a number and a way to check it. Where the team or instructor still owes us the number, the line says **FILL IN** with a suggestion. Evidence gets linked from `defense/evidence-index.md` as it lands. +Every target has a **number**, a **way to check it**, and the **lab that proves it**. The status column says what's already proven and where. "Not yet evidenced" means the check exists but hasn't been run in the target environment yet. Anything not met by the defense goes into the [risk register](risk-register.md) with an owner and a date. + +Status as of 2026-10-21, on branch `will_work`. ## Security -| Target | How we check | Lab | -| --- | --- | --- | -| 100% of `/api/**` calls without a valid JWT get `401`; wrong role gets `403` | Auth tests for no token, bad token, wrong role; repeated in smoke | 51 | -| 0 secrets, tokens, kubeconfigs, `.env`, or `*.tfstate` in git | `.gitignore`, diff review per the AI usage plan, secret scan in CI | 48–51 | -| 0 open findings at or above the scan threshold. **FILL IN:** threshold (suggest High) | Dependency and image scan in Actions | 51 | +| ID | Target | How we check | Lab | Status | +| --- | --- | --- | --- | --- | +| NFR-S1 | 100% of `/api/**` calls without a valid JWT (missing, expired, forged, garbage) get `401` Problem Details | `SecurityIT` (`noToken_…`, `expiredToken_is401`, `tokenSignedWithAnotherKey_…`, `garbageToken_is401`), `CustomerApiIT.search_withoutBearer_unauthorized`, `InteractionApiIT.list_withoutBearer_unauthorized` | 51 | Met (CI green on PR #22) | +| NFR-S2 | 100% of ADMIN-only actions done by an AGENT get `403` and change nothing: `DELETE` a customer, close or reopen through `PUT`, `/actuator/metrics` | `SecurityIT.agentClosingCustomer_…`, `agentClosingCustomerThroughPut_…`, `agentReopeningClosedCustomer_…`, `healthIsPublic_butMetricsAreAdminOnly`, plus `CustomerServiceTest` | 51 | Met | +| NFR-S3 | Access tokens live at most **15 minutes**. The app **refuses to start** without `CRM_JWT_SECRET` of at least 32 bytes | `crm.security.jwt.ttl: 15m` in `application.yml`; startup check in `SecurityConfig.jwtSigningKey` | 51 | Met | +| NFR-S4 | **0** secrets, tokens, kubeconfigs, `.env` files or `*.tfstate` in git history | `.gitignore` (root and `infra/terraform/`), the Trivy `secret` scanner on every CI run, and a full-history secret scan before any visibility change | 48–51 | Met (history scan on 2026-10-21 found none) | +| NFR-S5 | **0** unaccepted fixable HIGH/CRITICAL findings in dependencies and images by the defense | Trivy repository and image reports (artifacts `trivy-repository-`, `trivy-images-`) | 51 | **Not met yet.** Trivy reports but doesn't block (`exit-code: "0"`). Exit condition is in the CI/CD runbook (R-08) | +| NFR-S6 | CodeQL (Java + TypeScript) runs on every PR with **0** open alerts | `codeql.yml` run results | 51 | **Blocked.** Upload fails on the private repo (R-03) | ## Traceability -| Target | How we check | Lab | -| --- | --- | --- | -| 100% of interaction creates store the request's correlation id (default `lab-request-001`) in the row, the event, and the log line | Integration test, then console consumer and log grep in the demo | 49 | -| 100% of deployed pods run an image pinned by digest, and each digest maps to one Actions run | `kubectl get pods -o jsonpath` against the run summary | 51 | +| ID | Target | How we check | Lab | Status | +| --- | --- | --- | --- | --- | +| NFR-T1 | 100% of new interactions store the request's correlation id in the row **and** the event. The value comes from the `X-Correlation-Id` header, else the body, else `lab-request-001` | `InteractionServiceTest.create_correlationPrecedence_headerThenRequestThenDefault`, `InteractionApiIT.createAndList_forAmina_persistsRow` | 49 | Met | +| NFR-T2 | 100% of API log lines for a request carry `correlationId=…`, and the id is echoed in the response header | Log pattern in `application.yml`, `CorrelationIdFilterTest`, `HealthEndpointsIT.correlationId_isEchoedOnResponses` | 49/51 | Met. Two caveats are in R-10 and R-18 | +| NFR-T3 | 100% of deployed pods run an image pinned by `sha256` digest that maps to one Capstone CI run | `capstone-deploy` only accepts `sha256:<64 hex>`. Compare `kubectl get pods -o jsonpath='{..image}'` with the `image-digests-` artifact | 51 | Not yet evidenced (no deploy yet, R-01) | ## Recoverability -| Target | How we check | Lab | -| --- | --- | --- | -| Roll back to the previous digest in **FILL IN** minutes (suggest 10) | Timed rollback rehearsal before the stage-to-prod-like gate | 51 | -| Schema rebuilds from an empty Postgres 16 with 0 manual SQL steps | Fresh `docker compose up postgres`, start the API, Flyway applies | 50 | -| 0 committed interactions lost while Kafka is down | Stop Kafka, POST for `CUS-1001`, row is still there | 49 | -| Data loss window **FILL IN** (depends on where Postgres runs) | Restore drill, once hosting is known | 51 | +| ID | Target | How we check | Lab | Status | +| --- | --- | --- | --- | --- | +| NFR-R1 | Roll back to the previous digest pair in **10 minutes or less**, from deciding to roll back to the smoke going green again | Timed rehearsal: a new approved Capstone Deploy run with the previous digests (runbook "Rollback") | 51 | Not yet evidenced (R-01) | +| NFR-R2 | The schema rebuilds from an empty PostgreSQL 16 with **0** manual SQL steps | Every integration-test run starts an empty Testcontainers `postgres:16` and Flyway applies V1–V3 | 49–50 | Met | +| NFR-R3 | **0** committed interactions lost while Kafka is down | Experiment: stop Kafka (`docker compose stop kafka`), `POST` for `CUS-1001`, then check the row in PostgreSQL | 49 | **Not yet tested.** We expect the row to stay, but the HTTP call may be slow or return an error while the Kafka client waits (R-06). Team to confirm by running it | +| NFR-R4 | Data-loss window (backup point) | Restore drill, once database hosting is known | 51 | **Team to confirm.** Depends on who runs PostgreSQL on the cluster | +| NFR-R5 | A poison or unknown-version event never blocks the topic. It lands on `.DLT` after at most **3** attempts | `InteractionEventConsumerIT.unsupportedVersion_goesToDeadLetterTopic_…`, `CustomerLifecycleEventConsumerIT.unsupportedVersion_…` | 49 | Met for bad versions. A non-JSON record is not covered (R-12) | + +## Correctness and idempotency + +| ID | Target | How we check | Lab | Status | +| --- | --- | --- | --- | --- | +| NFR-C1 | Invalid input or an unknown customer creates **0** rows and **0** events | `InteractionApiIT.create_unknownCustomer_notFound_andNothingPersisted`, `create_invalidType_badRequest_andNothingPersisted`, `InteractionServiceTest.create_unknownCustomer_neverPersistsOrPublishes` | 49 | Met | +| NFR-C2 | Redelivering the same event causes **0** extra side effects | `InteractionEventConsumerIT.duplicateDelivery_appliesOnlyOnce`, `CustomerLifecycleEventConsumerIT.duplicateDelivery_isAuditedOnce` | 49 | Met | ## Performance -| Target | How we check | Lab | -| --- | --- | --- | -| p95 under **FILL IN** ms (suggest 500) for `POST` and `GET /api/v1/interactions` at **FILL IN** concurrent users (suggest 10) on synthetic data | Short scripted load run against stage, results in `reports/` | 51 | +| ID | Target | How we check | Lab | Status | +| --- | --- | --- | --- | --- | +| NFR-P1 | p95 **500 ms or less** for `POST /api/v1/interactions` and `GET /api/v1/interactions?customerId=CUS-1001`, over **100** sequential calls with a valid token, synthetic data, local Compose | A timed run of 100 calls, e.g. a JMeter or Postman collection runner, or a curl loop. Results saved in `reports/` | 50–51 | **Not measured yet.** Team to confirm the tool and who runs it | +| NFR-P2 | Login responds in **1 s or less** (one BCrypt check) | Same timed run, 20 logins | 51 | Not measured yet | ## Operability -| Target | How we check | Lab | -| --- | --- | --- | -| `/actuator/health` readiness reports UP within **FILL IN** seconds of pod start (suggest 60) | Readiness probe and `kubectl rollout status` | 51 | -| Post-deploy smoke finishes in under **FILL IN** minutes (suggest 2), and any non-2xx for `CUS-1001` fails the deploy | Smoke job in the CD run | 51 | -| 100% of API request log lines carry the correlation id | Grep logs for `lab-request-001` after the demo calls | 49 | +| ID | Target | How we check | Lab | Status | +| --- | --- | --- | --- | --- | +| NFR-O1 | Backend readiness reports `UP` within **150 s** of pod start (startup probe: 30 × 5 s), and the rollout finishes within the deploy's **300 s** timeout | Probes in `deploy/k3s/base/backend.yaml`; `kubectl rollout status --timeout=300s` in `capstone-deploy` | 51 | Probe endpoints proven by `HealthEndpointsIT`. In-cluster timing not yet evidenced | +| NFR-O2 | A database outage takes the pod out of service (readiness `DOWN`) **without** restarting it (liveness ignores the DB) | Health groups in `application.yml` (readiness = `readinessState,db`; liveness = `livenessState`) | 51 | Configured. Forced-fault demo not yet recorded | +| NFR-O3 | The post-deploy smoke finishes in **under 2 minutes**, and any failed step fails the deploy job | `scripts/smoke-crm.sh` (`set -euo pipefail`): readiness, frontend, login, then create, read and soft-delete a `CUS-1001` interaction | 51 | Local smoke passed (`reports/local-test-run-2026-10-21.md`). Cluster not yet | +| NFR-O4 | PR checks (Capstone CI) finish in **under 10 minutes** | Actions run duration | 51 | Met. About 3–4 minutes per run on 2026-10-21 | +| NFR-O5 | `mvn -B clean verify` is green twice in a row with the same results | Two back-to-back runs, locally and in CI | 49 | Partly. Capstone CI was green on 4 runs in a row on 2026-10-21 (different commits). A back-to-back double run on one commit isn't recorded yet | + +## Accessibility + +| ID | Target | How we check | Lab | Status | +| --- | --- | --- | --- | --- | +| NFR-A1 | Login, customer and interaction forms are usable by keyboard only. Every input has a `