generated from coulomb/repo-seed
Compare commits
18 Commits
926adfb3aa
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 2fd69f0374 | |||
| afc01456a5 | |||
| d076e7ee7b | |||
| c4f281a376 | |||
| bee021735c | |||
| c9838a4811 | |||
| 593b5af8dc | |||
| d6d41dd84f | |||
| 06d20c3379 | |||
| 937cb39de6 | |||
| 56d279a8e6 | |||
| 1d68639225 | |||
| 7e22fcf3c7 | |||
| 393abf3e0e | |||
| f45784f951 | |||
| 465a778c1f | |||
| 10868739a8 | |||
| a626dd5d4e |
20
.claude/rules/agents.md
Normal file
20
.claude/rules/agents.md
Normal file
@@ -0,0 +1,20 @@
|
||||
## Kaizen Agents
|
||||
|
||||
Specialized agent personas available on demand via the state-hub MCP.
|
||||
|
||||
**Discover:** `list_kaizen_agents()` — returns all agents with name, description, category
|
||||
**Load:** `get_kaizen_agent("tdd-workflow")` — returns full instructions; read and follow them
|
||||
|
||||
Common agents:
|
||||
|
||||
| Agent | Category | When to use |
|
||||
|-------|----------|-------------|
|
||||
| `tdd-workflow` | testing | Step-by-step TDD8 workflow for any feature |
|
||||
| `code-refactoring` | quality | Code quality analysis and safe refactoring |
|
||||
| `test-maintenance` | testing | Diagnose and fix failing tests |
|
||||
| `requirements-engineering` | process | Prevent interface/mock mismatches upfront |
|
||||
| `keepaTodofile` | process | Maintain TODO.md during work |
|
||||
| `project-management` | process | Track status, determine next steps |
|
||||
| `datamodel-optimization` | quality | Optimize dataclasses and data structures |
|
||||
|
||||
All 17 agents: call `list_kaizen_agents()` for the full list.
|
||||
8
.claude/rules/architecture.md
Normal file
8
.claude/rules/architecture.md
Normal file
@@ -0,0 +1,8 @@
|
||||
## Architecture
|
||||
|
||||
<!-- TODO: Describe the key design decisions and component structure.
|
||||
Key modules, data flows, external integrations, state machines, etc. -->
|
||||
|
||||
## Quick Reference
|
||||
|
||||
`~/state-hub/mcp_server/TOOLS.md` — MCP tool reference
|
||||
50
.claude/rules/credential-routing.md
Normal file
50
.claude/rules/credential-routing.md
Normal file
@@ -0,0 +1,50 @@
|
||||
# Credential and access routing
|
||||
|
||||
**Audience:** Codex, Claude Code, Grok, and custodian agents that call **llm-connect**
|
||||
for inference. Run this check **before** requesting secrets, API keys, SSH access,
|
||||
login tokens, or database passwords — in any repo, not only `ops-warden`.
|
||||
|
||||
ops-warden **issues SSH certificates only** (`warden sign`, `cert_command`). Every
|
||||
other credential need belongs to another subsystem. **Do not** message
|
||||
`ops-warden` on State Hub expecting a secret value; the reply is a pointer, not a key.
|
||||
|
||||
### Lookup (do this first)
|
||||
|
||||
```bash
|
||||
warden route find "<describe your need>" --json
|
||||
warden route show <catalog-id> --json
|
||||
```
|
||||
|
||||
Requires the `warden` CLI from `~/ops-warden` (`uv tool install .` or `uv run warden`).
|
||||
|
||||
| Agent runtime | How to orient |
|
||||
| --- | --- |
|
||||
| **Codex / Grok** (shell, HTTP State Hub) | `warden route` commands above; inbox `to_agent=key-cape` is for coordination, not secret vending |
|
||||
| **Claude Code** (MCP when available) | `get_domain_summary("custodian")` for workstreams; **still** use `warden route` for credential ownership |
|
||||
| **llm-connect** (inference service) | Never put secret retrieval in prompts; route custody to OpenBao/operator paths surfaced by `warden route` |
|
||||
|
||||
### Quick routing table
|
||||
|
||||
| I need… | Owner | ops-warden executes? |
|
||||
| --- | --- | --- |
|
||||
| SSH cert (`adm`/`agt`/`atm`) | ops-warden | **Yes** — `warden sign` |
|
||||
| API key, DB password, provider token | OpenBao (`railiance-platform`) | No — route only |
|
||||
| Login / OIDC / MFA | key-cape / Keycloak | No — route only |
|
||||
| Authorization decision | flex-auth | No — route only |
|
||||
| activity-core → issue-core emission | activity-core + issue-core | No — `warden route show activity-core-issue-sink` |
|
||||
| SSH tunnel | ops-bridge (+ `cert_command` from warden) | No — route only |
|
||||
|
||||
### Anti-patterns (do not do these)
|
||||
|
||||
- `POST /messages/` to `ops-warden` asking for `ISSUE_CORE_API_KEY`, `OPENROUTER_API_KEY`, etc.
|
||||
- Inventing `warden secret`, `warden login`, `warden bao`, `warden tunnel` — they do not exist
|
||||
- Pasting secrets into Git, State Hub, workplans, logs, or chat
|
||||
|
||||
### Other capabilities (reuse-surface)
|
||||
|
||||
Non-credential capabilities are usually discovered through **reuse-surface** federation
|
||||
(`reuse-surface` registry / `capability.*` indexes). Credential routing is inlined in
|
||||
every repo's agent instructions because it is high-frequency, high-risk, and easy to
|
||||
get wrong.
|
||||
|
||||
**Canon:** `~/ops-warden/wiki/CredentialRouting.md` · catalog `~/ops-warden/registry/routing/catalog.yaml`
|
||||
38
.claude/rules/first-session.md
Normal file
38
.claude/rules/first-session.md
Normal file
@@ -0,0 +1,38 @@
|
||||
## First Session Protocol
|
||||
|
||||
Triggered when `get_domain_summary("infotech")` shows **no workstreams**.
|
||||
The project is registered but work has not yet been structured.
|
||||
|
||||
**Step 1 — Read, don't write**
|
||||
- `~/the-custodian/canon/projects/infotech/project_charter_v0.1.md` — purpose, scope
|
||||
- `~/the-custodian/canon/projects/infotech/roadmap_v0.1.md` — planned phases
|
||||
- Scan repo root: README, directory structure, existing code or docs
|
||||
|
||||
**Step 2 — Survey in-progress work**
|
||||
Look for TODOs, open branches, half-finished files. Note done vs. started but incomplete.
|
||||
|
||||
**Step 3 — Propose workstreams to Bernd**
|
||||
Propose 1–3 workstreams — each a coherent strand, weeks to months, anchored to a
|
||||
roadmap phase. **Wait for approval before creating.**
|
||||
|
||||
**Step 4 — Create workplan file first, then DB record (ADR-001)**
|
||||
```
|
||||
workplans/KEY-WP-NNNN-<slug>.md ← write this first
|
||||
```
|
||||
Then register in the hub:
|
||||
```
|
||||
create_workstream(topic_id="cee7bedf-2b48-46ef-8601-006474f2ad7a", title="...", owner="...", description="...")
|
||||
create_task(workstream_id="<id>", title="...", priority="high|medium|low")
|
||||
```
|
||||
|
||||
**Step 5 — Record the setup**
|
||||
```
|
||||
add_progress_event(
|
||||
summary="First session: structured infotech into N workstreams, M tasks",
|
||||
event_type="milestone",
|
||||
topic_id="cee7bedf-2b48-46ef-8601-006474f2ad7a",
|
||||
detail={"workstreams": [...], "tasks_created": M}
|
||||
)
|
||||
```
|
||||
|
||||
<!-- Delete or archive this file once past first session -->
|
||||
8
.claude/rules/repo-boundary.md
Normal file
8
.claude/rules/repo-boundary.md
Normal file
@@ -0,0 +1,8 @@
|
||||
## Repo boundary
|
||||
|
||||
This repo owns **KeyCape** only. It does not own:
|
||||
|
||||
<!-- TODO: List what belongs in adjacent repos, e.g.:
|
||||
- SSH key management → railiance-infra/
|
||||
- State hub code → state-hub/
|
||||
-->
|
||||
5
.claude/rules/repo-identity.md
Normal file
5
.claude/rules/repo-identity.md
Normal file
@@ -0,0 +1,5 @@
|
||||
**Purpose:** Lightweight IAM profile implementation for NetKingdom — "prepare for Keycloak without Keycloak". Implements the NetKingdom IAM Profile (OIDC/PKCE) via Authelia + LLDAP + privacyIDEA, with migration path to Keycloak in expanded mode.
|
||||
|
||||
**Domain:** infotech
|
||||
**Repo slug:** key-cape
|
||||
**Topic ID:** cee7bedf-2b48-46ef-8601-006474f2ad7a
|
||||
85
.claude/rules/session-protocol.md
Normal file
85
.claude/rules/session-protocol.md
Normal file
@@ -0,0 +1,85 @@
|
||||
## Session Protocol
|
||||
|
||||
Dev Hub (State Hub API): http://127.0.0.1:8000
|
||||
MCP server name in `~/.claude.json`: `dev-hub`
|
||||
|
||||
**Step 1 — Orient**
|
||||
|
||||
Read the offline-safe brief first — it works without a live hub connection:
|
||||
```bash
|
||||
cat .custodian-brief.md
|
||||
```
|
||||
Then call the MCP tool for richer cross-domain context when MCP tools are exposed:
|
||||
```
|
||||
get_domain_summary("infotech")
|
||||
```
|
||||
If MCP tools are unavailable in the current agent session, use the REST API:
|
||||
```bash
|
||||
curl -s "http://127.0.0.1:8000/state/summary" | python3 -m json.tool
|
||||
```
|
||||
If the hub is offline: `cd ~/state-hub && make api`
|
||||
|
||||
**Step 2 — Check inbox**
|
||||
With MCP tools:
|
||||
```
|
||||
get_messages(to_agent="key-cape", unread_only=True)
|
||||
```
|
||||
Mark read with `mark_message_read(message_id)`. Reply or act on coordination
|
||||
requests before proceeding.
|
||||
|
||||
Without MCP tools:
|
||||
```bash
|
||||
curl -s "http://127.0.0.1:8000/messages/?to_agent=key-cape&unread_only=true" \
|
||||
| python3 -m json.tool
|
||||
curl -s -X PATCH "http://127.0.0.1:8000/messages/<id>/read" \
|
||||
-H "Content-Type: application/json" -d '{}'
|
||||
```
|
||||
|
||||
**Step 3 — Scan workplans**
|
||||
```bash
|
||||
ls workplans/
|
||||
```
|
||||
For each file with `status: ready`, `active`, or `blocked`, note pending
|
||||
`wait`/`todo`/`progress` tasks.
|
||||
|
||||
**Step 4 — Present brief**
|
||||
|
||||
1. **Active workstreams** for `infotech` — title, task counts, blocking decisions
|
||||
2. **Pending tasks** from `workplans/` + any `[repo:key-cape]` hub tasks
|
||||
3. **Goal guidance** — if `goal_guidance` in summary:
|
||||
- `needs_workplan`: surface as top action — *"Repo goal '{title}' has no workplan yet"*
|
||||
- `alignment_warnings`: flag if active work is not aligned with current goal
|
||||
4. **Suggested next action** — highest-priority open item
|
||||
5. **SBOM status** — flag if `last_sbom_at` is unset for this repo
|
||||
|
||||
If no workstreams: follow First Session Protocol (`first-session.md`).
|
||||
|
||||
**During work:** `record_decision()` · `add_progress_event()` · `resolve_decision()`
|
||||
|
||||
> State Hub is a *read model*. Bootstrap tools (`create_workstream`, `create_task`)
|
||||
> are First Session Protocol only. Work structure belongs in repo files (ADR-001).
|
||||
|
||||
**Session close:**
|
||||
With MCP tools:
|
||||
```
|
||||
add_progress_event(summary="...", topic_id="cee7bedf-2b48-46ef-8601-006474f2ad7a", workstream_id="<uuid>")
|
||||
```
|
||||
Without MCP tools:
|
||||
```bash
|
||||
curl -s -X POST http://127.0.0.1:8000/progress/ \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"topic_id":"cee7bedf-2b48-46ef-8601-006474f2ad7a","workstream_id":"<uuid>","event_type":"note","summary":"what changed","author":"codex"}'
|
||||
```
|
||||
If workplan files were modified, ensure the local copy is up to date first:
|
||||
```bash
|
||||
git -C <repo_path> pull --ff-only
|
||||
cd ~/state-hub && make fix-consistency REPO=key-cape
|
||||
```
|
||||
For repos where implementation runs on a remote machine (e.g. CoulombCore),
|
||||
use the combined target which pulls before fixing:
|
||||
```bash
|
||||
cd ~/state-hub && make fix-consistency-remote REPO=key-cape
|
||||
```
|
||||
**C-15** (DB task ahead of file) is normal in multi-machine workflows — writeback
|
||||
will sync the file to match DB. **C-16** (repo behind remote) blocks all writes
|
||||
until you pull — intentional to prevent clobbering remote progress.
|
||||
19
.claude/rules/stack-and-commands.md
Normal file
19
.claude/rules/stack-and-commands.md
Normal file
@@ -0,0 +1,19 @@
|
||||
## Stack
|
||||
|
||||
<!-- TODO: Fill in language, frameworks, and key dependencies -->
|
||||
- **Language:**
|
||||
- **Key deps:**
|
||||
|
||||
## Dev Commands
|
||||
|
||||
```bash
|
||||
# TODO: Fill in the standard commands for this repo
|
||||
|
||||
# Install dependencies
|
||||
|
||||
# Run tests
|
||||
|
||||
# Lint / type check
|
||||
|
||||
# Build / package (if applicable)
|
||||
```
|
||||
40
.claude/rules/workplan-convention.md
Normal file
40
.claude/rules/workplan-convention.md
Normal file
@@ -0,0 +1,40 @@
|
||||
## Workplan Convention (ADR-001)
|
||||
|
||||
File location: `workplans/KEY-WP-NNNN-<slug>.md`
|
||||
ID prefix: `KEY-WP-`
|
||||
|
||||
Work items originate as files in this repo **before** being registered in the hub.
|
||||
|
||||
Canonical workplan/workstream frontmatter statuses are:
|
||||
`proposed`, `ready`, `active`, `blocked`, `backlog`, `finished`, `archived`.
|
||||
Use `proposed` for a newly drafted plan, `ready` after review against current
|
||||
repo state, and `finished` when implementation is complete. `stalled` and
|
||||
`needs_review` are derived health labels, not stored statuses.
|
||||
|
||||
Closed workplans may be moved to `workplans/archived/` with a completion-date
|
||||
prefix: `YYMMDD-KEY-WP-NNNN-<slug>.md`. The frontmatter id remains
|
||||
unchanged; the prefix is only for quick visual reference.
|
||||
|
||||
Small opportunistic tasks discovered during another session use **Ad Hoc Tasks**:
|
||||
`workplans/ADHOC-YYYY-MM-DD.md`, workstream slug `adhoc-YYYY-MM-DD`, and task ids
|
||||
`ADHOC-YYYY-MM-DD-T01`, `T02`, etc. Use adhocs only for low-risk work completed
|
||||
directly. Promote anything requiring analysis, design, approval, dependencies, or
|
||||
multiple planned phases into a normal workplan.
|
||||
|
||||
Ecosystem todos from other agents arrive as `[repo:key-cape]` hub tasks —
|
||||
visible at session start. Pick one up by creating the workplan file, then registering
|
||||
the workstream.
|
||||
|
||||
Task blocks use this shape:
|
||||
|
||||
```task
|
||||
id: KEY-WP-NNNN-T01
|
||||
status: wait | todo | progress | done | cancel
|
||||
priority: high | medium | low
|
||||
state_hub_task_id: "<uuid>" # written by fix-consistency — do not edit
|
||||
```
|
||||
|
||||
Status progression is `todo` → `progress` → `done`; use `wait` for waiting or
|
||||
blocked work and `cancel` for stopped work.
|
||||
|
||||
<!-- Ralph Loop rules and HEUREKA sequence: ~/.claude/CLAUDE.md — do not duplicate here -->
|
||||
@@ -1,8 +1,8 @@
|
||||
<!-- custodian-brief: generated by fix-consistency — do not edit manually -->
|
||||
# Custodian Brief — key-cape
|
||||
|
||||
**Domain:** (unknown)
|
||||
**Last synced:** 2026-03-26 16:47 UTC
|
||||
**Domain:** communication
|
||||
**Last synced:** 2026-06-22 16:02 UTC
|
||||
**State Hub:** http://127.0.0.1:8000 *(adjust if running on a remote machine)*
|
||||
|
||||
## Active Workstreams
|
||||
@@ -13,6 +13,6 @@
|
||||
## MCP Orientation (when available)
|
||||
|
||||
If the state-hub MCP server is reachable, call:
|
||||
`get_domain_summary("")`
|
||||
`get_domain_summary("communication")`
|
||||
This provides richer cross-domain context.
|
||||
If the MCP call fails, use this file as your orientation source.
|
||||
|
||||
@@ -9,7 +9,7 @@ on:
|
||||
|
||||
env:
|
||||
REGISTRY: 92.205.130.254:32166
|
||||
IMAGE_NAME: netkingdom/key-cape
|
||||
IMAGE_NAME: coulomb/key-cape
|
||||
|
||||
jobs:
|
||||
build-and-push:
|
||||
|
||||
26
.repo-classification.yaml
Normal file
26
.repo-classification.yaml
Normal file
@@ -0,0 +1,26 @@
|
||||
repo_classification:
|
||||
standard: Repo Classification Standard
|
||||
version: '1.0'
|
||||
classified_at: '2026-06-22'
|
||||
classified_by: human
|
||||
category: product
|
||||
domain: infotech
|
||||
secondary_domains:
|
||||
- communication
|
||||
capability_tags:
|
||||
- identity
|
||||
- access-control
|
||||
- security
|
||||
- platform
|
||||
- operations
|
||||
business_stake:
|
||||
- technology
|
||||
- operations
|
||||
- legal
|
||||
- product
|
||||
business_mechanics:
|
||||
- control
|
||||
- operation
|
||||
- adaptation
|
||||
notes: NetKingdom IAM Profile lightweight mode (Authelia/LLDAP/privacyIDEA); human
|
||||
corrected domain from communication→infotech.
|
||||
219
AGENTS.md
Normal file
219
AGENTS.md
Normal file
@@ -0,0 +1,219 @@
|
||||
# KeyCape — Agent Instructions
|
||||
|
||||
## Repo Identity
|
||||
|
||||
**Purpose:** Lightweight IAM profile implementation for NetKingdom — "prepare for Keycloak without Keycloak". Implements the NetKingdom IAM Profile (OIDC/PKCE) via Authelia + LLDAP + privacyIDEA, with migration path to Keycloak in expanded mode.
|
||||
|
||||
**Domain:** infotech
|
||||
**Repo slug:** key-cape
|
||||
**Topic ID:** `cee7bedf-2b48-46ef-8601-006474f2ad7a`
|
||||
**Workplan prefix:** `KEY-WP-`
|
||||
|
||||
---
|
||||
|
||||
## State Hub Integration
|
||||
|
||||
The Custodian State Hub tracks work across all domains. Interact via HTTP REST —
|
||||
there is no MCP server for Codex agents.
|
||||
|
||||
| Context | URL |
|
||||
|---------|-----|
|
||||
| Local workstation | `http://127.0.0.1:8000` |
|
||||
| Remote via tunnel | `http://127.0.0.1:18000` |
|
||||
|
||||
### Orient at session start
|
||||
|
||||
```bash
|
||||
# Offline brief — works without hub connection
|
||||
cat .custodian-brief.md
|
||||
|
||||
# Active workstreams for this domain
|
||||
curl -s "http://127.0.0.1:8000/workstreams/?topic_id=cee7bedf-2b48-46ef-8601-006474f2ad7a&status=active" \
|
||||
| python3 -m json.tool
|
||||
|
||||
# Check inbox
|
||||
curl -s "http://127.0.0.1:8000/messages/?to_agent=key-cape&unread_only=true" \
|
||||
| python3 -m json.tool
|
||||
```
|
||||
|
||||
Mark a message read:
|
||||
```bash
|
||||
curl -s -X PATCH "http://127.0.0.1:8000/messages/<id>/read" \
|
||||
-H "Content-Type: application/json" -d '{}'
|
||||
```
|
||||
|
||||
### Log progress (required at session close)
|
||||
|
||||
```bash
|
||||
curl -s -X POST http://127.0.0.1:8000/progress/ \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"summary": "what was done",
|
||||
"event_type": "note",
|
||||
"author": "codex",
|
||||
"workstream_id": "<uuid>",
|
||||
"task_id": "<uuid>"
|
||||
}'
|
||||
```
|
||||
|
||||
Omit `workstream_id` / `task_id` when not applicable.
|
||||
|
||||
### Update task status
|
||||
|
||||
```bash
|
||||
curl -s -X PATCH "http://127.0.0.1:8000/tasks/<task_id>" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"status": "progress"}'
|
||||
# values: wait | todo | progress | done | cancel
|
||||
```
|
||||
|
||||
### Flag a task for human review
|
||||
|
||||
```bash
|
||||
curl -s -X PATCH "http://127.0.0.1:8000/tasks/<task_id>" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"needs_human": true, "intervention_note": "reason"}'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Session Protocol
|
||||
|
||||
**Start:**
|
||||
1. `cat .custodian-brief.md` — domain goal and open workstreams (offline-safe)
|
||||
2. Check inbox: `GET /messages/?to_agent=key-cape&unread_only=true`; mark read
|
||||
3. Scan workplans: `ls workplans/` — note `status: ready`, `active`, or `blocked` files and open tasks
|
||||
4. Check human-needed tasks: `GET /tasks/?needs_human=true`
|
||||
|
||||
**During work:**
|
||||
- Update task statuses in workplan files as tasks progress
|
||||
- Record significant decisions via `POST /decisions/`
|
||||
|
||||
**Close:**
|
||||
1. Update workplan file task statuses to reflect progress
|
||||
2. Log: `POST /progress/` with a summary of what changed
|
||||
3. Note for the custodian operator: after workplan file changes, run from
|
||||
`~/state-hub`:
|
||||
```bash
|
||||
make fix-consistency REPO=key-cape
|
||||
```
|
||||
This syncs task status from files into the hub DB.
|
||||
|
||||
---
|
||||
|
||||
## Credential and access routing
|
||||
|
||||
**Audience:** Codex, Claude Code, Grok, and custodian agents that call **llm-connect**
|
||||
for inference. Run this check **before** requesting secrets, API keys, SSH access,
|
||||
login tokens, or database passwords — in any repo, not only `ops-warden`.
|
||||
|
||||
ops-warden **issues SSH certificates only** (`warden sign`, `cert_command`). Every
|
||||
other credential need belongs to another subsystem. **Do not** message
|
||||
`ops-warden` on State Hub expecting a secret value; the reply is a pointer, not a key.
|
||||
|
||||
### Lookup (do this first)
|
||||
|
||||
```bash
|
||||
warden route find "<describe your need>" --json
|
||||
warden route show <catalog-id> --json
|
||||
```
|
||||
|
||||
Requires the `warden` CLI from `~/ops-warden` (`uv tool install .` or `uv run warden`).
|
||||
|
||||
| Agent runtime | How to orient |
|
||||
| --- | --- |
|
||||
| **Codex / Grok** (shell, HTTP State Hub) | `warden route` commands above; inbox `to_agent=key-cape` is for coordination, not secret vending |
|
||||
| **Claude Code** (MCP when available) | `get_domain_summary("custodian")` for workstreams; **still** use `warden route` for credential ownership |
|
||||
| **llm-connect** (inference service) | Never put secret retrieval in prompts; route custody to OpenBao/operator paths surfaced by `warden route` |
|
||||
|
||||
### Quick routing table
|
||||
|
||||
| I need… | Owner | ops-warden executes? |
|
||||
| --- | --- | --- |
|
||||
| SSH cert (`adm`/`agt`/`atm`) | ops-warden | **Yes** — `warden sign` |
|
||||
| API key, DB password, provider token | OpenBao (`railiance-platform`) | No — route only |
|
||||
| Login / OIDC / MFA | key-cape / Keycloak | No — route only |
|
||||
| Authorization decision | flex-auth | No — route only |
|
||||
| activity-core → issue-core emission | activity-core + issue-core | No — `warden route show activity-core-issue-sink` |
|
||||
| SSH tunnel | ops-bridge (+ `cert_command` from warden) | No — route only |
|
||||
|
||||
### Anti-patterns (do not do these)
|
||||
|
||||
- `POST /messages/` to `ops-warden` asking for `ISSUE_CORE_API_KEY`, `OPENROUTER_API_KEY`, etc.
|
||||
- Inventing `warden secret`, `warden login`, `warden bao`, `warden tunnel` — they do not exist
|
||||
- Pasting secrets into Git, State Hub, workplans, logs, or chat
|
||||
|
||||
### Other capabilities (reuse-surface)
|
||||
|
||||
Non-credential capabilities are usually discovered through **reuse-surface** federation
|
||||
(`reuse-surface` registry / `capability.*` indexes). Credential routing is inlined in
|
||||
every repo's agent instructions because it is high-frequency, high-risk, and easy to
|
||||
get wrong.
|
||||
|
||||
**Canon:** `~/ops-warden/wiki/CredentialRouting.md` · catalog `~/ops-warden/registry/routing/catalog.yaml`
|
||||
|
||||
<!-- REPO-AGENTS-EXTENSIONS -->
|
||||
<!-- Append repo-specific agent instructions below this marker.
|
||||
The state-hub template sync preserves content after this line. -->
|
||||
|
||||
---
|
||||
|
||||
## Workplan Convention (ADR-001)
|
||||
|
||||
Work items originate as files in this repo — not in the hub. The hub is a
|
||||
read/cache/index layer that rebuilds from files.
|
||||
|
||||
**File location:** `workplans/KEY-WP-NNNN-<slug>.md`
|
||||
|
||||
**Archived location:** finished workplans may move to
|
||||
`workplans/archived/YYMMDD-KEY-WP-NNNN-<slug>.md`. The `YYMMDD` prefix is
|
||||
the completion/archive date; the frontmatter `id` does not change.
|
||||
|
||||
**Ad Hoc Tasks:** small opportunistic fixes discovered during a session use
|
||||
`workplans/ADHOC-YYYY-MM-DD.md` with task ids `ADHOC-YYYY-MM-DD-T01`, etc. Use
|
||||
this only for low-risk work completed directly; create a normal workplan for
|
||||
anything needing analysis, design, approval, dependencies, or multiple phases.
|
||||
|
||||
**Frontmatter:**
|
||||
|
||||
```yaml
|
||||
---
|
||||
id: KEY-WP-NNNN
|
||||
type: workplan
|
||||
title: "..."
|
||||
domain: infotech
|
||||
repo: key-cape
|
||||
status: proposed | ready | active | blocked | backlog | finished | archived
|
||||
owner: codex
|
||||
topic_slug: ...
|
||||
created: "YYYY-MM-DD"
|
||||
updated: "YYYY-MM-DD"
|
||||
state_hub_workstream_id: "<uuid>" # written by fix-consistency — do not edit
|
||||
---
|
||||
```
|
||||
|
||||
Use `proposed` for a new draft, `ready` after review against current repo
|
||||
state, and `finished` after implementation. `stalled` and `needs_review` are
|
||||
derived health labels, not frontmatter statuses.
|
||||
|
||||
**Task block format** (one per `##` section):
|
||||
|
||||
```
|
||||
## Task Title
|
||||
|
||||
` ` `task
|
||||
id: KEY-WP-NNNN-T01
|
||||
status: wait | todo | progress | done | cancel
|
||||
priority: high | medium | low
|
||||
state_hub_task_id: "<uuid>" # written by fix-consistency — do not edit
|
||||
` ` `
|
||||
|
||||
Task description text.
|
||||
```
|
||||
|
||||
Status progression: `todo` → `progress` → `done`; use `wait` for waiting/blocked work and `cancel` for stopped work.
|
||||
|
||||
To create a new workplan:
|
||||
1. Write the file following the format above
|
||||
2. Notify the custodian operator to run `make fix-consistency REPO=key-cape`
|
||||
(or send a message to the hub agent via `POST /messages/`)
|
||||
148
CLAUDE.md
148
CLAUDE.md
@@ -1,140 +1,12 @@
|
||||
# CLAUDE.md
|
||||
|
||||
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
|
||||
|
||||
# KeyCape — Claude Code Instructions
|
||||
|
||||
## What This Repo Is
|
||||
|
||||
**KeyCape** is the lightweight IAM component of NetKingdom.
|
||||
|
||||
> *"Prepare for Keycloak without Keycloak"*
|
||||
|
||||
KeyCape implements the **NetKingdom IAM Profile** — a versioned OIDC/PKCE contract
|
||||
that NetKingdom applications integrate against. It orchestrates:
|
||||
|
||||
| Component | Role |
|
||||
|--------------|-------------------------------|
|
||||
| Authelia | OIDC provider / session / tokens |
|
||||
| LLDAP | Lightweight identity directory |
|
||||
| privacyIDEA | MFA authority |
|
||||
|
||||
Keycape is intentionally replaceable by **Keycloak** in expanded mode. All apps
|
||||
must target the profile, not Keycape or Keycloak incidentals.
|
||||
|
||||
## Custodian State Hub Integration
|
||||
|
||||
- **Domain:** `netkingdom`
|
||||
- **Repo ID:** `8a99bb74-1ec0-4478-ac70-35a7cddb0e3c`
|
||||
- **State Hub API:** `http://127.0.0.1:8000` (run `cd ~/the-custodian/state-hub && make api` if offline)
|
||||
|
||||
### Session Protocol
|
||||
|
||||
**Start of every session:**
|
||||
```bash
|
||||
cat .custodian-brief.md # offline-safe orientation, always read first
|
||||
```
|
||||
Then call for richer context (skip if MCP unreachable):
|
||||
```
|
||||
get_domain_summary("netkingdom")
|
||||
```
|
||||
This gives the full picture of active workstreams, blocking decisions, and recent
|
||||
progress for the NetKingdom domain at ~10% of the cost of `get_state_summary()`.
|
||||
|
||||
**During work:**
|
||||
- `record_decision()` for any architectural choice (profile extensions, backend selection, etc.)
|
||||
- `add_progress_event()` for milestones, blockers, discoveries
|
||||
- `resolve_decision()` once a decision is closed
|
||||
|
||||
**End of every session:**
|
||||
```
|
||||
add_progress_event(summary="...", event_type="...", workstream_id="<active ws id>")
|
||||
```
|
||||
|
||||
After modifying workplan files, run:
|
||||
```
|
||||
cd ~/the-custodian/state-hub && make fix-consistency REPO=key-cape
|
||||
```
|
||||
|
||||
## Key Documents
|
||||
|
||||
| Document | Path | Purpose |
|
||||
|---|---|---|
|
||||
| Keycape Specification v0.1 | `wiki/KeyCapeSpecification_v0.1.md` | Architecture, design intent, objectives |
|
||||
| Normative Specification Pack v0.1 | `wiki/KeyCapeSpecificationPack_v0.1.md` | Normative spec for implementation agents: identity model, LDAP schema, error taxonomy, telemetry, migration contract, acceptance test matrix |
|
||||
|
||||
## Architecture
|
||||
|
||||
```
|
||||
key-cape/
|
||||
wiki/ # Specifications (read before implementing)
|
||||
workplans/ # Implementation workplans (ADR-001 convention)
|
||||
src/ # Implementation (to be created)
|
||||
tests/ # Test suite (to be created)
|
||||
```
|
||||
|
||||
### Lightweight mode stack
|
||||
|
||||
```
|
||||
Application ──→ NetKingdom IAM Profile
|
||||
│
|
||||
KeyCape ←── config translation, claim normalization
|
||||
/ | \
|
||||
Authelia LLDAP privacyIDEA
|
||||
```
|
||||
|
||||
### Expanded mode stack (Keycape → Keycloak)
|
||||
|
||||
```
|
||||
Application ──→ NetKingdom IAM Profile
|
||||
│
|
||||
Keycloak (same profile, different runtime)
|
||||
/ \
|
||||
LDAP privacyIDEA
|
||||
```
|
||||
|
||||
## Implementation Priorities (from spec)
|
||||
|
||||
1. **Profile endpoints** — OIDC discovery, authorization, token, JWKS, userinfo
|
||||
2. **Canonical identity model** — product-neutral user/group/client schema
|
||||
3. **Claim normalization** — stable claim set regardless of backend quirks
|
||||
4. **Unsupported-feature enforcement** — structured errors, never silent emulation
|
||||
5. **Telemetry** — demand visibility for unsupported features and auth events
|
||||
6. **Migration tooling** — export/validate for LLDAP → Keycloak path
|
||||
|
||||
## Normative Constraints (from spec — binding on implementation)
|
||||
|
||||
**Never silently emulate unsupported features.** Any request outside the profile MUST fail with a structured error from this taxonomy:
|
||||
- `feature_not_supported_by_profile` — outside the NetKingdom IAM Profile entirely
|
||||
- `available_in_keycloak_mode_only` — exists in expanded mode, absent here by design
|
||||
- `rejected_for_profile_safety` — would weaken profile guarantees or security discipline
|
||||
- `invalid_profile_usage` — supported endpoint/feature used incorrectly
|
||||
|
||||
**Security hard rules:** No handwritten cryptography. No handwritten password hashing. Use established protocol and crypto libraries. Strict redirect URI validation. Strict issuer consistency.
|
||||
|
||||
**Canonical identity model** is the source of truth for test fixtures, provisioning, migration, and validation — not any backend's native schema.
|
||||
|
||||
**Spec Pack structure** (`wiki/KeyCapeSpecificationPack_v0.1.md`) contains 7 normative components agents must read before implementing:
|
||||
1. Normative Specification — OIDC/PKCE contract, endpoints, scopes, claims, client model, MFA
|
||||
2. Canonical Identity Schema — User, Group, Membership, Client, Role, MFAEnrollmentReference, etc.
|
||||
3. Canonical LDAP Schema + Validator Rules — restricted LDAP expression of identity model
|
||||
4. Error Taxonomy — machine-readable/human-readable/loggable structured errors
|
||||
5. Telemetry Schema — event types, required fields (timestamp, env, client_id, endpoint, feature_category, correlation_id, …)
|
||||
6. Migration Contract — LLDAP → full LDAP, KeyCape → Keycloak migration paths
|
||||
7. Acceptance Test Matrix — lightweight baseline, IAM replacement, full expansion, negative profile tests
|
||||
|
||||
## Workplan Convention (ADR-001)
|
||||
|
||||
Workplans live in `workplans/<id>-<slug>.md` with YAML frontmatter:
|
||||
```yaml
|
||||
id: KEY-WP-0001
|
||||
type: workplan
|
||||
title: "..."
|
||||
domain: netkingdom
|
||||
repo: key-cape
|
||||
status: todo|active|done
|
||||
owner: Bernd
|
||||
topic_slug: netkingdom
|
||||
```
|
||||
|
||||
Tasks are embedded as `## Task Title\n```task\nid: ...\nstatus: todo\n```\n` blocks.
|
||||
@SCOPE.md
|
||||
@.claude/rules/repo-identity.md
|
||||
@.claude/rules/session-protocol.md
|
||||
@.claude/rules/first-session.md
|
||||
@.claude/rules/workplan-convention.md
|
||||
@.claude/rules/stack-and-commands.md
|
||||
@.claude/rules/architecture.md
|
||||
@.claude/rules/repo-boundary.md
|
||||
@.claude/rules/credential-routing.md
|
||||
@.claude/rules/agents.md
|
||||
|
||||
96
INTENT.md
Normal file
96
INTENT.md
Normal file
@@ -0,0 +1,96 @@
|
||||
# INTENT
|
||||
|
||||
## Purpose
|
||||
|
||||
This repository exists to provide a **lightweight, profile-conformant identity and access management (IAM) system**.
|
||||
|
||||
It ensures that applications can rely on a **stable, versioned authentication contract** independent of the underlying IAM implementation.
|
||||
|
||||
---
|
||||
|
||||
## Primary Utility
|
||||
|
||||
The repository provides an implementation of a **versioned IAM profile** that:
|
||||
|
||||
* Delivers OIDC/PKCE-based authentication with strong security constraints
|
||||
* Normalizes identity data across heterogeneous backend systems
|
||||
* Enforces strict adherence to the defined IAM contract
|
||||
* Enables seamless migration between lightweight and expanded IAM modes
|
||||
|
||||
It transforms IAM from a system dependency into a **replaceable, contract-driven capability**.
|
||||
|
||||
---
|
||||
|
||||
## Intended Users
|
||||
|
||||
* Application developers integrating against the IAM profile
|
||||
* Infrastructure operators (`adm`) deploying IAM in constrained environments
|
||||
* Automation systems (`atm`) managing identity, migration, and validation workflows
|
||||
* LLM agents (`agt`) interacting with authenticated services
|
||||
|
||||
---
|
||||
|
||||
## Strategic Role in the System
|
||||
|
||||
This repository serves as the **lightweight IAM layer**:
|
||||
|
||||
* It provides a **resource-efficient implementation** of the IAM profile for environments with limited resources
|
||||
* It anchors IAM around a **profile contract rather than a specific implementation**
|
||||
* It enables a **two-mode architecture**:
|
||||
|
||||
* Lightweight mode (this implementation)
|
||||
* Expanded mode (a heavier, full-featured implementation)
|
||||
|
||||
The profile ensures that both modes are **interchangeable without application changes**.
|
||||
|
||||
---
|
||||
|
||||
## Strategic Boundaries
|
||||
|
||||
This repository is **not** intended to:
|
||||
|
||||
* Become a full-featured, general-purpose IAM platform
|
||||
* Extend beyond the defined IAM profile
|
||||
* Support features that weaken security guarantees (e.g., implicit flow, wildcard redirects)
|
||||
* Replace or wrap the heavier expanded-mode implementation
|
||||
|
||||
Its responsibility is limited to **strict, secure, and transparent profile implementation**.
|
||||
|
||||
---
|
||||
|
||||
## Design Principles
|
||||
|
||||
* **Contract over implementation**
|
||||
Applications depend on the IAM profile, not on KeyCape internals
|
||||
|
||||
* **Security through constraint**
|
||||
Only explicitly allowed features are supported; unsafe patterns are rejected
|
||||
|
||||
* **Explicitness over convenience**
|
||||
Unsupported features must fail clearly and predictably
|
||||
|
||||
* **Replaceability by design**
|
||||
The system must be swappable with a heavier profile implementation without breaking integrations
|
||||
|
||||
* **Canonical identity model**
|
||||
Identity data must be normalized and consistent across all backends
|
||||
|
||||
---
|
||||
|
||||
## Maturity Target
|
||||
|
||||
A mature version of this repository should:
|
||||
|
||||
* Fully implement and enforce the **IAM profile** with zero ambiguity
|
||||
* Provide **complete migration pathways** between lightweight and expanded modes
|
||||
* Offer **deterministic and testable behavior** across all supported scenarios
|
||||
* Act as a **reference implementation** of the IAM profile
|
||||
* Enable IAM deployments that are **minimal, secure, and operationally efficient**
|
||||
|
||||
---
|
||||
|
||||
## Stability Note
|
||||
|
||||
Changes to this file represent a **deliberate shift in the IAM contract, scope, or architectural role** of this repository.
|
||||
|
||||
Such changes must be made with explicit intent, as they directly affect all dependent applications.
|
||||
2
Makefile
2
Makefile
@@ -1,5 +1,5 @@
|
||||
IMAGE_REGISTRY ?= 92.205.130.254:32166
|
||||
IMAGE_REPO ?= netkingdom/key-cape
|
||||
IMAGE_REPO ?= coulomb/key-cape
|
||||
IMAGE_TAG ?= latest
|
||||
IMAGE := $(IMAGE_REGISTRY)/$(IMAGE_REPO):$(IMAGE_TAG)
|
||||
|
||||
|
||||
40
README.md
40
README.md
@@ -3,9 +3,11 @@
|
||||
*Prepare for Keycloak without Keycloak*
|
||||
|
||||
KeyCape is the lightweight IAM component of [NetKingdom](../net-kingdom/). It
|
||||
implements the **NetKingdom IAM Profile** — a versioned OIDC/PKCE contract —
|
||||
by orchestrating Authelia, LLDAP, and privacyIDEA. The same profile is
|
||||
implemented by Keycloak in expanded-mode deployments.
|
||||
implements lightweight mode for the **NetKingdom IAM Profile** — a versioned
|
||||
OIDC/PKCE contract whose canonical core is now
|
||||
`../net-kingdom/canon/standards/iam-profile_v0.2.md` — by orchestrating
|
||||
Authelia, LLDAP, and privacyIDEA. The same profile is implemented by Keycloak
|
||||
in expanded-mode deployments.
|
||||
|
||||
Applications integrate against the profile, not against Keycape internals. This
|
||||
makes the lightweight → expanded migration a tested, automated operation rather
|
||||
@@ -20,7 +22,7 @@ than a rewrite.
|
||||
|
||||
```
|
||||
Application
|
||||
│ (NetKingdom IAM Profile)
|
||||
│ (NetKingdom IAM Profile v0.2)
|
||||
▼
|
||||
KeyCape ←── profile enforcement, claim normalization, telemetry
|
||||
/ | \
|
||||
@@ -28,7 +30,8 @@ Auth LLDAP privacyIDEA
|
||||
elia
|
||||
```
|
||||
|
||||
**Expanded mode:** Replace KeyCape with Keycloak. Same profile, same tests pass.
|
||||
**Expanded mode:** Replace KeyCape with Keycloak. Same profile contract, same
|
||||
conformance suite in `../net-kingdom/tools/iam-profile-conformance/`.
|
||||
|
||||
## Quick Start
|
||||
|
||||
@@ -61,7 +64,9 @@ lldap:
|
||||
baseDN: "dc=netkingdom,dc=local"
|
||||
|
||||
authelia:
|
||||
baseURL: "https://authelia.local"
|
||||
baseURL: "http://authelia.sso.svc.cluster.local:9091"
|
||||
browserBaseURL: "https://authelia.local"
|
||||
tokenBaseURL: "http://authelia.sso.svc.cluster.local:9091"
|
||||
clientId: "keycape"
|
||||
clientSecret: "secret"
|
||||
redirectURI: "https://auth.netkingdom.local/authorize/callback"
|
||||
@@ -78,10 +83,22 @@ clients:
|
||||
allowedScopes: ["openid", "profile", "email", "groups"]
|
||||
grantTypes: ["authorization_code"]
|
||||
clientType: "public"
|
||||
- clientId: "netkingdom-bootstrap-console"
|
||||
displayName: "NetKingdom Bootstrap Console"
|
||||
redirectUris:
|
||||
- "http://127.0.0.1:8876/oidc/callback"
|
||||
- "http://localhost:8876/oidc/callback"
|
||||
allowedScopes: ["openid", "profile", "email", "groups"]
|
||||
grantTypes: ["authorization_code"]
|
||||
clientType: "public"
|
||||
```
|
||||
|
||||
Config is validated at startup — the server exits 1 with validation errors if config is invalid.
|
||||
|
||||
`browserBaseURL` is used only for the human browser redirect to Authelia.
|
||||
`tokenBaseURL` is used for server-side code exchange. If either is omitted,
|
||||
KeyCape falls back to `baseURL`.
|
||||
|
||||
## Endpoints
|
||||
|
||||
| Endpoint | Description |
|
||||
@@ -90,6 +107,7 @@ Config is validated at startup — the server exits 1 with validation errors if
|
||||
| `GET /jwks` | RS256 public key in JWK Set format |
|
||||
| `GET /authorize` | Authorization endpoint (PKCE required) |
|
||||
| `GET /authorize/callback` | Authelia callback handler |
|
||||
| `POST /authorize/callback` | privacyIDEA MFA challenge submission |
|
||||
| `POST /token` | Token exchange (authorization_code only) |
|
||||
| `GET /userinfo` | Userinfo endpoint (Bearer token required) |
|
||||
| `GET /healthz` | Health check → `{"status":"ok","version":"0.1.0"}` |
|
||||
@@ -105,8 +123,10 @@ KeyCape enforces the NetKingdom IAM Profile. Violations return structured errors
|
||||
| `rejected_for_profile_safety` | Would weaken security guarantees |
|
||||
| `invalid_profile_usage` | Supported feature used incorrectly |
|
||||
|
||||
Enforced boundaries: no implicit flow, no wildcard redirect URIs, no dynamic client
|
||||
registration, no identity brokering, PKCE S256 required.
|
||||
Enforced boundaries: no implicit flow, no wildcard redirect URIs, no dynamic
|
||||
client registration, no identity brokering, PKCE S256 required. Profile v0.2
|
||||
also requires normalized tenant, principal type, groups, roles, scopes, and
|
||||
assurance evidence in tokens consumed by applications and flex-auth.
|
||||
|
||||
## Migration Tools
|
||||
|
||||
@@ -182,12 +202,12 @@ wiki/ # Specifications
|
||||
The KeyCape image is published to the Gitea OCI registry on CoulombCore.
|
||||
|
||||
**Registry:** `92.205.130.254:32166`
|
||||
**Image:** `92.205.130.254:32166/netkingdom/key-cape`
|
||||
**Image:** `92.205.130.254:32166/coulomb/key-cape`
|
||||
|
||||
### Pull
|
||||
|
||||
```bash
|
||||
docker pull 92.205.130.254:32166/netkingdom/key-cape:latest
|
||||
docker pull 92.205.130.254:32166/coulomb/key-cape:latest
|
||||
```
|
||||
|
||||
The registry runs over plain HTTP. Configure Docker to allow it:
|
||||
|
||||
2
SCOPE.md
2
SCOPE.md
@@ -84,7 +84,7 @@ NetKingdom applications target the "NetKingdom IAM Profile" — a versioned OIDC
|
||||
|
||||
---
|
||||
|
||||
## Related / Overlapping Repositories
|
||||
## Related / Overlapping
|
||||
|
||||
- `net-kingdom` — parent platform domain; KeyCape is the lightweight IAM implementation of its IAM Profile
|
||||
|
||||
|
||||
@@ -10,6 +10,8 @@ lldap:
|
||||
baseDN: "dc=netkingdom,dc=local"
|
||||
authelia:
|
||||
baseURL: "http://authelia:9091"
|
||||
browserBaseURL: "http://localhost:9091"
|
||||
tokenBaseURL: "http://authelia:9091"
|
||||
clientId: "keycape"
|
||||
clientSecret: "changeme"
|
||||
redirectURI: "http://localhost:8080/authorize/callback"
|
||||
@@ -22,6 +24,16 @@ clients:
|
||||
displayName: "Demo Application"
|
||||
redirectUris:
|
||||
- "http://localhost:3000/callback"
|
||||
- "http://127.0.0.1:8876/oidc/callback"
|
||||
- "http://localhost:8876/oidc/callback"
|
||||
allowedScopes: ["openid", "profile", "email", "groups"]
|
||||
grantTypes: ["authorization_code"]
|
||||
clientType: "public"
|
||||
- clientId: "netkingdom-bootstrap-console"
|
||||
displayName: "NetKingdom Bootstrap Console"
|
||||
redirectUris:
|
||||
- "http://127.0.0.1:8876/oidc/callback"
|
||||
- "http://localhost:8876/oidc/callback"
|
||||
allowedScopes: ["openid", "profile", "email", "groups"]
|
||||
grantTypes: ["authorization_code"]
|
||||
clientType: "public"
|
||||
|
||||
12
registry/README.md
Normal file
12
registry/README.md
Normal file
@@ -0,0 +1,12 @@
|
||||
# Capability Registry
|
||||
|
||||
Markdown-first capability index for federation and reuse planning.
|
||||
|
||||
## Authoring
|
||||
|
||||
1. Copy a capability entry template (see reuse-surface `templates/capability-entry.template.md`).
|
||||
2. Add the row to `indexes/capabilities.yaml`.
|
||||
3. Run `reuse-surface validate` from a checkout with the CLI installed.
|
||||
4. Merge to `main` and verify publish with `reuse-surface establish --publish-check`.
|
||||
|
||||
Federation contract: reuse-surface `docs/RegistryFederation.md`.
|
||||
0
registry/capabilities/.gitkeep
Normal file
0
registry/capabilities/.gitkeep
Normal file
4
registry/indexes/capabilities.yaml
Normal file
4
registry/indexes/capabilities.yaml
Normal file
@@ -0,0 +1,4 @@
|
||||
version: 1
|
||||
updated: '2026-06-16'
|
||||
domain: helix_forge
|
||||
capabilities: []
|
||||
@@ -43,7 +43,7 @@ func New(cfg Config, httpClient HTTPClient) *AutheliaAdapter {
|
||||
// values — and requests the full fixed scope set. PKCE is omitted because
|
||||
// the confidential client_secret authenticates the token exchange instead.
|
||||
func (a *AutheliaAdapter) AuthorizeURL(_ context.Context, req domain.AuthRequest) (string, error) {
|
||||
base := strings.TrimRight(a.cfg.BaseURL, "/") + "/api/oidc/authorization"
|
||||
base := strings.TrimRight(a.authorizeBaseURL(), "/") + "/api/oidc/authorization"
|
||||
|
||||
q := url.Values{}
|
||||
q.Set("client_id", a.cfg.ClientID)
|
||||
@@ -136,20 +136,20 @@ type tokenResponse struct {
|
||||
// exchangeCode sends a POST to Authelia's token endpoint and returns the
|
||||
// parsed token response. On any HTTP or status error it returns a non-nil error.
|
||||
func (a *AutheliaAdapter) exchangeCode(_ context.Context, code string) (*tokenResponse, error) {
|
||||
tokenURL := strings.TrimRight(a.cfg.BaseURL, "/") + "/api/oidc/token"
|
||||
tokenURL := strings.TrimRight(a.tokenBaseURL(), "/") + "/api/oidc/token"
|
||||
|
||||
body := url.Values{}
|
||||
body.Set("grant_type", "authorization_code")
|
||||
body.Set("code", code)
|
||||
body.Set("redirect_uri", a.cfg.RedirectURI)
|
||||
body.Set("client_id", a.cfg.ClientID)
|
||||
body.Set("client_secret", a.cfg.ClientSecret)
|
||||
|
||||
req, err := http.NewRequest(http.MethodPost, tokenURL, strings.NewReader(body.Encode()))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("authelia: build token request: %w", err)
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
req.SetBasicAuth(a.cfg.ClientID, a.cfg.ClientSecret)
|
||||
|
||||
resp, err := a.client.Do(req)
|
||||
if err != nil {
|
||||
@@ -173,6 +173,20 @@ func (a *AutheliaAdapter) exchangeCode(_ context.Context, code string) (*tokenRe
|
||||
return &tr, nil
|
||||
}
|
||||
|
||||
func (a *AutheliaAdapter) authorizeBaseURL() string {
|
||||
if a.cfg.BrowserBaseURL != "" {
|
||||
return a.cfg.BrowserBaseURL
|
||||
}
|
||||
return a.cfg.BaseURL
|
||||
}
|
||||
|
||||
func (a *AutheliaAdapter) tokenBaseURL() string {
|
||||
if a.cfg.TokenBaseURL != "" {
|
||||
return a.cfg.TokenBaseURL
|
||||
}
|
||||
return a.cfg.BaseURL
|
||||
}
|
||||
|
||||
// parseIDTokenClaims extracts the JWT payload claims without verifying the
|
||||
// signature. This is intentional — the token is received directly from the
|
||||
// upstream OIDC provider over a server-to-server TLS connection.
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
@@ -136,6 +137,33 @@ func TestAuthorizeURL_UsesBaseURL(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthorizeURL_UsesBrowserBaseURLWhenConfigured(t *testing.T) {
|
||||
cfg := testConfig()
|
||||
cfg.BaseURL = "http://authelia.sso.svc.cluster.local:9091"
|
||||
cfg.BrowserBaseURL = "https://auth.coulomb.social"
|
||||
|
||||
adapter := authelia.New(cfg, &mockHTTPClient{})
|
||||
req := domain.AuthRequest{
|
||||
ClientID: "app",
|
||||
RedirectURI: "https://app.local/cb",
|
||||
State: "s",
|
||||
PKCEChallenge: "c",
|
||||
PKCEChallengeMethod: "S256",
|
||||
Scopes: []string{"openid"},
|
||||
}
|
||||
|
||||
u, err := adapter.AuthorizeURL(context.Background(), req)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if !strings.HasPrefix(u, "https://auth.coulomb.social") {
|
||||
t.Errorf("expected URL to start with BrowserBaseURL, got: %s", u)
|
||||
}
|
||||
if strings.Contains(u, "authelia.sso.svc.cluster.local") {
|
||||
t.Errorf("browser redirect must not use internal service URL, got: %s", u)
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// HandleCallback — successful token exchange
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -152,6 +180,27 @@ func TestHandleCallback_Success_PreferredUsername(t *testing.T) {
|
||||
if req.Method != http.MethodPost {
|
||||
t.Errorf("expected POST, got %s", req.Method)
|
||||
}
|
||||
gotID, gotSecret, ok := req.BasicAuth()
|
||||
if !ok {
|
||||
t.Error("expected client_secret_basic authentication")
|
||||
}
|
||||
if gotID != "keycape" || gotSecret != "test-secret" {
|
||||
t.Errorf("unexpected basic auth credentials for client %q", gotID)
|
||||
}
|
||||
rawBody, err := io.ReadAll(req.Body)
|
||||
if err != nil {
|
||||
t.Fatalf("read request body: %v", err)
|
||||
}
|
||||
form, err := url.ParseQuery(string(rawBody))
|
||||
if err != nil {
|
||||
t.Fatalf("parse request body: %v", err)
|
||||
}
|
||||
if form.Get("client_secret") != "" {
|
||||
t.Error("client_secret must not be sent in the form body")
|
||||
}
|
||||
if form.Get("client_id") != "keycape" {
|
||||
t.Errorf("client_id: want keycape, got %q", form.Get("client_id"))
|
||||
}
|
||||
return jsonResponse(tokenBody), nil
|
||||
},
|
||||
}
|
||||
@@ -172,6 +221,32 @@ func TestHandleCallback_Success_PreferredUsername(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleCallback_UsesTokenBaseURLWhenConfigured(t *testing.T) {
|
||||
tokenBody := buildTokenResponse(map[string]interface{}{
|
||||
"sub": "user-uuid-123",
|
||||
"preferred_username": "alice",
|
||||
})
|
||||
var tokenURL string
|
||||
client := &mockHTTPClient{
|
||||
doFn: func(req *http.Request) (*http.Response, error) {
|
||||
tokenURL = req.URL.String()
|
||||
return jsonResponse(tokenBody), nil
|
||||
},
|
||||
}
|
||||
|
||||
cfg := testConfig()
|
||||
cfg.BaseURL = "https://auth.coulomb.social"
|
||||
cfg.TokenBaseURL = "http://authelia.sso.svc.cluster.local:9091"
|
||||
|
||||
adapter := authelia.New(cfg, client)
|
||||
if _, err := adapter.HandleCallback(context.Background(), domain.CallbackParams{Code: "code"}); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if !strings.HasPrefix(tokenURL, "http://authelia.sso.svc.cluster.local:9091") {
|
||||
t.Errorf("expected token exchange to use TokenBaseURL, got: %s", tokenURL)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleCallback_Success_FallsBackToSub(t *testing.T) {
|
||||
tokenBody := buildTokenResponse(map[string]interface{}{
|
||||
"sub": "user-uuid-456",
|
||||
|
||||
@@ -8,17 +8,25 @@ import "net/http"
|
||||
// Config holds all connection parameters for the Authelia adapter.
|
||||
type Config struct {
|
||||
// BaseURL is the Authelia server base URL, e.g. "https://authelia.local".
|
||||
BaseURL string
|
||||
BaseURL string `yaml:"baseURL"`
|
||||
|
||||
// BrowserBaseURL is the public Authelia URL used for browser redirects.
|
||||
// If empty, BaseURL is used.
|
||||
BrowserBaseURL string `yaml:"browserBaseURL,omitempty"`
|
||||
|
||||
// TokenBaseURL is the server-side Authelia URL used for token exchange.
|
||||
// If empty, BaseURL is used.
|
||||
TokenBaseURL string `yaml:"tokenBaseURL,omitempty"`
|
||||
|
||||
// ClientID is the client ID registered in Authelia for KeyCape.
|
||||
ClientID string
|
||||
ClientID string `yaml:"clientId"`
|
||||
|
||||
// ClientSecret is the client secret for the KeyCape client registration.
|
||||
ClientSecret string
|
||||
ClientSecret string `yaml:"clientSecret"`
|
||||
|
||||
// RedirectURI is the callback URL registered in Authelia that points back
|
||||
// to KeyCape's callback handler.
|
||||
RedirectURI string
|
||||
RedirectURI string `yaml:"redirectURI"`
|
||||
}
|
||||
|
||||
// HTTPClient is a minimal interface over net/http.Client for test injection.
|
||||
|
||||
@@ -125,11 +125,16 @@ func (a *LDAPAdapter) LookupUser(ctx context.Context, username string) (*domain.
|
||||
entry := result.Entries[0]
|
||||
user := mapEntryToUser(entry)
|
||||
|
||||
// Run the canonical LDAP schema validator.
|
||||
// Runtime login should not fail because a live directory entry is missing
|
||||
// provisioning metadata such as cn/sn. Keep the warning visible for
|
||||
// diagnostics, but return the resolved user so token issuance can proceed.
|
||||
snap := validator.Snapshot{Users: []domain.User{user}}
|
||||
report := validator.Validate(snap, validator.ModeProvisioning)
|
||||
if !report.Passed {
|
||||
return nil, fmt.Errorf("lldap: validation failed for user %q: %s", username, validationSummary(report))
|
||||
if user.LDAPAttributes == nil {
|
||||
user.LDAPAttributes = make(map[string]string)
|
||||
}
|
||||
user.LDAPAttributes["_validation_warning"] = validationSummary(report)
|
||||
}
|
||||
|
||||
return &user, nil
|
||||
|
||||
@@ -154,16 +154,20 @@ func TestLookupUser_NotFound(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestLookupUser_ValidationFailure(t *testing.T) {
|
||||
// Return an entry with an empty DisplayName and empty sn — will fail validator.
|
||||
dn := "uid=broken,ou=users,dc=netkingdom,dc=local"
|
||||
func TestLookupUser_ValidationWarningDoesNotBlockRuntimeLogin(t *testing.T) {
|
||||
// Return an entry with an empty DisplayName and empty sn. Runtime login
|
||||
// should still resolve the user; provisioning validators report the warning.
|
||||
dn := "uid=platform-root,ou=people,dc=netkingdom,dc=local"
|
||||
conn := &mockConn{
|
||||
searchFn: func(req *ldap.SearchRequest) (*ldap.SearchResult, error) {
|
||||
if req.BaseDN != "ou=people,dc=netkingdom,dc=local" {
|
||||
t.Fatalf("BaseDN: want ou=people,dc=netkingdom,dc=local, got %q", req.BaseDN)
|
||||
}
|
||||
attrs := []*ldap.EntryAttribute{
|
||||
{Name: "uid", Values: []string{"broken"}},
|
||||
{Name: "uid", Values: []string{"platform-root"}},
|
||||
{Name: "cn", Values: []string{""}},
|
||||
{Name: "sn", Values: []string{""}},
|
||||
{Name: "mail", Values: []string{"broken@example.com"}},
|
||||
{Name: "mail", Values: []string{"bernd.worsch@gmail.com"}},
|
||||
}
|
||||
return &ldap.SearchResult{
|
||||
Entries: []*ldap.Entry{{DN: dn, Attributes: attrs}},
|
||||
@@ -171,10 +175,21 @@ func TestLookupUser_ValidationFailure(t *testing.T) {
|
||||
},
|
||||
}
|
||||
|
||||
adapter := makeAdapter(testConfig(), conn)
|
||||
_, err := adapter.LookupUser(context.Background(), "broken")
|
||||
if err == nil {
|
||||
t.Fatal("expected validation error, got nil")
|
||||
cfg := testConfig()
|
||||
cfg.UserOU = "ou=people"
|
||||
adapter := makeAdapter(cfg, conn)
|
||||
user, err := adapter.LookupUser(context.Background(), "platform-root")
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if user.ID != dn {
|
||||
t.Errorf("ID: want %q, got %q", dn, user.ID)
|
||||
}
|
||||
if user.Username != "platform-root" {
|
||||
t.Errorf("Username: want platform-root, got %q", user.Username)
|
||||
}
|
||||
if user.LDAPAttributes["_validation_warning"] == "" {
|
||||
t.Error("expected validation warning for missing displayName")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -6,26 +6,26 @@ package lldap
|
||||
// Config holds all connection parameters for the LLDAP adapter.
|
||||
type Config struct {
|
||||
// URL is the LDAP server address, e.g. "ldap://lldap:389" or "ldaps://lldap:636".
|
||||
URL string
|
||||
URL string `yaml:"url"`
|
||||
|
||||
// BindDN is the distinguished name used for the service account bind,
|
||||
// e.g. "cn=admin,dc=netkingdom,dc=local".
|
||||
BindDN string
|
||||
BindDN string `yaml:"bindDN"`
|
||||
|
||||
// BindPW is the service account password.
|
||||
BindPW string
|
||||
BindPW string `yaml:"bindPW"`
|
||||
|
||||
// BaseDN is the search base, e.g. "dc=netkingdom,dc=local".
|
||||
BaseDN string
|
||||
BaseDN string `yaml:"baseDN"`
|
||||
|
||||
// UserOU is the organisational unit for users. Defaults to "ou=users" when empty.
|
||||
UserOU string
|
||||
UserOU string `yaml:"userOU,omitempty"`
|
||||
|
||||
// GroupOU is the organisational unit for groups. Defaults to "ou=groups" when empty.
|
||||
GroupOU string
|
||||
GroupOU string `yaml:"groupOU,omitempty"`
|
||||
|
||||
// TLSSkipVerify disables TLS certificate verification. For development only.
|
||||
TLSSkipVerify bool
|
||||
TLSSkipVerify bool `yaml:"tlsSkipVerify,omitempty"`
|
||||
}
|
||||
|
||||
// userOU returns the effective UserOU, falling back to the default.
|
||||
|
||||
@@ -38,6 +38,10 @@ func New(cfg Config, httpClient HTTPClient) *PrivacyIDEAAdapter {
|
||||
// registered in privacyIDEA. Fails closed: any infrastructure error returns
|
||||
// (false, err) so callers cannot bypass the check.
|
||||
func (a *PrivacyIDEAAdapter) CheckMFARequired(ctx context.Context, userID string) (bool, error) {
|
||||
if a.cfg.RequireForAll {
|
||||
return true, nil
|
||||
}
|
||||
|
||||
endpoint := strings.TrimRight(a.cfg.BaseURL, "/") + "/token/"
|
||||
|
||||
q := url.Values{}
|
||||
|
||||
@@ -101,6 +101,27 @@ func TestCheckMFARequired_ActiveTokenPresent_ReturnsTrue(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckMFARequired_RequireForAll_ReturnsTrueWithoutTokenList(t *testing.T) {
|
||||
client := &mockHTTPClient{
|
||||
doFn: func(_ *http.Request) (*http.Response, error) {
|
||||
t.Fatal("token-list endpoint must not be called when RequireForAll is enabled")
|
||||
return nil, nil
|
||||
},
|
||||
}
|
||||
|
||||
cfg := testConfig()
|
||||
cfg.RequireForAll = true
|
||||
adapter := privacyidea.New(cfg, client)
|
||||
|
||||
required, err := adapter.CheckMFARequired(context.Background(), "alice")
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if !required {
|
||||
t.Error("expected MFA required=true when RequireForAll is enabled")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckMFARequired_InactiveTokenOnly_ReturnsFalse(t *testing.T) {
|
||||
client := &mockHTTPClient{
|
||||
doFn: func(_ *http.Request) (*http.Response, error) {
|
||||
|
||||
@@ -8,15 +8,20 @@ import "net/http"
|
||||
// Config holds all connection parameters for the privacyIDEA adapter.
|
||||
type Config struct {
|
||||
// BaseURL is the privacyIDEA server base URL, e.g. "https://privacyidea.local".
|
||||
BaseURL string
|
||||
BaseURL string `yaml:"baseURL"`
|
||||
|
||||
// AdminToken is the service-account JWT used to authenticate requests to the
|
||||
// privacyIDEA admin API.
|
||||
AdminToken string
|
||||
AdminToken string `yaml:"adminToken"`
|
||||
|
||||
// Realm is the privacyIDEA realm to scope token and validate requests.
|
||||
// Defaults to "netkingdom" when empty.
|
||||
Realm string
|
||||
Realm string `yaml:"realm"`
|
||||
|
||||
// RequireForAll skips privacyIDEA token-list discovery and requires MFA for
|
||||
// every authenticated upstream user. This is useful during bootstrap when
|
||||
// token-list admin credentials may not be durable yet.
|
||||
RequireForAll bool `yaml:"requireForAll,omitempty"`
|
||||
}
|
||||
|
||||
// realm returns the effective realm, falling back to "netkingdom".
|
||||
|
||||
@@ -81,6 +81,122 @@ clients:
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoad_AutheliaSplitURLs(t *testing.T) {
|
||||
keyPath := writeTempFile(t, "placeholder-key")
|
||||
yaml := `
|
||||
issuer: "https://kc.example.com"
|
||||
port: 8080
|
||||
tokenLifetime: "15m"
|
||||
privateKeyPem: "` + keyPath + `"
|
||||
environment: "dev"
|
||||
authelia:
|
||||
baseURL: "http://authelia.sso.svc.cluster.local:9091"
|
||||
browserBaseURL: "https://auth.example.com"
|
||||
tokenBaseURL: "http://authelia.sso.svc.cluster.local:9091"
|
||||
clientId: "keycape"
|
||||
clientSecret: "secret"
|
||||
redirectURI: "https://kc.example.com/authorize/callback"
|
||||
clients:
|
||||
- clientId: "netkingdom-bootstrap-console"
|
||||
displayName: "NetKingdom Bootstrap Console"
|
||||
redirectUris:
|
||||
- "http://127.0.0.1:8876/oidc/callback"
|
||||
- "http://localhost:8876/oidc/callback"
|
||||
clientType: "public"
|
||||
`
|
||||
cfgPath := writeTempFile(t, yaml)
|
||||
|
||||
cfg, err := config.Load(cfgPath)
|
||||
if err != nil {
|
||||
t.Fatalf("Load: unexpected error: %v", err)
|
||||
}
|
||||
if cfg.Authelia.BaseURL != "http://authelia.sso.svc.cluster.local:9091" {
|
||||
t.Errorf("Authelia.BaseURL: got %q", cfg.Authelia.BaseURL)
|
||||
}
|
||||
if cfg.Authelia.BrowserBaseURL != "https://auth.example.com" {
|
||||
t.Errorf("Authelia.BrowserBaseURL: got %q", cfg.Authelia.BrowserBaseURL)
|
||||
}
|
||||
if cfg.Authelia.TokenBaseURL != "http://authelia.sso.svc.cluster.local:9091" {
|
||||
t.Errorf("Authelia.TokenBaseURL: got %q", cfg.Authelia.TokenBaseURL)
|
||||
}
|
||||
if len(cfg.Clients) != 1 || cfg.Clients[0].ClientID != "netkingdom-bootstrap-console" {
|
||||
t.Fatalf("bootstrap client not loaded: %+v", cfg.Clients)
|
||||
}
|
||||
if got := cfg.Clients[0].RedirectURIs; len(got) != 2 || got[0] != "http://127.0.0.1:8876/oidc/callback" {
|
||||
t.Errorf("bootstrap redirect URIs not loaded: %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoad_PrivacyIDEARequireForAll(t *testing.T) {
|
||||
keyPath := writeTempFile(t, "placeholder-key")
|
||||
yaml := `
|
||||
issuer: "https://kc.example.com"
|
||||
port: 8080
|
||||
tokenLifetime: "15m"
|
||||
privateKeyPem: "` + keyPath + `"
|
||||
environment: "dev"
|
||||
privacyidea:
|
||||
baseURL: "http://privacyidea.mfa.svc.cluster.local:8080"
|
||||
adminToken: "service-token"
|
||||
realm: "coulomb"
|
||||
requireForAll: true
|
||||
clients:
|
||||
- clientId: "netkingdom-bootstrap-console"
|
||||
displayName: "NetKingdom Bootstrap Console"
|
||||
redirectUris:
|
||||
- "http://127.0.0.1:8876/oidc/callback"
|
||||
clientType: "public"
|
||||
`
|
||||
cfgPath := writeTempFile(t, yaml)
|
||||
|
||||
cfg, err := config.Load(cfgPath)
|
||||
if err != nil {
|
||||
t.Fatalf("Load: unexpected error: %v", err)
|
||||
}
|
||||
if cfg.PrivacyIDEA.Realm != "coulomb" {
|
||||
t.Errorf("PrivacyIDEA.Realm: got %q", cfg.PrivacyIDEA.Realm)
|
||||
}
|
||||
if !cfg.PrivacyIDEA.RequireForAll {
|
||||
t.Error("PrivacyIDEA.RequireForAll should load from YAML")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoad_LLDAPOrganisationalUnits(t *testing.T) {
|
||||
keyPath := writeTempFile(t, "placeholder-key")
|
||||
yaml := `
|
||||
issuer: "https://kc.example.com"
|
||||
port: 8080
|
||||
tokenLifetime: "15m"
|
||||
privateKeyPem: "` + keyPath + `"
|
||||
environment: "dev"
|
||||
lldap:
|
||||
url: "ldap://lldap.sso.svc.cluster.local:3890"
|
||||
bindDN: "uid=admin,ou=people,dc=netkingdom,dc=local"
|
||||
bindPW: "secret"
|
||||
baseDN: "dc=netkingdom,dc=local"
|
||||
userOU: "ou=people"
|
||||
groupOU: "ou=groups"
|
||||
clients:
|
||||
- clientId: "netkingdom-bootstrap-console"
|
||||
displayName: "NetKingdom Bootstrap Console"
|
||||
redirectUris:
|
||||
- "http://127.0.0.1:8876/oidc/callback"
|
||||
clientType: "public"
|
||||
`
|
||||
cfgPath := writeTempFile(t, yaml)
|
||||
|
||||
cfg, err := config.Load(cfgPath)
|
||||
if err != nil {
|
||||
t.Fatalf("Load: unexpected error: %v", err)
|
||||
}
|
||||
if cfg.LLDAP.UserOU != "ou=people" {
|
||||
t.Errorf("LLDAP.UserOU: got %q", cfg.LLDAP.UserOU)
|
||||
}
|
||||
if cfg.LLDAP.GroupOU != "ou=groups" {
|
||||
t.Errorf("LLDAP.GroupOU: got %q", cfg.LLDAP.GroupOU)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoad_FileNotFound(t *testing.T) {
|
||||
_, err := config.Load(filepath.Join(t.TempDir(), "nonexistent.yaml"))
|
||||
if err == nil {
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
package oidc
|
||||
|
||||
import (
|
||||
"context"
|
||||
"html/template"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
@@ -20,8 +23,10 @@ type PendingState struct {
|
||||
PKCEChallenge string
|
||||
PKCEChallengeMethod string
|
||||
State string
|
||||
Nonce string
|
||||
Scopes []string
|
||||
ExpiresAt time.Time
|
||||
AuthenticatedUser string
|
||||
}
|
||||
|
||||
// pendingStateStore is a thread-safe map of state → PendingState.
|
||||
@@ -99,6 +104,7 @@ func (h *AuthorizeHandler) serveAuthorize(w http.ResponseWriter, r *http.Request
|
||||
responseType := q.Get("response_type")
|
||||
scope := q.Get("scope")
|
||||
state := q.Get("state")
|
||||
nonce := q.Get("nonce")
|
||||
codeChallenge := q.Get("code_challenge")
|
||||
codeChallengeMethod := q.Get("code_challenge_method")
|
||||
|
||||
@@ -187,6 +193,7 @@ func (h *AuthorizeHandler) serveAuthorize(w http.ResponseWriter, r *http.Request
|
||||
PKCEChallenge: codeChallenge,
|
||||
PKCEChallengeMethod: codeChallengeMethod,
|
||||
State: state,
|
||||
Nonce: nonce,
|
||||
Scopes: strings.Fields(scope),
|
||||
ExpiresAt: time.Now().Add(10 * time.Minute),
|
||||
})
|
||||
@@ -212,6 +219,17 @@ func (h *AuthorizeHandler) serveAuthorize(w http.ResponseWriter, r *http.Request
|
||||
func (h *AuthorizeHandler) ServeHTTPCallback(w http.ResponseWriter, r *http.Request) {
|
||||
h.init()
|
||||
ctx := r.Context()
|
||||
|
||||
if r.Method == http.MethodPost {
|
||||
h.serveMFASubmission(w, r)
|
||||
return
|
||||
}
|
||||
if r.Method != http.MethodGet {
|
||||
w.Header().Set("Allow", "GET, POST")
|
||||
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
q := r.URL.Query()
|
||||
|
||||
state := q.Get("state")
|
||||
@@ -229,7 +247,6 @@ func (h *AuthorizeHandler) ServeHTTPCallback(w http.ResponseWriter, r *http.Requ
|
||||
http.Error(w, "authorization request expired", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
h.pending.Delete(state)
|
||||
|
||||
// Handle upstream callback.
|
||||
result, err := h.Auth.HandleCallback(ctx, domain.CallbackParams{
|
||||
@@ -248,42 +265,110 @@ func (h *AuthorizeHandler) ServeHTTPCallback(w http.ResponseWriter, r *http.Requ
|
||||
http.Error(w, "authentication failed", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
if result == nil || result.Username == "" {
|
||||
h.pending.Delete(state)
|
||||
h.Emitter.Emit(ctx, telemetry.Event{
|
||||
Timestamp: time.Now(),
|
||||
EventType: telemetry.EventAuthFailure,
|
||||
ClientID: ps.ClientID,
|
||||
Endpoint: "/authorize/callback",
|
||||
Result: "failure",
|
||||
ErrorType: "auth_failed",
|
||||
})
|
||||
http.Error(w, "authentication failed", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
// Check MFA requirement.
|
||||
mfaRequired, err := h.MFA.CheckMFARequired(ctx, result.Username)
|
||||
if err != nil {
|
||||
h.Emitter.Emit(ctx, telemetry.Event{
|
||||
Timestamp: time.Now(),
|
||||
EventType: telemetry.EventAuthFailure,
|
||||
ClientID: ps.ClientID,
|
||||
Endpoint: "/authorize/callback",
|
||||
Result: "failure",
|
||||
ErrorType: "mfa_check_error",
|
||||
})
|
||||
http.Error(w, "mfa check error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
if mfaRequired {
|
||||
if mfaToken == "" {
|
||||
ps.AuthenticatedUser = result.Username
|
||||
h.pending.Store(state, ps)
|
||||
h.renderMFAChallenge(w, ps, "")
|
||||
return
|
||||
}
|
||||
if err := h.MFA.ValidateMFAToken(ctx, result.Username, mfaToken); err != nil {
|
||||
h.Emitter.Emit(ctx, telemetry.Event{
|
||||
Timestamp: time.Now(),
|
||||
EventType: telemetry.EventAuthFailure,
|
||||
ClientID: ps.ClientID,
|
||||
Endpoint: "/authorize/callback",
|
||||
Result: "failure",
|
||||
ErrorType: "mfa_failed",
|
||||
})
|
||||
h.pending.Delete(state)
|
||||
h.emitMFAFailure(ctx, ps.ClientID)
|
||||
http.Error(w, "MFA validation failed", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
h.pending.Delete(state)
|
||||
h.completeAuthorization(w, r, ps, result.Username)
|
||||
}
|
||||
|
||||
func (h *AuthorizeHandler) serveMFASubmission(w http.ResponseWriter, r *http.Request) {
|
||||
ctx := r.Context()
|
||||
if err := r.ParseForm(); err != nil {
|
||||
http.Error(w, "invalid form", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
state := r.Form.Get("state")
|
||||
mfaToken := r.Form.Get("mfa_token")
|
||||
|
||||
ps, ok := h.pending.Load(state)
|
||||
if !ok {
|
||||
http.Error(w, "unknown or expired state", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if time.Now().After(ps.ExpiresAt) {
|
||||
h.pending.Delete(state)
|
||||
http.Error(w, "authorization request expired", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if ps.AuthenticatedUser == "" {
|
||||
h.pending.Delete(state)
|
||||
http.Error(w, "mfa challenge not active", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if strings.TrimSpace(mfaToken) == "" {
|
||||
h.renderMFAChallenge(w, ps, "Enter the one-time code.")
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.MFA.ValidateMFAToken(ctx, ps.AuthenticatedUser, mfaToken); err != nil {
|
||||
h.pending.Delete(state)
|
||||
h.emitMFAFailure(ctx, ps.ClientID)
|
||||
http.Error(w, "MFA validation failed", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
h.pending.Delete(state)
|
||||
h.completeAuthorization(w, r, ps, ps.AuthenticatedUser)
|
||||
}
|
||||
|
||||
func (h *AuthorizeHandler) completeAuthorization(w http.ResponseWriter, r *http.Request, ps *PendingState, username string) {
|
||||
// Generate authorization code and store PKCE session.
|
||||
sess := &PKCESession{
|
||||
ClientID: ps.ClientID,
|
||||
RedirectURI: ps.RedirectURI,
|
||||
PKCEChallenge: ps.PKCEChallenge,
|
||||
PKCEChallengeMethod: ps.PKCEChallengeMethod,
|
||||
State: state,
|
||||
Username: result.Username,
|
||||
State: ps.State,
|
||||
Nonce: ps.Nonce,
|
||||
Username: username,
|
||||
Scopes: ps.Scopes,
|
||||
ExpiresAt: time.Now().Add(10 * time.Minute),
|
||||
}
|
||||
authCode := h.Sessions.Create(sess)
|
||||
|
||||
h.Emitter.Emit(ctx, telemetry.Event{
|
||||
h.Emitter.Emit(r.Context(), telemetry.Event{
|
||||
Timestamp: time.Now(),
|
||||
EventType: telemetry.EventAuthSuccess,
|
||||
ClientID: ps.ClientID,
|
||||
@@ -293,14 +378,94 @@ func (h *AuthorizeHandler) ServeHTTPCallback(w http.ResponseWriter, r *http.Requ
|
||||
})
|
||||
|
||||
// Redirect to client with code and state.
|
||||
redirectTo := ps.RedirectURI + "?code=" + authCode + "&state=" + state
|
||||
http.Redirect(w, r, redirectTo, http.StatusFound)
|
||||
redirectTo, err := url.Parse(ps.RedirectURI)
|
||||
if err != nil {
|
||||
http.Error(w, "invalid redirect_uri", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
q := redirectTo.Query()
|
||||
q.Set("code", authCode)
|
||||
q.Set("state", ps.State)
|
||||
redirectTo.RawQuery = q.Encode()
|
||||
http.Redirect(w, r, redirectTo.String(), http.StatusFound)
|
||||
}
|
||||
|
||||
func (h *AuthorizeHandler) emitMFAFailure(ctx context.Context, clientID string) {
|
||||
h.Emitter.Emit(ctx, telemetry.Event{
|
||||
Timestamp: time.Now(),
|
||||
EventType: telemetry.EventAuthFailure,
|
||||
ClientID: clientID,
|
||||
Endpoint: "/authorize/callback",
|
||||
Result: "failure",
|
||||
ErrorType: "mfa_failed",
|
||||
})
|
||||
}
|
||||
|
||||
func (h *AuthorizeHandler) renderMFAChallenge(w http.ResponseWriter, ps *PendingState, errorMessage string) {
|
||||
clientName := ps.ClientID
|
||||
if client, ok := h.ClientConfig[ps.ClientID]; ok && client.DisplayName != "" {
|
||||
clientName = client.DisplayName
|
||||
}
|
||||
status := http.StatusOK
|
||||
if errorMessage != "" {
|
||||
status = http.StatusBadRequest
|
||||
}
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
w.WriteHeader(status)
|
||||
_ = mfaChallengeTemplate.Execute(w, struct {
|
||||
State string
|
||||
Username string
|
||||
ClientName string
|
||||
ErrorMessage string
|
||||
}{
|
||||
State: ps.State,
|
||||
Username: ps.AuthenticatedUser,
|
||||
ClientName: clientName,
|
||||
ErrorMessage: errorMessage,
|
||||
})
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
var mfaChallengeTemplate = template.Must(template.New("mfa-challenge").Parse(`<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>KeyCape MFA</title>
|
||||
<style>
|
||||
:root { color-scheme: light; font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; }
|
||||
body { margin: 0; min-height: 100vh; display: grid; place-items: center; background: #f6f7f9; color: #17202a; }
|
||||
main { width: min(420px, calc(100vw - 32px)); background: #fff; border: 1px solid #dfe4ea; border-radius: 8px; padding: 28px; box-shadow: 0 18px 45px rgba(23, 32, 42, .08); }
|
||||
h1 { margin: 0 0 6px; font-size: 22px; font-weight: 650; letter-spacing: 0; }
|
||||
p { margin: 0 0 20px; color: #52606d; line-height: 1.45; }
|
||||
label { display: block; margin: 0 0 8px; font-size: 13px; font-weight: 650; color: #344054; }
|
||||
input[type="text"] { width: 100%; box-sizing: border-box; height: 44px; border: 1px solid #c9d3df; border-radius: 6px; padding: 0 12px; font: inherit; background: #fff; }
|
||||
input[type="text"]:focus { outline: 2px solid #2f80ed; outline-offset: 2px; border-color: #2f80ed; }
|
||||
button { width: 100%; height: 44px; border: 0; border-radius: 6px; margin-top: 16px; background: #17324d; color: #fff; font: inherit; font-weight: 650; cursor: pointer; }
|
||||
button:focus { outline: 2px solid #2f80ed; outline-offset: 2px; }
|
||||
.meta { font-size: 13px; color: #667085; }
|
||||
.error { margin: 0 0 12px; color: #b42318; font-size: 13px; font-weight: 650; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<h1>Verify sign-in</h1>
|
||||
<p class="meta">{{.Username}} for {{.ClientName}}</p>
|
||||
{{if .ErrorMessage}}<p class="error">{{.ErrorMessage}}</p>{{end}}
|
||||
<form method="post" action="/authorize/callback" autocomplete="off">
|
||||
<input type="hidden" name="state" value="{{.State}}">
|
||||
<label for="mfa_token">One-time code</label>
|
||||
<input id="mfa_token" name="mfa_token" type="text" inputmode="numeric" autocomplete="one-time-code" required autofocus>
|
||||
<button type="submit">Verify</button>
|
||||
</form>
|
||||
</main>
|
||||
</body>
|
||||
</html>`))
|
||||
|
||||
func uriRegistered(registered []string, target string) bool {
|
||||
for _, u := range registered {
|
||||
if u == target {
|
||||
|
||||
@@ -45,14 +45,20 @@ type mockMFAProvider struct {
|
||||
required bool
|
||||
requiredErr error
|
||||
|
||||
validateErr error
|
||||
validateErr error
|
||||
validateCalls int
|
||||
validatedUser string
|
||||
validatedToken string
|
||||
}
|
||||
|
||||
func (m *mockMFAProvider) CheckMFARequired(_ context.Context, _ string) (bool, error) {
|
||||
return m.required, m.requiredErr
|
||||
}
|
||||
|
||||
func (m *mockMFAProvider) ValidateMFAToken(_ context.Context, _, _ string) error {
|
||||
func (m *mockMFAProvider) ValidateMFAToken(_ context.Context, user, token string) error {
|
||||
m.validateCalls++
|
||||
m.validatedUser = user
|
||||
m.validatedToken = token
|
||||
return m.validateErr
|
||||
}
|
||||
|
||||
@@ -80,10 +86,21 @@ func testClient() map[string]*domain.Client {
|
||||
return map[string]*domain.Client{
|
||||
"test-client": {
|
||||
ClientID: "test-client",
|
||||
DisplayName: "Test Client",
|
||||
RedirectURIs: []string{"https://app.example.com/callback"},
|
||||
AllowedScopes: []string{"openid", "profile", "email"},
|
||||
ClientType: "public",
|
||||
},
|
||||
"netkingdom-bootstrap-console": {
|
||||
ClientID: "netkingdom-bootstrap-console",
|
||||
DisplayName: "NetKingdom Bootstrap Console",
|
||||
RedirectURIs: []string{
|
||||
"http://127.0.0.1:8876/oidc/callback",
|
||||
"http://localhost:8876/oidc/callback",
|
||||
},
|
||||
AllowedScopes: []string{"openid", "profile", "email", "groups"},
|
||||
ClientType: "public",
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -146,6 +163,28 @@ func TestAuthorizeHandler_ValidRequest_RedirectsToAuthelia(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthorizeHandler_BootstrapConsoleRedirectURI_RedirectsToAuthelia(t *testing.T) {
|
||||
auth := &mockAuthProvider{authorizeURL: "https://authelia.example.com/auth?state=bootstrap"}
|
||||
mfa := &mockMFAProvider{}
|
||||
emitter := &captureEmitter{}
|
||||
|
||||
h := newAuthorizeHandler(auth, mfa, emitter)
|
||||
params := validAuthorizeParams()
|
||||
params.Set("client_id", "netkingdom-bootstrap-console")
|
||||
params.Set("redirect_uri", "http://127.0.0.1:8876/oidc/callback")
|
||||
|
||||
req := authorizeRequest(params)
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusFound {
|
||||
t.Errorf("expected 302 redirect, got %d (body: %s)", w.Code, w.Body.String())
|
||||
}
|
||||
if loc := w.Header().Get("Location"); loc != "https://authelia.example.com/auth?state=bootstrap" {
|
||||
t.Errorf("expected Authelia redirect, got %q", loc)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthorizeHandler_EmitsAuthStart(t *testing.T) {
|
||||
auth := &mockAuthProvider{authorizeURL: "https://authelia.example.com/auth"}
|
||||
mfa := &mockMFAProvider{}
|
||||
@@ -449,6 +488,164 @@ func TestAuthorizeCallback_MFAFailed_AuthFailure(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthorizeCallback_MFARequired_RendersChallengeWithoutToken(t *testing.T) {
|
||||
auth := &mockAuthProvider{
|
||||
callbackResult: &domain.AuthResult{Username: "alice"},
|
||||
}
|
||||
mfa := &mockMFAProvider{required: true}
|
||||
emitter := &captureEmitter{}
|
||||
|
||||
sessions := oidc.NewSessionStore()
|
||||
h := &oidc.AuthorizeHandler{
|
||||
ClientConfig: testClient(),
|
||||
Auth: auth,
|
||||
MFA: mfa,
|
||||
Sessions: sessions,
|
||||
Emitter: emitter,
|
||||
}
|
||||
|
||||
h.PendingStates().Store("random-state", &oidc.PendingState{
|
||||
ClientID: "test-client",
|
||||
RedirectURI: "https://app.example.com/callback",
|
||||
PKCEChallenge: "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM",
|
||||
PKCEChallengeMethod: "S256",
|
||||
State: "random-state",
|
||||
Scopes: []string{"openid"},
|
||||
ExpiresAt: time.Now().Add(5 * time.Minute),
|
||||
})
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet,
|
||||
"/authorize/callback?code=authelia-code&state=random-state", nil)
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTPCallback(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Errorf("expected 200 challenge page, got %d (body: %s)", w.Code, w.Body.String())
|
||||
}
|
||||
body := w.Body.String()
|
||||
for _, want := range []string{"Verify sign-in", "alice", "Test Client", `name="mfa_token"`} {
|
||||
if !strings.Contains(body, want) {
|
||||
t.Errorf("challenge page missing %q in body: %s", want, body)
|
||||
}
|
||||
}
|
||||
if mfa.validateCalls != 0 {
|
||||
t.Errorf("MFA token should not be validated until form submission, got %d calls", mfa.validateCalls)
|
||||
}
|
||||
ps, ok := h.PendingStates().Load("random-state")
|
||||
if !ok {
|
||||
t.Fatal("expected pending state to remain for MFA form submission")
|
||||
}
|
||||
if ps.AuthenticatedUser != "alice" {
|
||||
t.Errorf("AuthenticatedUser: want alice, got %q", ps.AuthenticatedUser)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthorizeCallback_MFASubmission_ValidToken_RedirectsWithCode(t *testing.T) {
|
||||
auth := &mockAuthProvider{}
|
||||
mfa := &mockMFAProvider{required: true}
|
||||
emitter := &captureEmitter{}
|
||||
|
||||
sessions := oidc.NewSessionStore()
|
||||
h := &oidc.AuthorizeHandler{
|
||||
ClientConfig: testClient(),
|
||||
Auth: auth,
|
||||
MFA: mfa,
|
||||
Sessions: sessions,
|
||||
Emitter: emitter,
|
||||
}
|
||||
|
||||
h.PendingStates().Store("random-state", &oidc.PendingState{
|
||||
ClientID: "test-client",
|
||||
RedirectURI: "https://app.example.com/callback?from=bootstrap",
|
||||
PKCEChallenge: "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM",
|
||||
PKCEChallengeMethod: "S256",
|
||||
State: "random-state",
|
||||
Scopes: []string{"openid"},
|
||||
ExpiresAt: time.Now().Add(5 * time.Minute),
|
||||
AuthenticatedUser: "alice",
|
||||
})
|
||||
|
||||
form := url.Values{"state": {"random-state"}, "mfa_token": {"123456"}}
|
||||
req := httptest.NewRequest(http.MethodPost, "/authorize/callback", strings.NewReader(form.Encode()))
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTPCallback(w, req)
|
||||
|
||||
if w.Code != http.StatusFound {
|
||||
t.Errorf("expected 302 redirect, got %d (body: %s)", w.Code, w.Body.String())
|
||||
}
|
||||
if mfa.validatedUser != "alice" || mfa.validatedToken != "123456" {
|
||||
t.Errorf("validated MFA: want alice/123456, got %q/%q", mfa.validatedUser, mfa.validatedToken)
|
||||
}
|
||||
loc := w.Header().Get("Location")
|
||||
parsed, err := url.Parse(loc)
|
||||
if err != nil {
|
||||
t.Fatalf("invalid Location header: %v", err)
|
||||
}
|
||||
if parsed.Query().Get("from") != "bootstrap" {
|
||||
t.Errorf("expected original redirect query to be preserved, got %q", loc)
|
||||
}
|
||||
if parsed.Query().Get("code") == "" {
|
||||
t.Error("expected code param in redirect, got empty")
|
||||
}
|
||||
if parsed.Query().Get("state") != "random-state" {
|
||||
t.Errorf("expected state=random-state, got %q", parsed.Query().Get("state"))
|
||||
}
|
||||
if _, ok := h.PendingStates().Load("random-state"); ok {
|
||||
t.Error("expected pending MFA state to be deleted after successful submission")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthorizeCallback_MFASubmission_InvalidToken_AuthFailure(t *testing.T) {
|
||||
auth := &mockAuthProvider{}
|
||||
mfa := &mockMFAProvider{
|
||||
required: true,
|
||||
validateErr: domain.ErrMFAFailed,
|
||||
}
|
||||
emitter := &captureEmitter{}
|
||||
|
||||
h := &oidc.AuthorizeHandler{
|
||||
ClientConfig: testClient(),
|
||||
Auth: auth,
|
||||
MFA: mfa,
|
||||
Sessions: oidc.NewSessionStore(),
|
||||
Emitter: emitter,
|
||||
}
|
||||
h.PendingStates().Store("random-state", &oidc.PendingState{
|
||||
ClientID: "test-client",
|
||||
RedirectURI: "https://app.example.com/callback",
|
||||
PKCEChallenge: "abc",
|
||||
PKCEChallengeMethod: "S256",
|
||||
State: "random-state",
|
||||
Scopes: []string{"openid"},
|
||||
ExpiresAt: time.Now().Add(5 * time.Minute),
|
||||
AuthenticatedUser: "alice",
|
||||
})
|
||||
|
||||
form := url.Values{"state": {"random-state"}, "mfa_token": {"wrong"}}
|
||||
req := httptest.NewRequest(http.MethodPost, "/authorize/callback", strings.NewReader(form.Encode()))
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTPCallback(w, req)
|
||||
|
||||
if w.Code != http.StatusUnauthorized {
|
||||
t.Errorf("expected 401, got %d", w.Code)
|
||||
}
|
||||
if _, ok := h.PendingStates().Load("random-state"); ok {
|
||||
t.Error("expected pending MFA state to be deleted after invalid submission")
|
||||
}
|
||||
found := false
|
||||
for _, ev := range emitter.events {
|
||||
if ev.EventType == telemetry.EventAuthFailure && ev.ErrorType == "mfa_failed" {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Error("expected mfa_failed auth_failure telemetry event")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthorizeCallback_AuthProviderFailed_AuthFailure(t *testing.T) {
|
||||
auth := &mockAuthProvider{
|
||||
callbackErr: domain.ErrAuthFailed,
|
||||
|
||||
@@ -15,6 +15,7 @@ type PKCESession struct {
|
||||
PKCEChallenge string // S256 challenge
|
||||
PKCEChallengeMethod string // always "S256"
|
||||
State string
|
||||
Nonce string
|
||||
Username string // set after auth
|
||||
Scopes []string
|
||||
ExpiresAt time.Time
|
||||
|
||||
@@ -111,6 +111,9 @@ func (h *TokenHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
"exp": exp.Unix(),
|
||||
"iat": now.Unix(),
|
||||
}
|
||||
if sess.Nonce != "" {
|
||||
claims["nonce"] = sess.Nonce
|
||||
}
|
||||
|
||||
scopeSet := make(map[string]bool)
|
||||
for _, s := range sess.Scopes {
|
||||
|
||||
@@ -107,6 +107,7 @@ func seededSession(sessions *oidc.SessionStore, verifier string) (code string) {
|
||||
PKCEChallenge: challenge,
|
||||
PKCEChallengeMethod: "S256",
|
||||
State: "state1",
|
||||
Nonce: "nonce1",
|
||||
Username: "alice",
|
||||
Scopes: []string{"openid", "profile", "email", "groups"},
|
||||
ExpiresAt: time.Now().Add(10 * time.Minute),
|
||||
@@ -323,6 +324,9 @@ func TestTokenHandler_JWTClaims_CorrectSubAndIssuer(t *testing.T) {
|
||||
if claims["aud"] != "test-client" {
|
||||
t.Errorf("aud: expected test-client, got %v", claims["aud"])
|
||||
}
|
||||
if claims["nonce"] != "nonce1" {
|
||||
t.Errorf("nonce: expected nonce1, got %v", claims["nonce"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestTokenHandler_ScopeFiltering_ProfileScope(t *testing.T) {
|
||||
|
||||
@@ -224,9 +224,13 @@ The lightweight stack shall be considered valid production infrastructure where
|
||||
|
||||
---
|
||||
|
||||
## 8. NetKingdom IAM Profile v0.1
|
||||
## 8. NetKingdom IAM Profile
|
||||
|
||||
This section defines the initial minimum profile to be supported.
|
||||
This section defines the initial minimum profile supported by the KeyCape v0.1
|
||||
specification. The canonical NetKingdom profile has since moved to
|
||||
`net-kingdom/canon/standards/iam-profile_v0.2.md`; KeyCape conformance should
|
||||
be measured against that profile and the executable suite in
|
||||
`net-kingdom/tools/iam-profile-conformance/`.
|
||||
|
||||
## 8.1 Supported authentication model
|
||||
|
||||
@@ -282,11 +286,15 @@ Initial standard claims may include:
|
||||
* `email` if present
|
||||
* `name` if present
|
||||
|
||||
Optional NetKingdom-specific claims may include:
|
||||
NetKingdom profile v0.2 requires these normalized claims before applications
|
||||
or flex-auth consume a token:
|
||||
|
||||
* groups
|
||||
* roles
|
||||
* tenant or environment markers if explicitly defined
|
||||
* `tenant`
|
||||
* `principal_type`
|
||||
* `groups`
|
||||
* `roles`
|
||||
* `scope` or `scp`
|
||||
* `assurance`
|
||||
|
||||
Claim names, types, and semantics must be fixed by the profile and validated in tests.
|
||||
|
||||
@@ -786,9 +794,11 @@ Canonical fixtures conform if they pass canonical model and LDAP schema validati
|
||||
|
||||
The following implementation artifacts should be created next:
|
||||
|
||||
### 21.1 NetKingdom IAM Profile v0.1
|
||||
### 21.1 NetKingdom IAM Profile
|
||||
|
||||
A more formal profile document with endpoint-by-endpoint detail.
|
||||
A formal canonical profile document now exists in net-kingdom as
|
||||
`canon/standards/iam-profile_v0.2.md`, with endpoint-by-endpoint detail,
|
||||
tenant/principal/assurance claims, and executable conformance checks.
|
||||
|
||||
### 21.2 Canonical identity model schema
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
id: KEY-WP-0001
|
||||
type: workplan
|
||||
title: "KeyCape Implementation — Lightweight IAM Profile"
|
||||
domain: netkingdom
|
||||
domain: infotech
|
||||
repo: key-cape
|
||||
status: done
|
||||
owner: Bernd
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
id: KEY-WP-0002
|
||||
type: workplan
|
||||
title: "KeyCape Container Image — Build & Publish to Gitea OCI Registry"
|
||||
domain: netkingdom
|
||||
domain: infotech
|
||||
repo: key-cape
|
||||
status: done
|
||||
owner: netkingdom
|
||||
@@ -32,7 +32,7 @@ registry on CoulombCore (`92.205.130.254:32166`), triggered automatically on
|
||||
every merge to `main` and on semver tags (`v*`).
|
||||
|
||||
**Gitea OCI registry endpoint:** `92.205.130.254:32166`
|
||||
**Image name:** `92.205.130.254:32166/netkingdom/key-cape`
|
||||
**Image name:** `92.205.130.254:32166/coulomb/key-cape`
|
||||
|
||||
> **Why Gitea, not GHCR?**
|
||||
> The net-kingdom cluster is self-hosted. Keeping images in Gitea (also
|
||||
@@ -67,7 +67,7 @@ the push target runs.
|
||||
|
||||
```makefile
|
||||
IMAGE_REGISTRY ?= 92.205.130.254:32166
|
||||
IMAGE_REPO ?= netkingdom/key-cape
|
||||
IMAGE_REPO ?= coulomb/key-cape
|
||||
IMAGE_TAG ?= latest
|
||||
IMAGE := $(IMAGE_REGISTRY)/$(IMAGE_REPO):$(IMAGE_TAG)
|
||||
|
||||
@@ -122,7 +122,7 @@ state_hub_task_id: "749472fc-edb9-4948-9ebc-58d5f38327ee"
|
||||
|
||||
Add `image`, `push`, and `image-tag` targets to `Makefile` with
|
||||
`IMAGE_REGISTRY`, `IMAGE_REPO`, `IMAGE_TAG` variables defaulting to the
|
||||
Gitea endpoint and `netkingdom/key-cape:latest`.
|
||||
Gitea endpoint and `coulomb/key-cape:latest`.
|
||||
|
||||
Gate: `make image` builds successfully locally; `IMAGE_TAG=dev make image`
|
||||
produces a differently-tagged image.
|
||||
@@ -163,7 +163,7 @@ state_hub_task_id: "2dde67f9-944f-418d-a2e9-7367bc556425"
|
||||
|
||||
On CoulombCore, create/update `/etc/rancher/k3s/registries.yaml` to add
|
||||
the Gitea NodePort as an HTTP mirror. Restart k3s (or send SIGHUP) and
|
||||
verify `crictl pull 92.205.130.254:32166/netkingdom/key-cape:latest` works.
|
||||
verify `crictl pull 92.205.130.254:32166/coulomb/key-cape:latest` works.
|
||||
|
||||
Gate: image pull from within the cluster succeeds without TLS errors.
|
||||
|
||||
@@ -209,10 +209,10 @@ IMAGE_TAG=dev make push
|
||||
Then verify the image is pullable from CoulombCore:
|
||||
```bash
|
||||
# on CoulombCore
|
||||
crictl pull 92.205.130.254:32166/netkingdom/key-cape:dev
|
||||
crictl pull 92.205.130.254:32166/coulomb/key-cape:dev
|
||||
```
|
||||
|
||||
Gate: pull succeeds; image is listed in Gitea → Packages → netkingdom/key-cape.
|
||||
Gate: pull succeeds; image is listed in Gitea -> Packages -> coulomb/key-cape.
|
||||
|
||||
---
|
||||
|
||||
@@ -227,7 +227,7 @@ state_hub_task_id: "946cd34d-94da-4fa9-a781-ed36f6c827a3"
|
||||
|
||||
Add a "Container Image" section to `README.md` documenting:
|
||||
- Registry URL and image name
|
||||
- How to pull (`docker pull 92.205.130.254:32166/netkingdom/key-cape:latest`)
|
||||
- How to pull (`docker pull 92.205.130.254:32166/coulomb/key-cape:latest`)
|
||||
- How to build and push locally (Makefile targets)
|
||||
- CI secrets required for the Actions workflow
|
||||
|
||||
|
||||
200
workplans/KEY-WP-0003-bootstrap-console-oidc-mfa-login.md
Normal file
200
workplans/KEY-WP-0003-bootstrap-console-oidc-mfa-login.md
Normal file
@@ -0,0 +1,200 @@
|
||||
---
|
||||
id: KEY-WP-0003
|
||||
type: workplan
|
||||
title: "Bootstrap Console OIDC Login and MFA Verification"
|
||||
domain: infotech
|
||||
repo: key-cape
|
||||
status: finished
|
||||
owner: codex
|
||||
topic_slug: netkingdom
|
||||
created: "2026-05-24"
|
||||
updated: "2026-05-24"
|
||||
state_hub_workstream_id: "02990009-a2b3-44f6-a579-487fbacae41a"
|
||||
---
|
||||
|
||||
# KEY-WP-0003 - Bootstrap Console OIDC Login and MFA Verification
|
||||
|
||||
## Problem
|
||||
|
||||
The NetKingdom security bootstrap console now acts as a local OIDC client
|
||||
callback so the operator can verify the dedicated platform-root login before
|
||||
approving custody mode. The current live KeyCape deployment rejects that flow
|
||||
with:
|
||||
|
||||
```json
|
||||
{
|
||||
"error": "invalid_profile_usage",
|
||||
"description": "redirect_uri does not match any registered URI",
|
||||
"feature": "redirect_uri"
|
||||
}
|
||||
```
|
||||
|
||||
That error is correct profile enforcement: KeyCape only accepts exact
|
||||
registered redirect URIs. The live `demo-app` registration has not yet been
|
||||
updated to allow the local bootstrap console callback:
|
||||
|
||||
- `http://127.0.0.1:8876/oidc/callback`
|
||||
- `http://localhost:8876/oidc/callback`
|
||||
|
||||
After that is fixed, there is a second usability/security gap. KeyCape checks
|
||||
privacyIDEA MFA after the Authelia callback, but the browser flow currently
|
||||
expects an `mfa_token` query parameter instead of presenting a proper OTP
|
||||
challenge page to the human operator.
|
||||
|
||||
## Goal
|
||||
|
||||
Make the bootstrap console's "Start demo OIDC login" button a real
|
||||
end-to-end verification path for the current lightweight IAM stack:
|
||||
|
||||
1. KeyCape accepts the bootstrap console callback URI by exact registration.
|
||||
2. The browser leaves KeyCape for the public Authelia login URL.
|
||||
3. After password login, KeyCape presents a minimal MFA challenge when
|
||||
privacyIDEA requires one.
|
||||
4. KeyCape issues an OIDC authorization code to the bootstrap console callback.
|
||||
5. The console can exchange the code and let the operator mark
|
||||
`OIDC login verified` without exposing tokens or secrets.
|
||||
|
||||
This keeps KeyCape's security posture intact: no wildcard redirect URIs, no
|
||||
dynamic client registration, no token display, and no storage of OTP material.
|
||||
|
||||
## Design Notes
|
||||
|
||||
- Prefer a dedicated public client named `netkingdom-bootstrap-console` for
|
||||
long-lived clarity. Reusing `demo-app` is acceptable for the immediate
|
||||
unblock only if the deployment/runbook clearly labels it as a bootstrap test
|
||||
client.
|
||||
- The bootstrap callback is local-only and operator-attended. It must be an
|
||||
exact URI in config, not a wildcard or dynamic registration exception.
|
||||
- Browser-facing Authelia redirects must use the public Authelia base URL
|
||||
(`https://auth.coulomb.social`) so the human login page opens correctly.
|
||||
- KeyCape may still need an internal service URL for back-channel token
|
||||
exchange. If so, split the current single Authelia URL into browser-facing
|
||||
authorize URL and internal token URL instead of making the browser use an
|
||||
in-cluster hostname.
|
||||
- The MFA prompt should collect only a one-time code, post it back to KeyCape,
|
||||
validate with privacyIDEA, and then continue the normal OIDC code flow.
|
||||
- This work unblocks the NetKingdom custody gate in
|
||||
`NET-WP-0015-platform-root-custody-and-openbao-identity-bootstrap`.
|
||||
|
||||
## Implementation Notes
|
||||
|
||||
**2026-05-24:** Implemented in source:
|
||||
|
||||
- added `netkingdom-bootstrap-console` as a public OIDC client in the sample
|
||||
KeyCape config, while keeping the local callback registered on `demo-app`
|
||||
for compatibility,
|
||||
- split Authelia browser redirects from server-side token exchange via
|
||||
`browserBaseURL` and `tokenBaseURL`,
|
||||
- added a browser MFA challenge page at `POST /authorize/callback` that
|
||||
validates the one-time code with privacyIDEA before issuing the downstream
|
||||
OIDC authorization code,
|
||||
- updated NetKingdom's `keycape-config` generation template and bootstrap
|
||||
console to use the dedicated client,
|
||||
- added regression tests for callback registration, split Authelia URLs, MFA
|
||||
challenge rendering, valid OTP continuation, and invalid OTP failure.
|
||||
|
||||
Live use still requires deployment: build/publish the updated KeyCape image,
|
||||
refresh the live `keycape-config` Secret through the custodian age-key unlock
|
||||
ceremony, and restart the KeyCape deployment.
|
||||
|
||||
---
|
||||
|
||||
## T01 - Register the bootstrap console callback client
|
||||
|
||||
```task
|
||||
id: KEY-WP-0003-T01
|
||||
status: done
|
||||
priority: high
|
||||
state_hub_task_id: "b396c99f-d711-475a-9cba-4f03a1db561d"
|
||||
```
|
||||
|
||||
Add a KeyCape client registration for the bootstrap console. Either create a
|
||||
dedicated `netkingdom-bootstrap-console` public client or update `demo-app`
|
||||
temporarily with these exact redirect URIs:
|
||||
|
||||
- `http://127.0.0.1:8876/oidc/callback`
|
||||
- `http://localhost:8876/oidc/callback`
|
||||
|
||||
Update the sample config, tests, and deployment/runbook references so the
|
||||
registered client is reproducible and not just a live-cluster patch.
|
||||
|
||||
Gate: an authorize request using the local callback no longer returns
|
||||
`invalid_profile_usage` for `redirect_uri`.
|
||||
|
||||
## T02 - Separate browser-facing and internal Authelia URLs if needed
|
||||
|
||||
```task
|
||||
id: KEY-WP-0003-T02
|
||||
status: done
|
||||
priority: high
|
||||
state_hub_task_id: "46172e6d-3e11-493c-b223-79c2fc321aec"
|
||||
```
|
||||
|
||||
Confirm whether the current `authelia.baseURL` is safe to use for both browser
|
||||
redirects and server-side token exchange. If not, add explicit configuration
|
||||
for the browser authorize base URL and internal token/userinfo base URL.
|
||||
|
||||
Gate: the first browser redirect leaves `https://kc.coulomb.social` for
|
||||
`https://auth.coulomb.social/...`; server-side token exchange still works from
|
||||
inside the deployment.
|
||||
|
||||
## T03 - Add a browser MFA challenge step
|
||||
|
||||
```task
|
||||
id: KEY-WP-0003-T03
|
||||
status: done
|
||||
priority: high
|
||||
state_hub_task_id: "92fca4d0-6215-4ea6-9f80-9178ae183acb"
|
||||
```
|
||||
|
||||
When `CheckMFARequired` returns true after the Authelia callback, render a
|
||||
minimal KeyCape MFA challenge page instead of requiring `mfa_token` in the
|
||||
callback query string. The page should:
|
||||
|
||||
- show the authenticated username and client display name,
|
||||
- collect only the OTP code,
|
||||
- preserve the pending OIDC state server-side,
|
||||
- validate with privacyIDEA,
|
||||
- continue to issue the normal authorization code on success,
|
||||
- fail closed with the existing telemetry on invalid MFA.
|
||||
|
||||
Gate: a user enrolled in privacyIDEA can complete password + OTP in the
|
||||
browser and is returned to the registered downstream callback.
|
||||
|
||||
## T04 - Add end-to-end profile tests for the bootstrap login path
|
||||
|
||||
```task
|
||||
id: KEY-WP-0003-T04
|
||||
status: done
|
||||
priority: medium
|
||||
state_hub_task_id: "079a5929-1864-4461-a64c-746cebca469d"
|
||||
```
|
||||
|
||||
Add tests that cover:
|
||||
|
||||
- local bootstrap callback registration,
|
||||
- rejection of unregistered callbacks remains intact,
|
||||
- Authelia browser redirect uses the expected public URL,
|
||||
- MFA-required login presents a challenge instead of immediate failure,
|
||||
- invalid OTP fails closed,
|
||||
- valid OTP produces an authorization code bound to the original PKCE session.
|
||||
|
||||
Gate: `make test` passes and the negative redirect URI tests remain green.
|
||||
|
||||
## T05 - Document the live rollout ceremony
|
||||
|
||||
```task
|
||||
id: KEY-WP-0003-T05
|
||||
status: done
|
||||
priority: medium
|
||||
state_hub_task_id: "1d67225d-a20b-4e36-9b2e-20836be2f439"
|
||||
```
|
||||
|
||||
Document the deployment path for updating live KeyCape config without
|
||||
regenerating unrelated secrets. The runbook must fit the NetKingdom custodian
|
||||
age-key model: decrypt or unlock only during an attended ceremony, apply the
|
||||
updated client registration/config, restart KeyCape, and remove plaintext
|
||||
secret material afterward.
|
||||
|
||||
Gate: an operator can update the live `keycape-config` Secret and verify the
|
||||
bootstrap console OIDC login without printing or committing secrets.
|
||||
Reference in New Issue
Block a user